title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
listlengths
1
5
add() argument after * must be a sequence, not Settings
38,658,684
<p>I'm trying to build a game that moves a ship left and right with the arrow keys and fires bullets when the spacebar is pressed. When I press the spacebar my game crashes and this error is shown: Traceback (most recent call last):</p> <pre><code>TypeError: add() argument after * must be a sequence, not Settings </code></pre> <p>Here's my code:</p> <pre><code>class Settings(): """A class to store all settings for Alien Invasion.""" def __init__(self): """Initialize the game's settings.""" # Screen settings self.screen_width = 800 self.screen_height = 480 self.bg_color = (230, 230, 230) # Ship settings self.ship_speed_factor = 1.5 # Bullet settings self.bullet_speed_factor = 1 self.bullet_width = 3 self.bullet_height = 15 self.bullet_color = 60, 60, 60 import pygame from pygame.sprite import Sprite class Bullet(Sprite): """A class to manage bullets fired from the ship""" def _init__(self, ai_settings, screen, ship): """Create a bullet object at the ship's current position.""" super(Bullet, self).__init__() self.screen = screen # Create a bullet rect at (0, 0) and then set correct position. self.rect = pygame.Rect(0, 0, ai_settings.bullet_width, ai_settings.bullet_height) self.rect.centerx = ship.rect.centerx self.rect.top = ship.rect.top # Store the bullet's position as a decimal value. self.y = float(self.rect.y) self.color = ai_settings.bullet_color self.speed_factor = ai_settings.bullet_speed_factor def update(self): """Move the bullet up the screen""" # Update the decimal position of the bullet. self.y -= self.speed_factor # Update the rect position. self.rect.y = self.y def draw_bullet(self): """Draw the bullet to the screen.""" pygame.draw.rect(self.screen, self.color, self.rect) import sys import pygame from bullet import Bullet def check_keydown_events(event, ai_settings, screen, ship, bullets): """Respond to keypresses.""" if event.key == pygame.K_RIGHT: ship.moving_right = True elif event.key == pygame.K_LEFT: ship.moving_left = True elif event.key == pygame.K_SPACE: # Create a new bullet and add it to the bullets group. new_bullet = Bullet(ai_settings, screen, ship) bullets.add(new_bullet) def check_keyup_events(event, ship): """Respind to key releases.""" if event.key == pygame.K_RIGHT: ship.moving_right = False elif event.key == pygame.K_LEFT: ship.moving_left = False def check_events(ai_settings, screen, ship, bullets): """Respond to keypresses and mouse events.""" for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() elif event.type == pygame.KEYDOWN: check_keydown_events(event, ai_settings, screen, ship, bullets) elif event.type == pygame.KEYUP: check_keyup_events(event, ship) </code></pre> <p>And finally the main file:</p> <pre><code>import pygame from pygame.sprite import Group from settings import Settings from ship import Ship import game_functions as gf def run_game(): # Initialize pygame, settings, and screen object. pygame.init() ai_settings = Settings() screen = pygame.display.set_mode( (ai_settings.screen_width, ai_settings.screen_height)) pygame.display.set_caption("Alien Invasion") # Make a ship. ship = Ship(ai_settings, screen) # Make a group to store bullets in. bullets = Group() # Start the main loop for the game. while True: # Watch the keyboard and mouse events. gf.check_events(ai_settings, screen, ship, bullets) ship.update() bullets.update() gf.update_screen(ai_settings, screen, ship, bullets) run_game() </code></pre> <p>The trace: </p> <pre><code>Traceback (most recent call last): File "C:\Users\martin\Desktop\python_work\alien_invasion\alien_invasion.py", line 30, in &lt;module&gt; run_game() File "C:\Users\martin\Desktop\python_work\alien_invasion\alien_invasion.py", line 25, in run_game gf.check_events(ai_settings, screen, ship, bullets) File "C:\Users\martin\Desktop\python_work\alien_invasion\game_functions.py", line 33, in check_events check_keydown_events(event, ai_settings, screen, ship, bullets) File "C:\Users\martin\Desktop\python_work\alien_invasion\game_functions.py", line 15, in check_keydown_events new_bullet = Bullet(ai_settings, screen, ship) File "C:\Users\martin\Anaconda3\lib\site-packages\pygame\sprite.py", line 124, in __init__ self.add(*groups) File "C:\Users\martin\Anaconda3\lib\site-packages\pygame\sprite.py", line 142, in add self.add(*group) TypeError: add() argument after * must be a sequence, not Settings </code></pre>
2
2016-07-29T12:19:23Z
38,662,125
<p>Yes Jokab is right, you forgot the extra underscore. However, for future practice it is important to learn to read the Python <code>TrackBack</code>. It usually gives you a good idea of where the problem is. For example, take the <code>TrackBack</code> you pasted here. Python first tells you it had a problem running <code>run_game()</code>. So python then says that <strong>in</strong> your game running function it has a problem calling the method <code>gf.check_events(ai_settings, screen, ship, bullets)</code>. It then looked at your initialization of the bullet class <code>new_bullet = Bullet(ai_settings, screen, ship</code> and has a problem with it. And in the very next line is were it gives the <code>TypeError</code>. Now, while you could figure out exactly what python is saying about the <code>TypeError</code>, which is a viable option. But just from looking at it you could determine that it has a problem adding your bullet object to the sprites group. Which means that if I were you, I'd start my searching in the <code>Bullet</code> class. And sure enough there is a typo in your <code>__init__</code> function.</p> <p>While it is not the end of the world if you don't learn how to read python <code>TrackBack</code>'s, It will save you plenty of time in the long run.</p> <p>~Mr.Pyton</p>
1
2016-07-29T15:11:20Z
[ "python", "pygame", "sprite", "add" ]
Pandas: append symbol to cells in column
38,658,752
<p>I create dataframe with </p> <pre><code>df3 = np.round(df2[["All"]]/df['Gender'].count()*100, 2).rename(columns={"All":'%'}) </code></pre> <p>and I want to add <code>%</code> after every number. How can I do it? <code>df</code>:</p> <pre><code>Third party unique identifier Qsex Gender 9ea3e3cb6719f3d336d324c446f486bd 1 male d1b69bc4cccf0afef66debf4e3f0643e 2 female f574fc585db0cddef88306ef6f32da59 1 male 8bc0a586bf0abec653c29cf4160753f9 1 male 7c22b56929378ec2eb3a536b4f4bc4e0 2 female 23d8433168c46d57a271a6b979037094 1 male 5743b7eec1b018572b6c5b44542a67a5 2 female f176289325aa4a6fa56c0179e9cbd101 1 male c729933ff7db798ae07c59d971f40a70 1 male </code></pre> <p>df2 </p> <pre><code> Qsex 1.0 2.0 All Gender Female 0 72342 72342 Male 51537 0 51537 All 51537 72342 123879 </code></pre>
0
2016-07-29T12:22:48Z
38,660,163
<p>I think you need first add <code>normalize</code> to <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.crosstab.html" rel="nofollow"><code>crosstab</code></a>, then <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.round.html" rel="nofollow"><code>round</code></a>, multiple by <code>100</code>, convert to <code>string</code> and last add <code>%</code>:</p> <pre><code>df2 = pd.crosstab(df.Gender, df.Qsex, margins=True, normalize=True) .round(2) .mul(100) .astype(str) + '%' print (df2) Qsex 1 2 All Gender female 0.0% 33.0% 33.0% male 67.0% 0.0% 67.0% All 67.0% 33.0% 100.0% </code></pre> <p>because if use <code>astype(str) + '%'</code> only:</p> <pre><code>df2 = pd.crosstab(df.Gender, df.Qsex, margins=True).astype(str) + '%' print (df2) Qsex 1 2 All Gender female 0% 3% 3% male 6% 0% 6% All 6% 3% 9% </code></pre>
1
2016-07-29T13:28:46Z
[ "python", "pandas" ]
Remapping `numpy.array` with missing values
38,658,811
<p>I'm dealing with some large data sets - observations as a function of time - which are not continuous in time (i.e., there is a lot of missing data, where the complete record is absent). To make things fun, there are a lot of data sets, all with missing records, all at random places... </p> <p>I somehow need to get the data "synchronised" in time, with missing data flagged as missing data, instead of being completely absent. I've managed to get this partially working, but I'm still having some problems. </p> <p>Example:</p> <pre><code>import numpy as np # The date range (in the format that I'm dealing with), which I define # myself for the period in which I'm interested dc = np.arange(2010010100, 2010010106) # Observation dates (d1) and values (v1) d1 = np.array([2010010100, 2010010104, 2010010105]) # date v1 = np.array([10, 11, 12 ]) # values # Another data set with (partially) other times d2 = np.array([2010010100, 2010010102, 2010010104]) # date v2 = np.array([13, 14, 15 ]) # values # For now set -1 as fill_value v1_filled = -1 * np.ones_like(dc) v2_filled = -1 * np.ones_like(dc) v1_filled[dc.searchsorted(d1)] = v1 v2_filled[dc.searchsorted(d2)] = v2 </code></pre> <p>This gives me the desired result:</p> <pre><code>v1_filled = [10 -1 -1 -1 11 12] v2_filled = [13 -1 14 -1 15 -1] </code></pre> <p>but only if the values in <code>d1</code> or <code>d2</code> are also in <code>dc</code>; if a value in <code>d1</code> or <code>d2</code> is not in <code>dc</code> the code fails because then <code>searchsorted</code> behaves as:</p> <blockquote> <p>If there is no suitable index, return either 0 or N (where N is the length of <code>a</code>). </p> </blockquote> <p>So for example, if I change <code>d2</code> and <code>v2</code> to:</p> <pre><code>d2 = np.array([2010010100, 2010010102, 2010010104, 0]) # date v2 = np.array([13, 14, 15, 9999]) # values </code></pre> <p>The result is </p> <pre><code>[9999 -1 14 -1 15 -1] </code></pre> <p>In this case, because <code>d2=0</code> is not in <code>dc</code>, it should discard that value, instead of inserting it at the start (or end). Any idea how to easily achieve that?</p>
1
2016-07-29T12:25:50Z
38,667,956
<p>If you do <code>d2 = np.intersect1d(dc, d2)</code> before calling <code>dc.searchsorted(d2)</code> it will remove all elements in d2 that are not in dc.</p>
1
2016-07-29T21:48:13Z
[ "python", "numpy" ]
How to improve performance for large lists in python
38,659,123
<p>I have a large list with say 10 million of integers (sorted) "alist". What I need is to get the smallest distance between some of the integers (from a "blist") and the neighbours in the list. I do it by finding the position of the integer I look for, get the item before and after and measure the difference:</p> <pre><code>alist=[1, 4, 30, 1000, 2000] #~10 million integers blist=[4, 30, 1000] #~8 million integers for b in blist: position=alist.index(b) distance=min([b-alist[position-1],alist[position+1]-b]) </code></pre> <p>This operation has to be repeated millions of times and, unfortunately, it takes ages on my machine. Is there a way to improve performance of this code? I use python 2.6 and python 3 is not an option.</p>
0
2016-07-29T12:39:57Z
38,659,683
<p>I really like the Numpy module for this kind of computing.</p> <p>In your case, that would be (this is the long answer, could be factorized to be more efficient): </p> <pre><code>import numpy as np alist = [1, 4, 30, 1000, 2000] blist = [4, 30, 1000] a_array = np.asarray(alist) b_array = np.asarray(blist) a_index = np.searchsorted(a_array, b_array) # gives the indexes of the elements of b_array in a_array a_array_left = a_array[a_index - 1] a_array_right = a_array[a_index + 1] distance_left = np.abs(b_array - a_array_left) distance_right = np.abs(a_array_right - b_array) min_distance = np.min([distance_left, distance_right], axis=0) </code></pre> <p>It will not work if the first element of blist is the first of alist, same for the end. I guess :</p> <pre><code>alist = [b[0] - 1] + alist + [b[-1] + 1] </code></pre> <p>is a dirty workaround.</p> <p><strong>Benchmark</strong><br> the "still running" may me my computer's fault..</p> <pre><code>alist = sorted(list(np.random.randint(0, 10000, 10000000))) blist = sorted(list(alist[1000000:9000001])) a_array = np.asarray(alist) b_array = np.asarray(blist) </code></pre> <p>Vectorized solution</p> <pre><code>%%timeit a_index = np.searchsorted(a_array, b_array) a_array_left = a_array[a_index - 1] a_array_right = a_array[a_index + 1] min_distance = np.min([b_array - a_array_left, a_array_right - b_array], axis=0) 1 loop, best of 3: 591 ms per loop </code></pre> <p>Binary Search solution</p> <pre><code>%%timeit for b in blist: position = bisect.bisect_left(alist, b) distance = min([b-alist[position-1],alist[position+1]-b]) Still running.. </code></pre> <p>OP's solution</p> <pre><code>%%timeit for b in blist: position=alist.index(b) distance=min([b-alist[position-1],alist[position+1]-b]) Still running.. </code></pre> <p><strong> Smaller Inputs </strong></p> <pre><code>alist = sorted(list(np.random.randint(0, 10000, 1000000))) blist = sorted(list(alist[100000:900001])) a_array = np.asarray(alist) b_array = np.asarray(blist) </code></pre> <p>Vectorized solution</p> <pre><code>%%timeit a_index = np.searchsorted(a_array, b_array) a_array_left = a_array[a_index - 1] a_array_right = a_array[a_index + 1] min_distance = np.min([b_array - a_array_left, a_array_right - b_array], axis=0) 10 loops, best of 3: 53.2 ms per loop </code></pre> <p>Binary Search solution</p> <pre><code>%%timeit for b in blist: position = bisect.bisect_left(alist, b) distance = min([b-alist[position-1],alist[position+1]-b]) 1 loop, best of 3: 1.57 s per loop </code></pre> <p>OP's solution</p> <pre><code>%%timeit for b in blist: position=alist.index(b) distance=min([b-alist[position-1],alist[position+1]-b]) Still running.. </code></pre>
1
2016-07-29T13:05:01Z
[ "python", "performance", "list", "optimization" ]
How to improve performance for large lists in python
38,659,123
<p>I have a large list with say 10 million of integers (sorted) "alist". What I need is to get the smallest distance between some of the integers (from a "blist") and the neighbours in the list. I do it by finding the position of the integer I look for, get the item before and after and measure the difference:</p> <pre><code>alist=[1, 4, 30, 1000, 2000] #~10 million integers blist=[4, 30, 1000] #~8 million integers for b in blist: position=alist.index(b) distance=min([b-alist[position-1],alist[position+1]-b]) </code></pre> <p>This operation has to be repeated millions of times and, unfortunately, it takes ages on my machine. Is there a way to improve performance of this code? I use python 2.6 and python 3 is not an option.</p>
0
2016-07-29T12:39:57Z
38,659,932
<p>I suggest using <strong>binary search</strong>. Makes it much faster, doesn't cost extra memory, and only requires a little change. Instead of <code>alist.index(b)</code>, simply use <a href="https://docs.python.org/3.5/library/bisect.html#bisect.bisect_left" rel="nofollow"><code>bisect_left(alist, b)</code></a>.</p> <p>In case your <code>blist</code> is sorted as well, you could also use a very simple incremental search, searching the current <code>b</code> not from the beginning of <code>alist</code> but from the index of the previous <code>b</code>.</p> <p>Benchmarks with <strong>Python 2.7.11</strong> and lists containing 10 million and 8 million ints:</p> <pre><code>389700.01 seconds Andy_original (time estimated) 377100.01 seconds Andy_no_lists (time estimated) 6.30 seconds Stefan_binary_search 2.15 seconds Stefan_incremental_search 3.57 seconds Stefan_incremental_search2 1.21 seconds Jacquot_NumPy (0.74 seconds Stefan_only_search_no_distance) </code></pre> <p>Andy's originals would take about 4.5 days, so I only used every 100000-th entry of <code>blist</code> and scaled up. Binary search is much faster, incremental search is faster still, and NumPy beats them all, though they all take only seconds.</p> <p>The last entry taking 0.74 seconds is my incremental search without the <code>distance = min(...)</code> line, so it's not comparable. But it shows that the search only takes about 34% of the total 2.15 seconds. So there's not much more that I could do, as now the <code>distance = min(...)</code> calculation is responsible for most of the time.</p> <p>The results with <strong>Python 3.5.1</strong> are similar:</p> <pre><code>509819.56 seconds Andy_original (time estimated) 505257.32 seconds Andy_no_lists (time estimated) 8.35 seconds Stefan_binary_search 4.61 seconds Stefan_incremental_search 4.53 seconds Stefan_incremental_search2 1.39 seconds Jacquot_NumPy (1.45 seconds Stefan_only_search_no_distance) </code></pre> <p>The complete code with all versions and tests:</p> <pre><code>def Andy_original(alist, blist): for b in blist: position = alist.index(b) distance = min([b-alist[position-1], alist[position+1]-b]) def Andy_no_lists(alist, blist): for b in blist: position = alist.index(b) distance = min(b-alist[position-1], alist[position+1]-b) from bisect import bisect_left def Stefan_binary_search(alist, blist): for b in blist: position = bisect_left(alist, b) distance = min(b-alist[position-1], alist[position+1]-b) def Stefan_incremental_search(alist, blist): position = 0 for b in blist: while alist[position] &lt; b: position += 1 distance = min(b-alist[position-1], alist[position+1]-b) def Stefan_incremental_search2(alist, blist): position = 0 for b in blist: position = alist.index(b, position) distance = min(b-alist[position-1], alist[position+1]-b) import numpy as np def Jacquot_NumPy(alist, blist): a_array = np.asarray(alist) b_array = np.asarray(blist) a_index = np.searchsorted(a_array, b_array) # gives the indexes of the elements of b_array in a_array a_array_left = a_array[a_index - 1] a_array_right = a_array[a_index + 1] distance_left = np.abs(b_array - a_array_left) distance_right = np.abs(a_array_right - b_array) min_distance = np.min([distance_left, distance_right], axis=0) def Stefan_only_search_no_distance(alist, blist): position = 0 for b in blist: while alist[position] &lt; b: position += 1 from time import time alist = list(range(10000000)) blist = [i for i in alist[1:-1] if i % 5] blist_small = blist[::100000] for func in Andy_original, Andy_no_lists: t0 = time() func(alist, blist_small) t = time() - t0 print('%9.2f seconds %s (time estimated)' % (t * 100000, func.__name__)) for func in Stefan_binary_search, Stefan_incremental_search, Stefan_incremental_search2, Jacquot_NumPy, Stefan_only_search_no_distance: t0 = time() func(alist, blist) t = time() - t0 print('%9.2f seconds %s' % (t, func.__name__)) </code></pre>
4
2016-07-29T13:17:26Z
[ "python", "performance", "list", "optimization" ]
Remove text below barcode in python barcode.py library
38,659,202
<p>Does anyone know how to remove text below a bar-code? Bar-code is generated using <code>barcode.py</code> library. I was trying to check in <a href="https://bitbucket.org/whitie/python-barcode" rel="nofollow">https://bitbucket.org/whitie/python-barcode</a> but could not find solution,what properties should be written in barcode saving line in python:</p> <pre><code>ean = barcode.get('code39', str(row['PART']), writer=ImageWriter()) </code></pre> <p>Attaching barcode picture with marked line what i would like to remove from barcode generation. <a href="http://i.stack.imgur.com/qQtes.png" rel="nofollow"><img src="http://i.stack.imgur.com/qQtes.png" alt="enter image description here"></a></p>
1
2016-07-29T12:43:12Z
38,690,298
<p>Looking at the code, it appears you can set the attribute <code>'human'</code> (human-readable text) to a non-empty string to override the text at the bottom. If this is set to a string with a single blank, <code>' '</code>, the text will be empty.</p>
0
2016-08-01T02:40:11Z
[ "python", "python-2.7", "barcode" ]
Numpy suddenly uses all CPUs
38,659,217
<p>Until recently when I used numpy methods like np.dot(A,B), only a single core was used. However, since today suddently all 8 cores of my linux machine are being used, which is a problem.</p> <p>A minimal working example:</p> <pre><code>import numpy as np N = 100 a = np.random.rand(N,N) b = np.random.rand(N,N) for i in range(100000): a = np.dot(a,b) </code></pre> <p>On my other laptop it works all fine on a single core. Could this be due to some new libraries? </p> <p>This morning I updated matplotlib and cairocffi via pip, but that's all.</p> <p>Any ideas how to go back to a single core?</p> <p>Edit:</p> <p>When I run</p> <pre><code>np.__config__.show() </code></pre> <p>I get the following output</p> <pre><code>openblas_info: libraries = ['openblas', 'openblas'] define_macros = [('HAVE_CBLAS', None)] language = c library_dirs = ['/usr/local/lib'] openblas_lapack_info: libraries = ['openblas', 'openblas'] define_macros = [('HAVE_CBLAS', None)] language = c library_dirs = ['/usr/local/lib'] lapack_opt_info: libraries = ['openblas', 'openblas'] define_macros = [('HAVE_CBLAS', None)] language = c library_dirs = ['/usr/local/lib'] blas_mkl_info: NOT AVAILABLE blas_opt_info: libraries = ['openblas', 'openblas'] define_macros = [('HAVE_CBLAS', None)] language = c library_dirs = ['/usr/local/lib'] </code></pre>
2
2016-07-29T12:44:07Z
38,659,540
<p>This could be because <code>numpy</code> is linking against multithreaded openBLAS libraries. Try setting the global environment variable to set threading affinity as:</p> <pre><code>export OPENBLAS_MAIN_FREE=1 # Now run your python script. </code></pre> <p>Another workaround could to use <code>ATLAS</code> instead of <code>OpenBLAS</code>. Please see this post for more information (<a href="https://shahhj.wordpress.com/2013/10/27/numpy-and-blas-no-problemo/" rel="nofollow">https://shahhj.wordpress.com/2013/10/27/numpy-and-blas-no-problemo/</a>). This post proposes some other workarounds as well which might be worth trying. </p>
2
2016-07-29T12:58:36Z
[ "python", "numpy" ]
Numpy suddenly uses all CPUs
38,659,217
<p>Until recently when I used numpy methods like np.dot(A,B), only a single core was used. However, since today suddently all 8 cores of my linux machine are being used, which is a problem.</p> <p>A minimal working example:</p> <pre><code>import numpy as np N = 100 a = np.random.rand(N,N) b = np.random.rand(N,N) for i in range(100000): a = np.dot(a,b) </code></pre> <p>On my other laptop it works all fine on a single core. Could this be due to some new libraries? </p> <p>This morning I updated matplotlib and cairocffi via pip, but that's all.</p> <p>Any ideas how to go back to a single core?</p> <p>Edit:</p> <p>When I run</p> <pre><code>np.__config__.show() </code></pre> <p>I get the following output</p> <pre><code>openblas_info: libraries = ['openblas', 'openblas'] define_macros = [('HAVE_CBLAS', None)] language = c library_dirs = ['/usr/local/lib'] openblas_lapack_info: libraries = ['openblas', 'openblas'] define_macros = [('HAVE_CBLAS', None)] language = c library_dirs = ['/usr/local/lib'] lapack_opt_info: libraries = ['openblas', 'openblas'] define_macros = [('HAVE_CBLAS', None)] language = c library_dirs = ['/usr/local/lib'] blas_mkl_info: NOT AVAILABLE blas_opt_info: libraries = ['openblas', 'openblas'] define_macros = [('HAVE_CBLAS', None)] language = c library_dirs = ['/usr/local/lib'] </code></pre>
2
2016-07-29T12:44:07Z
38,662,889
<p>Assuming you have root access, Pankaj Daga's answer is propably ok.</p> <p>In my case I reinstalled my local numpy version, which turned out to solve the problem.</p>
0
2016-07-29T15:51:41Z
[ "python", "numpy" ]
.join() elements of a user generated list using range in Python
38,659,238
<p>In my program user enters a number (input_n) that will go through :<br> 0+1+2+ ... + n = n*(n+1)/2 axiom.</p> <p>My desired output for an input_n &lt;= 10 (in this case : 5)</p> <pre><code>[0, 1, 2, 3, 4, 5] 0 + 1 + 2 + 3 + 4 + 5 = 15 5*(5+1)/2 = 15 </code></pre> <p>My desired output for an input_n > 10 (in this case : 999)</p> <pre><code>[0, 1, 2, 3, 4, 5, ... , 995 , 996, 997, 998, 999] 0 + 1 + 2 + 3 + 4 + 5 + ... + 995 + 996 + 997 + 998 + 999 = 499500 999*(999+1)/2 = 499500 </code></pre> <p>I thought I could use two range functions with a " + ... + " string between them in a print statement. But what I'm typing must be nonsensical since I get a syntax error :</p> <pre><code>SyntaxError: Generator expression must be parenthesized if not sole argument </code></pre> <p>What does that error mean ? I get that the expression in question must be parenthesized. I tried to correct the error with my beginner's logic but my attempts failed. </p> <p>Here's my code :</p> <pre><code>input_n = int(input("Choisissez un nombre : ")) input_list = list() for i in range(0,input_n+1): input_list.append(i) if input_n &lt;= 10: print ("+".join(str(i) for i in input_list) + " = ", sum(input_list)) print (str(input_n)+'*'+'('+str(input_n)+'+1)/2 = ', int(input_n*(input_n+1)/2)) elif input_n &gt; 10: print("+".join(str(i) for i in range(5)) + " + ... +" + "+".join(str(i) for i in range(input_n-5,input_n+1), sum(input_list))) print (str(input_n)+'*'+'('+str(input_n)+'+1)/2 = ', int(input_n*(input_n+1)/2)) </code></pre> <hr> <p>For noobs, like me : I already got answers for previous encountered problems in this <a href="http://stackoverflow.com/questions/38595362/join-items-of-a-list-with-sign-in-a-string">topic</a>, you should definetly check the answers given.</p>
0
2016-07-29T12:44:54Z
38,659,315
<p>The traceback is showing you this:</p> <blockquote> <pre><code>....join(str(i) for i in range(input_n-5,input_n+1), sum(input_list))) </code></pre> </blockquote> <p>What is written here makes no sense. Revise it until it does.</p>
3
2016-07-29T12:48:14Z
[ "python", "list", "range" ]
.join() elements of a user generated list using range in Python
38,659,238
<p>In my program user enters a number (input_n) that will go through :<br> 0+1+2+ ... + n = n*(n+1)/2 axiom.</p> <p>My desired output for an input_n &lt;= 10 (in this case : 5)</p> <pre><code>[0, 1, 2, 3, 4, 5] 0 + 1 + 2 + 3 + 4 + 5 = 15 5*(5+1)/2 = 15 </code></pre> <p>My desired output for an input_n > 10 (in this case : 999)</p> <pre><code>[0, 1, 2, 3, 4, 5, ... , 995 , 996, 997, 998, 999] 0 + 1 + 2 + 3 + 4 + 5 + ... + 995 + 996 + 997 + 998 + 999 = 499500 999*(999+1)/2 = 499500 </code></pre> <p>I thought I could use two range functions with a " + ... + " string between them in a print statement. But what I'm typing must be nonsensical since I get a syntax error :</p> <pre><code>SyntaxError: Generator expression must be parenthesized if not sole argument </code></pre> <p>What does that error mean ? I get that the expression in question must be parenthesized. I tried to correct the error with my beginner's logic but my attempts failed. </p> <p>Here's my code :</p> <pre><code>input_n = int(input("Choisissez un nombre : ")) input_list = list() for i in range(0,input_n+1): input_list.append(i) if input_n &lt;= 10: print ("+".join(str(i) for i in input_list) + " = ", sum(input_list)) print (str(input_n)+'*'+'('+str(input_n)+'+1)/2 = ', int(input_n*(input_n+1)/2)) elif input_n &gt; 10: print("+".join(str(i) for i in range(5)) + " + ... +" + "+".join(str(i) for i in range(input_n-5,input_n+1), sum(input_list))) print (str(input_n)+'*'+'('+str(input_n)+'+1)/2 = ', int(input_n*(input_n+1)/2)) </code></pre> <hr> <p>For noobs, like me : I already got answers for previous encountered problems in this <a href="http://stackoverflow.com/questions/38595362/join-items-of-a-list-with-sign-in-a-string">topic</a>, you should definetly check the answers given.</p>
0
2016-07-29T12:44:54Z
38,659,469
<p>You forgot to close the bracket of the <code>join</code> built-in method, so I guess this is what you want:</p> <pre><code>&gt;&gt;&gt; input_list = list(range(21)) &gt;&gt;&gt; &gt;&gt;&gt; input_n = 20 &gt;&gt;&gt; print("+".join(str(i) for i in range(5)) + " + ... +" + "+".join(str(i) for i in range(input_n-5,input_n+1)) + ' = ', sum(input_list)) 0+1+2+3+4 + ... +15+16+17+18+19+20 = 210 </code></pre>
1
2016-07-29T12:55:35Z
[ "python", "list", "range" ]
Explode list of lists into separate lists python
38,659,375
<p>I currently have a list of lists like </p> <pre><code>L = [['E2', 'C1', 'A1', 'B1', 'C2'], ['C1', 'D1', 'A1'], ['C1', 'C2']] </code></pre> <p>My aim is to compare L[i] against L[i+1] to make groups. For example, L[2] is a subset of L[0] so I would eliminate it. My two different list will be L[0] and L[1].</p> <p>For this, if I can somehow explode the list of list into different list, it will be easily achievable by iterating <code>cmp(L[i], L[i+1])</code>. By different list I mean, I will store each element as separate variable. => L_1 = L[0], L_2 = L[1] and L_3 = L[2].</p> <p>zip only seems to do a kind of map between two lists. Can anyone suggest a function available?</p>
0
2016-07-29T12:51:40Z
38,659,798
<p>You could map your list of list to create a list of sets. if you then iterate over that list, it would be possible to check if they are subsets of each other</p> <pre class="lang-python prettyprint-override"><code>LSets = map(set, L) filteredL = filter(lambda s: not any(s.issubset(s2) for s2 in LSets if s != s2), LSets) </code></pre>
0
2016-07-29T13:11:07Z
[ "python", "list", "python-2.7", "split" ]
How do I get a Python distribution URL?
38,659,408
<p>In their setup.py Python packages provides some information. This information can then be found in the PKG_INFO file of the egg.</p> <p>How can I access them once I have installed the package?</p> <p>For instance, if I have the following module:</p> <pre><code>setup(name='myproject', version='1.2.0.dev0', description='Demo of a setup.py file.', long_description=README + "\n\n" + CHANGELOG + "\n\n" + CONTRIBUTORS, license='Apache License (2.0)', classifiers=[ "Programming Language :: Python", "Programming Language :: Python :: 2", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.4", "Programming Language :: Python :: 3.5", "Programming Language :: Python :: Implementation :: CPython", "Programming Language :: Python :: Implementation :: PyPy", "Topic :: Internet :: WWW/HTTP", "Topic :: Internet :: WWW/HTTP :: WSGI :: Application", "License :: OSI Approved :: Apache Software License" ], keywords="web sync json storage services", url='https://github.com/Kinto/kinto') </code></pre> <p>How can I use Python to get back the information provided in the setup.py?</p> <p>I was thinking of something similar to that:</p> <pre><code>import pkg_resource url = pkg_resource.get_distribution(__package__).url </code></pre> <p>Any idea?</p>
0
2016-07-29T12:52:43Z
38,659,619
<p>There is apparently a private API that let you do that with <code>pkg_resources</code>:</p> <pre><code>import pkg_resources d = pkg_resources.get_distribution(__package__) metadata = d._get_metadata(d.PKG_INFO) home_page = [m for m in metadata if m.startswith('Home-page:')] url = home_page[0].split(':', 1)[1].strip() </code></pre> <p>I wish we could do better.</p>
0
2016-07-29T13:02:09Z
[ "python", "setuptools", "pkg-resources" ]
Python: How to remove a comment line and write on the same file?
38,659,425
<p>I've a list of commented file where I need to remove the comment lines in that files(#) and need to write on that same file.</p> <p><strong>comment file:</strong></p> <pre><code>#Hi this the comment define host { use template host_name google_linux address 192.168.0.12 } #commented config #ddefine host { #d use template1 #d host_name fb_linux #d address 192.168.0.13 #d} </code></pre> <p>The code I wrote to remove the comment line in a file ?</p> <p><strong>code:</strong></p> <pre><code>&gt;&gt;&gt; with open('commentfile.txt','r+') as file: ... for line in file: ... if not line.strip().startswith('#'): ... print line, ... file.write(line) ... define host { use template host_name google_linux address 192.168.0.12 } &gt;&gt;&gt; with open('commentfile.txt','r+') as file: ... for line in file: ... if line.strip().startswith('#'): ... continue ... print line, ... file.write(line) ... define host { use template host_name google_linux address 192.168.0.12 } </code></pre> <p>I tried using the above two methods the print output returns correct but could not able to write on the same file again.</p> <p><strong>Output in file:</strong></p> <pre><code>cat commentfile.txt #Hi this the comment define host { use template host_name google_linux address 192.168.0.12 } #commented config #ddefine host { #d use template1 #d host_name fb_linux #d address 192.168.0.13 #d} </code></pre> <p><strong>Expected Output:</strong></p> <pre><code> cat commentfile.txt define host { use template host_name google_linux address 192.168.0.12 } </code></pre> <p>I've even tried Regular expression method but didn't work to write on the same file.</p> <p><strong>RE method:</strong></p> <pre><code>for line in file: m = re.match(r'^([^#]*)#(.*)$', line) if m: continue </code></pre> <p>Any hint would be helpful ?</p>
0
2016-07-29T12:53:33Z
38,659,546
<p>I don't think you can write lines to a file that you are looping over, you'll need to write out to a different file, which you can move over the original file after the loop. </p> <p>Or, you can read all lines into memory, close and reopen the file and write over the lines with the newly processed lines </p>
0
2016-07-29T12:58:43Z
[ "python" ]
Python: How to remove a comment line and write on the same file?
38,659,425
<p>I've a list of commented file where I need to remove the comment lines in that files(#) and need to write on that same file.</p> <p><strong>comment file:</strong></p> <pre><code>#Hi this the comment define host { use template host_name google_linux address 192.168.0.12 } #commented config #ddefine host { #d use template1 #d host_name fb_linux #d address 192.168.0.13 #d} </code></pre> <p>The code I wrote to remove the comment line in a file ?</p> <p><strong>code:</strong></p> <pre><code>&gt;&gt;&gt; with open('commentfile.txt','r+') as file: ... for line in file: ... if not line.strip().startswith('#'): ... print line, ... file.write(line) ... define host { use template host_name google_linux address 192.168.0.12 } &gt;&gt;&gt; with open('commentfile.txt','r+') as file: ... for line in file: ... if line.strip().startswith('#'): ... continue ... print line, ... file.write(line) ... define host { use template host_name google_linux address 192.168.0.12 } </code></pre> <p>I tried using the above two methods the print output returns correct but could not able to write on the same file again.</p> <p><strong>Output in file:</strong></p> <pre><code>cat commentfile.txt #Hi this the comment define host { use template host_name google_linux address 192.168.0.12 } #commented config #ddefine host { #d use template1 #d host_name fb_linux #d address 192.168.0.13 #d} </code></pre> <p><strong>Expected Output:</strong></p> <pre><code> cat commentfile.txt define host { use template host_name google_linux address 192.168.0.12 } </code></pre> <p>I've even tried Regular expression method but didn't work to write on the same file.</p> <p><strong>RE method:</strong></p> <pre><code>for line in file: m = re.match(r'^([^#]*)#(.*)$', line) if m: continue </code></pre> <p>Any hint would be helpful ?</p>
0
2016-07-29T12:53:33Z
38,660,015
<p>Some pseudocode</p> <p>open file in read open a new file in write mode call it temp loop through and do some operation (delete comments, add what ever you need to add) and write to the temp file close the original file and delete it then rename your temp file to your old file so it would be like </p> <pre><code>fileVar = open(file, 'r') tempFile = open(file, 'w') for line in file: # do your operations #you could write at the same time tempFile.write(linePostOperations) fileVar.close() os.remove(filePath) tempFile.close() os.rename(tempFileName, newFileName) </code></pre>
0
2016-07-29T13:21:59Z
[ "python" ]
Dictionary of pair in python
38,659,513
<p>I am new to python and was trying to make a <code>dict of pairs</code> in python. What I would have done in <code>c++</code> is</p> <pre><code>dist[make_pair(a,b)]=1 </code></pre> <p>I am not sure how I can do the same in python</p> <p><strong>Edit</strong> What I basically want to do is to map a pair of two integers to some value- for example-</p> <pre><code>(1,2) -&gt; 1 (1,3) -&gt; 2 (2,1) -&gt;3 </code></pre> <p>I want to map pairs to some integer value</p>
1
2016-07-29T12:57:31Z
38,659,609
<p>You can use the data structure "tuple" as a key in the dictionary. If you want to define a function that returns a n-tuple given n inputs, you can do that also.</p> <pre><code>a = 4 b = 5 dict_example = dict() dict_example[(a,b)] = 1 print dict_example[(a,b)] </code></pre> <p>This prints the value of key (a,b), which is 1</p>
4
2016-07-29T13:01:47Z
[ "python" ]
Dictionary of pair in python
38,659,513
<p>I am new to python and was trying to make a <code>dict of pairs</code> in python. What I would have done in <code>c++</code> is</p> <pre><code>dist[make_pair(a,b)]=1 </code></pre> <p>I am not sure how I can do the same in python</p> <p><strong>Edit</strong> What I basically want to do is to map a pair of two integers to some value- for example-</p> <pre><code>(1,2) -&gt; 1 (1,3) -&gt; 2 (2,1) -&gt;3 </code></pre> <p>I want to map pairs to some integer value</p>
1
2016-07-29T12:57:31Z
38,659,641
<p>To create an element having the tuple (a,b) as key, and 1 as a value, you just have to do :</p> <pre><code>new_dict = {(a,b) : 1} </code></pre> <p>If such a dict already exist, and you want to add the pair a,b as a key and 1 as a value, you have to do :</p> <pre><code>existing_dict[(a,b)] = 1 </code></pre> <p>You can also use <code>existing_dict[a,b] = 1</code> as Duncan pointed out.</p>
2
2016-07-29T13:03:04Z
[ "python" ]
Dictionary of pair in python
38,659,513
<p>I am new to python and was trying to make a <code>dict of pairs</code> in python. What I would have done in <code>c++</code> is</p> <pre><code>dist[make_pair(a,b)]=1 </code></pre> <p>I am not sure how I can do the same in python</p> <p><strong>Edit</strong> What I basically want to do is to map a pair of two integers to some value- for example-</p> <pre><code>(1,2) -&gt; 1 (1,3) -&gt; 2 (2,1) -&gt;3 </code></pre> <p>I want to map pairs to some integer value</p>
1
2016-07-29T12:57:31Z
38,660,098
<p>I guess you tried using an array as a dict key, like:</p> <pre><code>&gt;&gt;&gt; d = {} &gt;&gt;&gt; pair = [0, 1] &gt;&gt;&gt; d[pair] = 'foo' TypeError: unhashable type: 'list' </code></pre> <p>Ok, what is that? Python dict keys must not be mutable. They can be numbers, strings and other hashable types - you can't use mutable types like lists, dicts and other mutable collections.</p> <p>There is a collection that is very like a list but is not mutable: the tuple.</p> <pre><code>&gt;&gt;&gt; d[tuple(pair)] = 'foo' &gt;&gt;&gt; d {(1, 2): 'foo'} </code></pre> <p>As you can see, the literal for a tuple is <code>(v1, v2, ..., vN)</code>. In places where it is not ambiguous, you can even omit the parenthesis:</p> <pre><code>&gt;&gt;&gt; pair = 0, 1 &gt;&gt;&gt; pair (0, 1) </code></pre> <p>More than once I was bit by this when I left a trailing comma while refactoring code:</p> <pre><code>&gt;&gt;&gt; x = 1, # I meant x = 1 &gt;&gt;&gt; x (1,) </code></pre> <p>That is the literal for a tuple with just 1 element.</p>
1
2016-07-29T13:26:08Z
[ "python" ]
IPython 5.0 and key bindings in console
38,659,721
<p>The new release of IPython does not depend any more on <code>readline</code> but uses the pure Python library <code>prompt-toolkit</code>, solving maintenance problems on Apple's and Windows' systems.</p> <p>A new feature is the ability to edit a multi-line code block, using the cursor keys to move freely in the code block — with this power it comes, at least for me, a problem: because a <kbd>ret</kbd> inserts a new line in your code, to pass the whole block to the interpreter you have to use the shortcut <kbd>alt</kbd>+<kbd>ret</kbd> or possibly the less convenient key sequence <kbd>esc</kbd> followed by <kbd>ret</kbd>.</p> <p>I say, this is a problem, because my terminal emulator of choice is the XTerm and, on many Linux distributions, the shortcut <kbd>alt</kbd>+<kbd>ret</kbd> is not passed to the application but it is directly used by the XTerm in which IPython is running, to toggle the screen-fullness of the said terminal (@ThomasDickey, xterm's mantainer and co-author pointed out that, by default, xterm doesn't care to send to the application the modifier bit on Enter even when one unbinds the Fullscreen action).</p> <p>For this reason I'd like to modify at least this specific IPython key binding.</p> <p>I've found instructions (sort of) for the previouos versions, the <code>readline</code> based ones, of IPython that do not apply to the new, 5.0 version.</p> <p>What I would need are instructions that lead me to find, in IPython's user documentation, the names of the possible actions that I can bind, the names of the shortcuts to bind with the actions and the procedure to follow to configure a new key binding.</p> <p>Failing to have this type of canonical answer, I <em>may</em> be happy with a recipe to accomplish this specific keybinding, with the condition that the recipe still works in IPython 6.0</p>
17
2016-07-29T13:07:07Z
39,015,985
<p>The <kbd>ctrl</kbd>+<kbd>j</kbd> or <kbd>ctrl</kbd>+<kbd>m</kbd> keyboard shortcuts are validating the entry.</p>
2
2016-08-18T10:35:20Z
[ "python", "ipython", "keyboard-shortcuts", "xterm" ]
IPython 5.0 and key bindings in console
38,659,721
<p>The new release of IPython does not depend any more on <code>readline</code> but uses the pure Python library <code>prompt-toolkit</code>, solving maintenance problems on Apple's and Windows' systems.</p> <p>A new feature is the ability to edit a multi-line code block, using the cursor keys to move freely in the code block — with this power it comes, at least for me, a problem: because a <kbd>ret</kbd> inserts a new line in your code, to pass the whole block to the interpreter you have to use the shortcut <kbd>alt</kbd>+<kbd>ret</kbd> or possibly the less convenient key sequence <kbd>esc</kbd> followed by <kbd>ret</kbd>.</p> <p>I say, this is a problem, because my terminal emulator of choice is the XTerm and, on many Linux distributions, the shortcut <kbd>alt</kbd>+<kbd>ret</kbd> is not passed to the application but it is directly used by the XTerm in which IPython is running, to toggle the screen-fullness of the said terminal (@ThomasDickey, xterm's mantainer and co-author pointed out that, by default, xterm doesn't care to send to the application the modifier bit on Enter even when one unbinds the Fullscreen action).</p> <p>For this reason I'd like to modify at least this specific IPython key binding.</p> <p>I've found instructions (sort of) for the previouos versions, the <code>readline</code> based ones, of IPython that do not apply to the new, 5.0 version.</p> <p>What I would need are instructions that lead me to find, in IPython's user documentation, the names of the possible actions that I can bind, the names of the shortcuts to bind with the actions and the procedure to follow to configure a new key binding.</p> <p>Failing to have this type of canonical answer, I <em>may</em> be happy with a recipe to accomplish this specific keybinding, with the condition that the recipe still works in IPython 6.0</p>
17
2016-07-29T13:07:07Z
39,029,256
<p>You could change xterm's configuration.</p> <p>xterm is configurable (and documented). In the xterm manual, the <a href="http://invisible-island.net/xterm/manpage/xterm.html#h3-Default-Key-Bindings" rel="nofollow"><em>Default Key Bindings</em></a> section shows the default binding for this key:</p> <pre><code> Alt &lt;Key&gt;Return:fullscreen() \n\ </code></pre> <p>You can <em>suppress</em> that binding in more than one way:</p> <ul> <li>using the <strong><code>omitTranslation</code></strong> resource to suppress the feature</li> <li>setting the <strong><code>fullscreen</code></strong> resource to <strong><code>never</code></strong></li> </ul> <p>However, just suppressing it will not make it send something interesting (xterm ignores the modifier for <kbd>Enter</kbd>). Setting a <strong><code>translation</code></strong> resource works, e.g., in your <code>$HOME/.Xdefaults</code> file:</p> <pre><code>*VT100*translations: #override \n\ Alt &lt;Key&gt;Return: string("\033[27;3;13~") </code></pre>
4
2016-08-19T00:02:18Z
[ "python", "ipython", "keyboard-shortcuts", "xterm" ]
IPython 5.0 and key bindings in console
38,659,721
<p>The new release of IPython does not depend any more on <code>readline</code> but uses the pure Python library <code>prompt-toolkit</code>, solving maintenance problems on Apple's and Windows' systems.</p> <p>A new feature is the ability to edit a multi-line code block, using the cursor keys to move freely in the code block — with this power it comes, at least for me, a problem: because a <kbd>ret</kbd> inserts a new line in your code, to pass the whole block to the interpreter you have to use the shortcut <kbd>alt</kbd>+<kbd>ret</kbd> or possibly the less convenient key sequence <kbd>esc</kbd> followed by <kbd>ret</kbd>.</p> <p>I say, this is a problem, because my terminal emulator of choice is the XTerm and, on many Linux distributions, the shortcut <kbd>alt</kbd>+<kbd>ret</kbd> is not passed to the application but it is directly used by the XTerm in which IPython is running, to toggle the screen-fullness of the said terminal (@ThomasDickey, xterm's mantainer and co-author pointed out that, by default, xterm doesn't care to send to the application the modifier bit on Enter even when one unbinds the Fullscreen action).</p> <p>For this reason I'd like to modify at least this specific IPython key binding.</p> <p>I've found instructions (sort of) for the previouos versions, the <code>readline</code> based ones, of IPython that do not apply to the new, 5.0 version.</p> <p>What I would need are instructions that lead me to find, in IPython's user documentation, the names of the possible actions that I can bind, the names of the shortcuts to bind with the actions and the procedure to follow to configure a new key binding.</p> <p>Failing to have this type of canonical answer, I <em>may</em> be happy with a recipe to accomplish this specific keybinding, with the condition that the recipe still works in IPython 6.0</p>
17
2016-07-29T13:07:07Z
39,154,587
<p>Modifying keyboard shortcuts in configuration when using prompt_toolkit is not (yet) possible; though it is pretty easy if you install IPython from source. If you look at the file <code>IPython/terminal/shortcuts.py</code> you will see that it contains the various logic; in particular you will find:</p> <pre><code># Ctrl+J == Enter, seemingly registry.add_binding(Keys.ControlJ, filter=(HasFocus(DEFAULT_BUFFER) &amp; ~HasSelection() &amp; insert_mode ))(newline_or_execute_outer(shell)) </code></pre> <p>This bind CtrlJ (enter) to the function <code>newline_or_execute_outer</code> which is responsible for adding new lines; it's define later in the file. In particular if you press enter twice at the end of a block of code, it should execute the block without the need to use any other shortcuts.</p> <p>Strip the logic that adds new lines:</p> <pre><code>def execute_outer(shell): def execute(event): """When the user presses return, insert a newline or execute the code.""" b = event.current_buffer # some logic to also dismiss the completer b.accept_action.validate_and_handle(event.cli, b) return execute </code></pre> <p>Bind it around line 20-something:</p> <pre><code>registry.add_binding(Keys.ControlE, filter=(HasFocus(DEFAULT_BUFFER) &amp; ~HasSelection() &amp; insert_mode ))(execute_outer(shell)) </code></pre> <p>And enjoy. If you are unhappy with the documentation we welcome help; For example, taking the gist of the answers there and contributing them back. It is a bit hurtful to read harsh comments when we do say in release notes:</p> <pre><code>New terminal interface The overhaul of the terminal interface will probably cause a range of minor issues for existing users. This is inevitable for such a significant change, and we’ve done our best to minimise these issues. Some changes that we’re aware of, with suggestions on how to handle them: IPython no longer uses readline configuration (~/.inputrc). We hope that the functionality you want (e.g. vi input mode) will be available by configuring IPython directly (see Terminal IPython options). If something’s missing, please file an issue. ... </code></pre> <p>Helping actually improving IPython to have configurable keybinding with actions name is also appreciated, so then you will be able to answer your own question.</p>
0
2016-08-25T20:55:58Z
[ "python", "ipython", "keyboard-shortcuts", "xterm" ]
place values by condition with numpy
38,659,742
<p>I have a three channel matrix and I want to place the value which is less than 27</p> <pre><code>a=numpy.arange(27).reshape(3,3,3) a[a&lt;27]=0 </code></pre> <p>However, If I want to replace only on first channel, the way I can do is to write a for loop</p> <pre><code>for i in range(3): for j in range(3): if a[i][j][0] &lt; 27: a[i][j][0]=0 </code></pre> <p>I am not sure how to do this with a more simple way.</p> <p>thank you</p>
0
2016-07-29T13:08:08Z
38,659,823
<p>You can try with:</p> <pre><code>a=numpy.arange(27).reshape(3,3,3) a[a[:,:,0]&lt;27, 0]=0 </code></pre>
2
2016-07-29T13:12:07Z
[ "python", "numpy" ]
place values by condition with numpy
38,659,742
<p>I have a three channel matrix and I want to place the value which is less than 27</p> <pre><code>a=numpy.arange(27).reshape(3,3,3) a[a&lt;27]=0 </code></pre> <p>However, If I want to replace only on first channel, the way I can do is to write a for loop</p> <pre><code>for i in range(3): for j in range(3): if a[i][j][0] &lt; 27: a[i][j][0]=0 </code></pre> <p>I am not sure how to do this with a more simple way.</p> <p>thank you</p>
0
2016-07-29T13:08:08Z
38,659,861
<p>I think, you were looking for this: <code>a[:,:,0][a[:,:,0]&lt;27]=0</code></p>
1
2016-07-29T13:14:07Z
[ "python", "numpy" ]
Factorial code not working
38,659,842
<p>Don't know what's wrong, code is giving 12 instead of 24</p> <pre><code>def factorial(x): m=x-1 while m&gt;0: t=x*m m-=1 return t else: return 1 print factorial(4) </code></pre>
-6
2016-07-29T13:13:09Z
38,660,008
<p>your code return value at first iteration and you assign new value to t every iteration </p> <pre><code>def factorial(x): ... t = 1 ... while x&gt;0: ... t *= x ... x-=1 ... ... return t print factorial(4) output: 24 </code></pre> <p>----or----</p> <pre><code>from operator import mul def factorial(x): return reduce(mul, range(1,x+1)) print factorial(4) output: 24 </code></pre>
1
2016-07-29T13:21:18Z
[ "python" ]
Make undirected graph from adjacency list
38,659,961
<p>I'm trying to make an undirected graph from an adjacency list to practice the Karger's Min Cut algorithm. The following is my code</p> <pre><code>class Vertex(object): '''Represents a vertex, with the indices of edges incident on it''' def __init__(self,name,edgeIndices=[]): self.name = name self.edgeIndices = edgeIndices def getName(self): return self.name def addEdge(self,ind): self.edgeIndices.append(ind) def getEdges(self): return self.edgeIndices def __eq__(self,other): return self.name == other.name class Edge(object): '''Represents an edge with the indices of its endpoints''' def __init__(self,ends): self.ends = ends def getEnds(self): return self.ends def __eq__(self,other): return (self.ends == other.ends)\ or ((self.ends[1],self.ends[0]) == other.ends) class Graph(object): def __init__(self,vertices,edges): self.edges = edges self.vertices = vertices def createGraph(filename): '''Input: Adjacency list Output: Graph object''' vertices = [] edges = [] with open(filename) as f: for line in f: elements = line.split() newVert = Vertex(elements[0]) if newVert not in vertices: vertices.append(newVert) for verts in elements[1:]: otherVert = Vertex(verts) if otherVert not in vertices: vertices.append(otherVert) end1 = vertices.index(newVert) end2 = vertices.index(otherVert) newEdge = Edge((end1,end2)) if newEdge not in edges: edges.append(newEdge) newVert.addEdge(edges.index(newEdge)) return Graph(vertices,edges) </code></pre> <p>Suppose the adjacency list is as follows with vertices represented by integers</p> <pre><code>1 -&gt; 2,3,4 2 -&gt; 1,3 3 -&gt; 1,2,4 4 -&gt; 1,3 </code></pre> <p>In total, this graph will have five edges, so the length of list holding indices of edges a vertex is associated with can't more than 5 long.</p> <p>For instance, I expect the vertex '2' to have indices of just two edges, i.e. edges with vertices 1 and 3. Instead, what I get is <code>[0, 1, 2, 3, 0, 2, 1, 3]</code>. I need help to figure out what is going wrong.</p>
0
2016-07-29T13:18:59Z
38,661,626
<p>First error comes from the Vertex init. When passing a list as default argument, Python instantiates it once, and share this instance with all future instances of Vertex. Pass None, and use a local list if no list is given.</p> <pre><code>class Vertex(object): def __init__(self,name,edgeIndices=None): self.name = name self.edgeIndices = edgeIndices if edgeIndices else [] </code></pre> <p>In the createGraph method, when the vertex already exists in the graph you need to use it. See the added <code>else: newVert = ...</code> You also seem to have an issue with the ligne splitting. See the iteration over <code>elements[2].split(',')</code>.</p> <pre><code>def createGraph(filename): '''Input: Adjacency list Output: Graph object''' vertices = [] edges = [] with open(filename) as f: for line in f: elements = line.split() newVert = Vertex(elements[0]) if newVert not in vertices: vertices.append(newVert) else: newVert = vertices[vertices.index(newVert)] for verts in elements[2].split(','): otherVert = Vertex(verts) if otherVert not in vertices: vertices.append(otherVert) end1 = vertices.index(newVert) end2 = vertices.index(otherVert) newEdge = Edge((end1,end2)) if newEdge not in edges: edges.append(newEdge) newVert.addEdge(edges.index(newEdge)) return Graph(vertices,edges) </code></pre> <p>As a side note, I would try to use a dict to store the vertices (and edges) and do the lookup. <code>List.index</code> is used a lot, and you may create a lot of objects for nothing.</p>
0
2016-07-29T14:44:07Z
[ "python", "graph", "undirected-graph" ]
Make undirected graph from adjacency list
38,659,961
<p>I'm trying to make an undirected graph from an adjacency list to practice the Karger's Min Cut algorithm. The following is my code</p> <pre><code>class Vertex(object): '''Represents a vertex, with the indices of edges incident on it''' def __init__(self,name,edgeIndices=[]): self.name = name self.edgeIndices = edgeIndices def getName(self): return self.name def addEdge(self,ind): self.edgeIndices.append(ind) def getEdges(self): return self.edgeIndices def __eq__(self,other): return self.name == other.name class Edge(object): '''Represents an edge with the indices of its endpoints''' def __init__(self,ends): self.ends = ends def getEnds(self): return self.ends def __eq__(self,other): return (self.ends == other.ends)\ or ((self.ends[1],self.ends[0]) == other.ends) class Graph(object): def __init__(self,vertices,edges): self.edges = edges self.vertices = vertices def createGraph(filename): '''Input: Adjacency list Output: Graph object''' vertices = [] edges = [] with open(filename) as f: for line in f: elements = line.split() newVert = Vertex(elements[0]) if newVert not in vertices: vertices.append(newVert) for verts in elements[1:]: otherVert = Vertex(verts) if otherVert not in vertices: vertices.append(otherVert) end1 = vertices.index(newVert) end2 = vertices.index(otherVert) newEdge = Edge((end1,end2)) if newEdge not in edges: edges.append(newEdge) newVert.addEdge(edges.index(newEdge)) return Graph(vertices,edges) </code></pre> <p>Suppose the adjacency list is as follows with vertices represented by integers</p> <pre><code>1 -&gt; 2,3,4 2 -&gt; 1,3 3 -&gt; 1,2,4 4 -&gt; 1,3 </code></pre> <p>In total, this graph will have five edges, so the length of list holding indices of edges a vertex is associated with can't more than 5 long.</p> <p>For instance, I expect the vertex '2' to have indices of just two edges, i.e. edges with vertices 1 and 3. Instead, what I get is <code>[0, 1, 2, 3, 0, 2, 1, 3]</code>. I need help to figure out what is going wrong.</p>
0
2016-07-29T13:18:59Z
38,664,193
<p>I would recommend to take a look at Dict, OrderedDict, Linked List based graph implementations. The are far more effective then based on lists and indexes. To make you code work you can do the following:</p> <p>Change a Vertex to avoid issue described in previous answer:</p> <pre><code>class Vertex(object): def __init__(self,name, edgeIndices=None): self.name = name self.edgeIndices = edgeIndices or [] </code></pre> <p>Let the graph do some work:</p> <pre><code>class Graph(object): def __init__(self): self.edges = [] self.vertices = [] def add_vertex(self, name): vertex = Vertex(name) if vertex not in self.vertices: self.vertices.append(vertex) def add_edge(self, *names): self._add_vertices(names) edge = self._add_edge(names) self._update_vertices_links(edge, names) def get_vertex_index(self, name): vertex = Vertex(name) return self.vertices.index(vertex) def get_vertex(self, name): return self.vertices[self.get_vertex_index(name)] def _update_vertices_links(self, edge, names): for name in names: vertex = self.get_vertex(name) vertex.addEdge(self.edges.index(edge)) def _add_edge(self, names): edge = Edge((self.get_vertex_index(names[0]), self.get_vertex_index(names[1]))) if edge not in self.edges: self.edges.append(edge) return edge def _add_vertices(self, names): for name in names: self.add_vertex(name) def __repr__(self): return "Vertices: %s\nEdges: %s" % (self.vertices, self.edges) </code></pre> <p>Create Graph:</p> <pre><code>def createGraph(filename): with open(filename) as f: graph = Graph() for line in f: elements = line.strip().split() graph.add_vertex(elements[0]) for element in elements[2].split(","): graph.add_edge(elements[0], element) return graph </code></pre> <p>Run it:</p> <pre><code>graph = createGraph('input.txt') print graph </code></pre> <p>Output for your input:</p> <pre><code>Vertices: [&lt;Name:1 Edges:[0, 1, 2]&gt;, &lt;Name:2 Edges:[0, 3]&gt;, &lt;Name:3 Edges:[1, 3, 4]&gt;, &lt;Name:4 Edges:[2, 4]&gt;] Edges: [(0, 1), (0, 2), (0, 3), (1, 2), (2, 3)] </code></pre>
0
2016-07-29T17:13:53Z
[ "python", "graph", "undirected-graph" ]
save() got an unexpected keyword argument
38,660,128
<p>Calling LocationDescription.l_edit returns error "save() got an unexpected keyword argument 'location'". Keyword name looks random though and may point to different fields at different times. The method l_edit was stripped of functionality, but the error persists. Curiously, self.location = kwargs['location'] followed by self.save() works just fine.</p> <p>models.py</p> <pre><code>class LocationDescription(models.Model): location = models.ForeignKey(Location) description = models.ForeignKey(Localization) YEAR_CHOICES = ( (LocationDescriptionYear.any.value, 'Any'), (LocationDescriptionYear.winter.value, 'Winter'), (LocationDescriptionYear.spring.value, 'Spring'), (LocationDescriptionYear.summer.value, 'Summer'), (LocationDescriptionYear.autumn.value, 'Autumn'), ) year = models.IntegerField(choices=YEAR_CHOICES, default=0) DAY_CHOICES = ( (LocationDescriptionDaytime.any.value, 'Any'), (LocationDescriptionDaytime.night.value, 'Night'), (LocationDescriptionDaytime.morning.value, 'Morning'), (LocationDescriptionDaytime.day.value, 'Day'), (LocationDescriptionDaytime.evening.value, 'Evening'), ) day = models.IntegerField(choices=DAY_CHOICES, default=0) weather_type = models.ForeignKey('Weather', blank=True, null=True) order = models.IntegerField(default=0) code_check = models.TextField(blank=True, null=True) @classmethod def l_create(cls, request, **kwargs): l = Localization() l.write(request, kwargs['description']) kwargs['description'] = l item = cls(**kwargs) item.save() return item def l_delete(self): l = self.description self.delete() l.delete() def l_edit(self, **kwargs): super(LocationDescription, self).save(**kwargs) @classmethod def localize(cls, locale, **kwargs): if locale == 'eng': result = cls.objects.filter(**kwargs).annotate(text=F('description__eng')) elif locale == 'rus': result = cls.objects.filter(**kwargs).annotate(text=F('description__rus')) else: raise KeyError for r in result: if r.text is None or r.text == '': setattr(r, 'text', 'Error: localization text missing!') return result </code></pre> <p>views.py</p> <pre><code> location = Location.objects.get(pk=int(request.POST.get('location', ''))) weather_type = Weather.objects.get(pk=int(request.POST.get('weather_type', ''))) item = LocationDescription.objects.get(pk=int(request.POST.get('id', ''))) item.l_edit(location=location, year=request.POST.get('year', ''), day=request.POST.get('day', ''), weather_type=weather_type, order=request.POST.get('order', ''), code_check=request.POST.get('code_check', ''), ) </code></pre>
1
2016-07-29T13:27:10Z
38,660,288
<p><code>save</code> does not require those named arguments you're passing. Besides, since you're not overriding the default <code>save</code> method I don't see the need for <code>super</code>.</p> <p>You can simply set those attributes on that instance of your model and call <code>save</code> like would with a model object:</p> <pre><code>def l_edit(self, **kwargs): for k in kwargs: setattr(self, k, kwargs[k]) self.save() </code></pre> <p>On a side note, using <a href="https://docs.djangoproject.com/en/1.9/ref/models/querysets/#update" rel="nofollow"><code>update</code></a> is more efficient than your current approach if you don't need to have the <code>item</code> in memory.</p>
2
2016-07-29T13:35:26Z
[ "python", "django" ]
python __new__ - how to implement when not subclassing
38,660,148
<p><strong>Part A</strong></p> <p>I want to do some checking on arguments to a class instantiation and possibly return <code>None</code> if it doesn't make sense to even create the object.</p> <p>I've read the docs but I don't understand <strong>what to return</strong> in this case.</p> <pre><code>class MyClass: def __new__(cls, Param): if Param == 5: return None else: # What should 'X' be? return X </code></pre> <p>What should <code>X</code> be in <code>return X</code>?<br/></p> <ul> <li>It cannot be <code>self</code> because the object doesn't exist yet so <code>self</code> is not a valid keyword in this context.</li> </ul> <p><strong>Part B</strong></p> <p>Tied to my question, I don't understand the <strong>need</strong> to have the <code>cls</code> parameter.</p> <p>If you call the constructor of <code>MyClass</code> - <code>var = MyClass(1)</code> - won't <code>cls</code> always be <code>MyClass</code>?<br/> How could it be anything else?</p> <p>According to the docs, <code>cls</code> in <code>object.__new__(cls[, ...])</code> is:</p> <blockquote> <p><a href="https://docs.python.org/3/reference/datamodel.html#object.__new__" rel="nofollow">. . .the class of which an instance was requested as its first argument.</a></p> </blockquote>
1
2016-07-29T13:27:53Z
38,660,327
<p>(I'm assuming you are using Python 3 because you provided a link to Python 3 docs)</p> <p><code>X</code> could be <code>super().__new__(cls)</code>.</p> <p><code>super()</code> returns the parent class (in this case it is simply <code>object</code>). Most of the times when you are overriding methods you will need to call the parent class's method at some point.</p> <p>See this example:</p> <pre><code>class MyClass: def __new__(cls, param): if param == 5: return None else: return super().__new__(cls) def __init__(self, param): self.param = param </code></pre> <p>And then:</p> <pre><code>a = MyClass(1) print(a) print(a.param) &gt;&gt; &lt;__main__.MyClass object at 0x00000000038964A8&gt; 1 b = MyClass(5) print(b) print(b.param) &gt;&gt; None Traceback (most recent call last): File "main.py", line 37, in &lt;module&gt; print(b.param) AttributeError: 'NoneType' object has no attribute 'param' </code></pre>
0
2016-07-29T13:37:20Z
[ "python" ]
python __new__ - how to implement when not subclassing
38,660,148
<p><strong>Part A</strong></p> <p>I want to do some checking on arguments to a class instantiation and possibly return <code>None</code> if it doesn't make sense to even create the object.</p> <p>I've read the docs but I don't understand <strong>what to return</strong> in this case.</p> <pre><code>class MyClass: def __new__(cls, Param): if Param == 5: return None else: # What should 'X' be? return X </code></pre> <p>What should <code>X</code> be in <code>return X</code>?<br/></p> <ul> <li>It cannot be <code>self</code> because the object doesn't exist yet so <code>self</code> is not a valid keyword in this context.</li> </ul> <p><strong>Part B</strong></p> <p>Tied to my question, I don't understand the <strong>need</strong> to have the <code>cls</code> parameter.</p> <p>If you call the constructor of <code>MyClass</code> - <code>var = MyClass(1)</code> - won't <code>cls</code> always be <code>MyClass</code>?<br/> How could it be anything else?</p> <p>According to the docs, <code>cls</code> in <code>object.__new__(cls[, ...])</code> is:</p> <blockquote> <p><a href="https://docs.python.org/3/reference/datamodel.html#object.__new__" rel="nofollow">. . .the class of which an instance was requested as its first argument.</a></p> </blockquote>
1
2016-07-29T13:27:53Z
38,660,455
<p>You could just return the instance of cls like this <code>return object.__ new__(cls)</code>. Because every class is subclass of <code>object</code>, you can use that as a object creator for your class. The returnes object is passed as a first argument to the <code>__init__()</code> with the any number of positional argument or any number of keyword argument you passed to new. There you will create instance variable assigning those values.</p>
0
2016-07-29T13:43:50Z
[ "python" ]
Keep Columns When Aggregating an Empty DataFrame
38,660,332
<p>I'm working in pandas 0.18.0 on python 2.7.9.</p> <p>Take a sample <code>DataFrame</code> and group by a few columns, then sum over a different column for the result, like this:</p> <pre><code>&gt;&gt;&gt; df = pandas.DataFrame([[1,2,3],[4,5,6],[1,2,9]], columns=['a','b','c']) &gt;&gt;&gt; print df a b c 0 1 2 3 1 4 5 6 2 1 2 9 &gt;&gt;&gt; df.groupby(['a','b'], as_index=False)['c'].sum() a b c 0 1 2 12 1 4 5 6 </code></pre> <p>That all looks great, but when the same operation is preformed on an empty <code>DataFrame</code> the columns are dropped from the result:</p> <pre><code>&gt;&gt;&gt; empty = pandas.DataFrame(columns=['a','b','c']) &gt;&gt;&gt; print empty Empty DataFrame Columns: [a, b, c] Index: [] &gt;&gt;&gt; empty.groupby(['a','b'], as_index=False)['c'].sum() Empty DataFrame Columns: [] Index: [] </code></pre> <p>Were someone to reference valid columns from the result later in the code, a key error would result. Is there a way to keep the columns?</p>
2
2016-07-29T13:37:25Z
38,661,437
<p>I believe this is a standard result of groupby.sum() (see here <a href="http://pandas.pydata.org/pandas-docs/stable/missing_data.html" rel="nofollow">http://pandas.pydata.org/pandas-docs/stable/missing_data.html</a>).</p> <p>The only way I can think would be to write an if statement checking if the dataframe is empty, e.g.:</p> <pre><code>if sum(empty.isnull().sum()) == 9: print "empty dataframe" elif sum(empty.isnull().sum()) &lt; 9: empty.groupby(['a','b'], as_index=False)['c'].sum() </code></pre> <p>This should keep your empty dataframe with column headers. Hope this helps.</p>
1
2016-07-29T14:33:28Z
[ "python", "pandas", "group-by" ]
Rearranging numbers from list in python3
38,660,437
<p>Lets say I have an list of numbers </p> <p>a = [ 1,2,3,4,5,6,7,8,9,10]</p> <p>and I want to print the output as </p> <pre><code>1 2 3 4 5 6 7 8 9 10 </code></pre> <p>How can I do it in python3.</p> <p><strong><em>My attempt:</em></strong></p> <pre><code>a = [1,2,3,4,5,6,7,8,9,10] for i in a: print(a[i]," ") i=i+1 </code></pre> <p>I'm getting <code>IndexError: list index out of range</code> and also I don't know to print 1 element in 1'st row , 2nd and 3rd in second row and so on.</p>
-3
2016-07-29T13:42:35Z
38,661,254
<p>One way to do this in Python 3 is to use <a href="https://docs.python.org/3/library/itertools.html#itertools.islice" rel="nofollow"><code>islice</code></a> on an <a href="https://docs.python.org/3/library/functions.html#iter" rel="nofollow"><code>iterator</code></a> :</p> <pre><code>from itertools import islice a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] it = iter(a) print('\n'.join([' '.join([str(u)for u in islice(it, i)])for i in range(1,5)])) </code></pre> <p><strong>output</strong></p> <pre><code>1 2 3 4 5 6 7 8 9 10 </code></pre>
3
2016-07-29T14:25:25Z
[ "python", "list", "python-3.x" ]
Uploading files to S3 bucket - Python Django
38,660,525
<p>I want to put a string (which is an xml response) into a file and then upload it to a amazon s3 bucket. Following is my function in Python3</p> <pre><code>def excess_data(user, resume): res_data = BytesIO(bytes(resume, "UTF-8")) file_name = 'name_of_file/{}_resume.xml'.format(user.id) s3 = S3Storage(bucket="Name of bucket", endpoint='s3-us-west-2.amazonaws.com') response = s3.save(file_name, res_data) url = s3.url(file_name) print(url) print(response) return get_bytes_from_url(url) </code></pre> <p>However, when I run this script I keep getting the error - <code>AttributeError: Unable to determine the file's size.</code> Any idea how to resolve this?</p> <p>Thanks in advance!</p>
1
2016-07-29T13:47:10Z
38,660,786
<p>I am using <a href="https://django-storages.readthedocs.io/en/latest/backends/amazon-S3.html" rel="nofollow">s3boto</a> (requires python-boto) in my Django projects to connect with S3. </p> <p>Using boto is easy to do what you want to do:</p> <pre><code>&gt;&gt;&gt; from boto.s3.key import Key &gt;&gt;&gt; k = Key(bucket) &gt;&gt;&gt; k.key = 'foobar' &gt;&gt;&gt; k.set_contents_from_string('This is a test of S3') </code></pre> <p>See this <a href="http://boto.cloudhackers.com/en/latest/s3_tut.html" rel="nofollow">documentation</a> the section Storing Data.</p> <p>I hope that it helps with your problem. </p>
2
2016-07-29T14:00:46Z
[ "python", "django", "amazon-web-services", "amazon-s3" ]
Putting gif image in tkinter window
38,660,528
<p>I'm trying to insert a gif image in a new tkinter window when a button is clicked but I keep getting this error</p> <pre><code>Exception in Tkinter callback Traceback (most recent call last): File "C:\Users\Afro\AppData\Local\Programs\Python\Python35\lib\idlelib\run.py", line 119, in main seq, request = rpc.request_queue.get(block=True, timeout=0.05) File "C:\Users\Afro\AppData\Local\Programs\Python\Python35\lib\queue.py", line 172, in get raise Empty queue.Empty During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\Afro\AppData\Local\Programs\Python\Python35\lib\tkinter\__init__.py", line 1549, in __call__ return self.func(*args) File "C:/Users/Afro/Desktop/mff.py", line 8, in sex canvas = tkinter.Label(wind,image = photo) File "C:\Users\Afro\AppData\Local\Programs\Python\Python35\lib\tkinter\__init__.py", line 2605, in __init__ Widget.__init__(self, master, 'label', cnf, kw) File "C:\Users\Afro\AppData\Local\Programs\Python\Python35\lib\tkinter\__init__.py", line 2138, in __init__ (widgetName, self._w) + extra + self._options(cnf)) _tkinter.TclError: image "pyimage1" doesn't exist </code></pre> <p>Here's the code. The image and the location actually exists.</p> <pre><code>import tkinter def six(): wind = tkinter.Tk() photo = tkinter.PhotoImage(file = 'American-Crime-Story-1.gif') self = photo canvas = tkinter.Label(wind,image = photo) canvas.grid(row = 0, column = 0) def base(): ssw = tkinter.Tk() la = tkinter.Button(ssw,text = 'yes',command=six) la.grid() base() </code></pre> <p>What am I doing wrong?</p>
2
2016-07-29T13:47:19Z
38,660,769
<p>You are trying to create two instances of <code>Tk</code> window. You <em>can't</em> do that. If you want second window or pop-up window you should use <a href="http://effbot.org/tkinterbook/toplevel.htm" rel="nofollow">Toplevel()</a> widget.</p> <p>Also, <code>self</code> doesn't mean anything in this context. Using the widget's image property would be better <a href="http://effbot.org/pyfaq/why-do-my-tkinter-images-not-appear.htm" rel="nofollow">to keep a reference</a>.</p> <pre><code>import tkinter ssw = tkinter.Tk() def six(): toplvl = tkinter.Toplevel() #created Toplevel widger photo = tkinter.PhotoImage(file = 'American-Crime-Story-1.gif') lbl = tkinter.Label(toplvl ,image = photo) lbl.image = photo #keeping a reference in this line lbl.grid(row=0, column=0) def base(): la = tkinter.Button(ssw,text = 'yes',command=six) la.grid(row=0, column=0) #specifying row and column values is much better base() ssw.mainloop() </code></pre>
2
2016-07-29T13:59:37Z
[ "python", "python-3.x", "tkinter" ]
Executing root-required script from non-root user
38,660,561
<p>I'm using the Apache CGI mod to allow execution of python scripts via HTTP(S) request. The problem is that the script I want to be executed, <strong>backup.py</strong>, at one point executes a subprocess call where a <strong>mysqldump</strong> command is being piped into <strong>sudo -i</strong>. The problem is that the CGI "user", <strong>www-data</strong>, doesn't have root access, and I certainly don't want to give it that in general, just for this specific task. How can I allow <strong>www-data</strong> to perform only a <strong>mysqldump</strong> command only under <strong>sudo -i</strong>?</p>
1
2016-07-29T13:48:53Z
38,660,731
<p>One way of elevating the permissions for a specific script, is to use the sudoers file.</p> <p>Create a file containing the script you wan't to execute with root permissions, lets say at <code>/path/to/script.sh</code>.</p> <p>Then, edit the <code>sudoers</code> file with <code>sudo visudo</code>, and add the following line:</p> <pre><code>www-data ALL = (root) NOPASSWD: /path/to/script.sh </code></pre> <p>where the the usernames and the path are set as appropriate.</p>
2
2016-07-29T13:57:49Z
[ "python", "bash", "cgi", "sudo", "sudoers" ]
When/How does an anonymous file object close?
38,660,609
<p>In the comments of <a href="http://stackoverflow.com/questions/38234224/learning-python-the-hard-way-ex-17-i-got-the-one-liner-but?">this question</a> about a python one-liner, it occurred to me I have no idea how python handles anonymous file objects. From the question:</p> <pre><code>open(to_file, 'w').write(open(from_file).read()) </code></pre> <p>There are two calls to <code>open</code> without using the <code>with</code> keyword (which is usually how I handle files). I have, in the past, used this kind of unnamed file. IIRC, it seemed there was a leftover OS-level lock on the file that would expire after a minute or two.</p> <p>So what happens to these file handles? Are they cleaned up by garbage collection? By the OS? What happens to the Python machine and file when <code>close()</code> is called, and will it all happen anyway when the script finishes and some time passes?</p>
4
2016-07-29T13:51:43Z
38,660,804
<p>The files will get closed after the garbage collector collects them, CPython will collect them immediately because it uses reference counting, but this is not a guaranteed behavior.</p> <p>If you use files without closing them in a loop you might run out of file descriptors, that's why it's recommended to use the with statement (if you're using 2.5 you can use <code>from __future__ import with_statement</code>).</p>
1
2016-07-29T14:01:47Z
[ "python", "file", "filesystems" ]
When/How does an anonymous file object close?
38,660,609
<p>In the comments of <a href="http://stackoverflow.com/questions/38234224/learning-python-the-hard-way-ex-17-i-got-the-one-liner-but?">this question</a> about a python one-liner, it occurred to me I have no idea how python handles anonymous file objects. From the question:</p> <pre><code>open(to_file, 'w').write(open(from_file).read()) </code></pre> <p>There are two calls to <code>open</code> without using the <code>with</code> keyword (which is usually how I handle files). I have, in the past, used this kind of unnamed file. IIRC, it seemed there was a leftover OS-level lock on the file that would expire after a minute or two.</p> <p>So what happens to these file handles? Are they cleaned up by garbage collection? By the OS? What happens to the Python machine and file when <code>close()</code> is called, and will it all happen anyway when the script finishes and some time passes?</p>
4
2016-07-29T13:51:43Z
38,660,881
<p>Monitoring the file descriptor on Linux (by checking /proc/$$/fds) and the File Handle on Windows (using SysInternals tools) it appears that the file is closed immediately after the statement.</p> <p>This cannot be guarenteed however, since the garbage collector has to execute. In the testing I have done it does get closed at once every time.</p> <p>The <code>with</code> statement is recommended to be used with <code>open</code>, however the occasions when it is actually needed are rare. It is difficult to demonstrate a scenario where you <em>must</em> use <code>with</code>, but it is probably a good idea to be safe. </p> <p>So your one-liner becomes:</p> <pre><code>with open(to_file, 'w') as tof, open(from_file) as fof: tof.write(fof.read()) </code></pre> <p>The advantage of <code>with</code> is that the special method (in the io class) called <code>__exit__()</code> is guaranteed* to be called.</p> <p>* Unless you do something like <code>os._exit()</code>.</p>
4
2016-07-29T14:05:55Z
[ "python", "file", "filesystems" ]
How to run a script as a File in Java?
38,660,690
<p>I have a Python script which is a resource in my project. Along with the script is an XML file that the script needs in order to run properly. I am reading in both files as an InputStream and then creating temp files for both:</p> <pre><code>InputStream is = (this.getClass().getClassLoader().getResourceAsStream("InterWebApp.py")); File script = File.createTempFile("script", ".py"); Files.copy(is, script.toPath(), StandardCopyOption.REPLACE_EXISTING); InputStream is1 = (this.getClass().getClassLoader().getResourceAsStream("setup.xml")); File xml = File.createTempFile("config", ".xml"); Files.copy(is1, xml.toPath(), StandardCopyOption.REPLACE_EXISTING); </code></pre> <p>However, I am not sure how to launch the script as a process:</p> <pre><code>Process p = Runtime.getRuntime().exec("." + script.getAbsolutePath()); p.waitFor(); </code></pre> <p>The above code throws an IOException. How do I run <code>script.py</code> and ensure it has access to <code>config.xml</code>? Right now the Python script just parses the XML file using the absolute path, but this path would not be the same for the temp file.</p>
0
2016-07-29T13:55:53Z
38,660,845
<p>Basically, you're asking yourself for trouble since you ask it for the absolute path, but then prefix it with ".", which is generally a <em>relative path</em> modifier. Try <code>.exec(script.getAbsolutePath())</code> for starters. Also, depending on your operating system and/or configuration, <code>.py</code> files might or might not be recognized as executable (for example, on Unix systems only files with an executable flag will be recognized as executable). You might actually want to find the location of the Python executable and pass the script as a parameter.</p>
1
2016-07-29T14:04:21Z
[ "java", "python", "maven" ]
Copy whitespace from string to string in Python
38,660,812
<p>I want to copy whitespace like spaces and tabs from string to string in Python 2. For example if I have a string with 3 spaces at first and one tab at the end like " Hi\t" I want to copy those whitespace to another string for example string like "hello" would become " hello\t" Is that possible to do easily?</p>
0
2016-07-29T14:02:18Z
38,660,996
<p>Yes, this is of course possible. I would use <a href="https://docs.python.org/2/library/re.html" rel="nofollow">regex</a> for that.</p> <pre><code>import re hi = " Hi\t" hello = "hello" spaces = re.match(r"^(\s*).+?(\s*)$", hi) if spaces: left, right = spaces.groups() string = "{}{}{}".format(left, hello, right) print(string) # Out: " hello\t" </code></pre>
1
2016-07-29T14:12:00Z
[ "python", "string", "python-2.7", "whitespace" ]
Python Threading/Thread Implementation
38,660,815
<p>I have been trying to make my first attempt at a threaded script. Its going to eventually be a web scraper that hopefully works a little faster then the original linear scraping script I previously made.</p> <p>After hours of reading and playing with some example code. Im still not sure what is considered correct as far as an implementation goes.</p> <p>Currently I have the following code that I have been playing with:</p> <pre><code>from Queue import Queue import threading def scrape(queue): global workers print worker.getName() print queue.get() queue.task_done() workers -= 1 queue = Queue(maxsize=0) threads = 10 workers = 0 with open('test.txt') as in_file: for line in in_file: queue.put(line) while not (queue.empty()): if (threads != workers): worker = threading.Thread(target=scrape, args=(queue,)) worker.setDaemon(True) worker.start() workers += 1 </code></pre> <p>The idea is that I have a list of URLs in the test.txt file. I open the file and put all of the URLs in the queue. From there I get 10 threads running that pull from the queue and scrape a webpage, or in this example simply print out the line that was pulled.</p> <p>Once the function is done I remove a 'worker thread' and then a new one replaces it until the queue is empty.</p> <p>In my real world implementation at some point I will have to take the data from my function scrapes and write it to a .csv file. But, right now Im just trying to understand how to implement the threads correctly. </p> <p>I have seen similar examples like the above that use 'Thread'...and I have also seen 'threading' examples that utilize an inherited class. I'd just like to know what I should be using and the proper way to manage it.</p> <p>Go easy on me here, Im just an beginner trying to understand threads....and yes I know it can get very complicated. However, I think this should be easy enough for a first try...</p>
2
2016-07-29T14:02:25Z
38,661,233
<p>On Python 2.x <a href="https://docs.python.org/2/library/multiprocessing.html#module-multiprocessing.dummy" rel="nofollow">multiprocessing.dummy</a> (which uses threads) is a good choice as it is easy to use (also possible in Python 3.x)</p> <p>If you find out scraping is CPU-limited and you have multiple CPU cores, this way you can quite simply switch to real <a href="https://docs.python.org/2/library/multiprocessing.html" rel="nofollow">multiprocessing</a> possibly gaining a big speedup.</p> <p>(Python often does not profit from multiple CPUs with threading as much as with multiple processes because of a <a href="https://docs.python.org/3/glossary.html#term-global-interpreter-lock" rel="nofollow">performance optimization</a> - you have to find out yourself what is faster in your case)</p> <p>With mutliprocessing.dummy you could do</p> <pre><code>from multiprocessing.dummy import Pool # from multiprocessing import Pool # if you want to use more cpus def scrape(url): data = {"sorted": sorted(url)} # normally you would do something more interesting return (url, data) urls=[] threads = 10 if __name__=="__main__": with open('test.txt') as in_file: urls.extend(in_file) # lines p=Pool(threads) results=list(p.imap_unordered(scrape,urls)) p.close() print results # normally you would process your results here </code></pre> <p>On Python 3.x, <a href="https://docs.python.org/3/library/concurrent.futures.html" rel="nofollow">concurrent.futures</a> might be a better choice.</p>
2
2016-07-29T14:24:12Z
[ "python", "multithreading" ]
pandas read_csv raises ValueError
38,660,900
<p>I want to read txt data seperated by ',' and '\t', and I use code below: </p> <p><code>io_df = pd.read_csv('input_output.txt',sep='\D|\t',engine = 'python')</code></p> <p>This triggered error information below:</p> <p><code>--------------------------------------------------------------------------- ValueError Traceback (most recent call last) &lt;ipython-input-38-5ab0138d93ac&gt; in &lt;module&gt;() ----&gt; 1 io_df = pd.read_csv('input_output.txt',sep='\D|\t',engine = 'python')</code></p> <p>How to solve this?</p>
0
2016-07-29T14:06:46Z
38,660,990
<p>For me works <code>sep=",|\t"</code>:</p> <pre><code>pd.read_csv('test.csv', sep=",|\t", engine = 'python') </code></pre> <p>Sample:</p> <pre><code>import pandas as pd df = pd.read_csv('https://dl.dropboxusercontent.com/u/84444599/test.csv', sep=",|\t", engine = 'python') print (df) col col1 col2 0 a d t 1 d u l </code></pre>
0
2016-07-29T14:11:34Z
[ "python", "pandas" ]
Python __new__ - how can cls be different than class that __new__ is in
38,661,030
<p><a href="https://docs.python.org/3/reference/datamodel.html#object.__new__" rel="nofollow">Documentation for <code>object.__new__(cls[, ...])</code> says:</a></p> <blockquote> <p>Called to create a new instance of class <code>cls</code>. __ <code>new</code> __ is a static method (special-cased so you need not declare it as such) that takes the class of which an instance was requested as its first argument.</p> </blockquote> <p>So if you have <code>var = MyClass()</code> and</p> <pre><code>class MyClass: def __new__(cls): ... </code></pre> <p>Won't <code>cls</code> ALWAYS be equal to <code>MyClass</code> ?</p>
1
2016-07-29T14:13:32Z
38,661,152
<p>Try this:</p> <pre><code>class MyClass: def __new__(cls): print(cls) class Yac(MyClass): pass x = Yac() print(x) </code></pre> <p>We get:</p> <pre><code>&lt;class '__main__.Yac'&gt; None </code></pre> <p>By the way, this is fine in Python 3, but will not work in Python 2. In Python 2 <code>__new__</code> is only supported in "new-style" classes:</p> <pre><code>class MyClass(object): </code></pre> <p>In Python 3 all classes are "new-style".</p>
2
2016-07-29T14:20:31Z
[ "python" ]
Proper way to use weak references in Python
38,661,039
<p>I have two classes Parent and Child. At any point in time, there will only be one Parent but there can be multiple Child objects. The Parent will need to keep reference to the Child objects in a dictionary indexed by the Child name. The Child also needs a reference to the Parent since it can call one of the Parent's functions.</p> <p>I know that I should use weakref here. I have two ways of doing this:</p> <p><strong>Method One</strong></p> <pre><code>class Child(): def __init__( self, parent, name ): self.parent_ = weakref.proxy( parent ) self.name_ = name class Parent(): def __init__( self ): self.children = {} def createChild( self, name ): self.children[ name ] = Child( self, name ) </code></pre> <p><strong>Method Two</strong></p> <pre><code>class Child(): def __init__( self, parent, name ): self.parent_ = parent self.name_ = name class Parent(): def __init__( self ): self.children = {} def createChild( self, name ): self.children[ name ] = Child( weakref.proxy( self ), name ) </code></pre> <ol> <li>Is there difference b/w Method One and Method Two?</li> <li>What is the best way to achieve this functionality?</li> </ol> <p><strong>Edit</strong>: When the Parent dies, Children should also die. I don't want any Child object to exist if the Parent doesn't exist.</p>
0
2016-07-29T14:13:55Z
38,661,345
<p>Do you really need weak references here? If you used your method one with just </p> <pre><code>self.parent = parent </code></pre> <p>you would achieve what you intend to do. A weak reference to parent would allow the parent object to be destroyed if it isn't referenced anywhere strongly anymore, but in this case children would be unable to call parent's functions as the object wouldn't exist.</p> <p>Methods 1 and 2 look the same to me. </p> <p>R</p>
0
2016-07-29T14:29:33Z
[ "python", "weak-references" ]
Proper way to use weak references in Python
38,661,039
<p>I have two classes Parent and Child. At any point in time, there will only be one Parent but there can be multiple Child objects. The Parent will need to keep reference to the Child objects in a dictionary indexed by the Child name. The Child also needs a reference to the Parent since it can call one of the Parent's functions.</p> <p>I know that I should use weakref here. I have two ways of doing this:</p> <p><strong>Method One</strong></p> <pre><code>class Child(): def __init__( self, parent, name ): self.parent_ = weakref.proxy( parent ) self.name_ = name class Parent(): def __init__( self ): self.children = {} def createChild( self, name ): self.children[ name ] = Child( self, name ) </code></pre> <p><strong>Method Two</strong></p> <pre><code>class Child(): def __init__( self, parent, name ): self.parent_ = parent self.name_ = name class Parent(): def __init__( self ): self.children = {} def createChild( self, name ): self.children[ name ] = Child( weakref.proxy( self ), name ) </code></pre> <ol> <li>Is there difference b/w Method One and Method Two?</li> <li>What is the best way to achieve this functionality?</li> </ol> <p><strong>Edit</strong>: When the Parent dies, Children should also die. I don't want any Child object to exist if the Parent doesn't exist.</p>
0
2016-07-29T14:13:55Z
38,661,377
<p>Your two approaches are equivalent, they evaluate to the exact same result.</p> <p>Weak references are used, when you want referred objects to be garbage collected even though your (<em>weak</em>) references do still exist. In your case, your <code>Parent</code> has regular references to your <code>Child</code> instances, but the children only hold weak references to their common parent. This means, that -- in certain cases -- the parent would be garbage collected even though there are still children that might want to use it.</p> <p>I think, you can just use a regular, strong reference here.</p>
0
2016-07-29T14:31:00Z
[ "python", "weak-references" ]
Proper way to use weak references in Python
38,661,039
<p>I have two classes Parent and Child. At any point in time, there will only be one Parent but there can be multiple Child objects. The Parent will need to keep reference to the Child objects in a dictionary indexed by the Child name. The Child also needs a reference to the Parent since it can call one of the Parent's functions.</p> <p>I know that I should use weakref here. I have two ways of doing this:</p> <p><strong>Method One</strong></p> <pre><code>class Child(): def __init__( self, parent, name ): self.parent_ = weakref.proxy( parent ) self.name_ = name class Parent(): def __init__( self ): self.children = {} def createChild( self, name ): self.children[ name ] = Child( self, name ) </code></pre> <p><strong>Method Two</strong></p> <pre><code>class Child(): def __init__( self, parent, name ): self.parent_ = parent self.name_ = name class Parent(): def __init__( self ): self.children = {} def createChild( self, name ): self.children[ name ] = Child( weakref.proxy( self ), name ) </code></pre> <ol> <li>Is there difference b/w Method One and Method Two?</li> <li>What is the best way to achieve this functionality?</li> </ol> <p><strong>Edit</strong>: When the Parent dies, Children should also die. I don't want any Child object to exist if the Parent doesn't exist.</p>
0
2016-07-29T14:13:55Z
38,662,122
<p>In answer to your questions:</p> <ol> <li>Methods 1 and 2 are equivalent.</li> <li>In general, there is no need to call <code>weakref.proxy()</code> directly. In this case you can use a <a href="https://docs.python.org/2/library/weakref.html#weakref.WeakValueDictionary" rel="nofollow" title="WeakValueDictionary">WeakValueDictionary</a>, which is a:</li> </ol> <blockquote> <p>Mapping class that references values weakly. Entries in the dictionary will be discarded when no strong reference to the value exists any more.</p> </blockquote> <p>I think you want this outside of the parent class (since you want it to still be around if the parent is deleted), with keys identifying the children and values giving the parent. So you'd have something like this:</p> <pre><code>registry = weakref.WeakValueDictionary() class Child(): def __init__(self, parent, name): self.parent = parent self.name = name class Parent(): def __init__(self): pass def createChild(self, name): child = Child(self, name) registry[child] = self </code></pre> <p>As an aside, the names <code>Child</code> and <code>Parent</code> are a bit confusing here - by convention they imply that <code>Child</code> inherits from <code>Parent</code> (in which case you could just call the parent's method on the child directly and not need the "child" to know the parent's name). What you have here is a <strong>has-a</strong> relationship rather than an <strong>is-a</strong> relationship.</p>
0
2016-07-29T15:11:14Z
[ "python", "weak-references" ]
Splat operator in conjuction with function
38,661,053
<p>I have this program in python which prints the sum of numbers.I have used the splat operator(*). When i print the result i get the result as <strong>None</strong>? Can anyone correct this? I have tried many things like passing multiple arguments but it simply doesn't work.</p> <pre><code> def addition(*no): sum = 0 for n in no: sum=sum+n print addition(4) </code></pre>
0
2016-07-29T14:14:42Z
38,661,123
<p>You need to return your <code>sum</code> variable using a <code>return</code> statement:</p> <pre><code>def addition(*no): sum = 0 for n in no: sum=sum+n return sum print addition(4) </code></pre> <p>You're getting <code>None</code> because a function which never uses a <code>return</code> returns <code>None</code> in Python.</p> <p>Also note that, if you ever need to write a function which does this in a production environment, there's the <code>sum</code> function:</p> <pre><code>def addition(*no): return sum(no) </code></pre>
0
2016-07-29T14:18:46Z
[ "python" ]
Connection closes immediately on open
38,661,067
<p>I am running a very simple echo websocket server as below:</p> <pre><code>#!/usr/bin/python import datetime import tornado.httpserver import tornado.websocket import tornado.ioloop import tornado.web class WSHandler(tornado.websocket.WebSocketHandler): clients = [] def open(self): print('new connection') self.write_message("Hello World") WSHandler.clients.append(self) def on_message(self, message): print('message received %s' % message) self.write_message('ECHO: ' + message) def on_close(self): print('connection closed') WSHandler.clients.remove(self) @classmethod def write_to_clients(cls): print("Writing to clients") for client in cls.clients: client.write_message("Hi there!") def check_origin(self, origin): return True application = tornado.web.Application([ (r'/websocket', WSHandler), ]) if __name__ == "__main__": http_server = tornado.httpserver.HTTPServer(application) http_server.listen(80) tornado.ioloop.IOLoop.instance().start() </code></pre> <p>I am connecting to this with javascript as below</p> <pre><code>var ws = new WebSocket("ws://localhost:80/websocket"); </code></pre> <p>In the console I see </p> <pre><code>new connection connection closed </code></pre> <p>What I do not understand is why I am seeing the <code>connection closed</code> in the console. The client also indicates that the connection is closed but I do not see any good reason for this. Any help would be greatly appreciated. To replicate run the python code as admin, open any JS console and enter the JS code. My desired outcome is for the socket to not be immediately closed. This is somewhat based on what I read in the <a href="http://www.tornadoweb.org/en/stable/websocket.html" rel="nofollow">tornado docs</a>. </p> <hr> <p><strong>edit</strong> update by commenting out <code>self.write_message("Hello World")</code> in the <code>open</code> method, the connection does not close. However running the example code from the docs now yields something interesting.</p> <pre><code>var ws = new WebSocket("ws://localhost:80/websocket"); ws.onopen = function() { ws.send("Hello, world"); }; ws.onmessage = function (evt) { alert(evt.data); }; </code></pre> <p>server side output is</p> <pre><code>new connection message received Hello, world connection closed </code></pre> <p>There is no corresponding alert on the client side as expected</p> <p>The new question is the same as the old which is why does the server say <code>connection closed</code>? It looks like <code>self.write_message</code> may be the culprit. </p>
4
2016-07-29T14:15:35Z
38,662,232
<p>Not sure if this is helpful in any way, but I ran your code and it works exactly as you would expect it to work. I don't get the connection closed message as indicated in your question, until I call <code>ws.close()</code>. (tornado 4.4.1). </p> <p>Whatever the issue is, it seems to be in your environment, not your code. </p>
0
2016-07-29T15:16:48Z
[ "javascript", "python", "websocket", "tornado", "python-3.4" ]
lxml removes unwrapped text inside tag
38,661,087
<p>Here is my python code with lxml</p> <pre><code>import urllib.request from lxml import etree #import lxml.html as html from copy import deepcopy from lxml import etree from lxml import html some_xml_data = "&lt;span&gt;text1&lt;div&gt;ddd&lt;/div&gt;text2&lt;div&gt;ddd&lt;/div&gt;text3&lt;/span&gt;" root = etree.fromstring(some_xml_data) [c] = root.xpath('//span') print(etree.tostring(root)) #b'&lt;span&gt;text1&lt;div&gt;ddd&lt;/div&gt;text2&lt;div&gt;ddd&lt;/div&gt;text3&lt;/span&gt;' #output as expected #but if i do some changes for e in c.iterchildren("*"): if e.tag == 'div': e.getparent().remove(e) print(etree.tostring(root)) #b'&lt;span&gt;text1&lt;/span&gt;' text2 and text3 removed! how to prevent this deletion? </code></pre> <p>It looks like after I do some changes on lxml tree (delete some tags) lxml also remove some unwrapped text! how to prevent lxml doing this and save unwrpapped text?</p>
0
2016-07-29T14:16:52Z
38,661,479
<p>The text after <strong></strong> node is called <strong>tail</strong>, and they can be reserved by appending to parent's text, here is a sample:</p> <pre><code>In [1]: from lxml import html In [2]: s = "&lt;span&gt;text1&lt;div&gt;ddd&lt;/div&gt;text2&lt;div&gt;ddd&lt;/div&gt;text3&lt;/span&gt;" ...: In [3]: tree = html.fromstring(s) In [4]: for node in tree.iterchildren("div"): ...: if node.tail: ...: node.getparent().text += node.tail ...: node.getparent().remove(node) ...: In [5]: html.tostring(tree) Out[5]: b'&lt;span&gt;text1text2text3&lt;/span&gt;' </code></pre> <p>I use <code>html</code> as it's more likely the structure than xml. And you can simply <code>iterchildren</code> with <code>div</code> to avoid additional check for tag.</p>
1
2016-07-29T14:35:26Z
[ "python", "lxml" ]
Best way to store scraped data in Python for analysis
38,661,144
<p>I am scraping data of football player statistics from the web using python and Beautiful Soup. I will be scraping from multiple sources, and each source will have a variety of variables about each player which include strings, integers, and booleans. For example player name, position drafted, pro bowl pick (y/n).</p> <p>Eventually I would like to put this data into a data mining tool or an analysis tool in order to find trends. This will need to be searchable and I will need to be able to add data to a player's info when I am scraping from a new source in a different order.</p> <p>What techniques should I use to store the data so that I will best be able to add too it and the analyze it later?</p>
-1
2016-07-29T14:20:05Z
38,661,572
<p>Use a layered approach: downloading, parsing, storage, analysis.</p> <p>Separate the layers. Most importantly, don't just download data and then store it in the final parsed format. You will inevitably realise you missed something and need to scrape it all over again. Use something like <code>requests</code> + <code>requests_cache</code> (I found that extending <code>requests_cache.backends.BaseCache</code> and storing it on the filesystem is more convenient examining scraped html than the default sqlite storage backend).</p> <p>For parsing you're already using beautiful soup which works fine.</p> <p>For storage &amp; analysis use a database. Avoid the temptation to go with NoSQL -- as soon as you need to run aggregate queries you'll regret it.</p>
1
2016-07-29T14:41:02Z
[ "python", "database", "numpy", "web-scraping" ]
Succinct way to access a single value from a Pandas DataFrame by index
38,661,164
<p>Suppose I have a DataFrame generated like so:</p> <pre><code>import numpy as np import pandas as pd np.random.seed(seed=0) df = pd.DataFrame(index=list('AB'), columns=list('CD'), data=np.random.randn(2,2)) </code></pre> <p>which looks like</p> <pre><code> C D A 1.764052 0.400157 B 0.978738 2.240893 </code></pre> <p>and suppose I'd like to increase the value in row A, column C by 1. The way I've found to do this is:</p> <pre><code>df['C'][df.index.isin(['A'])] += 1 </code></pre> <p>The left hand side seems quite verbose; I was hoping there might be a shorter way to do this?</p>
2
2016-07-29T14:20:53Z
38,661,204
<p>You can use <code>.at</code> for accessing/setting scalars. Take a look at <a href="http://stackoverflow.com/questions/28757389/loc-vs-iloc-vs-ix-vs-at-vs-iat">this answer</a> for a comparison of them.</p> <pre><code>df Out: C D A 1.764052 0.400157 B 0.978738 2.240893 df.at['A', 'C'] += 1 df Out: C D A 2.764052 0.400157 B 0.978738 2.240893 </code></pre>
1
2016-07-29T14:22:27Z
[ "python", "pandas" ]
Succinct way to access a single value from a Pandas DataFrame by index
38,661,164
<p>Suppose I have a DataFrame generated like so:</p> <pre><code>import numpy as np import pandas as pd np.random.seed(seed=0) df = pd.DataFrame(index=list('AB'), columns=list('CD'), data=np.random.randn(2,2)) </code></pre> <p>which looks like</p> <pre><code> C D A 1.764052 0.400157 B 0.978738 2.240893 </code></pre> <p>and suppose I'd like to increase the value in row A, column C by 1. The way I've found to do this is:</p> <pre><code>df['C'][df.index.isin(['A'])] += 1 </code></pre> <p>The left hand side seems quite verbose; I was hoping there might be a shorter way to do this?</p>
2
2016-07-29T14:20:53Z
38,661,206
<p>You can use <code>loc</code> directly on the col:</p> <pre><code>In [298]: df['C'].loc['A'] += 1 df Out[298]: C D A 2.764052 0.400157 B 0.978738 2.240893 </code></pre> <p>or compound it by passing the row label as first arg on the df and select the col of interest after the comma:</p> <pre><code>In [300]: df.loc['A','C'] += 1 df Out[300]: C D A 2.764052 0.400157 B 0.978738 2.240893 </code></pre>
3
2016-07-29T14:22:29Z
[ "python", "pandas" ]
Succinct way to access a single value from a Pandas DataFrame by index
38,661,164
<p>Suppose I have a DataFrame generated like so:</p> <pre><code>import numpy as np import pandas as pd np.random.seed(seed=0) df = pd.DataFrame(index=list('AB'), columns=list('CD'), data=np.random.randn(2,2)) </code></pre> <p>which looks like</p> <pre><code> C D A 1.764052 0.400157 B 0.978738 2.240893 </code></pre> <p>and suppose I'd like to increase the value in row A, column C by 1. The way I've found to do this is:</p> <pre><code>df['C'][df.index.isin(['A'])] += 1 </code></pre> <p>The left hand side seems quite verbose; I was hoping there might be a shorter way to do this?</p>
2
2016-07-29T14:20:53Z
38,661,211
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.ix.html" rel="nofollow"><code>ix</code></a>:</p> <pre><code>np.random.seed(seed=0) df = pd.DataFrame(index=list('AB'), columns=list('CD'), data=np.random.randn(2,2)) df.ix['A','C'] += 1 print (df) C D A 2.764052 0.400157 B 0.978738 2.240893 </code></pre>
2
2016-07-29T14:22:47Z
[ "python", "pandas" ]
How to open folder and place text files in dataframe and rename dataframe based on file name?
38,661,182
<p>I am trying to open a folder which has multiple text files and put each file in its own dataframe and name each dataframe by the filename. </p> <p>My code so far is recognizing the 5 files in the folder but is not putting the data in the files into dataframes based on their file names. could someone show me how to do this? </p> <p>code: import os import pandas as pd import pypyodbc</p> <pre><code>loc = 'D:/filepath to folder with files' os.chdir(loc) filelist = os.listdir() #print (len((pd.concat([pd.read_csv(item, names=[item[:-4]]) for item in filelist],axis=1)))) data = [] path = loc files = [f for f in os.listdir(path) if os.path.isfile(f)] for f in files: with open(f,'r') as myfile: data.append(myfile.read()) df = pd.DataFrame(data) print (df.shape) </code></pre> <p>thank you in advance</p> <p>-edit- How the data in the files looks:</p> <pre><code>0010010000013 1 CITY OF HOUSTON 1.000 0010020000001 1 CURRENT OWNER 1.000 0010020000003 1 MILBY CHARLES FAMILY PTNSH 1.000 0010020000004 1 FEAGIN MICHAEL RYAN TRUST 1.000 0010020000013 1 BUFFALO BAYOU PARTNERSHIP 1.000 0010020000015 1 BUFFALO BAYOU PARTNERSHIP 1.000 0010020000016 1 USRP PAC LP SPAGHETTI WAREHOUSE 1.000 0010020000023 1 CITY OF HOUSTON 1.000 0010020000024 1 LUISA MILBY FEAGIN 2007 TRUST 1.000 0010030000001 1 BUFFALO BAYOU PARTNERSHIP 1.000 </code></pre> <p>-edit- Final answer</p> <pre><code>dfs = {os.path.basename(f): pd.read_csv(f, sep='\t', header=None,encoding='cp037',error_bad_lines=False) for f in glob.glob('D:/TX/Houston_County/Real_acct_owner/*.txt')} </code></pre>
1
2016-07-29T14:21:32Z
38,661,520
<p>Something like this should create a dict where each key (= filename) holds the dataframe with the respective file's contents.</p> <pre><code>filedfs = {} for f in files: filedfs[f] = pd.read_csv(os.path.join(loc, f)) </code></pre> <p>Or, as a one-liner as proposed by @MaxU:</p> <pre><code>dfs = {os.path.basename(f): pd.read_csv(f, delim_whitespace=True, header=None) for f in glob.glob('c:/data/*.csv')} </code></pre>
4
2016-07-29T14:37:21Z
[ "python", "pandas", "dataframe", "python-3.5" ]
How to open folder and place text files in dataframe and rename dataframe based on file name?
38,661,182
<p>I am trying to open a folder which has multiple text files and put each file in its own dataframe and name each dataframe by the filename. </p> <p>My code so far is recognizing the 5 files in the folder but is not putting the data in the files into dataframes based on their file names. could someone show me how to do this? </p> <p>code: import os import pandas as pd import pypyodbc</p> <pre><code>loc = 'D:/filepath to folder with files' os.chdir(loc) filelist = os.listdir() #print (len((pd.concat([pd.read_csv(item, names=[item[:-4]]) for item in filelist],axis=1)))) data = [] path = loc files = [f for f in os.listdir(path) if os.path.isfile(f)] for f in files: with open(f,'r') as myfile: data.append(myfile.read()) df = pd.DataFrame(data) print (df.shape) </code></pre> <p>thank you in advance</p> <p>-edit- How the data in the files looks:</p> <pre><code>0010010000013 1 CITY OF HOUSTON 1.000 0010020000001 1 CURRENT OWNER 1.000 0010020000003 1 MILBY CHARLES FAMILY PTNSH 1.000 0010020000004 1 FEAGIN MICHAEL RYAN TRUST 1.000 0010020000013 1 BUFFALO BAYOU PARTNERSHIP 1.000 0010020000015 1 BUFFALO BAYOU PARTNERSHIP 1.000 0010020000016 1 USRP PAC LP SPAGHETTI WAREHOUSE 1.000 0010020000023 1 CITY OF HOUSTON 1.000 0010020000024 1 LUISA MILBY FEAGIN 2007 TRUST 1.000 0010030000001 1 BUFFALO BAYOU PARTNERSHIP 1.000 </code></pre> <p>-edit- Final answer</p> <pre><code>dfs = {os.path.basename(f): pd.read_csv(f, sep='\t', header=None,encoding='cp037',error_bad_lines=False) for f in glob.glob('D:/TX/Houston_County/Real_acct_owner/*.txt')} </code></pre>
1
2016-07-29T14:21:32Z
38,661,619
<p><strong><em>input:</em></strong></p> <pre><code>0010010000013,1,CITY OF HOUSTON,1.000 0010020000001,1,CURRENT OWNER,1.000 </code></pre> <p><strong><em>code:</em></strong></p> <pre><code>import os import pandas loc = 'folder/' list_of_df = [] for f in os.listdir(loc): if f.endswith(".txt"): df = pandas.read_csv(loc+f, sep = ',', names = ['number', 'count', 'buyer', 'status']) list_of_df.append(df) for df in list_of_df: print df print '--' </code></pre>
0
2016-07-29T14:43:46Z
[ "python", "pandas", "dataframe", "python-3.5" ]
FileNotFoundError WinError 3
38,661,464
<p>I'm trying to learn how to edit files, but I'm a bit of a python novice, and not all that bright, so when I get a FileNotFoundError I can't figure out how to fix it despite several searches on the interwebz.</p> <pre><code>import os old = 'Users\My Name\Pictures\2013\182904_10201130467645938_341581100_n' new = 'Users\My Name\Pictures\2013\Death_Valley_1' os.rename(old, new) </code></pre>
-1
2016-07-29T14:34:54Z
38,661,671
<p><code>'Users\My Name\Pictures\2013\182904_10201130467645938_341581100_n'</code> is a relative path. </p> <p>Unless you are running your code from the directory that contains the <code>Users</code> dir (which if you are using Windows would most probably be the root <code>C:</code> dir), Python isn't going to find that file.</p> <p>You also have to make sure to include the file extension if it has any.</p> <p>There are few ways to solve this, the easiest one will be to use the absolute paths in your code, ie <code>'C:\Users\My Name\Pictures\2013\182904_10201130467645938_341581100_n.jpg'</code>.</p> <p>You will also want to use <code>r</code> before the paths, so you want need to escape every <code>\</code> character.</p> <pre><code>import os old = r'C:\Users\My Name\Pictures\2013\182904_10201130467645938_341581100_n.jpg' new = r'C:\Users\My Name\Pictures\2013\Death_Valley_1.jpg' os.rename(old, new) </code></pre> <p>This of course assumes your drive letter is <code>C</code>.</p>
1
2016-07-29T14:46:55Z
[ "python", "windows-7", "rename" ]
Some anomaly in printing result for list
38,661,490
<p>Hi I have two list snip and phras. I tried to run them in for loop in two different ways. I was expecting them to give the same output but they are giving different. How so ?</p> <pre><code>snip = ['Hi john', 'Hi sam', 'Hi lila'] phras = ['lets play','lets paint'] for s in snip,phras: result = s[:] print result # output is ['lets play', 'lets paint'] # Now lets run again snip = ['Hi john', 'Hi sam', 'Hi lila'] phras = ['lets play','lets paint'] for s in snip,phras: result = s[:] print result #output is ['Hi john', 'Hi sam', 'Hi lila'] # ['lets play','lets paint'] </code></pre>
-5
2016-07-29T14:35:47Z
38,661,532
<p>Your print statement is outside of your first loop so it only shows the last value assigned to <code>result</code> whereas the second print statement is inside of the loop and therefore prints <em>each</em> value of <code>result</code></p>
5
2016-07-29T14:38:01Z
[ "python", "python-2.7" ]
how to predict binary outcome with categorical and continuous features using scikit-learn?
38,661,631
<p>I need advice choosing a model and machine learning algorithm for a classification problem. </p> <p>I'm trying to predict a binary outcome for a subject. I have 500,000 records in my data set and 20 continuous and categorical features. Each subject has 10--20 records. The data is labeled with its outcome.</p> <p>So far I'm thinking logistic regression model and kernel approximation, based on the cheat-sheet <a href="http://scikit-learn.org/stable/tutorial/machine_learning_map/" rel="nofollow">here</a>. </p> <p>I am unsure where to start when implementing this in either R or Python.</p> <p>Thanks!</p>
1
2016-07-29T14:44:28Z
38,666,799
<p>Choosing an algorithm and optimizing the parameter is a difficult task in any data mining project. Because it must customized for your data and problem. Try different algorithm like SVM,Random Forest, Logistic Regression, KNN and... and test Cross Validation for each of them and then compare them. You can use <a href="http://scikit-learn.org/stable/modules/grid_search.html" rel="nofollow">GridSearch in sickit learn</a> to try different parameters and optimize the parameters for each algorithm. also try <a href="https://github.com/rsteca/sklearn-deap" rel="nofollow">this project</a> witch test a range of parameters with genetic algorithm</p>
0
2016-07-29T20:13:37Z
[ "python", "machine-learning" ]
how to predict binary outcome with categorical and continuous features using scikit-learn?
38,661,631
<p>I need advice choosing a model and machine learning algorithm for a classification problem. </p> <p>I'm trying to predict a binary outcome for a subject. I have 500,000 records in my data set and 20 continuous and categorical features. Each subject has 10--20 records. The data is labeled with its outcome.</p> <p>So far I'm thinking logistic regression model and kernel approximation, based on the cheat-sheet <a href="http://scikit-learn.org/stable/tutorial/machine_learning_map/" rel="nofollow">here</a>. </p> <p>I am unsure where to start when implementing this in either R or Python.</p> <p>Thanks!</p>
1
2016-07-29T14:44:28Z
38,671,098
<h2>Features</h2> <p>If your categorical features don't have too many possible different values, you might want to have a look at <a href="http://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.OneHotEncoder.html" rel="nofollow"><code>sklearn.preprocessing.OneHotEncoder</code></a>.</p> <h2>Model choice</h2> <p>The choice of "the best" model depends mainly on the amount of available training data and the simplicity of the decision boundary you expect to get.</p> <p>You can try dimensionality reduction to 2 or 3 dimensions. Then you can visualize your data and see if there is a nice decision boundary.</p> <p>With 500,000 training examples you can think about using a neural network. I can recommend <a href="http://keras.io/" rel="nofollow">Keras</a> for beginners and <a href="https://www.tensorflow.org/" rel="nofollow">TensorFlow</a> for people who know how neural networks work.</p> <p>You should also know that there are <a href="http://scikit-learn.org/stable/modules/ensemble.html" rel="nofollow">Ensemble methods</a>.</p> <p>A nice cheat sheet what to use is on <a href="http://scikit-learn.org/stable/tutorial/machine_learning_map/" rel="nofollow">in the sklearn tutorial</a> you already found:</p> <p><img src="http://scikit-learn.org/stable/_static/ml_map.png" alt=""></p> <p>Just try it, compare different results. Without more information it is not possible to give you better advice.</p>
0
2016-07-30T06:37:02Z
[ "python", "machine-learning" ]
ctypes struct returned from library
38,661,635
<p>Given a simple C file:</p> <pre><code>#include &lt;stdio.h&gt; typedef struct point { int x; int y; } POINT; POINT get_point() { POINT p = {1, 2}; return p; } </code></pre> <p>And I have a simple python file:</p> <pre><code>from ctypes import * import os lib_name = '/testlib.so' test_lib = CDLL(os.getcwd() + lib_name) class POINT(Structure): _fields_ = [('x', c_int), ('y', c_int)] # Sets p1 to the integer 1 p1 = test_lib.get_point() # Sets p2 to the struct POINT with values {1, 0} p2 = POINT(test_lib.get_point()) </code></pre> <p>How can I set my returned value to the struct <code>POINT</code> with values <code>{1, 2}</code>? </p>
1
2016-07-29T14:44:37Z
38,663,141
<p>What you ar asking is nto the sole problem in your example. Just to answer just what you asked first: you have to annotate the C function return type, so that ctypes know it is a memory address - otherwise it is a (4 byte) integer by default (while in any 64 byte OS, pointers are 8 bytes long).</p> <p>Then you can create Python side POINT structures by using the (hidden) "from_address" method in your POINT class:</p> <pre><code>test_lib.get_point.restype = c_void_p p = POINT.from_address(test_lib.get_point()) print(p.x, p.y) </code></pre> <p>Before that works, however, you have a more fundamental issue on the C side: the POINT structure you declare on your example only exists while <code>get_point</code> is running, and is deallocated afterwards. The code above would lead to a segmentation fault.</p> <p>Your C code have to allocate memory properly. And also, you should take provisions to deallocate data structures you allocate in C - otherwise you will have memory leaks as each call to the function in C allocates more memory and you don't free that. (Notice that this memory won't be freed by itself when the Python POINT object goes out of scope).</p> <p>Your C code could be like this:</p> <pre><code>#include &lt;stdlib.h&gt; #include &lt;stdio.h&gt; typedef struct point { int x; int y; } POINT; POINT *get_point() { POINT *p; POINT initial = {1, 2}; p = malloc(sizeof(POINT)); *p = initial; return p; } void free_point(POINT *p) { free(p); } </code></pre> <p>And with this Python part:</p> <pre><code>from ctypes import * import os lib_name = '/testlib.so' test_lib = CDLL(os.getcwd() + lib_name) class POINT(Structure): _fields_ = [('x', c_int), ('y', c_int)] test_lib.get_point.restype = c_void_p p1 = POINT.from_address( test_lib.get_point()) print (p1.x, p1.y) test_lib.free_point(byref(p1)) del p1 </code></pre> <p>everything should just work.</p> <p>(just so that this answer is a complete ctypes example, I will add the GCC commands to build the testlib file:</p> <pre><code>gcc -c -fPIC test.c -o test.o gcc test.o -shared -o testlib.so </code></pre> <p>)</p>
1
2016-07-29T16:05:45Z
[ "python", "c", "python-2.7", "wrapper", "ctypes" ]
Issue with a global variable setting
38,661,669
<p>The program is supposed to update the value of the global variable <code>int_choice</code> every time a player scores (it's a pong game)</p> <p><code>int_choice</code> can only have a value of 1 or 0. If it's 1, the function <code>left_or_right</code> "tells" the ball to go right, if it's 0, the ball goes left.</p> <p><code>int_choice</code> is updated in few places: at the beginning it's initialized, then in the <code>left_or_right()</code> function, then in the <code>draw()</code> function.</p> <p>Every time the user scores, the ball should be respawned from the centre of the table towards that user, but the ball always respawns twice in the same direction and then twice in the opposite direction and so on, regardless of who was the last one to score. </p> <p>Here's the code:</p> <pre><code>import random int_choice = random.randint(0,1) direc = None def left_or_right(): global direc, int_choice if int_choice == 0: direc = "LEFT" elif int_choice == 1: direc = "RIGHT" return direc def spawn_ball(direction): left_or_right() global ball_pos, ball_vel # these are vectors stored as lists ball_pos = [WIDTH / 2, HEIGHT / 2] if direction == "LEFT": ball_vel[0] = (random.randrange(12, 25)*(-0.1)) print "Velocity[0]: ", ball_vel[0] ball_vel[1] = (random.randrange(6, 19)*(-0.1)) elif direction == "RIGHT": ball_vel[0] = (random.randrange(12, 25)*(0.1)) print "Velocity[0]: ", ball_vel[0] ball_vel[1] = (random.randrange(6, 19)*(-0.1)) print "Velocity[1]: ", ball_vel[1] def new_game(): global paddle1_pos, paddle2_pos, paddle1_vel, paddle2_vel, direc global score1, score2, spawn_ball(direc) score1 = 0 score2 = 0 def draw(canvas): global remaining_names, score1, score2, paddle1_pos, paddle2_pos, ball_pos, ball_vel, BALL_RADIUS, direc global int_choice # update ball ball_pos[0] += ball_vel[0] ball_pos[1] += ball_vel[1] if ball_pos[1] - BALL_RADIUS &lt;= 0: ball_vel[1] = ball_vel[1] + (ball_vel[1] * (-2)) elif ball_pos[1] + BALL_RADIUS &gt;= HEIGHT: ball_vel[1] = ball_vel[1] + (ball_vel[1] * (-2)) elif ball_pos[0] - BALL_RADIUS &lt;= (0 + PAD_WIDTH): if (ball_pos[1] &gt; paddle1_pos) and (ball_pos[1] &lt; (paddle1_pos + PAD_HEIGHT)): ball_vel[0] = ball_vel[0] + (ball_vel[0] * (-2.1)) else: int_choice = 1 spawn_ball(direc) score2 = score2 + 1 elif (ball_pos[0] + BALL_RADIUS) &gt;= (WIDTH - PAD_WIDTH): if (ball_pos[1] &gt; paddle2_pos) and (ball_pos[1] &lt; (paddle2_pos + PAD_HEIGHT)): ball_vel[0] = ball_vel[0] + (ball_vel[0] * (-2.1)) else: int_choice = 0 spawn_ball(direc) score1 = score1 + 1 </code></pre>
0
2016-07-29T14:46:54Z
38,661,817
<p>Your problem exists because you update the variable at the wrong time in your code. Let's look at an example of what happens after a game ends.</p> <pre><code>int_choice = 0 spawn_ball(direc) </code></pre> <p>You set int_choice to 0, then you call spawn_ball(direc), but direc is the <strong>old</strong> direction - it hasn't changed yet, only int_choice has. So now direc has been bound to the "direction" variable in your spawn_ball function. Even though spawn_ball immediately calls left_or_right(), that will <strong>only update direc, not direction</strong>, meaning that spawn_ball will continue with the same direction it was originally passed in, no matter what the call to left_or_right did.</p> <p>The quick solution would be to say</p> <pre><code>def spawn_ball(direction): direction = left_or_right() </code></pre> <p>Which will likely fix that problem. However, I would suggest you refactor your code quite a bit - it is very bad style. Passing around global variables as you are is so prone to errors like this one - using locals passed around through function calls is a much better option.</p>
1
2016-07-29T14:54:34Z
[ "python", "global-variables", "pong" ]
Issue with a global variable setting
38,661,669
<p>The program is supposed to update the value of the global variable <code>int_choice</code> every time a player scores (it's a pong game)</p> <p><code>int_choice</code> can only have a value of 1 or 0. If it's 1, the function <code>left_or_right</code> "tells" the ball to go right, if it's 0, the ball goes left.</p> <p><code>int_choice</code> is updated in few places: at the beginning it's initialized, then in the <code>left_or_right()</code> function, then in the <code>draw()</code> function.</p> <p>Every time the user scores, the ball should be respawned from the centre of the table towards that user, but the ball always respawns twice in the same direction and then twice in the opposite direction and so on, regardless of who was the last one to score. </p> <p>Here's the code:</p> <pre><code>import random int_choice = random.randint(0,1) direc = None def left_or_right(): global direc, int_choice if int_choice == 0: direc = "LEFT" elif int_choice == 1: direc = "RIGHT" return direc def spawn_ball(direction): left_or_right() global ball_pos, ball_vel # these are vectors stored as lists ball_pos = [WIDTH / 2, HEIGHT / 2] if direction == "LEFT": ball_vel[0] = (random.randrange(12, 25)*(-0.1)) print "Velocity[0]: ", ball_vel[0] ball_vel[1] = (random.randrange(6, 19)*(-0.1)) elif direction == "RIGHT": ball_vel[0] = (random.randrange(12, 25)*(0.1)) print "Velocity[0]: ", ball_vel[0] ball_vel[1] = (random.randrange(6, 19)*(-0.1)) print "Velocity[1]: ", ball_vel[1] def new_game(): global paddle1_pos, paddle2_pos, paddle1_vel, paddle2_vel, direc global score1, score2, spawn_ball(direc) score1 = 0 score2 = 0 def draw(canvas): global remaining_names, score1, score2, paddle1_pos, paddle2_pos, ball_pos, ball_vel, BALL_RADIUS, direc global int_choice # update ball ball_pos[0] += ball_vel[0] ball_pos[1] += ball_vel[1] if ball_pos[1] - BALL_RADIUS &lt;= 0: ball_vel[1] = ball_vel[1] + (ball_vel[1] * (-2)) elif ball_pos[1] + BALL_RADIUS &gt;= HEIGHT: ball_vel[1] = ball_vel[1] + (ball_vel[1] * (-2)) elif ball_pos[0] - BALL_RADIUS &lt;= (0 + PAD_WIDTH): if (ball_pos[1] &gt; paddle1_pos) and (ball_pos[1] &lt; (paddle1_pos + PAD_HEIGHT)): ball_vel[0] = ball_vel[0] + (ball_vel[0] * (-2.1)) else: int_choice = 1 spawn_ball(direc) score2 = score2 + 1 elif (ball_pos[0] + BALL_RADIUS) &gt;= (WIDTH - PAD_WIDTH): if (ball_pos[1] &gt; paddle2_pos) and (ball_pos[1] &lt; (paddle2_pos + PAD_HEIGHT)): ball_vel[0] = ball_vel[0] + (ball_vel[0] * (-2.1)) else: int_choice = 0 spawn_ball(direc) score1 = score1 + 1 </code></pre>
0
2016-07-29T14:46:54Z
38,661,849
<p>You pass in the <strong>old</strong> value of <code>direc</code>, before <code>left_or_right</code> is called.</p> <p>Say, you set <code>int_cohice</code> to 1:</p> <pre><code>int_choice = 1 spawn_ball(direc) # old value of `direc`, nothing changed this yet </code></pre> <p>then in <code>spawn_ball()</code>:</p> <pre><code>def spawn_ball(direction): left_or_right() </code></pre> <p>so <code>direction</code> is set the <em>old</em> value, but <code>left_or_right()</code> sets it to a <em>new</em> value, which is then <em>entirely ignored</em> in <code>spawn_ball()</code>. You use <code>direction</code> throughout the function.</p> <p>The quick fix is to use the return value of <code>left_or_right()</code>; or use the <code>direc</code> global. Since either operates on globals, there is no point in passing in <code>direc</code> here:</p> <pre><code>int_choice = 1 spawn_ball() # don't pass anything in </code></pre> <p>and</p> <pre><code>def spawn_ball(): direction = left_or_right() </code></pre> <p>However, the better way is to <em>always</em> pass in a direction, and completely remove the (double) globals.</p> <p>Just pass in a number, you can give that number symbolic names:</p> <pre><code>LEFT, RIGHT = 0, 1 # symbolic names for direction def spawn_ball(direction): ball_pos = [WIDTH / 2, HEIGHT / 2] if direction == LEFT: # using the global symbolic name return ball_pos, [ random.randrange(12, 25)*(-0.1), random.randrange(6, 19)*(-0.1)] else: # naturally the other option is going to be RIGHT return ball_pos, [ random.randrange(12, 25)*(0.1) random.randrange(6, 19)*(-0.1)] </code></pre> <p>Note that the function <strong>returns</strong> new ball positions and velocity; store the result when you call the function:</p> <pre><code>ball_pos, ball_vel = spawn_ball(direction) </code></pre> <p>Perhaps the <code>draw</code> function still treats these as globals, but that's no longer a concern for the <code>spawn_ball()</code> function at the very least.</p> <p>Now all you need to do is set one <em>local</em> variable to either <code>LEFT</code> or <code>RIGHT</code> to spawn a ball and pass that variable into the function.</p>
4
2016-07-29T14:56:09Z
[ "python", "global-variables", "pong" ]
Where is the xml file generated saved after running xmlrunner?
38,661,688
<p>I have my unittest suite and this piece of code. Where is the xml file saved?</p> <pre><code> if __name__ == '__main__': unittest.main(verbosity=2, testRunner=xmlrunner.XMLTestRunner(filename='test-reports.xml')) </code></pre> <p>Thanks in advance</p>
0
2016-07-29T14:47:45Z
39,506,176
<p>The problem was that I was running the tests with PyCharm's predefined running settings for unittest, however this requires the following command to run and generate the files:</p> <pre><code>python -m &lt;name-of-the-test&gt; </code></pre>
0
2016-09-15T08:16:34Z
[ "python", "unit-testing" ]
Want to replace backslash in python3 string
38,661,695
<p>I have a string</p> <pre><code>"abc INC\","None", "0", "test" </code></pre> <p>From this string I want to replace any occurrence of backslash when it appears before " with a pipe |. I wrote the following code but it actually takes out " and leaves the \ behind. </p> <pre><code>import re str = "\"abc INC\\\",\"None\", \"0\", \"test\"" str = re.sub("(\\\")", "|", str) print(str) Output: |abc INC\|,|None|, |0|, |test| Desired Output: "abc INC|","None", "0", "test" </code></pre> <p>Can someone point out what am I doing wrong?</p>
1
2016-07-29T14:48:09Z
38,661,814
<p>You can use the following <em>positive lookahead</em> assertion <code>'\\(?=")'</code>:</p> <pre><code>import re my_str = "\"abc INC\\\",\"None\", \"0\", \"test\"" p = re.sub(r'\\(?=")', '|', my_str) print(p) # '"abc INC|","None", "0", "test"' </code></pre> <p>Try not to use builtin names as names for variables, viz. <code>str</code>, to avoid shadowing the builtin.</p>
0
2016-07-29T14:54:29Z
[ "python", "regex", "python-3.x" ]
Want to replace backslash in python3 string
38,661,695
<p>I have a string</p> <pre><code>"abc INC\","None", "0", "test" </code></pre> <p>From this string I want to replace any occurrence of backslash when it appears before " with a pipe |. I wrote the following code but it actually takes out " and leaves the \ behind. </p> <pre><code>import re str = "\"abc INC\\\",\"None\", \"0\", \"test\"" str = re.sub("(\\\")", "|", str) print(str) Output: |abc INC\|,|None|, |0|, |test| Desired Output: "abc INC|","None", "0", "test" </code></pre> <p>Can someone point out what am I doing wrong?</p>
1
2016-07-29T14:48:09Z
38,661,827
<p>See Jamie Zawinksi's <a href="https://blog.codinghorror.com/regular-expressions-now-you-have-two-problems/" rel="nofollow">famous quote about regular expressions</a>. Try to only resort to the use of re's when absolutely necessary. In this case, it isn't.</p> <p>The actual content of string <code>str</code> (bad name for a variable, by the way, since there's a built-in type of that name) is</p> <pre><code>"abc INC\","None", "0", "test" </code></pre> <p>Why not just</p> <pre><code>str.replace('\\"', '|"') </code></pre> <p>which will do exactly what you want.</p>
2
2016-07-29T14:55:07Z
[ "python", "regex", "python-3.x" ]
Want to replace backslash in python3 string
38,661,695
<p>I have a string</p> <pre><code>"abc INC\","None", "0", "test" </code></pre> <p>From this string I want to replace any occurrence of backslash when it appears before " with a pipe |. I wrote the following code but it actually takes out " and leaves the \ behind. </p> <pre><code>import re str = "\"abc INC\\\",\"None\", \"0\", \"test\"" str = re.sub("(\\\")", "|", str) print(str) Output: |abc INC\|,|None|, |0|, |test| Desired Output: "abc INC|","None", "0", "test" </code></pre> <p>Can someone point out what am I doing wrong?</p>
1
2016-07-29T14:48:09Z
38,662,101
<p>This must solve your problem:</p> <pre><code>import re s = "\"abc INC\\\",\"None\", \"0\", \"test\"" s = re.sub(r"\\", "|", s) </code></pre> <p>Also don't use str as a variable name, it is a reserved keyword.</p>
0
2016-07-29T15:09:53Z
[ "python", "regex", "python-3.x" ]
Want to replace backslash in python3 string
38,661,695
<p>I have a string</p> <pre><code>"abc INC\","None", "0", "test" </code></pre> <p>From this string I want to replace any occurrence of backslash when it appears before " with a pipe |. I wrote the following code but it actually takes out " and leaves the \ behind. </p> <pre><code>import re str = "\"abc INC\\\",\"None\", \"0\", \"test\"" str = re.sub("(\\\")", "|", str) print(str) Output: |abc INC\|,|None|, |0|, |test| Desired Output: "abc INC|","None", "0", "test" </code></pre> <p>Can someone point out what am I doing wrong?</p>
1
2016-07-29T14:48:09Z
38,662,113
<p>For literal backslashes in python regexes you need to escape twice, giving you the pattern <code>'\\\\"'</code> or <code>"\\\\\""</code>. The first escaping is needed for python to actually put a backslash into the string. But regex patterns themself use backshlashes as a special character (for things like <code>\w</code> word characters, etc.). The <a href="https://docs.python.org/3/library/re.html#regular-expression-syntax" rel="nofollow">documentation</a> states:</p> <blockquote> <p>The special sequences consist of '\' and a character from the list below. If the ordinary character is not on the list, then the resulting RE will match the second character. </p> </blockquote> <p>So the pattern <code>\"</code> will match a single <code>"</code> because <code>"</code> is not a character with a special meaning there.</p> <p>You can use the raw notation to only escape once: <code>r'\\"'</code>.</p>
0
2016-07-29T15:10:45Z
[ "python", "regex", "python-3.x" ]
how to convert a scientific notation number preserving precision
38,661,903
<p>I have a some numbers like:</p> <pre><code>1.8816764231589208e-06 &lt;type 'float'&gt; </code></pre> <p>how I can convert to </p> <pre><code>0.00000018816764231589208 </code></pre> <p>Preserving all precision</p>
-1
2016-07-29T14:58:40Z
38,662,359
<p>This is not an easy problem, because binary floating point numbers cannot always represent decimal fractions exactly, and the number you have chosen is one such.</p> <p>Therefore, you need to know how many digits of precision you want. In your exact case, see what happens when I try to print it with various formats.</p> <pre><code>&gt;&gt;&gt; x = 1.8816764231589208e-06 &gt;&gt;&gt; for i in range(10, 30): ... fmt = "{:.%df}" % i ... print fmt, fmt.format(x) ... {:.10f} 0.0000018817 {:.11f} 0.00000188168 {:.12f} 0.000001881676 {:.13f} 0.0000018816764 {:.14f} 0.00000188167642 {:.15f} 0.000001881676423 {:.16f} 0.0000018816764232 {:.17f} 0.00000188167642316 {:.18f} 0.000001881676423159 {:.19f} 0.0000018816764231589 {:.20f} 0.00000188167642315892 {:.21f} 0.000001881676423158921 {:.22f} 0.0000018816764231589208 {:.23f} 0.00000188167642315892079 {:.24f} 0.000001881676423158920791 {:.25f} 0.0000018816764231589207915 {:.26f} 0.00000188167642315892079146 {:.27f} 0.000001881676423158920791458 {:.28f} 0.0000018816764231589207914582 {:.29f} 0.00000188167642315892079145823 &gt;&gt;&gt; </code></pre> <p>As you will observe, Python is happy to provide many digits of precision, but in fact the later ones are spurious: a standard Python float is stored in 64 bits, but only 52 of those are used to represent the significant figures, meaning you can get at most 16 significant digits.</p> <p>The real lesson here is that Python has no way to exactly store 1.8816764231589208e-06 as a floating point number. This is not so much a language limitation as a representational limitation of the floating-point implementation.</p> <p>The formatting shown above may, however, allow you to solve your problem.</p>
1
2016-07-29T15:23:52Z
[ "python", "math", "scientific-notation" ]
how to convert a scientific notation number preserving precision
38,661,903
<p>I have a some numbers like:</p> <pre><code>1.8816764231589208e-06 &lt;type 'float'&gt; </code></pre> <p>how I can convert to </p> <pre><code>0.00000018816764231589208 </code></pre> <p>Preserving all precision</p>
-1
2016-07-29T14:58:40Z
38,662,807
<p>The value you presented is not properly stored as Rory Daulton suggests in his comment. So your float <code>1.8816764231589208e-06 &lt;type 'float'&gt;</code> could be explained by this example:</p> <pre><code>&gt;&gt;&gt; from decimal import Decimal &gt;&gt;&gt; a = 1.8816764231589208e-06 &gt;&gt;&gt; g = 0.0000018816764231589208 # g == a &gt;&gt;&gt; Decimal(a) # Creates a Decimal object with the passed float Decimal('0.000001881676423158920791458225373060653140555587015114724636077880859375') &gt;&gt;&gt; Decimal('0.0000018816764231589208') # Exact value stored using str Decimal('0.0000018816764231589208') &gt;&gt;&gt; Decimal(a) == Decimal('0.0000018816764231589208') False # See the problem here? Your float did not # represent the number you "saw" &gt;&gt;&gt; Decimal(a).__float__() 1.8816764231589208e-06 &gt;&gt;&gt; Decimal(a).__float__() == a True </code></pre> <p>If you want precise decimals, use Decimal or some other class to represent numbers rather than binary representations such as float. Your <code>0.0000018816764231589208</code> of type <code>float</code>, is actually the number shown by <code>Decimal()</code>.</p>
0
2016-07-29T15:48:01Z
[ "python", "math", "scientific-notation" ]
Why is python 3 looking in my python 2.7 package directory for packages?
38,661,908
<p>OS (Linux): Ubuntu 14.04.4 LTS</p> <p>For some reason, my python 3.5.2 is looking into the python 2.7 packages directory instead of its own:</p> <pre><code>] python3 -m ensurepip Ignoring indexes: https://pypi.python.org/simple Requirement already satisfied (use --upgrade to upgrade): setuptools in /usr/local/lib/python3.5/site-packages Requirement already satisfied (use --upgrade to upgrade): pip in /usr/local/lib/python2.7/dist-packages </code></pre> <p>More details:</p> <pre><code>] python3 Python 3.5.2 (default, Jul 29 2016, 09:41:38) [GCC 6.1.1 20160511] on linux Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import site; site.getsitepackages() ['/usr/local/lib/python3.5/site-packages'] &gt;&gt;&gt; </code></pre> <p>^^^-- That seems correct and does not mention anything about the 2.7 packages directory.</p> <p>It looks like it should only be looking in <code>/usr/local/lib/python3.5/site-packages</code>, but for some reason, it is also looking in <code>/usr/local/lib/python2.7/dist-packages</code> where it has no business in looking.</p> <p>For example look what happens when I try to install <code>psycopg2</code> as a python3 module:</p> <pre><code>] python3 -m pip install psycopg2 Requirement already satisfied (use --upgrade to upgrade): psycopg2 in /usr/local/lib/python2.7/dist-packages </code></pre> <p>It is finding it as an installed package in the 2.7 distribution and failing to install it's python 3 version in <code>/usr/local/lib/python3.5/site-packages</code>.</p> <p>To add even more confusion into the mix, I try going straight for pip3, but to no avail:</p> <pre><code>] pip3 install psycopg2 Requirement already satisfied (use --upgrade to upgrade): psycopg2 in /usr/local/lib/python2.7/dist-packages ] cat `which pip3` #!/usr/local/bin/python3 # -*- coding: utf-8 -*- import re import sys from pip import main if __name__ == '__main__': sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0]) sys.exit(main()) </code></pre> <p><strong>Update</strong>: <code>PYTHONPATH</code> was set to <code>/usr/local/lib/python2.7/dist-packages</code> . This was the cause of the issue above. Credit goes to user <em>be_good_do_good</em> for helping me figure out which <em>screw to turn</em> to get things to work as they should.</p>
5
2016-07-29T14:58:56Z
38,666,432
<p>PYTHONPATH might have been set to 2.7 distribution packages, which might be causing this.</p>
1
2016-07-29T19:45:42Z
[ "python", "python-3.x", "pip", "python-3.5", "python-3.5.2" ]
Rock Paper Scissors 2 player
38,661,984
<p>Here is my code for my 2 player game. What I'm having trouble with is no matter what, player 2 always wins and gives points to player 2. Can someone help me make it so Player 1 can also win and be assigned points.</p> <pre><code>def vshuman(): score = [0,0] while True: while True: user1_choice = input("Player 1 choose a weapon (1,2,3,4)") user2_choice = input("Player 2 choose a weapon(1,2,3,4)") if user1_choice == "1": user1_choice == 1 break if user2_choice == "1": user2_choice == 1 break elif user1_choice == "2": user1_choice == 2 break elif user2_choice == "2": user1_choice == 2 break elif user1_choice == "3": user1_choice == 3 break elif user2_choice == "3": user2_choice == 3 break elif user1_choice == "4": user1_choice == 4 main() elif user2_choice == "4": user1_choice == 4 main() if user1_choice == user2_choice: print("Tie") score[0] = score[0] + 1 score[1] = score[1] + 1 elif (user1_choice == 1 and user2_choice == 3): print("Player 1 won") score[0] = score[0] + 1 elif(user1_choice == 2 and user2_choice == 1): print("Player 1 won") score[0] = score[0] + 1 elif(user1_choice == 3 and user2_choice == 2): print("Player 1 won") score[0] = score[0] + 1 elif(user2_choice == 1 and user1_choice == 3): print("Player 2 won") score[1] = score[1] + 1 elif(user2_choice == 2 and user1_choice == 1): print("Player 2 won") score[1] = score[1] + 1 elif(user2_choice == 3 and user1_choice == 2): print("Player 2 won") score[1] = score[1] + 1 while True: answer = input("Play another Round") if answer == "y" or "Y": print(" score: Player 1 -",score[0]," Player 2 -",score[1]) break elif answer == "n" or "N": print("I hope you enjoyed! Final score Player 1 -",score[0]," Player 2 -",score[1]) break else: print("y or n") </code></pre>
-1
2016-07-29T15:03:14Z
38,662,445
<pre><code>score = [0,0] while 1: c1 = int(input("Player 1 choose a weapon (1,2,3) : ")) c2 = int(input("Player 2 choose a weapon (1,2,3) : ")) if c1 == c2: print('tie') score[0] += 1 score[1] += 1 elif (c1 - 1) % 3 == c2 % 3: print('Player 1 won') score[0] += 1 else : print('Player 2 won') score[1] += 1 print(" score: Player 1 -",score[0]," Player 2 -",score[1]) answer = input("Play another Round (y / n) : ") if answer.lower() != "y": break </code></pre>
0
2016-07-29T15:27:48Z
[ "python" ]
How to update a PySpark RDD of dictionaries based on some condition
38,662,209
<p>Firstly I understand the concept of persistent data structures and immutability with regards to RDD's.. update is the only word I could think of :)</p> <p>My question is:</p> <p>Given an RDD of dictionaries (or Row objects) how can I loop/map across and apply some transformation login on that RDD and receive back a new RDD with those transformations applied. Example:</p> <p>Given an RDD containing dictionaries:</p> <pre><code>fbb = sc.parallelize( [{'amount_gbp': -43.33, 'balance_gbp': 57.08, 'type': 'GED', 'id': 961690979, 'settled_jrnl_cr_datetime': u'(null)', 'virtual_cash_balance': 0, 'virtual_debt_balance': 0}, {'amount_gbp': 17.08, 'balance_gbp': 40.0, 'type': 'OIP', 'id': 962182953, 'settled_jrnl_cr_datetime': u'(null)', 'virtual_cash_balance': 0, 'virtual_debt_balance': 0}]) </code></pre> <p>I attempted to apply the function:</p> <pre><code>def update_virtual_cash_balance(x): x.update({'virtual_cash_balance': x['amount_gbp'] + x['balance_gbp']}) if x['type'] == 'GED' else x fbb.map(lambda x: update_virtual_cash_balance(x)).collect() </code></pre> <p>And expected:</p> <pre><code>[{'amount_gbp': -43.33, 'balance_gbp': 57.08, 'type': 'GED', 'id': 961690979, 'settled_jrnl_cr_datetime': u'(null)', 'virtual_cash_balance': 13.75, 'virtual_debt_balance': 0}, {'amount_gbp': 17.08, 'balance_gbp': 40.0, 'type': 'OIP', 'id': 962182953, 'settled_jrnl_cr_datetime': u'(null)', 'virtual_cash_balance': 0, 'virtual_debt_balance': 0}] </code></pre> <p>But got:</p> <pre><code>Out[411]: [None, None] </code></pre> <p>Any help with what I am misunderstanding would be great.</p>
1
2016-07-29T15:15:56Z
38,662,423
<ul> <li><code>update_virtual_cash_balance</code> doesn't return anything so you get <code>None</code></li> <li><code>update</code> method doesn't return anything so you would get <code>None</code> even if <code>update_virtual_cash_balance</code> returned value</li> <li>you shouldn't modify data in place. RDD is immutable and mutating data can have undesired effects.</li> </ul> <p>Try:</p> <pre><code>def update_virtual_cash_balance(x): if x['type'] == 'GED': z = x.copy() # shallow copy should be enough here z.update({'virtual_cash_balance': x['amount_gbp'] + x['balance_gbp']} return z return x </code></pre>
1
2016-07-29T15:26:49Z
[ "python", "pyspark" ]
Using functions with raw inputs
38,662,274
<p>I was experimenting with what I have learned so far and I wanted to create something that is interactive, using <code>raw_input()</code>. </p> <p>What I wanted to do was creating a function that will create a conversation which will go different directions based on input. However, I was unable to figure out how to make a function accept the <code>raw_input</code> as its argument. </p> <p>Here is the code that I've written;</p> <pre><code>drink = raw_input("Coffee or Tea?") def drinktype(drink): if drink == "Coffee": #I WANT TO INSERT A CODE HERE THAT WILL CALL THE FUNCTION coffee(x) elif drink == "Tea": print "Here is your tea." else: print "Sorry." x = raw_input("Americano or Latte?") def coffee(x): if x == "Americano": return "Here it is." elif x == "Latte": return "Here is your latte." else: return "We do not have that, sorry." </code></pre>
1
2016-07-29T15:19:22Z
38,662,406
<p>Are you looking for something like this?</p> <pre><code>drink = raw_input("Coffee or Tea?") def drinktype(drink): if drink == "Coffee": usercoffeetype = raw_input("What type of coffee do you drink?") coffee(usercoffeetype) elif drink == "Tea": print "Here is your tea." else: print "Sorry." x = raw_input("Americano or Latte?") def coffee(x) if x == "Americano": return "Here it is." elif x == "Latte": return "Here is your latte." else: return "We do not have that, sorry." </code></pre> <p>Also just a note - using variable names like "x" is generally not a good idea. It'd be better if your variable name actually described what it holds, like this:</p> <pre><code>def coffee(coffeechoice) if coffeechoice == "Americano": return "Here it is." elif coffeechoice == "Latte": return "Here is your latte." else: return "We do not have that, sorry." </code></pre>
0
2016-07-29T15:26:07Z
[ "python", "function" ]
Using functions with raw inputs
38,662,274
<p>I was experimenting with what I have learned so far and I wanted to create something that is interactive, using <code>raw_input()</code>. </p> <p>What I wanted to do was creating a function that will create a conversation which will go different directions based on input. However, I was unable to figure out how to make a function accept the <code>raw_input</code> as its argument. </p> <p>Here is the code that I've written;</p> <pre><code>drink = raw_input("Coffee or Tea?") def drinktype(drink): if drink == "Coffee": #I WANT TO INSERT A CODE HERE THAT WILL CALL THE FUNCTION coffee(x) elif drink == "Tea": print "Here is your tea." else: print "Sorry." x = raw_input("Americano or Latte?") def coffee(x): if x == "Americano": return "Here it is." elif x == "Latte": return "Here is your latte." else: return "We do not have that, sorry." </code></pre>
1
2016-07-29T15:19:22Z
38,662,434
<p>The request for americano or latte is something you only need to do if coffee is requested; it is irrelevant if the user requests tea. Once that is moved under the Coffee case, you can simply pass the returned value to your call to <code>coffee()</code>. The return value also needs to be printed.</p> <pre><code>def drinktype(drink): if drink == "Coffee": kind = raw_input("Americano or Latte?") print coffee(kind) elif drink == "Tea": print "Here is your tea." else: print "Sorry." def coffee(x) if x == "Americano": return "Here it is." elif x == "Latte": return "Here is your latte." else: return "We do not have that, sorry." drink = raw_input("Coffee or Tea?") drinktype(drink) </code></pre>
1
2016-07-29T15:27:16Z
[ "python", "function" ]
Using functions with raw inputs
38,662,274
<p>I was experimenting with what I have learned so far and I wanted to create something that is interactive, using <code>raw_input()</code>. </p> <p>What I wanted to do was creating a function that will create a conversation which will go different directions based on input. However, I was unable to figure out how to make a function accept the <code>raw_input</code> as its argument. </p> <p>Here is the code that I've written;</p> <pre><code>drink = raw_input("Coffee or Tea?") def drinktype(drink): if drink == "Coffee": #I WANT TO INSERT A CODE HERE THAT WILL CALL THE FUNCTION coffee(x) elif drink == "Tea": print "Here is your tea." else: print "Sorry." x = raw_input("Americano or Latte?") def coffee(x): if x == "Americano": return "Here it is." elif x == "Latte": return "Here is your latte." else: return "We do not have that, sorry." </code></pre>
1
2016-07-29T15:19:22Z
38,662,502
<p>Looks like you are trying to get something like the following</p> <pre><code>def coffee(): x = raw_input("Americano or Latte?") if x == "Americano": return "Here it is." elif x == "Latte": return "Here is your latte." else: return "We do not have that, sorry." def drinktype(drink): if drink == "Coffee": print coffee() elif drink == "Tea": print "Here is your tea." else: print "Sorry." drink = raw_input("Coffee or Tea?") drinktype(drink) </code></pre> <p>Please note that 1. correct indentation is crucial for you code to work 2. after defining a function drinktype(), you need to actually call it to let it run. (the last line is calling the function)</p>
0
2016-07-29T15:31:20Z
[ "python", "function" ]
Unexpected '{' in field name when doing string formatting
38,662,296
<p>I'm trying to write a small script that will automate some PHP boilerplate that I need to write. It should write a copy of the string <code>code</code> to the output file with the various replacement fields filled in for each dict in the <code>fields</code> list.</p> <p>However, I'm getting the error:</p> <pre><code>Traceback (most recent call last): File "writefields.py", line 43, in &lt;module&gt; formatted = code.format(**field) ValueError: unexpected '{' in field name </code></pre> <p>As far as I can tell, there are no extra braces in either the replacement fields or the dicts that should be causing issues, so any help would be appreciated.</p> <pre><code>code = ''' // {label} add_filter( 'submit_job_form_fields', 'frontend_add_{fieldname}_field' ); function frontend_add_{fieldname}_field($fields) { $fields['job']['job_{fieldname}'] = array( 'label' =&gt; __('{label}', 'job_manager'), 'type' =&gt; 'text', 'required' =&gt; {required}, 'priority' =&gt; 7, 'placeholder' =&gt; '{placeholder}' ); return $fields; } add_filter( 'job_manager_job_listing_data_fields', 'admin_add_{fieldname}_field' ); function admin_add_{fieldname}_field( $fields ) { $fields['_job_{fieldname}'] = array( 'label' =&gt; __( '{label}', 'job_manager' ), 'type' =&gt; 'text', 'placeholder' =&gt; '{placeholder}', 'description' =&gt; '' ); return $fields; } ''' fields = [ { 'fieldname': 'salary', 'label': 'Salary ($)', 'required': 'true', 'placeholder': 'e.g. 20000', }, { 'fieldname': 'test', 'label': 'Test Field', 'required': 'true', 'placeholder': '', } ] with open('field-out.txt', 'w') as f: for field in fields: formatted = code.format(**field) f.write(formatted) f.write('\n') </code></pre>
1
2016-07-29T15:20:29Z
38,662,335
<p>You need to <em>double</em> any <code>{</code> or <code>}</code> that are not part of a formatting placeholder. For example, you have:</p> <pre><code>function admin_add_{fieldname}_field( $fields ) { [....] } </code></pre> <p>in the string. The <code>{</code> and <code>}</code> there are not part of a placeholder.</p> <p>Doubling up those curly braces escapes them; the final output will contain single <code>{</code> and <code>}</code> characters again:</p> <pre><code>code = ''' // {label} add_filter( 'submit_job_form_fields', 'frontend_add_{fieldname}_field' ); function frontend_add_{fieldname}_field($fields) {{ $fields['job']['job_{fieldname}'] = array( 'label' =&gt; __('{label}', 'job_manager'), 'type' =&gt; 'text', 'required' =&gt; {required}, 'priority' =&gt; 7, 'placeholder' =&gt; '{placeholder}' ); return $fields; }} add_filter( 'job_manager_job_listing_data_fields', 'admin_add_{fieldname}_field' ); function admin_add_{fieldname}_field( $fields ) {{ $fields['_job_{fieldname}'] = array( 'label' =&gt; __( '{label}', 'job_manager' ), 'type' =&gt; 'text', 'placeholder' =&gt; '{placeholder}', 'description' =&gt; '' ); return $fields; }} ''' </code></pre>
4
2016-07-29T15:22:28Z
[ "python", "python-3.x", "string-formatting" ]
Python: Is it possible to create a package out of multiple external libraries?
38,662,331
<p>This issue has been driving me insane for the past few days.</p> <p>So basically, I'm trying to port over a Pure Python project to a proper PyCharm project. This is to basically improve code quality and project structure. </p> <p>I wish it was as simple as basically creating a virtualenv to house everything, but it isn't. This project will eventually be developed simultaneously by multiple developers with Git as source control, and the default libraries <strong>will be modified</strong>. I presume this means that the libraries should ideally be tracked by Git in the end. Virtualenv shouldn't help here as far as I know because it's not portable between systems (or at least that's still being tested).</p> <p>This project will also be, in the future, deployed to a Centos server.</p> <p>So the only plan I can think of to successfully pull off this would be to simply bring in all of the libraries (which was done using <code>pip install -t Libraries &lt;ExampleLibrary&gt;</code>) into a single folder, with a <code>__init__.py</code> inside, and use them from other python files as a package within the Pycharm project.</p> <p>Is this possible / recommended? I tried various methods to reference these libraries, but they all don't work during runtime. Somehow when the files in the library import something else from their own package, an ImportError is raised saying that there's no such module.</p> <p>Will accept any other suggestions too.</p> <p>Using Pycharm Community Edition.</p> <p>EDIT: After having a good night's rest I think the crux of the issue is really just project organization. Before I ported it over to Pycharm the project worked as expected, but this had all of the python files in the root directory, and the libraries in a subfolder of the root, with every project file having the same boilerplate code: <code>import os, sys absFilePath = os.path.dirname(os.path.abspath(__file__)); sys.path.insert(1, absFilePath + "/lib")</code> </p> <p>I was hoping that by using Pycharm to help me flesh out the packages, I could avoid having repeated boilerplate code.</p>
0
2016-07-29T15:22:19Z
38,670,374
<p><strong>Note: Not full solution.</strong></p> <p>The addition of the template code below forces the file containing the code to be in the same directory as the libs folder.</p> <p>For Pycharm, all I had to do was mark the libs folder as a source folder. Even with the addition of the template code to the file, the modified libraries still work as expected.</p> <p>For the Python Shell, this template code is still needed:</p> <pre><code>import os import sys absFilePath = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(1, absFilePath + "/lib") </code></pre>
0
2016-07-30T04:36:32Z
[ "python", "git", "pycharm", "packages" ]
How to speed this up: Searching through multiple lists of dates to find closest match. [Python]
38,662,494
<p>I have one list of dates, <code>master_time</code>. For each date in <code>master_time</code>, I am searching for the closest match in four other lists of dates; <code>time1</code>,<code>time2</code>,<code>time3</code>, and <code>time4</code>. The results are appended to "closestmatch" lists which will later be used to join dataframes containing timeseries information from different data sources. (Perhaps there is a better approach to the initial problem, but this is what I have come up with so far)</p> <p>To search through the 4 lists, I have created the following (rather bulky) loop:</p> <pre><code>master_time = [some list of dates...] time1 = [some other list of dates...] time2 = [some other list of dates...] time3 = [some other list of dates...] time4 = [some other list of dates...] closest2=[];closest4=[];closest5=[];closest6=[] for i in master_time: index_time=i closestTimestamp1=min(time1, key=lambda d: abs(d - index_time)) closestTimestamp2=min(time2, key=lambda d: abs(d - index_time)) closestTimestamp3=min(time3, key=lambda d: abs(d - index_time)) closestTimestamp4=min(time4, key=lambda d: abs(d - index_time)) closest1.append(str(closestTimestamp1)) closest2.append(str(closestTimestamp2)) closest3.append(str(closestTimestamp3)) closest4.append(str(closestTimestamp4)) print str(i) </code></pre> <p>This loop takes ~5 seconds per iteration (i.e. way too slow). I'm pretty new to Python in general, so I suspect there are a few ways I could streamline this to make it quicker. Any suggestions are greatly appreciated!</p>
0
2016-07-29T15:31:01Z
38,665,727
<pre><code>import random def find_best_match(master_list, secondary_list): master_list.sort() secondary_list.sort() secondary_len = len(secondary_list) - 1 secondary_index = 0 closests = [] for master_value in master_list: while True: delta_current = abs(master_value - secondary_list[secondary_index]) if secondary_index == secondary_len: break delta_next = abs(master_value - secondary_list[secondary_index+1]) if delta_current &lt; delta_next: break secondary_index += 1 closests.append(secondary_list[secondary_index]) return closests master_list = [random.random() * 10000 for _ in range(1000000)] list_1 = [random.random() * 10000 for _ in range(1000000)] list_2 = [random.random() * 10000 for _ in range(1000000)] closests_1 = find_best_match(master_list, list_1) closests_2 = find_best_match(master_list, list_2) </code></pre> <p>This algorithm has a running complexity of N (and not N^2 like your algorithm or N*log(N) like James proposal) and take less than 2 seconds to match 2 lists of 1.000.000 randoms numbers</p>
0
2016-07-29T18:51:51Z
[ "python", "datetime", "search", "matching" ]
pandas.DataFrame.replace with wildcards
38,662,509
<p>Does the <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.replace.html" rel="nofollow"><code>pandas.DataFrame.replace</code></a> regex replace support wildcards and "capture groups"?</p> <p>E.g., to replace <code>([A-Z])(\w+)</code> with <code>\2\1</code>?</p> <p>What kind of regular expression is supported? Does Perl's regex supported? E.g., OK to replace <code>([A-Z])(\w+)</code> with <code>\l\1\2</code> (<code>\l</code>: <em>Change the next character to lowercase</em>.)</p> <p><strong>UPDATE:</strong></p> <p>As Steve has pointed out, according to the <a href="https://docs.python.org/2/library/re.html" rel="nofollow">Python documentation</a>, it should work, but the following is not giving me what I expected:</p> <pre><code>df = pd.DataFrame({'A': np.random.choice(['foo', 'bar'], 100), 'B': np.random.choice(['one', 'two', 'three'], 100), 'C': np.random.choice(['I1', 'I2', 'I3', 'I4'], 100), 'D': np.random.randint(-10,11,100), 'E': np.random.randn(100)}) df.replace("f(.)(.)","b\1\2", regex=True,inplace=True) </code></pre> <p>What's wrong? </p> <p>Thx</p>
3
2016-07-29T15:31:35Z
38,662,618
<p>According to the <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.replace.html" rel="nofollow">pandas documentation</a>:</p> <blockquote> <p>Regex substitution is performed under the hood with re.sub. The rules for substitution for re.sub are the same.</p> </blockquote> <p>So, yes, any substitutions which can be performed with Python's <code>re.sub</code> (such as <code>\1</code>) can also be performed with <code>pandas.DataFrame.replace</code>. See the <a href="https://docs.python.org/2/library/re.html" rel="nofollow">Python documentation</a> for more information.</p>
2
2016-07-29T15:37:31Z
[ "python", "regex", "pandas", "replace", "dataframe" ]
NameError: name 'Name' is not defined in django form
38,662,514
<p>I want to render the following form but django throws out a error and i dont understand why. Thanks in advance. </p> <p>forms.py:</p> <pre><code>from django import forms from .models import equipment class neweqForm(forms.ModelForm): class Meta: model = equipment name = forms.CharField(label=Name, max_lenght=100) fabricator = forms.CharField(label=Hersteller, max_lenght=100) storeplace = forms.IntegerField(label=Regal) labour = forms.ChoiceField(label=Gewerk) </code></pre> <p>models.py: </p> <pre><code>from __future__ import unicode_literals from django.db import models # Create your models here. class equipment(models.Model): name = models.CharField(max_length=30) fabricator = models.CharField(max_length=30) storeplace = models.IntegerField() labor_choices = ( ('L', 'Licht'), ('T', 'Ton'), ('R', 'rigging'), ) labor = models.CharField(max_length=1, choices=labor_choices) </code></pre> <p>error: </p> <pre><code>NameError: name 'Name' is not defined </code></pre>
0
2016-07-29T15:31:55Z
38,662,572
<p>You are having <code>label</code> for each field, but you are using <code>Name</code>, <code>Hersteller</code>, etc to assign the value. You might have major misunderstanding about variables and strings. If you don't quote something, they are treated as variables in python. But they not defined anywhere else, so python let you know that those are undefined variables. </p> <p>Quick fixes would be adding quotes around all label values:</p> <pre><code>name = forms.CharField(label="Name", max_lenght=100) </code></pre> <p>You just pasted the error from the traceback, great, but you need to learn how to read the traceback going forward. If you read the traceback backwards, it tells you what are each function that's called that lead the ultimate error. I'm pretty sure that the line <code>name = forms.CharField(label=Name, max_lenght=100)</code> shows up in the end(if your calling something else it might be in the middle) which tells you that that's the location where error happens. You would benefit from this a lot while tracing the errors.</p>
3
2016-07-29T15:34:57Z
[ "python", "django" ]
Improve parsing speed of delimited configuration block
38,662,521
<p>I have a quite large configuration file that consists of blocks delimited by</p> <p><code>#start &lt;some-name&gt; ... #end &lt;some-name&gt;</code> were <code>some-name</code> has to be the same for the block. The block can appear multiple times but is never contained within itself. Only some other blocks may appear in certain blocks. I'm not interested in these contained blocks, but on the blocks in the second level.</p> <p>In the real file the names do not start with <code>blockX</code> but are very different from each other.</p> <p>An example:</p> <pre><code>#start block1 #start block2 /* string but no more name2 or name1 in here */ #end block2 #start block3 /* configuration data */ #end block3 #end block1 </code></pre> <p>This is being parsed with regex and is, when run without a debugger attached, quite fast. 0.23s for a <strike>2k</strike> 2.7MB file with simple rules like:</p> <pre><code>blocks2 = re.findAll('#start block2\s+(.*?)#end block2', contents) </code></pre> <p>I tried parsing this with pyparsing but the speed is VERY slow even without a debugger attached, it took 16s for the same file.</p> <p>My approach was to produce a pyparsing code that would mimic the simple parsing from the regex so I can use some of the other code for now and avoid having to parse every block now. The grammar is quite extense.</p> <p>Here is what I tried</p> <pre><code>block = [Group(Keyword(x) + SkipTo(Keyword('#end') + Keyword(x)) + Keyword('#end') - x )(x + '*') for x in ['block3', 'block4', 'block5', 'block6', 'block7', 'block8']] blocks = Keyword('#start') + block x = OneOrMore(blocks).searchString(contents) # I also tried parseString() but the results were similar. </code></pre> <p>What am I doing wrong? How can I optimize this to come anywhere close to the speed achieved by the regex implementation?</p> <p><strong>Edit:</strong> The previous example was way to easy compared to the real data, so i created a proper one now:</p> <pre><code>/* all comments are C comments */ VERSION 1 0 #start PROJECT project_name "what is it about" /* why not another comment here too! */ #start SECTION where_the_wild_things_are "explain this section" /* I need all sections at this level */ /* In the real data there are about 10k of such blocks. There are around 10 different names (types) of blocks */ #start INTERFACE_SPEC There can be anything in the section. Not Really but i want to skip anything until the matching (hash)end. /* can also have comments */ #end INTERFACE_SPEC #start some_other_section name 'section name' #start with_inner_section number_of_points 3 /* can have comments anywhere */ #end with_inner_section #end some_other_section /* basically comments can be anywhere */ #start some_other_section name 'section name' other_section_attribute X ref_to_section another_section #end some_other_section #start another_section degrees #start section_i_do_not_care_about_at_the_moment ref_to some_other_section /* of course can have comments */ #end section_i_do_not_care_about_at_the_moment #end another_section #end SECTION #end PROJECT </code></pre> <p>For this i had to expand your original suggestion. I hard coded the two outer blocks (PROJECT and SECTION) because they MUST exist.</p> <p>With this version the time is still at ~16s:</p> <pre><code>def test_parse(f): import pyparsing as pp import io comment = pp.cStyleComment start = pp.Literal("#start") end = pp.Literal("#end") ident = pp.Word(pp.alphas + "_", pp.printables) inner_ident = ident.copy() inner_start = start + inner_ident inner_end = end + pp.matchPreviousLiteral(inner_ident) inner_block = pp.Group(inner_start + pp.SkipTo(inner_end) + inner_end) version = pp.Literal('VERSION') - pp.Word(pp.nums)('major_version') - pp.Word(pp.nums)('minor_version') project = pp.Keyword('#start') - pp.Keyword('PROJECT') - pp.Word(pp.alphas + "_", pp.printables)( 'project_name') - pp.dblQuotedString + pp.ZeroOrMore(comment) - \ pp.Keyword('#start') - pp.Keyword('SECTION') - pp.Word(pp.alphas, pp.printables)( 'section_name') - pp.dblQuotedString + pp.ZeroOrMore(comment) - \ pp.OneOrMore(inner_block) + \ pp.Keyword('#end') - pp.Keyword('SECTION') + \ pp.ZeroOrMore(comment) - pp.Keyword('#end') - pp.Keyword('PROJECT') grammar = pp.ZeroOrMore(comment) - version.ignore(comment) - project.ignore(comment) with io.open(f) as ff: return grammar.parseString(ff.read()) </code></pre> <p>EDIT: Typo, said it was 2k but it instead it is a 2.7MB file.</p>
1
2016-07-29T15:32:18Z
38,679,130
<p>First of all, this code as posted doesn't work for me:</p> <pre><code>blocks = Keyword('#start') + block </code></pre> <p>Changing to this:</p> <pre><code>blocks = Keyword('#start') + MatchFirst(block) </code></pre> <p>at least runs against your sample text.</p> <p>Rather than hard-code all the keywords, you can try using one of pyparsing's adaptive expressions, <code>matchPreviousLiteral</code>:</p> <p><strong>(EDITED)</strong></p> <pre><code>def grammar(): import pyparsing as pp comment = pp.cStyleComment start = pp.Keyword("#start") end = pp.Keyword('#end') ident = pp.Word(pp.alphas + "_", pp.printables) integer = pp.Word(pp.nums) inner_ident = ident.copy() inner_start = start + inner_ident inner_end = end + pp.matchPreviousLiteral(inner_ident) inner_block = pp.Group(inner_start + pp.SkipTo(inner_end) + inner_end) VERSION, PROJECT, SECTION = map(pp.Keyword, "VERSION PROJECT SECTION".split()) version = VERSION - pp.Group(integer('major_version') + integer('minor_version')) project = (start - PROJECT + ident('project_name') + pp.dblQuotedString + start + SECTION + ident('section_name') + pp.dblQuotedString + pp.OneOrMore(inner_block)('blocks') + end + SECTION + end + PROJECT) grammar = version + project grammar.ignore(comment) return grammar </code></pre> <p>It is only necessary to call <code>ignore()</code> on the topmost expression in your grammar - it will propagate down to all internal expressions. Also, it should be unnecessary to sprinkle <code>ZeroOrMore(comment)</code>s in your grammar, if you have already called <code>ignore()</code>.</p> <p>I parsed a 2MB input string (containing 10,000 inner blocks) in about 16 seconds, so a 2K file should only take about 1/1000th as long.</p>
1
2016-07-30T22:40:00Z
[ "python", "pyparsing" ]
I can't install pycharm due to Sub-process /usr/bin/dpkg returned an error code (1)
38,662,559
<p>I've recently install anaconda and I'm using PyCharm as my IDE, but when I go to import some modules, they don't seem to exist, even though they were downloaded with anaconda. When I tried to download Matplotlib via the terminal I get this </p> <pre><code> Errors were encountered while processing: python-six python-wrapt python-pkg-resources python-pyflakes pyflakes python-lazy-object-proxy python-logilab-common python-astroid pylint python-egenix-mxtools python-egenix-mxdatetime python-pyinotify python-sip python-qt4 ninja-ide python-cycler python-dateutil python-pil:amd64 python-imaging python-pyparsing python-tz python-numpy python-matplotlib E: Sub-process /usr/bin/dpkg returned an error code (1) </code></pre> <p>Can someone please help me with this, I'm quite new to Linux and I'm really confused to what's going on. </p>
1
2016-07-29T15:34:09Z
38,662,632
<p>Below codes can be solved your problem;</p> <pre><code>sudo apt-get clean sudo apt-get install -f </code></pre>
0
2016-07-29T15:38:17Z
[ "python", "matplotlib", "pycharm", "anaconda" ]
lpsolve - results are different every time I change the order of constraints
38,662,613
<p>I have noticed a strange behaviour of lpsolve library (using it in python 3.4).</p> <p>When I <strong>change the order of constraints</strong> which I add to the lpsolve model the results are also slightly different.</p> <p>Will be glad for any hints why this is happening.</p> <p>Adding both models to reproduce the case:</p> <pre><code> lp model 1: http://pastie.org/private/mginn1s7orxkq58mv3dxrw lp model 2: http://pastie.org/private/ron5k7y3hipxhci1hap8nq </code></pre> <p>If you run both models you will get slightly different results (while the objective function is almost the same):</p> <pre><code> obj1: 458093300.0000001 obj2: 458093300.00000006 vars1: [0.0, 350260.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1900.0, 1198215.0, 318324.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 4310807.0, 0.0, 0.0, 0.0, 1345965.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 4505218.0, 0.0, 1689912.0, 0.0, 0.0, 0.0, 0.0, 0.0, 479929.0, 0.0, 0.0, 0.0, 0.0, 0.0, 782031.0, 0.0, 0.0, 190146.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 5224280.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 3058056.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 650240.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 509539.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1351133.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 301872.0, 5.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 380880.0, 268556.0, 1201311.0] vars2: [0.0, 350260.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1198215.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 515323.0, 0.0, 0.0, 0.0, 1345965.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 4505218.0, 0.0, 1010333.0, 0.0, 0.0, 0.0, 0.0, 0.0, 479938.0, 0.0, 0.0, 0.0, 0.0, 0.0, 782031.0, 0.0, 0.0, 190146.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 5224280.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 3082057.0, 0.0, 0.0, 3061853.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 650240.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 623447.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1347336.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 301872.0, 305463.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 536019.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 380880.0, 268556.0, 1201311.0] </code></pre> <p>Python code to reproduce:</p> <pre><code> from lpsolve55 import * mod1 = lpsolve("read_lp", "/home/../model_1.lp") mod2 = lpsolve("read_lp", "/home/../model_2.lp") res1 = lpsolve('solve', mod1) res2 = lpsolve('solve', mod2) obj1 = lpsolve('get_objective', mod1) obj2 = lpsolve('get_objective', mod2) vars1 = lpsolve('get_variables', mod1)[0] vars2 = lpsolve('get_variables', mod2)[0] print("obj1: ", obj1) print("obj2: ", obj2) print("vars1: ", vars1) print("vars2: ", vars2) </code></pre>
1
2016-07-29T15:37:02Z
38,665,683
<p>This could be because your model is not completely numerically stable. You probably have inputs variable who are not in the same range (eg: x1 can be -1..+1 and x2 can be -1000000..+1000000)</p>
1
2016-07-29T18:48:47Z
[ "python", "lpsolve" ]
Getting Turtle in Python to recognize click events
38,662,630
<p>I'm trying to make Connect 4 in python, but I can't figure out how to get the coordinates of the screen click so I can use them. Right now, I want to draw the board, then have someone click, draw a dot, then go back to the top of the while loop, wipe the screen and try again. I've tried a couple different options but none have seemed to work for me.</p> <pre><code>def play_game(): """ When this function runs, allows the user to play a game of Connect 4 against another person """ turn = 1 is_winner = False while is_winner == False: # Clears screen clear() # Draws empty board centers = draw_board() # Decides whose turn it is, change color appropriately if turn % 2 == 0: color = RED else: color = BLACK # Gets coordinates of click penup() onscreenclick(goto) dot(HOLE_SIZE, color) turn += 1 </code></pre>
0
2016-07-29T15:38:16Z
38,663,552
<p>I'm assuming that your using <strong>Turtle</strong> in python(hence the name.) If that's the case, Here's a link to a helpful post: <a href="http://stackoverflow.com/questions/17864085/turtle-in-python-trying-to-get-the-turtle-to-move-to-the-mouse-click-position-a">Turtle in python- Trying to get the turtle to move to the mouse click position and print its coordinates</a> I know, i know. I hate <strong>just link answers</strong> as much as the next guy. But The post I gave a link to can probably do a much better job of answering your question than I can.</p> <p>~Mr.Python</p>
0
2016-07-29T16:30:56Z
[ "python", "turtle-graphics" ]
Getting Turtle in Python to recognize click events
38,662,630
<p>I'm trying to make Connect 4 in python, but I can't figure out how to get the coordinates of the screen click so I can use them. Right now, I want to draw the board, then have someone click, draw a dot, then go back to the top of the while loop, wipe the screen and try again. I've tried a couple different options but none have seemed to work for me.</p> <pre><code>def play_game(): """ When this function runs, allows the user to play a game of Connect 4 against another person """ turn = 1 is_winner = False while is_winner == False: # Clears screen clear() # Draws empty board centers = draw_board() # Decides whose turn it is, change color appropriately if turn % 2 == 0: color = RED else: color = BLACK # Gets coordinates of click penup() onscreenclick(goto) dot(HOLE_SIZE, color) turn += 1 </code></pre>
0
2016-07-29T15:38:16Z
38,664,006
<p>Assuming you're using <code>turtle</code> as mentioned in your title:</p> <pre><code>&gt;&gt;&gt; import turtle &gt;&gt;&gt; help(turtle.onscreenclick) Help on function onscreenclick in module turtle: onscreenclick(fun, btn=1, add=None) Bind fun to mouse-click event on canvas. Arguments: fun -- a function with two arguments, the coordinates of the clicked point on the canvas. num -- the number of the mouse-button, defaults to 1 Example (for a TurtleScreen instance named screen) &gt;&gt;&gt; onclick(goto) &gt;&gt;&gt; # Subsequently clicking into the TurtleScreen will &gt;&gt;&gt; # make the turtle move to the clicked point. &gt;&gt;&gt; onclick(None) </code></pre> <p>That means that your callback function, which you have apparently named <code>goto</code>, will take two parameters, an X and Y location.</p> <pre><code>import turtle def goto(x, y): print('Moving to {}, {}'.format(x,y)) turtle.goto(x, y) turtle.onscreenclick(goto) turtle.goto(0,0) </code></pre> <p>Each click that you make will move the turtle to a different position. Note that <code>turtle</code> already has an event loop - you don't need one of your own. Just respond to the clicks.</p>
0
2016-07-29T17:01:23Z
[ "python", "turtle-graphics" ]
Getting Turtle in Python to recognize click events
38,662,630
<p>I'm trying to make Connect 4 in python, but I can't figure out how to get the coordinates of the screen click so I can use them. Right now, I want to draw the board, then have someone click, draw a dot, then go back to the top of the while loop, wipe the screen and try again. I've tried a couple different options but none have seemed to work for me.</p> <pre><code>def play_game(): """ When this function runs, allows the user to play a game of Connect 4 against another person """ turn = 1 is_winner = False while is_winner == False: # Clears screen clear() # Draws empty board centers = draw_board() # Decides whose turn it is, change color appropriately if turn % 2 == 0: color = RED else: color = BLACK # Gets coordinates of click penup() onscreenclick(goto) dot(HOLE_SIZE, color) turn += 1 </code></pre>
0
2016-07-29T15:38:16Z
38,676,484
<p>As well intentioned as the other answers are, I don't believe either addresses the actual problem. You've locked out events by introducing an infinite loop in your code:</p> <pre><code>is_winner = False while is_winner == False: </code></pre> <p>You can't do this with turtle graphics -- you set up the event handlers and initialization code but turn control over to the main loop event handler. My following rework show how you might do so:</p> <pre><code>import turtle colors = ["red", "black"] HOLE_SIZE = 2 turn = 0 is_winner = False def draw_board(): pass return (0, 0) def dot(color): turtle.color(color, color) turtle.stamp() def goto(x, y): global turn, is_winner # add code to determine if we have a winner if not is_winner: # Clears screen turtle.clear() turtle.penup() # Draws empty board centers = draw_board() turtle.goto(x, y) # Decides whose turn it is, change color appropriately color = colors[turn % 2 == 0] dot(color) turn += 1 else: pass def start_game(): """ When this function runs, sets up a new game of Connect 4 against another person """ global turn, is_winner turn = 1 is_winner = False turtle.shape("circle") turtle.shapesize(HOLE_SIZE) # Gets coordinates of click turtle.onscreenclick(goto) start_game() turtle.mainloop() </code></pre> <p>Run it and you'll see the desired behavior you described.</p>
1
2016-07-30T17:10:35Z
[ "python", "turtle-graphics" ]
Return with argument inside generator
38,662,643
<p>I know there's a similar question already asked, but doesn't answer what I need, as mine is a little different.</p> <p>My code:</p> <pre><code>def tFileRead(fileName, JSON=False): with open(fileName) as f: if JSON: return json.load(f) for line in f: yield line.rstrip('\n') </code></pre> <p>What I want to do: if <code>JSON</code> is true, it means its reading from a json file and I want to return <code>json.load(f)</code>, otherwise, I want to yield the lines of the file into a generator.</p> <p>I've tried the alternative of converting the generator into json, but that got very messy, very fast, and doesn't work very well.</p>
3
2016-07-29T15:38:43Z
38,662,904
<p>The first solution that came to my mind was to explicitly return a generator object which would provide the exact behavior you tried to achieve.</p> <p>The problem is: if you explicitly returned a generator object like this <code>return (line.rstrip('\n') for line in f)</code> the file would be closed after returning and any further reading from the file would raise an exception.</p> <p>You should write two functions here: one that reads a json file and one for the normal file. Then you can write a wrapper that desides on an argument which of these two functions to call.</p> <p>Or just move the iteration part into another function like this:</p> <pre><code>def iterate_file(file_name): with open(file_name) as fin: for line in fin: yield line.rstrip("\n") def file_read(file_name, as_json=False): if as_json: with open(file_name) as fin: return json.load(fin) else: return iterate_file(file_name) </code></pre>
1
2016-07-29T15:52:34Z
[ "python", "json", "generator", "readfile" ]
Return with argument inside generator
38,662,643
<p>I know there's a similar question already asked, but doesn't answer what I need, as mine is a little different.</p> <p>My code:</p> <pre><code>def tFileRead(fileName, JSON=False): with open(fileName) as f: if JSON: return json.load(f) for line in f: yield line.rstrip('\n') </code></pre> <p>What I want to do: if <code>JSON</code> is true, it means its reading from a json file and I want to return <code>json.load(f)</code>, otherwise, I want to yield the lines of the file into a generator.</p> <p>I've tried the alternative of converting the generator into json, but that got very messy, very fast, and doesn't work very well.</p>
3
2016-07-29T15:38:43Z
38,663,237
<p>You could <code>yield from</code> the dictionary loaded with JSON, thus iterating over the key-value-pairs in the dict, but this would not be your desired behaviour.</p> <pre><code>def tFileRead(fileName, JSON=False): with open(fileName) as f: if JSON: yield from json.load(f).items() # works, but differently for line in f: yield line.rstrip('\n') </code></pre> <p>It would be nice if you could just return a generator, but this will not work, since using <code>with</code>, the file is closed as soon as the function returns, i.e. before the generator is consumed.</p> <pre><code>def tFileRead(fileName, JSON=False): with open(fileName) as f: if JSON: return json.load(f) else: return (line.rstrip('\n') for line in f) # won't work </code></pre> <p>Alternatively, you could define another function just for yielding the lines from the file and use that in the generator:</p> <pre><code>def tFileRead(fileName, JSON=False): if JSON: with open(fileName) as f: return json.load(f) else: def withopen(fileName): with open(fileName) as f: yield from f return (line.rstrip('\n') for line in withopen(fileName)) </code></pre> <p>But once you are there, you can really just use two separate functions for reading the file en-block as JSON or for iterating the lines...</p>
0
2016-07-29T16:12:14Z
[ "python", "json", "generator", "readfile" ]
Finding Row with No Empty Strings
38,662,656
<p>I am trying to determine the type of data contained in each column of a <code>.csv</code> file so that I can make <code>CREATE TABLE</code> statements for MySQL. The program makes a list of all the column headers and then grabs the first row of data and determines each data type and appends it to the column header for proper syntax. For example:</p> <pre><code>ID Number Decimal Word 0 17 4.8 Joe </code></pre> <p>That would produce something like <code>CREATE TABLE table_name (ID int, Number int, Decimal float, Word varchar());</code>.</p> <p>The problem is that in some of the <code>.csv</code> files the first row contains a <code>NULL</code> value that is read as an empty string and messes up this process. My goal is to then search each row until one is found that contains no <code>NULL</code> values and use that one when forming the statement. This is what I have done so far, except it sometimes still returns rows that contains empty strings:</p> <pre><code>def notNull(p): # where p is a .csv file that has been read in another function tempCol = next(p) tempRow = next(p) col = tempCol[:-1] row = tempRow[:-1] if any('' in row for row in p): tempRow = next(p) row = tempRow[:-1] else: rowNN = row return rowNN </code></pre> <p><em>Note: The <code>.csv</code> file reading is done in a different function, whereas this function simply uses the already read <code>.csv</code> file as input <code>p</code>. Also each row is ended with a <code>,</code> that is treated as an extra empty string so I slice the last value off of each row before checking it for empty strings.</em></p> <p><strong>Question:</strong> What is wrong with the function that I created that causes it to not always return a row without empty strings? I feel that it is because the loop is not repeating itself as necessary but I am not quite sure how to fix this issue.</p>
0
2016-07-29T15:39:08Z
38,663,479
<p>I cannot really decipher your code. This is what I would do to only get rows without the empty string.</p> <pre><code>import csv def g(name): with open('file.csv', 'r') as f: r = csv.reader(f) # Skip headers row = next(r) for row in r: if '' not in row: yield row for row in g('file.csv'): print('row without empty values: {}'.format(row)) </code></pre>
2
2016-07-29T16:25:48Z
[ "python", "python-3.x", "csv" ]
matplotlib and subplots properties
38,662,667
<p>I'm adding a matplotlib figure to a canvas so that I may integrate it with pyqt in my application. I were looking around and using <code>plt.add_subplot(111)</code> seem to be the way to go(?) But I cannot add any properties to the subplot as I may with an "ordinary" plot</p> <p>figure setup</p> <pre><code>self.figure1 = plt.figure() self.canvas1 = FigureCanvas(self.figure1) self.graphtoolbar1 = NavigationToolbar(self.canvas1, frameGraph1) hboxlayout = qt.QVBoxLayout() hboxlayout.addWidget(self.graphtoolbar1) hboxlayout.addWidget(self.canvas1) frameGraph1.setLayout(hboxlayout) </code></pre> <p>creating subplot and adding data</p> <pre><code>df = self.quandl.getData(startDate, endDate, company) ax = self.figure1.add_subplot(111) ax.hold(False) ax.plot(df['Close'], 'b-') ax.legend(loc=0) ax.grid(True) </code></pre> <p>I'd like to set x and y labels, but if I do <code>ax.xlabel("Test")</code></p> <pre><code>AttributeError: 'AxesSubplot' object has no attribute 'ylabel' </code></pre> <p>which is possible if I did it by not using subplot </p> <pre><code>plt.figure(figsize=(7, 4)) plt.plot(df['Close'], 'k-') plt.grid(True) plt.legend(loc=0) plt.xlabel('value') plt.ylabel('frequency') plt.title('Histogram') locs, labels = plt.xticks() plt.setp(labels, rotation=25) plt.show() </code></pre> <p>So I guess my question is, is it not possible to modify subplots further? Or is it possible for me to plot graphs in a pyqt canvas, without using subplots so that I may get benefit of more properties for my plots.</p>
1
2016-07-29T15:39:57Z
38,662,845
<p><code>plt.subplot</code> returns a subplot object which is a type of axes object. It has two methods for adding axis labels: <a href="http://matplotlib.org/api/axes_api.html#matplotlib.axes.Axes.set_xlabel" rel="nofollow"><code>set_xlabel</code></a> and <a href="http://matplotlib.org/api/axes_api.html#matplotlib.axes.Axes.set_ylabel" rel="nofollow"><code>set_ylabel</code></a>:</p> <pre><code>ax = plt.subplot('111') ax.set_xlabel('X Axis') ax.set_ylabel('Y Axis') </code></pre> <p>You could also call <code>plt.xlabel</code> and <code>plt.ylabel</code> (like you did before) and specify the axes to which you want the label applied.</p> <pre><code>ax = plt.subplot('111') plt.xlabel('X Axis', axes=ax) plt.ylabel('Y Axis', axes=ax) </code></pre> <p>Since you only have one axes, you could also omit the <code>axes</code> kwarg since the label will automatically be applied to the current axes if one isn't specified.</p> <pre><code>ax = plt.subplot('111') plt.xlabel('X Axis') plt.ylabel('Y Axis') </code></pre>
2
2016-07-29T15:49:36Z
[ "python", "matplotlib" ]
Summing values from array and get a double
38,662,685
<p>I'm trying to run this loop to get <code>n</code> to be a decimal number. However, if I call values from the vector <code>p</code>, <code>n</code> also becomes a vector. </p> <p>How do I fix that?</p> <p>lamb=linspace(400,800,num=20)</p> <pre><code>for k in 1/lamb: AR2 = 1.55 p = [-0.003396, 0.6518, 66.01, 2435] n = 0.00 for i in range(0, 3): n = n + AR2+ p[i]/k**(10-i) </code></pre>
0
2016-07-29T15:41:07Z
38,662,843
<p><code>linspace(400,800,num=20)</code> is an array. Performing operations on it does it element-wise. For example:</p> <pre><code>&gt;&gt;&gt; linspace(400,800,num=20) array([ 400. , 421.05263158, 442.10526316, 463.15789474, 484.21052632, 505.26315789, 526.31578947, 547.36842105, 568.42105263, 589.47368421, 610.52631579, 631.57894737, 652.63157895, 673.68421053, 694.73684211, 715.78947368, 736.84210526, 757.89473684, 778.94736842, 800. ]) &gt;&gt;&gt; 2 + linspace(400,800,num-20) array([ 402. , 423.05263158, 444.10526316, 465.15789474, 486.21052632, 507.26315789, 528.31578947, 549.36842105, 570.42105263, 591.47368421, 612.52631579, 633.57894737, 654.63157895, 675.68421053, 696.73684211, 717.78947368, 738.84210526, 759.89473684, 780.94736842, 802. ]) </code></pre> <p>You can't just add or multiply an array by floats and get a float back. THe problem isn't with <code>p</code>, it's <code>linspace</code></p>
1
2016-07-29T15:49:32Z
[ "python", "arrays", "loops", "for-loop", "vector" ]
Summing values from array and get a double
38,662,685
<p>I'm trying to run this loop to get <code>n</code> to be a decimal number. However, if I call values from the vector <code>p</code>, <code>n</code> also becomes a vector. </p> <p>How do I fix that?</p> <p>lamb=linspace(400,800,num=20)</p> <pre><code>for k in 1/lamb: AR2 = 1.55 p = [-0.003396, 0.6518, 66.01, 2435] n = 0.00 for i in range(0, 3): n = n + AR2+ p[i]/k**(10-i) </code></pre>
0
2016-07-29T15:41:07Z
38,663,053
<p>If I set <code>lamb</code> and <code>AR2</code> to be numbers then I don't see <code>n</code> becoming an array i.e </p> <pre><code>AR2 = 1.55 p = [-0.003396, 0.6518, 66.01, 2435] n = 0.00 lamb = 0.97 AR2 = 1 for i in range(0, 3): n = n + AR2+ p[i]*lamb**(10-i) print(n) </code></pre> <p>Returns: </p> <pre><code> 0.9974957076650648 4930143116961103 55.22791346817842 </code></pre> <p>I hope this helps!</p>
0
2016-07-29T16:00:11Z
[ "python", "arrays", "loops", "for-loop", "vector" ]
Array Map to a unique key after discretization
38,662,744
<p>I have A 1D numpy observation array example [a,b,c,d]. a,b,c,d takes continous values, with each of them belonging to different finite domain.Example a lies from -2. to 2. etc.</p> <p>My goal is to map any such observation to a single number. Example [1,2,-3,4] and [1,2,-2.7,4] gets mapped to same number x, with the help of discretization. Also [1 0 0 1] and [0 1 1 0 ] should be mapped to seperate unique numbers!</p> <p>How would i go about this with numpy.</p>
0
2016-07-29T15:44:15Z
38,664,358
<p>If your discretization process is taking the nearest whole number (rounding towards minus infinity rather than towards zero) then you could do something like this</p> <pre><code>&gt;&gt;&gt; a = np.array([-1.6, -0.5, 1.2, 2.2]) &gt;&gt;&gt; (np.floor(a + 0.5) * [1000, 100, 10, 1]).sum() -1988.0 </code></pre>
0
2016-07-29T17:25:56Z
[ "python", "arrays", "numpy" ]
wxpython wx.Slider: how to fire an event only if a user pauses for some predetermined time
38,662,800
<p>I have a <code>wx.Slider</code> widget that is bound to an event handler. As a user moves the slider, some process will run. However, because the process can take up to 3 seconds to run, I don't want the event to fire continuously as the user moves the slider. Instead, I want the event to fire only if the user stops moving the slider for some amount of time (say, 2 seconds). I tried using <code>time.time()</code> with a <code>while</code>-loop (see code below), but it didn't work because the event would still fire repeatedly -- it's just that the firing got delayed. Any idea/pointer/suggestion would be greatly appreciated.</p> <pre><code>import wx import time class Example(wx.Frame): def __init__(self, *args, **kw): super(Example, self).__init__(*args, **kw) self.InitUI() def InitUI(self): pnl = wx.Panel(self) sld = wx.Slider(pnl, value=200, minValue=150, maxValue=500, pos=(20, 20), size=(250, -1), style=wx.SL_HORIZONTAL) self.counter = 0 sld.Bind(wx.EVT_SCROLL, self.OnSliderScroll) self.txt = wx.StaticText(pnl, label='200', pos=(20, 90)) self.SetSize((290, 200)) self.SetTitle('wx.Slider') self.Centre() self.Show(True) def OnSliderScroll(self, e): now = time.time() future = now + 2 while time.time() &lt; future: pass #substitute for the actual process. self.counter += 1 print self.counter def main(): ex = wx.App() Example(None) ex.MainLoop() if __name__ == '__main__': main() </code></pre>
0
2016-07-29T15:47:25Z
38,666,741
<p>Delaying with <code>time.sleep</code> will block your GUI. Use <code>wx.CallLater</code> instead, which in the sample below will trigger the delayed event until it has been restarted again.</p> <pre><code> def InitUi(self): # ... # Add a delay timer, set it up and stop it self.delay_slider_evt = wx.CallLater(2000, self.delayed_event) self.delay_slider_evt.Stop() def OnSliderScroll(self, e): # if delay timer does not run, start it, either restart it if not self.delay_slider_evt.IsRunning(): self.delay_slider_evt.Start(2000) else: self.delay_slider_evt.Restart(2000) def delayed_event(self): #substitute for the actual delayed process. self.counter += 1 print self.counter </code></pre>
1
2016-07-29T20:09:49Z
[ "python", "events", "event-handling", "slider", "wxpython" ]
Sort pandas DataFrame with function over column values
38,662,826
<p>Based on <a href="http://stackoverflow.com/questions/24988873/python-sort-descending-dataframe-with-pandas">python, sort descending dataframe with pandas</a>:</p> <p>Given:</p> <pre><code>from pandas import DataFrame import pandas as pd d = {'one':[2,3,1,4,5], 'two':[5,4,3,2,1], 'letter':['a','a','b','b','c']} df = DataFrame(d) </code></pre> <p>df then looks like this:</p> <pre><code>df: letter one two 0 a 2 5 1 a 3 4 2 b 1 3 3 b 4 2 4 c 5 1 </code></pre> <p>I would like to have something like:</p> <pre><code>f = lambda x,y: x**2 + y**2 test = df.sort(f('one', 'two')) </code></pre> <p>This should order the complete dataframe with respect to the sum of the squared values of column 'one' and 'two' and give me:</p> <pre><code>test: letter one two 2 b 1 3 3 b 4 2 1 a 3 4 4 c 5 1 0 a 2 5 </code></pre> <p>Ascending or descending order does not matter. Is there a nice and simple way to do that? I could not yet find a solution.</p>
2
2016-07-29T15:48:43Z
38,663,274
<p>Have you tried to create a new column and then sorting on that. I cannot comment on the original post, so i am just posting my solution.</p> <pre><code>df['c'] = df.a**2 + df.b**2 df = df.sort_values('c') </code></pre>
0
2016-07-29T16:14:37Z
[ "python", "sorting", "pandas", "dataframe" ]
Sort pandas DataFrame with function over column values
38,662,826
<p>Based on <a href="http://stackoverflow.com/questions/24988873/python-sort-descending-dataframe-with-pandas">python, sort descending dataframe with pandas</a>:</p> <p>Given:</p> <pre><code>from pandas import DataFrame import pandas as pd d = {'one':[2,3,1,4,5], 'two':[5,4,3,2,1], 'letter':['a','a','b','b','c']} df = DataFrame(d) </code></pre> <p>df then looks like this:</p> <pre><code>df: letter one two 0 a 2 5 1 a 3 4 2 b 1 3 3 b 4 2 4 c 5 1 </code></pre> <p>I would like to have something like:</p> <pre><code>f = lambda x,y: x**2 + y**2 test = df.sort(f('one', 'two')) </code></pre> <p>This should order the complete dataframe with respect to the sum of the squared values of column 'one' and 'two' and give me:</p> <pre><code>test: letter one two 2 b 1 3 3 b 4 2 1 a 3 4 4 c 5 1 0 a 2 5 </code></pre> <p>Ascending or descending order does not matter. Is there a nice and simple way to do that? I could not yet find a solution.</p>
2
2016-07-29T15:48:43Z
38,663,354
<p>You can create a temporary column to use in sort and then drop it:</p> <pre><code>df.assign(f = df['one']**2 + df['two']**2).sort_values('f').drop('f', axis=1) Out: letter one two 2 b 1 3 3 b 4 2 1 a 3 4 4 c 5 1 0 a 2 5 </code></pre>
3
2016-07-29T16:18:44Z
[ "python", "sorting", "pandas", "dataframe" ]
Sort pandas DataFrame with function over column values
38,662,826
<p>Based on <a href="http://stackoverflow.com/questions/24988873/python-sort-descending-dataframe-with-pandas">python, sort descending dataframe with pandas</a>:</p> <p>Given:</p> <pre><code>from pandas import DataFrame import pandas as pd d = {'one':[2,3,1,4,5], 'two':[5,4,3,2,1], 'letter':['a','a','b','b','c']} df = DataFrame(d) </code></pre> <p>df then looks like this:</p> <pre><code>df: letter one two 0 a 2 5 1 a 3 4 2 b 1 3 3 b 4 2 4 c 5 1 </code></pre> <p>I would like to have something like:</p> <pre><code>f = lambda x,y: x**2 + y**2 test = df.sort(f('one', 'two')) </code></pre> <p>This should order the complete dataframe with respect to the sum of the squared values of column 'one' and 'two' and give me:</p> <pre><code>test: letter one two 2 b 1 3 3 b 4 2 1 a 3 4 4 c 5 1 0 a 2 5 </code></pre> <p>Ascending or descending order does not matter. Is there a nice and simple way to do that? I could not yet find a solution.</p>
2
2016-07-29T15:48:43Z
38,663,355
<pre><code>from pandas import DataFrame import pandas as pd d = {'one':[2,3,1,4,5], 'two':[5,4,3,2,1], 'letter':['a','a','b','b','c']} df = pd.DataFrame(d) #f = lambda x,y: x**2 + y**2 array = [] for i in range(5): array.append(df.ix[i,1]**2 + df.ix[i,2]**2) array = pd.DataFrame(array, columns = ['Sum of Squares']) test = pd.concat([df,array],axis = 1, join = 'inner') test = test.sort_index(by = "Sum of Squares", ascending = True).drop('Sum of Squares',axis =1) </code></pre> <p>Just realized that you wanted this: </p> <pre><code> letter one two 2 b 1 3 3 b 4 2 1 a 3 4 4 c 5 1 0 a 2 5 </code></pre>
1
2016-07-29T16:18:44Z
[ "python", "sorting", "pandas", "dataframe" ]
Directory browser and entry bar using Tkinter
38,662,829
<p>I have managed to have an opening page, followed by a second page which contains a file browser button. I would like to have the option for user entry to this file browser (copy and paste into an entry bar). Following either the directory being user entered, or browsed using the button, I would like the directory to appear in the bar. </p> <pre><code>import tkinter as tk from tkinter import ttk from tkinter.filedialog import askdirectory LARGE_FONT= ("Calibri", 12) class RevitJournalSearch(tk.Tk): def __init__(self, *args, **kwargs): tk.Tk.__init__(self, *args, **kwargs) container = tk.Frame(self) container.pack(side="top", fill="both", expand = True) container.grid_rowconfigure(0, weight=1) container.grid_columnconfigure(0, weight=1) self.frames = {} for F in (StartPage, PageOne): frame = F(container, self) self.frames[F] = frame frame.grid(row=0, column=0, sticky="nsew") self.show_frame(StartPage) def show_frame(self, cont): frame = self.frames[cont] frame.tkraise() class StartPage(tk.Frame): def __init__(self, parent, controller): tk.Frame.__init__(self,parent) label = ttk.Label(self, text="""What to expect from this... \n \n-Browse folder location""", font=LARGE_FONT) label.pack(pady=10,padx=10) button1 = ttk.Button(self, text="Continue", command=lambda: controller.show_frame(PageOne)) button1.pack() button2 = ttk.Button(self, text="Close", command=quit) button2.pack() class PageOne(tk.Frame): def __init__(self, parent, controller, master): tk.Frame.__init__(self,parent) label = ttk.Label(self, text="File Select", font=LARGE_FONT) label.pack(pady=10,padx=10) errmsg = 'Error!' button_browser = ttk.Button(self, text="BROWSE", command= self.callback) button_browser.pack() def callback(self): self.name= askdirectory() app = RevitJournalSearch() app.mainloop() </code></pre> <p>I'm not sure where to place the <code>self.entry</code> code.</p>
0
2016-07-29T15:49:04Z
38,663,497
<p>I believe this is a duplicate of <a href="http://stackoverflow.com/questions/25282883/how-can-i-use-the-output-from-tkfiledialog-askdirectory-to-fill-a-tkinter-entry">this question</a>. What it boils down to is the following.</p> <ol> <li><p>Create a <a href="http://effbot.org/tkinterbook/variable.htm" rel="nofollow"><code>StringVar</code></a> variable, and then create an entry box that is dependent on this <code>StringVar</code>. The box will display whatever this variable is currently holding.</p> <pre><code>self.name = tk.StringVar() dir_box = tk.Entry(self, textvariable=self.name) </code></pre></li> <li><p>Set this variable with the return value of your <code>askdirectory</code> call.</p> <pre><code>def callback(self): filename = tkFileDialog.askdirectory() self.name.set(filename) </code></pre></li> </ol>
1
2016-07-29T16:27:18Z
[ "python", "tkinter", "entry", "file-browser" ]
how to query sympy constraints?
38,662,859
<p>At some point in my code, I add an upper constraint on a sympy symbol. <code>sympy.refine(x, sympy.Q.positive(upper_bound - x))</code></p> <p>I would liketo retrieve programmaticaly from the symbol "x" the value of upper_bound (and other constraints). Any idea as how to achieve this ?</p> <p>cheers</p>
2
2016-07-29T15:50:21Z
38,735,025
<p>The refine function does not work that way - it just simplifies an expression given a constraint. For example:</p> <pre><code>In [54]: import sympy In [55]: x = sympy.S('x') In [56]: expr = sympy.S('sqrt(x**2)') In [57]: sympy.refine(expr, sympy.Q.positive(x)) Out[57]: x In [58]: sympy.refine(expr, sympy.Q.negative(x)) Out[58]: -x In [59]: sympy.refine(expr, sympy.Q.real(x)) Out[59]: Abs(x) </code></pre> <p>Unfortunately, the use of inequalities does not appear to do anything useful at the moment:</p> <pre><code>In [62]: sympy.refine(expr, sympy.Q.is_true(x&gt;0)) Out[62]: sqrt(x**2) </code></pre> <p>You could probably do something useful with solveset:</p> <pre><code>In [68]: expr = sympy.S('A * x**2 + B * x + C') In [69]: sympy.solveset(expr, x, sympy.Interval(1,10)) Out[69]: ConditionSet(x, Eq(A*x**2 + B*x + C, 0), [1, 10]) </code></pre> <p>Or maybe a more useful example:</p> <pre><code>In [19]: a = sympy.S('(x**2)*(sin(x)+x)') In [20]: x = sympy.S('x') In [25]: b = sympy.solveset(a,x,sympy.Interval(-2,2)) In [26]: b Out[26]: ConditionSet(x, Eq(x + sin(x), 0), [-2, 2]) In [34]: b.base_set Out[34]: [-2, 2] </code></pre>
1
2016-08-03T05:24:18Z
[ "python", "sympy" ]
Create array with elements inserted without using np.insert
38,662,999
<p>I have two arrays, say,</p> <pre><code>n = [1,2,3,4,5,6,7,8,9] nc = [3,0,2,0,1,2,0,0,0] </code></pre> <p>The nonzero elements in nc are <code>ncz = [3,2,1,2]</code>. The elements in n corresponding to non zero elements in nc are <code>p = [1,3,5,6]</code>. I need to create a new array with elements of <code>p[1:]</code> inserted after <code>ncz.cumsum()[:-1]+1</code> i.e after <code>[4,6,7]</code> Is there any way to do this without using np.insert or a for loop? Suppose I have m such pairs of arrays. Would I be able to do the same thing for each pair without using a loop? The resulting arrays can be zero padded to bring them to the same shape. The result would be <code>[1, 2, 3, 4, 3, 5, 6, 5, 7, 6, 8, 9]</code></p> <p>To do it using np.insert, one would do:</p> <pre><code>n = np.array([1,2,3,4,5,6,7,8,9]) nc = np.array([3,0,2,0,1,2,0,0,0]) p1 = n[nc.nonzero()][1:] ncz1 = nc[nc.nonzero()][:-1].cumsum() result = np.insert(n,ncz1+1,p1) </code></pre> <p>I know how to do this using numpy insert operation, but I need to replicate it in theano and theano doesn't have an insert op.</p>
0
2016-07-29T15:57:37Z
38,667,908
<p>Because of its generality <code>np.insert</code> is rather complex (but available for study), but for your case, with a 1d array, and order insert points, it can be simplified to</p> <p><code>np.insert(n, i, p1)</code> with:</p> <pre><code>In [688]: n Out[688]: array([1, 2, 3, 4, 5, 6, 7, 8, 9]) In [689]: p1 Out[689]: array([13, 15, 16]) In [690]: i Out[690]: array([4, 6, 7], dtype=int32) </code></pre> <p>Target array, <code>z</code>, and the insertion points in that array:</p> <pre><code>In [691]: j=i+np.arange(len(i)) In [692]: z=np.zeros(len(n)+len(i),dtype=n.dtype) </code></pre> <p>make a boolean mask - True where <code>n</code> values go, <code>False</code> where <code>p1</code> values go.</p> <pre><code>In [693]: ind=np.ones(z.shape,bool) In [694]: ind[j]=False In [695]: ind Out[695]: array([ True, True, True, True, False, True, True, False, True, False, True, True], dtype=bool) </code></pre> <p>copy values in to the right slots:</p> <pre><code>In [696]: z[ind]=n In [697]: z[~ind]=p1 # z[j]=p1 would also work In [698]: z Out[698]: array([ 1, 2, 3, 4, 13, 5, 6, 15, 7, 16, 8, 9]) </code></pre> <p>This is typical of array operations that return a new array of a different size. Make the target, and copy the appropriate values. This is true even when the operations are done in compiled <code>numpy</code> code (e.g. <code>concatenate</code>).</p>
1
2016-07-29T21:44:09Z
[ "python", "arrays", "numpy" ]
Preventing multiple matches in list iteration
38,663,046
<p>I am relatively new to python, so I will try my best to explain what I am trying to do. I am trying to iterate through two lists of stars (which both contain record arrays), trying to match stars by their coordinates with a tolerance (in this case Ra and Dec, which are both indices within the record arrays). However, there appears to be multiple stars from one list that match the same star in the other. *This is due to both stars matching within the atol. Is there a way to prevent this? Here's what I have so far:</p> <pre><code>from __future__ import print_function import numpy as np ###importing data### Astars = list() for s in ApStars:###this is imported but not shown Astars.append(s) wStars = list() data1 = np.genfromtxt('6819.txt', dtype=None, delimiter=',', names=True) for star in data1: wStars.append(star) ###beginning matching stars between the Astars and wStars### list1 = list() list2 = list() for star,s in [(star,s) for star in wStars for s in Astars]: if np.logical_and(np.isclose(s["RA"],star["RA"], atol=0.000277778)==True , np.isclose(s["DEC"],star["DEC"],atol=0.000277778)==True): if star not in list1: list1.append(star) #matched wStars if s not in list2: list2.append(s) #matched Astars </code></pre> <p>I cannot decrease the atol because it goes beyond the instrumental error. What happens is this: There are multiple Wstars that match one Astar. I just want a star for a star, if it is possible.</p> <p>Any suggestions?</p>
6
2016-07-29T15:59:48Z
38,663,883
<p>First time answering a Question here (if I made a mistake please indicate).But it would seems that what David commented is correct in that "star is always in list1 (and s is always in list2". So I would suggest comparing and appending to a newlist1/newlist1 that keeps track of star and s.</p> <pre><code>newlist1 = list() newlist2 = list() #new list will keep the unique star and s for star in list1: for s in list2: #assuming the comparison works haven't test it yet if np.logical_and(np.isclose(s["RA"],star["RA"], atol=0.000277778)==True , np.isclose(s["DEC"],star["DEC"],atol=0.000277778)==True): if star not in newlist1: newlist1.append(s) if s not in newlist2: newlist2.append(s) break #once a match is found leave the second loop </code></pre>
0
2016-07-29T16:53:51Z
[ "python", "numpy" ]
Preventing multiple matches in list iteration
38,663,046
<p>I am relatively new to python, so I will try my best to explain what I am trying to do. I am trying to iterate through two lists of stars (which both contain record arrays), trying to match stars by their coordinates with a tolerance (in this case Ra and Dec, which are both indices within the record arrays). However, there appears to be multiple stars from one list that match the same star in the other. *This is due to both stars matching within the atol. Is there a way to prevent this? Here's what I have so far:</p> <pre><code>from __future__ import print_function import numpy as np ###importing data### Astars = list() for s in ApStars:###this is imported but not shown Astars.append(s) wStars = list() data1 = np.genfromtxt('6819.txt', dtype=None, delimiter=',', names=True) for star in data1: wStars.append(star) ###beginning matching stars between the Astars and wStars### list1 = list() list2 = list() for star,s in [(star,s) for star in wStars for s in Astars]: if np.logical_and(np.isclose(s["RA"],star["RA"], atol=0.000277778)==True , np.isclose(s["DEC"],star["DEC"],atol=0.000277778)==True): if star not in list1: list1.append(star) #matched wStars if s not in list2: list2.append(s) #matched Astars </code></pre> <p>I cannot decrease the atol because it goes beyond the instrumental error. What happens is this: There are multiple Wstars that match one Astar. I just want a star for a star, if it is possible.</p> <p>Any suggestions?</p>
6
2016-07-29T15:59:48Z
38,664,333
<p>I would change your approach entirely to fit the fact that these are astronomical objects you are talking about. I will ignore the loading functionality and assume that you already have your input lists <code>Astar</code> and <code>wStar</code>.</p> <p>We will find the <em>closest</em> star in <code>wStar</code> to each star in <code>Astar</code> using a Cartesian dot product. That <em>should</em> help resolve any ambiguities about the best match.</p> <pre><code># Pre-process the data a little def getCV(ra, de): return np.array([np.cos(aStar['DE']) * np.cos(aStar['RA']), np.cos(aStar['DE']) * np.sin(aStar['RA']), np.sin(aStar['DE'])]) for aStar in Astars: aStar['CV'] = getCV(aStar['RA'], aStar['DE']) for wStar in wStars: wStar['CV'] = getCV(wStar['RA'], wStar['DE']) # Construct lists of matching stars aList = [] wList = [] # This an extra list of lists of stars that are within tolerance but are # not best matches. This list will contain empty sublists, but never None wCandidates [] for aStar in AStars: for wStar in wStars: # Use native short-circuiting, and don't explicitly test for `True` if np.isclose(aStar["RA"], wStar["RA"], atol=0.000277778) and \ np.isclose(aStar["DEC"], wStar["DEC"], atol=0.000277778): newDot = np.dot(aStar['CV'], wStar['CV']) if aStar == aList[-1]: # This star already has a match, possibly update it if newDot &gt; bestDot: bestDot = newDot # Move the previous best match to list of candidates wCandidates[-1].append(wList[-1]) wList[-1] = wStar else: wCandidates[-1].append(wStar) else: # This star does not yet have a match bestDot = newDot aList.append(aStar) wList.append(wStar) wCandidates.append([]) </code></pre> <p>The result is that the stars at each index in <code>wList</code> represent the best match for the corresponding star in <code>aList</code>. Not all stars have a match at all, so not all stars will appear in either of the lists. Note that there may be some (very unlikely) cases where a star in <code>aList</code> is not the best match for the one in <code>wList</code>.</p> <p>We find the closest absolute distance between two stars by computing the Cartesian unit vectors based on <a href="http://www.astronexus.com/a-a/positions" rel="nofollow">these formulas</a> and taking the dot product. The closer the dot is to one, the closer the stars are together. This should help resolve the ambiguities.</p> <p>I pre-computed the cartesian vectors for the stars outside the main loop to avoid doing it over and over for <code>wStars</code>. The key name <code>'CV'</code> stands for Cartesian Vector. Change it as you see fit.</p> <p>Final note, this method does not check that a star from <code>wStars</code> matches with more than one <code>AStar</code>. It just ensures that the best <code>wStar</code> is selected for each <code>AStar</code>.</p> <p><strong>UPDATE</strong></p> <p>I added a third list to the output, which lists all the <code>wStars</code> candidates that were within tolerance of the corresponding <code>AStars</code> element, but did not get chosen as the best match.</p>
1
2016-07-29T17:24:30Z
[ "python", "numpy" ]
Preventing multiple matches in list iteration
38,663,046
<p>I am relatively new to python, so I will try my best to explain what I am trying to do. I am trying to iterate through two lists of stars (which both contain record arrays), trying to match stars by their coordinates with a tolerance (in this case Ra and Dec, which are both indices within the record arrays). However, there appears to be multiple stars from one list that match the same star in the other. *This is due to both stars matching within the atol. Is there a way to prevent this? Here's what I have so far:</p> <pre><code>from __future__ import print_function import numpy as np ###importing data### Astars = list() for s in ApStars:###this is imported but not shown Astars.append(s) wStars = list() data1 = np.genfromtxt('6819.txt', dtype=None, delimiter=',', names=True) for star in data1: wStars.append(star) ###beginning matching stars between the Astars and wStars### list1 = list() list2 = list() for star,s in [(star,s) for star in wStars for s in Astars]: if np.logical_and(np.isclose(s["RA"],star["RA"], atol=0.000277778)==True , np.isclose(s["DEC"],star["DEC"],atol=0.000277778)==True): if star not in list1: list1.append(star) #matched wStars if s not in list2: list2.append(s) #matched Astars </code></pre> <p>I cannot decrease the atol because it goes beyond the instrumental error. What happens is this: There are multiple Wstars that match one Astar. I just want a star for a star, if it is possible.</p> <p>Any suggestions?</p>
6
2016-07-29T15:59:48Z
38,665,487
<p>I haven't fully absorbed your issues, but I'll start with trying to simplify your calculation.</p> <p>Looks like <code>Apstars</code> and <code>data1</code> are structured arrays, both 1d with the same <code>dtype</code>.</p> <p>This list iteration could be replaced with:</p> <pre><code>Astars = list() for s in ApStars:###this is imported but not shown Astars.append(s) </code></pre> <p>with</p> <pre><code>Astarrs = list(ApStars) </code></pre> <p>or just omitted. If you can iterate on <code>ApStars</code> here, you can iterate on them in the list comprehension. Same for <code>wStars</code>.</p> <p>I'd rewrite the comparison as:</p> <pre><code>set1, set2 = set(), set() # for star,s in [(star,s) for star in data1 for s in ApStars]: # iteration on this list comprehension works, # but I think this nest iteration is clearer for star in data1: for s in ApStars: x1 = np.isclose(s["RA"],star["RA"], atol=0.000277778) x2 = np.isclose(s["DEC"],star["DEC"],atol=0.000277778) # isclose returns boolean, don't need the ==True if x1 &amp; x2: set1.add(star) set2.add(s) </code></pre> <p>Adding without replacement is easy with <code>set</code>, though the order is not defined (same as with dict).</p> <p>I'd like to explore whether 'extracting' the relevant fields before iteration is would help.</p> <pre><code>Apstars['RA'], data1['RA'], Apstars['DEC'], data1['DEC'] x1 = np.isclose(Apstars['RA'][:,None], data1['RA'], atol=...) x2 = np.isclose(Apstars['DEC']....) x12 = x1 &amp; x2 </code></pre> <p><code>x12</code> is a 2d boolean array; <code>x12[i,j]</code> is True when <code>Apstars[i]</code> is 'close' to <code>data1[j]</code>.</p>
0
2016-07-29T18:36:27Z
[ "python", "numpy" ]