title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
list
Regular expression to replace all occurrences of U.S
39,502,301
<p>I'm trying to write a regular expression to replace all occurrences of U.S. . Here's what I thought would work.</p> <pre><code>string = re.sub(r'\bU.S.\b', 'U S ', string) </code></pre> <p>When I run this it only finds the first occurrence. Why is this and how can I resolve this issue. Thanks </p>
0
2016-09-15T02:27:37Z
39,502,402
<p>if you are searching in a file, to find all occurrences and replace them, you need to search line by line.</p> <p>the . need to be \. because . itself has other meanings in RE. A safer way to implement is to write \b+ so it counts for 1 or more such cases.</p> <p>r doesnt mean repeat, it means escape character wont be processed</p> <p>by the way, you dont need to worry \b after the . because the RE will match everything before that, and ignore what is not matching. You are indeed getting the first part printed first time while you have the wrong RE, right?</p>
0
2016-09-15T02:45:16Z
[ "python" ]
Compare columns of Pandas dataframe for equality to produce True/False, even NaNs
39,502,345
<p>I have two columns in a pandas dataframe that are supposed to be identical. Each column has many NaN values. I would like to compare the columns, producing a 3rd column containing True / False values; <em>True</em> when the columns match, <em>False</em> when they do not.</p> <p>This si what I have tried:</p> <pre><code>df['new_column'] = (df['column_one] == df['column_two']) </code></pre> <p>The above works for the numbers, but not the NaN values. </p> <p>I know I could replace the NaNs with a value that doesn't make sense to be in each row (for my data this could be -9999), and then remove it later when I'm ready to echo out the comparison results, however I was wondering if there was a more pythonic method I was overlooking.</p>
1
2016-09-15T02:34:32Z
39,503,690
<p>Or you could just use the <code>equals</code> method:</p> <pre><code>df['new_column'] = df['column_one'].equals(df['column_two']) </code></pre> <p>It is a batteries included approach, and will work no matter the <code>dtype</code> or the content of the cells. You can also put it in a loop, if you want.</p>
2
2016-09-15T05:28:09Z
[ "python", "pandas", "dataframe" ]
Is there a more pythonic way to have multiple defaults arguments to a class?
39,502,385
<p>I have a class with many defaults since I can't function overload. Is there a better way than having multiple default arguments, or using kwargs? </p> <p>I thought about passing a dictionary in to my class but then how do I control whether or not the necessary arguments will be passed in? </p> <p>If there's a more pythonic way that I should be doing this?</p> <pre class="lang-py prettyprint-override"><code>class Editor: def __init__(self, ffmpeg: str, font_file=None, font_size=148, font_color="white", title_length=5, title_x="(w-text_w)/2", title_y="(h-text_h)/2", box=1, box_color="black", box_opacity=0.5, box_border_width=25): self.ffmpeg = ffmpeg self.commands = {'help': [self.ffmpeg, '-h']} self.command_sequence = [] self.titles= {"font": {"file": font_file, "size": font_size, "color": font_color}, "length": title_length, "box": {"status": box, "color": box_color, "opacity": box_opacity, "borderw": box_border_width}, "coordinates": {"x": title_x, "y": title_y}} </code></pre>
4
2016-09-15T02:41:51Z
39,502,433
<p>One way is to use <a href="https://en.wikipedia.org/wiki/Method_chaining" rel="nofollow">method chaining</a>.</p> <p>You can start with some class setting all (or most) parameters to defaults:</p> <pre><code>class Kls(object): def __init__(self): self._var0 = 0 self._var1 = 1 </code></pre> <p>Then you add methods for setting each needed one:</p> <pre><code> def set_var_0(self, val): self._var0 = val return self def set_var_1(self, val): self._var1 = val return self </code></pre> <p>Now, when you create an object, you can just set the necessary ones:</p> <pre><code>c = Kls() c = Kls().set_var_1(2) c = Kls().set_var_1(22).set_var_0(333) </code></pre> <p>Of course, you are not restricted to writing a method that sets a single parameter each time, you could write methods that set small "families" of parameters. These already might have regular default values, if needed.</p>
1
2016-09-15T02:51:02Z
[ "python", "class", "constructor", "default-arguments" ]
Is there a more pythonic way to have multiple defaults arguments to a class?
39,502,385
<p>I have a class with many defaults since I can't function overload. Is there a better way than having multiple default arguments, or using kwargs? </p> <p>I thought about passing a dictionary in to my class but then how do I control whether or not the necessary arguments will be passed in? </p> <p>If there's a more pythonic way that I should be doing this?</p> <pre class="lang-py prettyprint-override"><code>class Editor: def __init__(self, ffmpeg: str, font_file=None, font_size=148, font_color="white", title_length=5, title_x="(w-text_w)/2", title_y="(h-text_h)/2", box=1, box_color="black", box_opacity=0.5, box_border_width=25): self.ffmpeg = ffmpeg self.commands = {'help': [self.ffmpeg, '-h']} self.command_sequence = [] self.titles= {"font": {"file": font_file, "size": font_size, "color": font_color}, "length": title_length, "box": {"status": box, "color": box_color, "opacity": box_opacity, "borderw": box_border_width}, "coordinates": {"x": title_x, "y": title_y}} </code></pre>
4
2016-09-15T02:41:51Z
39,502,480
<p>You can specify default attributes on the class object itself if you expect them to be pretty standard, which can then be obscured by re-assigning those attributes on the instance when desired. You can also create multiple constructors using <code>@classmethod</code>, if you want different groups of arguments to be passed in.</p> <pre><code>class Editor(object): font_file: None font_size: 148 def __init__(self, ffmpeg=str): self.ffmpeg = ffmpeg @classmethod def with_box(cls, ffmpeg=str, box=1): new_editor = cls(ffmpeg) new_editor.box = box return new_editor </code></pre> <p>And then you would call:</p> <pre><code>Editor.with_box(ffmpeg=int, box=2) </code></pre> <p>and get back a properly box-initialized Editor instance.</p>
1
2016-09-15T02:58:22Z
[ "python", "class", "constructor", "default-arguments" ]
Truly recursive `tolist()` for NumPy structured arrays
39,502,461
<p>From what I understand, the recommended way to convert a NumPy array into a native Python list is to use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.tolist.html" rel="nofollow"><code>ndarray.tolist</code></a>.</p> <p>Alas, this doesn't seem to work recursively when using structured arrays. Indeed, some <code>ndarray</code> objects are being referenced in the resulting list, unconverted:</p> <pre><code>&gt;&gt;&gt; dtype = numpy.dtype([('position', numpy.int32, 3)]) &gt;&gt;&gt; values = [([1, 2, 3],)] &gt;&gt;&gt; a = numpy.array(values, dtype=dtype) &gt;&gt;&gt; a.tolist() [(array([1, 2, 3], dtype=int32),)] </code></pre> <p>I did write a simple function to workaround this issue:</p> <pre><code>def array_to_list(array): if isinstance(array, numpy.ndarray): return array_to_list(array.tolist()) elif isinstance(array, list): return [array_to_list(item) for item in array] elif isinstance(array, tuple): return tuple(array_to_list(item) for item in array) else: return array </code></pre> <p>Which, when used, provides the expected result:</p> <pre><code>&gt;&gt;&gt; array_to_list(a) == values True </code></pre> <p>The problem with this function is that it duplicates the job of <code>ndarray.tolist</code> by recreating each list/tuple that it outputs. Not optimal.</p> <p>So the questions are:</p> <ul> <li>is this behaviour of <code>ndarray.tolist</code> to be expected?</li> <li>is there a better way to make this happen?</li> </ul>
1
2016-09-15T02:55:55Z
39,502,944
<p>Just to generalize this a bit, I'll add an another field to your dtype</p> <pre><code>In [234]: dt = numpy.dtype([('position', numpy.int32, 3),('id','U3')]) In [235]: a=np.ones((3,),dtype=dt) </code></pre> <p>The <code>repr</code> display does use lists and tuples:</p> <pre><code>In [236]: a Out[236]: array([([1, 1, 1], '1'), ([1, 1, 1], '1'), ([1, 1, 1], '1')], dtype=[('position', '&lt;i4', (3,)), ('id', '&lt;U3')]) </code></pre> <p>but as you note, <code>tolist</code> does not expand the elements.</p> <pre><code>In [237]: a.tolist() Out[237]: [(array([1, 1, 1]), '1'), (array([1, 1, 1]), '1'), (array([1, 1, 1]), '1')] </code></pre> <p>Similarly, such an array can be created from the fully nested lists and tuples.</p> <pre><code>In [238]: a=np.array([([1,2,3],'str')],dtype=dt) In [239]: a Out[239]: array([([1, 2, 3], 'str')], dtype=[('position', '&lt;i4', (3,)), ('id', '&lt;U3')]) In [240]: a.tolist() Out[240]: [(array([1, 2, 3]), 'str')] </code></pre> <p>There's no problem recreating the array from this incomplete recursion:</p> <pre><code>In [250]: np.array(a.tolist(),dtype=dt) Out[250]: array([([1, 2, 3], 'str')], dtype=[('position', '&lt;i4', (3,)), ('id', '&lt;U3')]) </code></pre> <p>This is the first that I've seen anyone use <code>tolist</code> with a structured array like this, but I'm not too surprised. I don't know if developers would consider this a bug or not. </p> <p>Why do you need a pure list/tuple rendering of this array? </p> <p>I wonder if there's a function in <code>numpy/lib/recfunctions.py</code> that addresses this.</p>
0
2016-09-15T04:04:49Z
[ "python", "numpy", "structured-array" ]
Pygame (A bit racey) game bug
39,502,475
<p>in the game when you first start it there's the game start menu/intro, it has 2 buttons (Start Game) (Quit)</p> <p>Now when you start the game and you're actually playing, when you press P (Paused) there're 2 buttons (Continue) (Main Menu) if you click continue it completes the game normally. However when you click main menu it closes the game instead of returning to the intro, same problem is present when you crash with the car you have (Try Again) and (Main Menu) and also if you click Main Menu it closes the game</p> <p>Any ideas on what might be the problem ?(ignore the comments)</p> <pre><code>import pygame import time import random pygame.init() crash_sound = pygame.mixer.Sound("C:\Users\itzrb_000\Documents\Untitled.wav") pygame.mixer.music.load("C:\Users\itzrb_000\Downloads\Cool_Ride.mp3") display_width = 800 display_height = 600 black = (0,0,0) white = (255,255,255) red = (200,0,0) green = (0,200,0) blue = (0,0,255) bright_green = (0,255,0) bright_red = (255,0,0) car_width = 50 gameDisplay = pygame.display.set_mode((display_width,display_height))#game screen size pygame.display.set_caption('What A Ride') clock = pygame.time.Clock() carImg = pygame.image.load('C:\Users\itzrb_000\Downloads\Car_Green_Front.png') gameBackground = pygame.image.load('C:\WhatARide_Background.png') icon = pygame.image.load('C:\Users\itzrb_000\Downloads\Car_Green_Front - Copy.png') pygame.display.set_icon(icon) pause = False car1 = pygame.image.load('C:\Users\itzrb_000\Downloads\download (3).png') car2 = pygame.image.load('C:\Users\itzrb_000\Downloads\download (2).png') car3 = pygame.image.load('C:\Users\itzrb_000\Downloads\images.png') rock = pygame.image.load('C:\Users\itzrb_000\Downloads\Rock.png') def background(): gameDisplay.blit(gameBackground,(0,0)) '''def cars(ystart): objects = [car1, car2, car3, rock] num_of_objects = random.randint(1,4) for x in range(num_of_objects): y = random.choice(objects) objectblit = random.randrange(130, 625) - (y.get_width()) gameDisplay.blit(y,(random.randrange(130, 625)))''' def score(count): font = pygame.font.SysFont(None,25) text = font.render("Score: "+str(count),True, blue) gameDisplay.blit(text,(0,0)) def things(thingx, thingy, thingw, thingh, color): pygame.draw.rect(gameDisplay, color, [thingx, thingy, thingw, thingh]) def car(x,y): gameDisplay.blit(carImg,(x,y)) def text_objects(text,font): textSurface = font.render(text, True, white) return textSurface, textSurface.get_rect() def message_display(text): largeText = pygame.font.Font('freesansbold.ttf',115) TextSurf, TextRect = text_objects(text, largeText) TextRect.center = ((display_width*0.5),(display_height*0.5)) gameDisplay.blit(TextSurf, TextRect)#blit display object pygame.display.update() time.sleep(2) game_loop() def crash(): pygame.mixer.music.stop() pygame.mixer.Sound.play(crash_sound) largeText = pygame.font.Font("freesansbold.ttf", 115) TextSurf, TextRect = text_objects("You Crashed", largeText) TextRect.center = ((display_width * 0.5), (display_height * 0.5)) gameDisplay.blit(TextSurf, TextRect) # blit display object while True: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() quit() button("Try Again!", 300, 400, 200, 50, green, bright_green, game_loop) button("Main Menu!", 300, 470, 200, 50, red, bright_red, game_intro) pygame.display.update() clock.tick(20) def button(msg,x,y,w,h,ic,ac,action=None): mouse = pygame.mouse.get_pos() click = pygame.mouse.get_pressed() if x+w &gt; mouse[0] &gt; x and y+h &gt; mouse[1] &gt; y: pygame.draw.rect(gameDisplay, ac,(x,y,w,h)) if click[0] == 1 and action != None: action() else: pygame.draw.rect(gameDisplay, ic,(x,y,w,h)) smallText = pygame.font.SysFont("freesansbold.ttf",20) textSurf, textRect = text_objects(msg, smallText) textRect.center = ( (x+(w/2)), (y+(h/2)) ) gameDisplay.blit(textSurf, textRect) def quitgame(): pygame.quit() quit() def unpause(): global pause pause = False pygame.mixer.music.unpause() def paused(): global pause pause = True pygame.mixer.music.pause() largeText = pygame.font.Font("freesansbold.ttf", 115) TextSurf, TextRect = text_objects("Paused", largeText) TextRect.center = ((display_width * 0.5), (display_height * 0.5)) gameDisplay.blit(TextSurf, TextRect) # blit display object while pause == True: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() quit() button("Continue!", 300, 400, 200, 50, green, bright_green,unpause) button("Main Menu", 300, 470, 200, 50, red, bright_red,game_intro) pygame.display.update() clock.tick(20) def game_intro(): intro = True while intro: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() quit() gameDisplay.fill(blue) largeText = pygame.font.SysFont("comicsansms", 115) TextSurf, TextRect = text_objects("What A Ride", largeText) TextRect.center = ((display_width / 2), (display_height / 2)) gameDisplay.blit(TextSurf, TextRect) button("Start Game", 300, 400, 200, 50, green, bright_green,game_loop) button("Quit", 300, 470, 200, 50, red, bright_red,quitgame) pygame.display.update() clock.tick(20) def game_loop(): global pause pygame.mixer.music.play(-1) x = (display_width * 0.45) y = (display_height * 0.8) x_change = 0 thing_startx = random.randrange(130,625) thing_starty = -600 thing_speed = 5 thing_width = 100 thing_height = 100 dodged = 0 gameExit = False while not gameExit: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() quit() if event.type == pygame.KEYDOWN: if event.key == pygame.K_LEFT: x_change = -5 elif event.key == pygame.K_RIGHT: x_change = 5 if event.key == pygame.K_p: pause = True paused() if event.type == pygame.KEYUP: if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT: x_change = 0 print event x += x_change background() things(thing_startx, thing_starty, thing_width, thing_height, black) thing_starty += thing_speed car(x,y) score(dodged) if x &gt; 625 - car_width or x &lt; 130: crash() if thing_starty &gt; display_height: thing_starty = 0 - thing_height thing_startx = random.randrange(130,625) dodged += 1 thing_speed += 1 thing_width += (dodged*1.2) if y &lt; thing_starty+thing_height: if x &gt; thing_startx and x &lt; thing_startx + thing_width or x + car_width &gt; thing_startx and x + car_width &lt; thing_startx+thing_width: crash() pygame.display.update() clock.tick(51) #fps game_intro() game_loop() pygame.quit() quit() </code></pre>
2
2016-09-15T02:57:54Z
39,502,586
<p>Because you're not waiting for the mouse button to be released before you trigger your buttons.</p> <ul> <li>When <code>pause()</code> starts, it brings up two buttons.</li> <li>User moves mouse to <code>Main Menu</code>.</li> <li>User clicks mouse.</li> <li>As soon as the mouse button is depressed, <code>game_intro()</code> is called, which puts a <code>Quit</code> button in the same place.</li> <li>The mouse button is <em>still</em> depressed, so the game quits.</li> </ul>
1
2016-09-15T03:14:15Z
[ "python", "pygame" ]
Numpy: Single loop vectorized code slow compared to two loop iteration
39,502,630
<p>The following codes iterates over each element of two array to compute pairwise euclidean distance. </p> <pre><code>def compute_distances_two_loops(X, Y): num_test = X.shape[0] num_train = Y.shape[0] dists = np.zeros((num_test, num_train)) for i in range(num_test): for j in range(num_train): dists[i][j] = np.sqrt(np.sum((X[i] - Y[j])**2)) return dists </code></pre> <p>The following code serves the same purpose but with single loop.</p> <pre><code>def compute_distances_one_loop(X, Y): num_test = X.shape[0] num_train = Y.shape[0] dists = np.zeros((num_test, num_train)) for i in range(num_test): dists[i, :] = np.sqrt(np.sum((Y - X[i])**2, axis=1)) return dists </code></pre> <p>Below are time comparison for both.</p> <pre><code>two_loop_time = time_function(compute_distances_two_loops, X, Y) print ('Two loop version took %f seconds' % two_loop_time) &gt;&gt; Two loop version took 20.3 seconds one_loop_time = time_function(compute_distances_one_loop, X, Y) print ('One loop version took %f seconds' % one_loop_time) &gt;&gt; One loop version took 80.9 seconds </code></pre> <p>Both X and Y are numpy.ndarray with shape - </p> <p>X: (500, 3000) Y: (5000, 3000)</p> <p>Out of intuition the results are not correct, the single loop should run at least with same speed. What am I missing here ? </p> <p>PS: The result is not from a single run. I ran the code number of times, on different machines, the results are similar.</p>
0
2016-09-15T03:21:08Z
39,515,647
<p>The reason is size of arrays within the loop body. In the two loop variant works on two arrays of 3000 elements. This easily fits into at least the level 2 cache of a cpu which is much faster than the main memory but it is also large enough that computing the distance is much slower than the python loop iteration overhead.</p> <p>The second case the loop body works on on 5000 * 3000 elements. This is so much that the data needs go to main memory in each computation step (first the Y-X[i] subtraction into a temporary array, squaring the temporary into another temporary and then read it back to sum it). The main memory is much slower than the cpu for the simple operations involved so it takes much longer despite removing a loop. You could speed it up a bit by using inplace operations writing into preallocated temporary array, but it will still be slower than the two loop variant for these array sizes.</p> <p>Note that <code>scipy.spatial.distance.cdist(X, Y)</code> is probably going to be fastest as it does not need any temporaries at all</p>
0
2016-09-15T16:04:26Z
[ "python", "performance", "numpy", "time", "nearest-neighbor" ]
import helloWorld works in Unix but not Windows
39,502,666
<p>A book on Python that I'm reading gives the following example of how to import a module at the interactive prompt:</p> <pre><code>&gt;&gt;&gt; import helloWorld </code></pre> <p>This works fine in my Unix terminal, but when I try this same command at an interactive session under Windows, I either get a syntax error or the module can't be found. I have tried putting the full path of the module to no avail, and I have tried launching Python after first changing to the folder containing this module, but no luck. I even moved the "helloworld.py" file to the "C:\Python27" folder.</p> <p>I am baffled because the book shows this command working in a Windows command prompt.</p>
0
2016-09-15T03:24:47Z
39,503,739
<p>Python defaults to using a case-sensitive import, even on Windows. The Windows file API is case insensitive [1], but Windows filesystems are case preserving, which makes it possible to implement a case-sensitive import [2]. When Python tries to import <code>helloWorld</code>, it searches <code>sys.path</code> for packages and files named "helloWorld" plus any of the allowed extensions (e.g. .py, .pyc, .pyo, .pyd). The base filename without the extension has to match the exact case of the imported name. The case of the file extension itself is ignored.</p> <p><sup> [1] The object manager's old (i.e. NT 3.x and 4.x) ability to do case-sensitive lookups can be enabled via a registry setting. Then <code>CreateFile</code> and <code>FindFirstFile</code> can be called with a flag to enable case-sensitive lookups.<br> [2] Except if multiple files in a directory differ only by case. Handling that requires [1]. </sup></p>
0
2016-09-15T05:32:39Z
[ "python", "windows", "import" ]
condensing/reducing vertical spacing between widgets in tkinter (Python) (AKA: setting vertical line/text spacing/padding)
39,502,691
<p>Here's my program:</p> <pre><code>import tkinter as tk #Create main window object root = tk.Tk() #build GUI for i in range(5): tk.Label(root, text="hello", height=0).grid(row=i) #mainloop root.mainloop() </code></pre> <p>It produces the following (running in Xubuntu 16.04 LTS)</p> <p><a href="http://i.stack.imgur.com/UmTmH.png" rel="nofollow"><img src="http://i.stack.imgur.com/UmTmH.png" alt="enter image description here"></a></p> <p>Notice all that extra vertical space between the lines of text. I don't want that! How do I decrease it?</p> <p>If I run this code instead:</p> <pre><code>import tkinter as tk #Create main window object root = tk.Tk() #build GUI for i in range(5): tk.Label(root, text="hello", height=0).grid(row=i) tk.Grid.rowconfigure(root, i, weight=1) #allow vertical compression/expansion to fit window size after manual resizing #mainloop root.mainloop() </code></pre> <p>...it opens up and <em>initially looks exactly the same as before,</em> but now I can <em>manually</em> drag the box vertically to shrink it, like so:</p> <p><a href="http://i.stack.imgur.com/D4mHc.png" rel="nofollow"><img src="http://i.stack.imgur.com/D4mHc.png" alt="enter image description here"></a></p> <p>Notice how much more vertically-compressed it is! <strong>But, how do I do this programatically</strong>, so I don't have to <em>manually</em> drag it to make it this way? I want to set this tight vertical spacing from the start, but no matter which parameters I change in <code>Label</code>, <code>grid</code>, or <code>rowconfigure</code> I can't seem to make it work without me manually dragging the box with the mouse to resize and vertically compress the text.</p>
0
2016-09-15T03:27:43Z
39,502,951
<p>You can programatically modify the geometry just before starting the main loop instead of manually dragging it (change 0.6 to whatever % reduction you want):</p> <pre><code>import tkinter as tk #Create main window object root = tk.Tk() #build GUI for i in range(5): label = tk.Label(root, text = 'hello') label.grid(row=i) tk.Grid.rowconfigure(root, i, weight=1) #allow vertical compression/expansion to fit window size after manual resizing #mainloop root.update() root.geometry("{}x{}".format(root.winfo_width(), int(0.6*root.winfo_height()))) root.mainloop() </code></pre> <p>Here is a screenshot of the result running on Xubuntu 16.04 LTS with Python 3.5.2:</p> <p><a href="http://i.stack.imgur.com/Vovbe.png" rel="nofollow"><img src="http://i.stack.imgur.com/Vovbe.png" alt="enter image description here"></a></p>
0
2016-09-15T04:06:16Z
[ "python", "tkinter", "spacing" ]
condensing/reducing vertical spacing between widgets in tkinter (Python) (AKA: setting vertical line/text spacing/padding)
39,502,691
<p>Here's my program:</p> <pre><code>import tkinter as tk #Create main window object root = tk.Tk() #build GUI for i in range(5): tk.Label(root, text="hello", height=0).grid(row=i) #mainloop root.mainloop() </code></pre> <p>It produces the following (running in Xubuntu 16.04 LTS)</p> <p><a href="http://i.stack.imgur.com/UmTmH.png" rel="nofollow"><img src="http://i.stack.imgur.com/UmTmH.png" alt="enter image description here"></a></p> <p>Notice all that extra vertical space between the lines of text. I don't want that! How do I decrease it?</p> <p>If I run this code instead:</p> <pre><code>import tkinter as tk #Create main window object root = tk.Tk() #build GUI for i in range(5): tk.Label(root, text="hello", height=0).grid(row=i) tk.Grid.rowconfigure(root, i, weight=1) #allow vertical compression/expansion to fit window size after manual resizing #mainloop root.mainloop() </code></pre> <p>...it opens up and <em>initially looks exactly the same as before,</em> but now I can <em>manually</em> drag the box vertically to shrink it, like so:</p> <p><a href="http://i.stack.imgur.com/D4mHc.png" rel="nofollow"><img src="http://i.stack.imgur.com/D4mHc.png" alt="enter image description here"></a></p> <p>Notice how much more vertically-compressed it is! <strong>But, how do I do this programatically</strong>, so I don't have to <em>manually</em> drag it to make it this way? I want to set this tight vertical spacing from the start, but no matter which parameters I change in <code>Label</code>, <code>grid</code>, or <code>rowconfigure</code> I can't seem to make it work without me manually dragging the box with the mouse to resize and vertically compress the text.</p>
0
2016-09-15T03:27:43Z
39,509,806
<p>There are many ways to affect vertical spacing. </p> <p>When you use <code>grid</code> or <code>pack</code> there are options for padding (eg: <code>pady</code>, <code>ipady</code>, <code>minsize</code>). Also, the widget itself has many options which control its appearance. For example, in the case of a label you can set the <code>borderwidth</code>, <code>highlightthickness</code> and <code>pady</code> values to zero in order to make the widget less tall. </p> <p>Different systems have different default values for these various options, and for some of the options the default is something bigger than zero. When trying to configure the visual aspects of your GUI, the first step is to read the documentation, and look for options that affect the visual appearance. Then, you can start experimenting with them to see which ones give you the look that you desire.</p> <p>In your specific case, this is about the most compact you can get:</p> <pre><code>label = tk.Label(root, highlightthickness=0, borderwidth=0, pady=0, text="hello") label.grid(row=i, pady=0, ipady=0) </code></pre>
0
2016-09-15T11:20:21Z
[ "python", "tkinter", "spacing" ]
Pandas read_sql_query converting integer column to float
39,502,783
<p>I have the following line</p> <pre><code>df = pandas.read_sql_query(sql = sql_script, con=conn, coerce_float = False) </code></pre> <p>that pulls data from Postgres using a sql script. Pandas keeps setting some of the columns to type float64. They should be just int. These columns contain some null values. Is there a ways to pull the data without having Pandas setting them to float64?</p> <p>Thanks!</p>
2
2016-09-15T03:43:03Z
39,502,948
<p>As per the <a href="http://pandas.pydata.org/pandas-docs/stable/gotchas.html#support-for-integer-na" rel="nofollow">documentation</a>, the lack of NA representation in Numpy implies integer NA values can't be managed, so pandas promotes int columns into float.</p>
2
2016-09-15T04:05:26Z
[ "python", "pandas" ]
In Python using ctypes for passing pointer to struct pointer to C function
39,502,899
<p>In a C library there's:</p> <pre><code>typedef struct A * B; int create_b(B* b); </code></pre> <p>and using ctypes I need the Python equivalent to:</p> <pre><code>B b; create_b(&amp;b) </code></pre> <p>The struct A is implemented in Python as <code>class A(ctypes.Structure)</code>.</p> <p>So, I tried:</p> <pre><code>b = ctypes.POINTER(A) lib.create_b(ctypes.byref(b)) </code></pre> <p>but it's not working. There are many similar questions, but none I tried helped.</p>
-1
2016-09-15T03:59:44Z
39,515,197
<p>This line</p> <pre><code>b = ctypes.POINTER(A) </code></pre> <p>is just setting <code>b</code> to refer to the same type <code>ctypes.POINTER(A)</code>, where what is really wanted is a variable constructed with that type. The line is missing the parentheses at the end:</p> <pre><code>b = ctypes.POINTER(A)() </code></pre>
0
2016-09-15T15:41:14Z
[ "python", "c", "pointers", "ctypes" ]
Python Scrapy dynamic item with grouping by Xpath
39,502,914
<p>My page is as below</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div style="width:100%;" id="innerTSpec"&gt; &lt;table width="100%" cellpadding="0" cellspacing="0" class="PrintIE7in80PercentWidth PrintIE6in80PercentWidth"&gt; &lt;tr&gt;&lt;td &gt;&lt;/td&gt;&lt;td class="techspecheading"&gt; Header1&lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td &gt;&lt;/td&gt;&lt;td class="techspecdata"&gt; &lt;/td&gt;&lt;td width="10px"&gt;&lt;/td&gt;&lt;td class=""&gt; &lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td &gt;&lt;/td&gt;&lt;td class="techspecheading"&gt; &lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td &gt;&lt;/td&gt;&lt;td class="techspecdata"&gt; My Attribute1: &lt;/td&gt;&lt;td width="10px"&gt;&lt;/td&gt;&lt;td class="techspecdata"&gt; Value1 &lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td &gt;&lt;/td&gt;&lt;td class="techspecheading"&gt; &lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td &gt;&lt;/td&gt;&lt;td class="techspecdata"&gt; My Attribute2: &lt;/td&gt;&lt;td width="10px"&gt;&lt;/td&gt;&lt;td class="techspecdata"&gt; Value2 &lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td &gt;&lt;/td&gt;&lt;td class="techspecheading"&gt; &lt;/td&gt;&lt;/tr&gt; ---&gt; &lt;tr&gt;&lt;td &gt;&lt;/td&gt;&lt;td class="techspecheading"&gt; &lt;hr&gt;&lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td &gt;&lt;/td&gt;&lt;td class="techspecdata"&gt; &lt;/td&gt;&lt;td width="10px"&gt;&lt;/td&gt;&lt;td class=""&gt; &lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td &gt;&lt;/td&gt;&lt;td class="techspecheading"&gt; Header2&lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td &gt;&lt;/td&gt;&lt;td class="techspecdata"&gt; &lt;/td&gt;&lt;td width="10px"&gt;&lt;/td&gt;&lt;td class=""&gt; &lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td &gt;&lt;/td&gt;&lt;td class="techspecheading"&gt; &lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td &gt;&lt;/td&gt;&lt;td class="techspecdata"&gt; My Attribute3: &lt;/td&gt;&lt;td width="10px"&gt;&lt;/td&gt;&lt;td class="techspecdata"&gt; More Value1 &lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td &gt;&lt;/td&gt;&lt;td class="techspecheading"&gt; &lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td &gt;&lt;/td&gt;&lt;td class="techspecdata"&gt; My Attribute4: &lt;/td&gt;&lt;td width="10px"&gt;&lt;/td&gt;&lt;td class="techspecdata"&gt; More Value2 &lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td &gt;&lt;/td&gt;&lt;td class="techspecheading"&gt; &lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td &gt;&lt;/td&gt;&lt;td class="techspecdata"&gt; My Attribute5: &lt;/td&gt;&lt;td width="10px"&gt;&lt;/td&gt;&lt;td class="techspecdata"&gt; More Value3 &lt;/td&gt;&lt;/tr&gt; ---&gt; &lt;tr&gt;&lt;td &gt;&lt;/td&gt;&lt;td class="techspecheading"&gt; &lt;hr&gt;&lt;/td&gt;&lt;/tr&gt; &lt;/table&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <p>The Header and Attributes are not in fixed position it changes every time with page. I am trying to make like below:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>Header1 | Header2 |... ---------------------------------------------- My Attribute1:Value1|My Attribute3:More Value1|... My Attribute2:Value2|My Attribute4:More Value2|... |My Attribute5:More Value3|...</code></pre> </div> </div> </p> <p>NB: I am using dynamic items which will be added like </p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>My Item is as below -------------------------------------- class Website(Item): def __setitem__(self, key, value): if key not in self.fields: self.fields[key] = Field() self._values[key] = value -------------------------------------- and in spider adding as below -------------------------------------- item[Heading]=Body.xpath('..........').extract()</code></pre> </div> </div> </p>
1
2016-09-15T04:00:57Z
39,503,671
<p>I don't have scrapy installed, but I think you can easily modify it to use scrapy's <code>Items</code>.</p> <pre><code>from lxml.html import fromstring html = """ &lt;div style="width:100%;" id="innerTSpec"&gt; &lt;table width="100%" cellpadding="0" cellspacing="0" class="PrintIE7in80PercentWidth PrintIE6in80PercentWidth"&gt; &lt;tr&gt;&lt;td &gt;&lt;/td&gt;&lt;td class="techspecheading"&gt; Header1&lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td &gt;&lt;/td&gt;&lt;td class="techspecdata"&gt; &lt;/td&gt;&lt;td width="10px"&gt;&lt;/td&gt;&lt;td class=""&gt; &lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td &gt;&lt;/td&gt;&lt;td class="techspecheading"&gt; &lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td &gt;&lt;/td&gt;&lt;td class="techspecdata"&gt; My Attribute1: &lt;/td&gt;&lt;td width="10px"&gt;&lt;/td&gt;&lt;td class="techspecdata"&gt; Value1 &lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td &gt;&lt;/td&gt;&lt;td class="techspecheading"&gt; &lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td &gt;&lt;/td&gt;&lt;td class="techspecdata"&gt; My Attribute2: &lt;/td&gt;&lt;td width="10px"&gt;&lt;/td&gt;&lt;td class="techspecdata"&gt; Value2 &lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td &gt;&lt;/td&gt;&lt;td class="techspecheading"&gt; &lt;/td&gt;&lt;/tr&gt; ---&gt; &lt;tr&gt;&lt;td &gt;&lt;/td&gt;&lt;td class="techspecheading"&gt; &lt;hr&gt;&lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td &gt;&lt;/td&gt;&lt;td class="techspecdata"&gt; &lt;/td&gt;&lt;td width="10px"&gt;&lt;/td&gt;&lt;td class=""&gt; &lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td &gt;&lt;/td&gt;&lt;td class="techspecheading"&gt; Header2&lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td &gt;&lt;/td&gt;&lt;td class="techspecdata"&gt; &lt;/td&gt;&lt;td width="10px"&gt;&lt;/td&gt;&lt;td class=""&gt; &lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td &gt;&lt;/td&gt;&lt;td class="techspecheading"&gt; &lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td &gt;&lt;/td&gt;&lt;td class="techspecdata"&gt; My Attribute3: &lt;/td&gt;&lt;td width="10px"&gt;&lt;/td&gt;&lt;td class="techspecdata"&gt; More Value1 &lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td &gt;&lt;/td&gt;&lt;td class="techspecheading"&gt; &lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td &gt;&lt;/td&gt;&lt;td class="techspecdata"&gt; My Attribute4: &lt;/td&gt;&lt;td width="10px"&gt;&lt;/td&gt;&lt;td class="techspecdata"&gt; More Value2 &lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td &gt;&lt;/td&gt;&lt;td class="techspecheading"&gt; &lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td &gt;&lt;/td&gt;&lt;td class="techspecdata"&gt; My Attribute5: &lt;/td&gt;&lt;td width="10px"&gt;&lt;/td&gt;&lt;td class="techspecdata"&gt; More Value3 &lt;/td&gt;&lt;/tr&gt; ---&gt; &lt;tr&gt;&lt;td &gt;&lt;/td&gt;&lt;td class="techspecheading"&gt; &lt;hr&gt;&lt;/td&gt;&lt;/tr&gt; &lt;/table&gt; &lt;/div&gt; """ body = fromstring(html) heading = None item = {} for tr in body.xpath(r'//div[@id="innerTSpec"]//tr'): # Extract row data. Skip rows without data. data = tr.xpath(r'.//td[@class]/text()') data = list(filter(None, [txt.strip() for txt in data])) if not data: continue # Populate item. if len(data) == 1: heading = data[0] else: item.setdefault(heading, []).append(''.join(data)) print(item) </code></pre> <p><code>item</code>:</p> <pre><code>{ 'Header1': ['My Attribute1:Value1', 'My Attribute2:Value2'], 'Header2': ['My Attribute3:More Value1', 'My Attribute4:More Value2', 'My Attribute5:More Value3'] } </code></pre>
0
2016-09-15T05:25:51Z
[ "python", "xpath", "scrapy", "scrapy-spider" ]
Reverse a list without using built-in functions
39,502,915
<p>I'm using Python 3.5. </p> <p>As part of a problem, I'm trying to design a function that takes a list as input and reverts it. So if <code>x = [a, b, c]</code> the function would make <code>x = [c, b, a]</code>.</p> <p>The problem is, I'm not allowed to use any built-in functions, and it has got me stuck. My initial thought was the following loop inside a function:</p> <pre><code>for revert in range(1, len(x) + 1): y.append(x[-revert]) </code></pre> <p>And it works. But the problem is I'm using <code>len(x)</code>, which I believe is a built-in function, correct? </p> <p>So I searched around and have made the following very simple code:</p> <pre><code>y = x[::-1] </code></pre> <p>Which does exactly what I wanted, but it just seems almost too simple/easy and I'm not sure whether <code>"::"</code> counts as a function. </p> <p>So I was wondering if anyone had any hints/ideas how to manually design said function? It just seems really hard when you can't use any built-in functions and it has me stuck for quite some time now.</p>
9
2016-09-15T04:01:07Z
39,502,957
<p><code>range</code> and <code>len</code> are both <a href="https://docs.python.org/3/library/functions.html" rel="nofollow">built-in functions</a>. Since <code>list</code> <em>methods</em> are accepted, you could do this with <a href="https://docs.python.org/3.5/tutorial/datastructures.html#more-on-lists" rel="nofollow"><code>insert</code></a>. It is <em>reeaallyy slow</em><sup>*</sup> but it does the job for <em>small</em> lists without using any built-ins:</p> <pre><code>def rev(l): r = [] for i in l: r.insert(0, i) return r </code></pre> <p>By continuously inserting at the zero-th position you end up with a reversed version of the input list:</p> <pre><code>&gt;&gt;&gt; print(rev([1, 2, 3, 4])) [4, 3, 2, 1] </code></pre> <p>Doing:</p> <pre><code>def rev(l): return l[::-1] </code></pre> <p>could also be considered a solution. <code>::-1</code> (<code>::</code> has a different result) isn't a function (it's a slice) and <code>[]</code> is, again, a list method. Also, contrasting <code>insert</code>, it is faster and way more readable; just make sure you're able to understand and explain it. A nice explanation of how it works can be found <em><a href="http://stackoverflow.com/questions/766141/reverse-a-string-in-python?lq=1">in this S.O answer.</a></em></p> <p><sup>*Reeaaalllyyyy slow, see juanpa.arrivillaga's answer for cool plot and <code>append</code> with <code>pop</code> and take a look at in-place <code>reverse</code> on lists as done in Yoav Glazner's answer.</sup></p>
4
2016-09-15T04:06:49Z
[ "python", "list", "python-3.x" ]
Reverse a list without using built-in functions
39,502,915
<p>I'm using Python 3.5. </p> <p>As part of a problem, I'm trying to design a function that takes a list as input and reverts it. So if <code>x = [a, b, c]</code> the function would make <code>x = [c, b, a]</code>.</p> <p>The problem is, I'm not allowed to use any built-in functions, and it has got me stuck. My initial thought was the following loop inside a function:</p> <pre><code>for revert in range(1, len(x) + 1): y.append(x[-revert]) </code></pre> <p>And it works. But the problem is I'm using <code>len(x)</code>, which I believe is a built-in function, correct? </p> <p>So I searched around and have made the following very simple code:</p> <pre><code>y = x[::-1] </code></pre> <p>Which does exactly what I wanted, but it just seems almost too simple/easy and I'm not sure whether <code>"::"</code> counts as a function. </p> <p>So I was wondering if anyone had any hints/ideas how to manually design said function? It just seems really hard when you can't use any built-in functions and it has me stuck for quite some time now.</p>
9
2016-09-15T04:01:07Z
39,502,970
<p>Your example that works:</p> <pre><code>y = x[::-1] </code></pre> <p>uses Python <a href="https://docs.python.org/2.3/whatsnew/section-slices.html" rel="nofollow">slices notation</a> which is not a function in the sense that I assume you're requesting. Essentially <code>::</code> acts as a separator. A more verbose version of your code would be:</p> <pre><code>y = x[len(x):None:-1] </code></pre> <p>or</p> <pre><code>y = x[start:end:step] </code></pre> <p>I probably wouldn't be complaining that python makes your life really, really easily.</p> <hr> <p>Edit to be super pedantic. Someone could argue that calling <code>[]</code> at all is using an inbuilt python function because it's really syntactical sugar for the method <code>__getitem__()</code>.</p> <pre><code>x.__getitem__(0) == x[0] </code></pre> <p>And using <code>::</code> does make use of the <code>slice()</code> object.</p> <pre><code>x.__getitem__(slice(len(x), None, -1) == x[::-1] </code></pre> <p>But... if you were to argue this, anything you write in python would be using inbuilt python functions.</p>
0
2016-09-15T04:08:40Z
[ "python", "list", "python-3.x" ]
Reverse a list without using built-in functions
39,502,915
<p>I'm using Python 3.5. </p> <p>As part of a problem, I'm trying to design a function that takes a list as input and reverts it. So if <code>x = [a, b, c]</code> the function would make <code>x = [c, b, a]</code>.</p> <p>The problem is, I'm not allowed to use any built-in functions, and it has got me stuck. My initial thought was the following loop inside a function:</p> <pre><code>for revert in range(1, len(x) + 1): y.append(x[-revert]) </code></pre> <p>And it works. But the problem is I'm using <code>len(x)</code>, which I believe is a built-in function, correct? </p> <p>So I searched around and have made the following very simple code:</p> <pre><code>y = x[::-1] </code></pre> <p>Which does exactly what I wanted, but it just seems almost too simple/easy and I'm not sure whether <code>"::"</code> counts as a function. </p> <p>So I was wondering if anyone had any hints/ideas how to manually design said function? It just seems really hard when you can't use any built-in functions and it has me stuck for quite some time now.</p>
9
2016-09-15T04:01:07Z
39,502,975
<p><code>::</code> is not a function, it's a <em>python literal</em>. as well as <code>[]</code></p> <p>How to check if <code>::, []</code> are functions or not. Simple,</p> <pre><code> import dis a = [1,2] dis.dis(compile('a[::-1]', '', 'eval')) 1 0 LOAD_NAME 0 (a) 3 LOAD_CONST 0 (None) 6 LOAD_CONST 0 (None) 9 LOAD_CONST 2 (-1) 12 BUILD_SLICE 3 15 BINARY_SUBSCR 16 RETURN_VALUE </code></pre> <p>If <code>::,[]</code> were functions, you should find a label <code>CALL_FUNCTION</code> among python instructions executed by <code>a[::-1]</code> statement. So, they aren't. </p> <p>Look how python instructions looks like when you call a function, lets say <code>list()</code> function</p> <pre><code>&gt;&gt;&gt; dis.dis(compile('list()', '', 'eval')) 1 0 LOAD_NAME 0 (list) 3 CALL_FUNCTION 0 6 RETURN_VALUE </code></pre> <p>So, basically</p> <pre><code>def rev(f): return f[::-1] </code></pre> <p>works fine. But, I think you should do something like Jim suggested in his answer if your question is a homework or sent by you teacher. But, you can add this quickest way as a side note.</p> <p>If you teacher complains about <code>[::-1]</code> notation, show him the example I gave you. </p>
1
2016-09-15T04:10:29Z
[ "python", "list", "python-3.x" ]
Reverse a list without using built-in functions
39,502,915
<p>I'm using Python 3.5. </p> <p>As part of a problem, I'm trying to design a function that takes a list as input and reverts it. So if <code>x = [a, b, c]</code> the function would make <code>x = [c, b, a]</code>.</p> <p>The problem is, I'm not allowed to use any built-in functions, and it has got me stuck. My initial thought was the following loop inside a function:</p> <pre><code>for revert in range(1, len(x) + 1): y.append(x[-revert]) </code></pre> <p>And it works. But the problem is I'm using <code>len(x)</code>, which I believe is a built-in function, correct? </p> <p>So I searched around and have made the following very simple code:</p> <pre><code>y = x[::-1] </code></pre> <p>Which does exactly what I wanted, but it just seems almost too simple/easy and I'm not sure whether <code>"::"</code> counts as a function. </p> <p>So I was wondering if anyone had any hints/ideas how to manually design said function? It just seems really hard when you can't use any built-in functions and it has me stuck for quite some time now.</p>
9
2016-09-15T04:01:07Z
39,503,225
<p>Here's a solution that doesn't use built-in <em>functions</em> but relies on list methods. It reverse in-place, as implied by your specification:</p> <pre><code>&gt;&gt;&gt; x = [1,2,3,4] &gt;&gt;&gt; def reverse(seq): ... temp = [] ... while seq: ... temp.append(seq.pop()) ... seq[:] = temp ... &gt;&gt;&gt; reverse(x) &gt;&gt;&gt; x [4, 3, 2, 1] &gt;&gt;&gt; </code></pre> <h2>ETA</h2> <p>Jim, your answer using <code>insert</code> at position 0 was driving me nuts! That solution is quadratic time! You can use <code>append</code> and <code>pop</code> with a temporary list to achieve linear time using simple list methods. See (<code>reverse</code> is in blue, <code>rev</code> is green): <a href="http://i.stack.imgur.com/IiqWK.png" rel="nofollow"><img src="http://i.stack.imgur.com/IiqWK.png" alt=""></a></p> <p>If it feels a little bit like "cheating" using <code>seq[:] = temp</code>, we could always loop over <code>temp</code> and append every item into <code>seq</code> and the time complexity would still be linear but probably slower since it isn't using the C-based internals.</p>
1
2016-09-15T04:38:40Z
[ "python", "list", "python-3.x" ]
Reverse a list without using built-in functions
39,502,915
<p>I'm using Python 3.5. </p> <p>As part of a problem, I'm trying to design a function that takes a list as input and reverts it. So if <code>x = [a, b, c]</code> the function would make <code>x = [c, b, a]</code>.</p> <p>The problem is, I'm not allowed to use any built-in functions, and it has got me stuck. My initial thought was the following loop inside a function:</p> <pre><code>for revert in range(1, len(x) + 1): y.append(x[-revert]) </code></pre> <p>And it works. But the problem is I'm using <code>len(x)</code>, which I believe is a built-in function, correct? </p> <p>So I searched around and have made the following very simple code:</p> <pre><code>y = x[::-1] </code></pre> <p>Which does exactly what I wanted, but it just seems almost too simple/easy and I'm not sure whether <code>"::"</code> counts as a function. </p> <p>So I was wondering if anyone had any hints/ideas how to manually design said function? It just seems really hard when you can't use any built-in functions and it has me stuck for quite some time now.</p>
9
2016-09-15T04:01:07Z
39,503,285
<p>Another way ( just for completeness :) )</p> <pre><code>def another_reverse(lst): new_lst = lst.copy() # make a copy if you don't want to ruin lst... new_lst.reverse() # notice! this will reverse it in place return new_lst </code></pre>
1
2016-09-15T04:45:48Z
[ "python", "list", "python-3.x" ]
Reverse a list without using built-in functions
39,502,915
<p>I'm using Python 3.5. </p> <p>As part of a problem, I'm trying to design a function that takes a list as input and reverts it. So if <code>x = [a, b, c]</code> the function would make <code>x = [c, b, a]</code>.</p> <p>The problem is, I'm not allowed to use any built-in functions, and it has got me stuck. My initial thought was the following loop inside a function:</p> <pre><code>for revert in range(1, len(x) + 1): y.append(x[-revert]) </code></pre> <p>And it works. But the problem is I'm using <code>len(x)</code>, which I believe is a built-in function, correct? </p> <p>So I searched around and have made the following very simple code:</p> <pre><code>y = x[::-1] </code></pre> <p>Which does exactly what I wanted, but it just seems almost too simple/easy and I'm not sure whether <code>"::"</code> counts as a function. </p> <p>So I was wondering if anyone had any hints/ideas how to manually design said function? It just seems really hard when you can't use any built-in functions and it has me stuck for quite some time now.</p>
9
2016-09-15T04:01:07Z
39,503,790
<p>Another way for completeness, <code>range()</code> takes an optional step parameter that will allow you to step backwards through the list:</p> <pre><code>def reverse_list(l): return [l[i] for i in range(len(l)-1, -1, -1)] </code></pre>
0
2016-09-15T05:36:37Z
[ "python", "list", "python-3.x" ]
Reverse a list without using built-in functions
39,502,915
<p>I'm using Python 3.5. </p> <p>As part of a problem, I'm trying to design a function that takes a list as input and reverts it. So if <code>x = [a, b, c]</code> the function would make <code>x = [c, b, a]</code>.</p> <p>The problem is, I'm not allowed to use any built-in functions, and it has got me stuck. My initial thought was the following loop inside a function:</p> <pre><code>for revert in range(1, len(x) + 1): y.append(x[-revert]) </code></pre> <p>And it works. But the problem is I'm using <code>len(x)</code>, which I believe is a built-in function, correct? </p> <p>So I searched around and have made the following very simple code:</p> <pre><code>y = x[::-1] </code></pre> <p>Which does exactly what I wanted, but it just seems almost too simple/easy and I'm not sure whether <code>"::"</code> counts as a function. </p> <p>So I was wondering if anyone had any hints/ideas how to manually design said function? It just seems really hard when you can't use any built-in functions and it has me stuck for quite some time now.</p>
9
2016-09-15T04:01:07Z
39,504,037
<p>The most pythonic and efficient way to achieve this is by list slicing. And, since you mentioned you do not need any inbuilt function, it completely suffice your requirement. For example:</p> <pre><code>&gt;&gt;&gt; def reverse_list(list_obj): ... return list_obj[::-1] ... &gt;&gt;&gt; reverse_list([1, 3, 5 , 3, 7]) [7, 3, 5, 3, 1] </code></pre>
0
2016-09-15T06:01:37Z
[ "python", "list", "python-3.x" ]
Reverse a list without using built-in functions
39,502,915
<p>I'm using Python 3.5. </p> <p>As part of a problem, I'm trying to design a function that takes a list as input and reverts it. So if <code>x = [a, b, c]</code> the function would make <code>x = [c, b, a]</code>.</p> <p>The problem is, I'm not allowed to use any built-in functions, and it has got me stuck. My initial thought was the following loop inside a function:</p> <pre><code>for revert in range(1, len(x) + 1): y.append(x[-revert]) </code></pre> <p>And it works. But the problem is I'm using <code>len(x)</code>, which I believe is a built-in function, correct? </p> <p>So I searched around and have made the following very simple code:</p> <pre><code>y = x[::-1] </code></pre> <p>Which does exactly what I wanted, but it just seems almost too simple/easy and I'm not sure whether <code>"::"</code> counts as a function. </p> <p>So I was wondering if anyone had any hints/ideas how to manually design said function? It just seems really hard when you can't use any built-in functions and it has me stuck for quite some time now.</p>
9
2016-09-15T04:01:07Z
39,504,955
<p>Just iterate the list from right to left to get the items.. </p> <pre><code>a = [1,2,3,4] def reverse_the_list(a): reversed_list = [] for i in range(0, len(a)): reversed_list.append(a[len(a) - i - 1]) return reversed_list new_list = reverse_the_list(a) print new_list </code></pre>
0
2016-09-15T07:08:47Z
[ "python", "list", "python-3.x" ]
Why does Negative Lookahead times out with And/Or Pipe
39,502,927
<p>I have an And/Or regex i.e (PatternA|PatternB) in which I only take PatternA if PatternB does not exist (PatternB always comes after PatternA but is more important) so I put a negative lookahead in the PatternA Pipe.</p> <p>This works on shorter text blocks:</p> <p><a href="https://regex101.com/r/bU6cU6/5" rel="nofollow">https://regex101.com/r/bU6cU6/5</a></p> <p>But times out on longer text blocks:</p> <p><a href="https://regex101.com/r/bU6cU6/2" rel="nofollow">https://regex101.com/r/bU6cU6/2</a></p> <p>What I don't understand is if I put PatternA with the Neg Look ahead alone in the same long text block it takes only 32 steps to reject it:</p> <p><a href="https://regex101.com/r/bU6cU6/3" rel="nofollow">https://regex101.com/r/bU6cU6/3</a></p> <p>and if I put PatternB alone in the same long text block it only takes 18 steps to accept it:</p> <p><a href="https://regex101.com/r/bU6cU6/4" rel="nofollow">https://regex101.com/r/bU6cU6/4</a></p> <p>So I am not sure why it is taking 100,000+/timeout to first reject (32 steps) then accept (18 steps) with the pipes. Is there another/better way to construct so it checks PatternA first than PatternB because now it is doing something I don't understand to go from 50 steps to 100k +.</p>
2
2016-09-15T04:02:57Z
39,505,072
<p>Unanchored lookarounds used with a "global" regex (matching several occurrences) cause too much legwork, and are inefficient. They should be "anchored" to some concrete context. Often, they are executed at the beginning (lookaheads) or end (lookbehinds) of the string.</p> <p>In your case, you may "anchor" it by placing after <code>Option1:</code> to ensure it is only executed after <code>Option1:</code> is aready matched.</p> <pre><code>Option1:(?!.*Option2)\*.*?(?P&lt;Capture&gt;Bob|David|Ted|Alice)|\*Option2 (?P&lt;Capture2&gt;Juan) ^^^^^^^^^^^^^ </code></pre> <p>See <a href="https://regex101.com/r/vS6eJ2/1" rel="nofollow">this regex demo</a></p> <p>Some more answers:</p> <blockquote> <p>What I don't understand is if I put PatternA with the Neg Look ahead alone in the same long text block it takes only 32 steps to reject it</p> </blockquote> <p>Yes, but you tested it with internal optimizations ON. Disable them and you will see</p> <p><a href="http://i.stack.imgur.com/ieiNe.png" rel="nofollow"><img src="http://i.stack.imgur.com/ieiNe.png" alt="enter image description here"></a></p> <blockquote> <p>if I put PatternB alone in the same long text block it only takes 18 steps to accept it:</p> </blockquote> <p>The match is found as expected, in a very efficient way:</p> <p><a href="http://i.stack.imgur.com/5t8XD.png" rel="nofollow"><img src="http://i.stack.imgur.com/5t8XD.png" alt="enter image description here"></a></p>
1
2016-09-15T07:15:33Z
[ "python", "regex", "timeout", "negative-lookahead" ]
Why does Negative Lookahead times out with And/Or Pipe
39,502,927
<p>I have an And/Or regex i.e (PatternA|PatternB) in which I only take PatternA if PatternB does not exist (PatternB always comes after PatternA but is more important) so I put a negative lookahead in the PatternA Pipe.</p> <p>This works on shorter text blocks:</p> <p><a href="https://regex101.com/r/bU6cU6/5" rel="nofollow">https://regex101.com/r/bU6cU6/5</a></p> <p>But times out on longer text blocks:</p> <p><a href="https://regex101.com/r/bU6cU6/2" rel="nofollow">https://regex101.com/r/bU6cU6/2</a></p> <p>What I don't understand is if I put PatternA with the Neg Look ahead alone in the same long text block it takes only 32 steps to reject it:</p> <p><a href="https://regex101.com/r/bU6cU6/3" rel="nofollow">https://regex101.com/r/bU6cU6/3</a></p> <p>and if I put PatternB alone in the same long text block it only takes 18 steps to accept it:</p> <p><a href="https://regex101.com/r/bU6cU6/4" rel="nofollow">https://regex101.com/r/bU6cU6/4</a></p> <p>So I am not sure why it is taking 100,000+/timeout to first reject (32 steps) then accept (18 steps) with the pipes. Is there another/better way to construct so it checks PatternA first than PatternB because now it is doing something I don't understand to go from 50 steps to 100k +.</p>
2
2016-09-15T04:02:57Z
39,505,294
<p>Your main problem is the position of the lookahead. The lookahead has to be tried at every position, and it has to scan all the remaining characters every time. The longer test string is over 3500 characters long; that adds up.</p> <p>If your regex isn't anchored, you should always try to start it with something concrete that will fail or succeed quickly--literal text is the best. In this case, it's obvious that you can move the lookahead back: <code>Option1:\*(?!.*Option2)</code> instead of <code>(?!.*Option2)Option1:\*</code>. (Notice the lack of trailing <code>.*</code> in the lookahead; you didn't need that.)</p> <p>But why is PatternA so much quicker when you match it alone? Internal optimizations. When the regex is just <code>(?!.*Option2.*)Option1:\*.*?(?P&lt;Capture&gt;(Bob|David|Ted|Alice))</code>, the regex engine can tell that the match must start with <code>Option1:*</code>, so it goes straight to that position for its first match attempt. The longer regex is too complicated, and the optimization doesn't occur.</p> <p>You can test that by using the "regex debugger" option at Regex101, then checking <code>DISABLE INTERNAL ENGINE OPTIMIZATIONS</code>. The step count goes back to over 100,000.</p>
1
2016-09-15T07:27:28Z
[ "python", "regex", "timeout", "negative-lookahead" ]
Histogram with uneven heights within bins
39,502,946
<p>Why does my histogram look like this? I'm plotting it using the following code:</p> <pre><code>import matplotlib.pyplot as plt n, bins, patches = plt.hist(data, 25) plt.show() </code></pre> <p>where <code>data</code> contains about 500,000 sorted points. Shouldn't each bin be smooth at the top?</p> <p><a href="http://i.stack.imgur.com/fL8hB.png" rel="nofollow"><img src="http://i.stack.imgur.com/fL8hB.png" alt="enter image description here"></a></p>
0
2016-09-15T04:05:22Z
39,504,270
<p>I think <a href="http://matplotlib.org/examples/statistics/histogram_demo_histtypes.html" rel="nofollow">this example from the matplotlib gallery</a> displays the kind of plot you want. Therefore, you should either use <code>histtype="stepfilled"</code> or <code>histtype="bar"</code>.</p>
0
2016-09-15T06:20:59Z
[ "python", "matplotlib" ]
Histogram with uneven heights within bins
39,502,946
<p>Why does my histogram look like this? I'm plotting it using the following code:</p> <pre><code>import matplotlib.pyplot as plt n, bins, patches = plt.hist(data, 25) plt.show() </code></pre> <p>where <code>data</code> contains about 500,000 sorted points. Shouldn't each bin be smooth at the top?</p> <p><a href="http://i.stack.imgur.com/fL8hB.png" rel="nofollow"><img src="http://i.stack.imgur.com/fL8hB.png" alt="enter image description here"></a></p>
0
2016-09-15T04:05:22Z
39,505,119
<p>I suspect your data might not be a flat list, but, e.g., a list of lists or similarly structured. In that case, <code>hist</code> will bin by sublist. This script demonstrates the difference:</p> <pre><code>import random from matplotlib import pyplot as plt data = [[random.randint(0, x) for x in range(20)] for y in range(100)] plt.subplot(211) # structured plt.hist(data, 25) plt.subplot(212) # flattened plt.hist([i for l in data for i in l], 25) plt.show() </code></pre> <p>You will probably have to use some kind of similar "flattening" on your data.</p>
1
2016-09-15T07:18:10Z
[ "python", "matplotlib" ]
How to find the maximum by comparing previous value?
39,502,979
<p>I have a huge data set &amp; complex code that it takes so much time if I am trying to find the maximum by appending all intermediate results and compare. So I want to implement algorithm to find the maximum by comparing previous value. my algorithm goes like, </p> <pre><code>for i in range(len(y)): oldmax = y[0] if oldmax &gt;= y[i]: pass else: new_max = y[i] </code></pre> <p>then I want to store this newmax and compare with next string y[i+1] and go on (Only the maximum value should survive at the end). But I am not sure how to set this new_max to be something to be compared in the next loop. For example, let y = [3,1,5,6,4]. Since the y[0] is greater than y[1], it will pass until it meets 5. But since 6 and 4 are also greater than 3, the new_max ends up being 4 which is the last value.</p> <p>How should I fix the code? Any help will be appreciated!</p>
-1
2016-09-15T04:11:11Z
39,503,019
<p>Why don't you just use one variable and compare until <code>length - 1</code>? Also, you keep resetting <code>oldmax</code> to the first element on every iteration, causing inaccurate results. Set it's initial value but don't change it:</p> <pre><code>max_value = y[0] for i in range(len(y) - 1): if max_value &lt;= y[i + 1] max_value = y[i + 1] </code></pre> <p>Now what does is just has one variable, <code>max_value</code> which has an initial value of the first element. The loop goes from first element to <code>length - 1</code>, due to the accessing of element <code>i + 1</code>. If the max is less than the next value, reassign max to the next value. I also eliminated the extra if that did nothing and only checked if it was larger. </p> <hr> <p>You can get rid of all the code above by just using the builtin <a href="https://docs.python.org/2/library/functions.html#max" rel="nofollow"><code>max</code></a> function which takes in any iterable and returns the maximum value:</p> <pre><code>max_value = max(y) </code></pre>
1
2016-09-15T04:15:42Z
[ "python", "arrays", "database", "max" ]
How to find the maximum by comparing previous value?
39,502,979
<p>I have a huge data set &amp; complex code that it takes so much time if I am trying to find the maximum by appending all intermediate results and compare. So I want to implement algorithm to find the maximum by comparing previous value. my algorithm goes like, </p> <pre><code>for i in range(len(y)): oldmax = y[0] if oldmax &gt;= y[i]: pass else: new_max = y[i] </code></pre> <p>then I want to store this newmax and compare with next string y[i+1] and go on (Only the maximum value should survive at the end). But I am not sure how to set this new_max to be something to be compared in the next loop. For example, let y = [3,1,5,6,4]. Since the y[0] is greater than y[1], it will pass until it meets 5. But since 6 and 4 are also greater than 3, the new_max ends up being 4 which is the last value.</p> <p>How should I fix the code? Any help will be appreciated!</p>
-1
2016-09-15T04:11:11Z
39,503,740
<p><strong><em>If</em></strong> you want to do it like that, you don't need to work with <code>index</code>, which will probably be slightly slower on huge data. </p> <p>You can simply do:</p> <pre><code>newmax = y[0] for new in y: newmax = new if new &gt; newmax else newmax </code></pre> <p>You'd need to do a test on huge data though to see if this is fast enough.</p>
0
2016-09-15T05:32:55Z
[ "python", "arrays", "database", "max" ]
dinucleotide count and frequency
39,503,039
<p>Im trying to find the dinuc count and frequencies from a sequence in a text file, but my code is only outputting single nucleotide counts.</p> <pre><code>e = "ecoli.txt" ecnt = {} with open(e) as seq: for line in seq: for word in line.split(): for i in range(len(seqr)): dinuc = (seqr[i] + seqr[i:i+2]) for dinuc in seqr: if dinuc in ecnt: ecnt[dinuc] += 1 else: ecnt[dinuc] = 1 for x,y in ecnt.items(): print(x, y) </code></pre> <p>Sample input: "AAATTTCGTCGTTGCCC"</p> <p>Sample output: AA:2 TT:3 TC:2 CG:2 GT:2 GC:1 CC:2</p> <p>Right now, Im only getting single nucleotides for my output:</p> <p>C 83550600 A 60342100 T 88192300 G 92834000</p> <p>For the nucleotides that repeat i.e. "AAA", the count has to return all possible combinations of consecutive 'AA', so the output should be 2 rather than 1. It doesnt matter what order the dinucleotides are listed, I just need all combinations, and for the code to return the correct count for the repeated nucleotides. I was asking my TA and she said that my only problem was getting my 'for' loop to add the dinucleotides to my dictionary, and I think my range may or may not be wrong. The file is a really big one, so the sequence is split up into lines.</p> <p>Thank you so much in advance!!!</p>
0
2016-09-15T04:18:09Z
39,521,151
<p>I took a look at your code and found several things that you might want to take a look at. </p> <p>For testing my solution, since I did not have ecoli.txt, I generated one of my own with random nucleotides with the following function:</p> <pre><code>import random def write_random_sequence(): out_file = open("ecoli.txt", "w") num_nts = 500 nts_per_line = 80 nts = [] for i in range(num_nts): nt = random.choice(["A", "T", "C", "G"]) nts.append(nt) lines = [nts[i:i+nts_per_line] for i in range(0, len(nts), nts_per_line)] for line in lines: out_file.write("".join(line) + "\n") out_file.close() write_random_sequence() </code></pre> <p>Notice that this file has a single sequence of 500 nucleotides separated into lines of 80 nucleotides each. In order to count dinucleotides where you have the first nucleotide at the end of one line and the second nucleotide at the start of the next line, we need to merge all of these separate lines into a single string, without spaces. Let's do that first:</p> <pre><code>seq = "" with open("ecoli.txt", "r") as seq_data: for line in seq_data: seq += line.strip() </code></pre> <p>Try printing out "seq" and notice that it should be one giant string containing all of the nucleotides. Next, we need to find the dinucleotides in the sequence string. We can do this using slicing, which I see you tried. So for each position in the string, we look at both the current nucleotide and the one after it.</p> <pre><code>for i in range(len(seq)-1):#note the -1 dinuc = seq[i:i+2] </code></pre> <p>We can then do the counting of the nucleotides and storage of them in a dictionary "ecnt" very much like you had. The final code looks like this:</p> <pre><code>ecnt = {} seq = "" with open("ecoli.txt", "r") as seq_data: for line in seq_data: seq += line.strip() for i in range(len(seq)-1): dinuc = seq[i:i+2] if dinuc in ecnt: ecnt[dinuc] += 1 else: ecnt[dinuc] = 1 print ecnt </code></pre>
0
2016-09-15T22:17:32Z
[ "python", "dictionary", "bioinformatics", "sequences" ]
dinucleotide count and frequency
39,503,039
<p>Im trying to find the dinuc count and frequencies from a sequence in a text file, but my code is only outputting single nucleotide counts.</p> <pre><code>e = "ecoli.txt" ecnt = {} with open(e) as seq: for line in seq: for word in line.split(): for i in range(len(seqr)): dinuc = (seqr[i] + seqr[i:i+2]) for dinuc in seqr: if dinuc in ecnt: ecnt[dinuc] += 1 else: ecnt[dinuc] = 1 for x,y in ecnt.items(): print(x, y) </code></pre> <p>Sample input: "AAATTTCGTCGTTGCCC"</p> <p>Sample output: AA:2 TT:3 TC:2 CG:2 GT:2 GC:1 CC:2</p> <p>Right now, Im only getting single nucleotides for my output:</p> <p>C 83550600 A 60342100 T 88192300 G 92834000</p> <p>For the nucleotides that repeat i.e. "AAA", the count has to return all possible combinations of consecutive 'AA', so the output should be 2 rather than 1. It doesnt matter what order the dinucleotides are listed, I just need all combinations, and for the code to return the correct count for the repeated nucleotides. I was asking my TA and she said that my only problem was getting my 'for' loop to add the dinucleotides to my dictionary, and I think my range may or may not be wrong. The file is a really big one, so the sequence is split up into lines.</p> <p>Thank you so much in advance!!!</p>
0
2016-09-15T04:18:09Z
39,525,260
<p>A perfect opportunity to use a <code>defaultdict</code>:</p> <pre><code>from collections import defaultdict file_name = "ecoli.txt" dinucleotide_counts = defaultdict(int) sequence = "" with open(file_name) as file: for line in file: sequence += line.strip() for i in range(len(sequence) - 1): dinucleotide_counts[sequence[i:i + 2]] += 1 for key, value in sorted(dinucleotide_counts.items()): print(key, value) </code></pre>
0
2016-09-16T06:44:59Z
[ "python", "dictionary", "bioinformatics", "sequences" ]
Removing square brackets in pandas python for exporting to csv
39,503,095
<p>I have a dataset which prints like the following. I'm trying to export this dataset to CSV and I would like to remove the square brackets on the dataframe. I've tried the solution in this <a href="http://stackoverflow.com/questions/38147447/how-to-remove-square-bracket-from-pandas-dataframe">question</a> unsuccessfully. Any suggestion is appreciated.</p> <pre><code> A \ 2016-09-12 19:00:00, [143.328125, 35, 143.359375, 15] 2016-09-12 20:00:00, [143.4375, 22, 143.453125, 23] 2016-09-12 21:00:00, [143.484375, 17, 143.5, 22] 2016-09-12 22:00:00, [143.546875, 91, 143.5625, 1] 2016-09-12 23:00:00, [143.5, 3, 143.515625, 21] 2016-09-13 00:00:00, [143.46875, 27, 143.484375, 9] 2016-09-13 01:00:00, [143.421875, 12, 143.4375, 78] 2016-09-13 02:00:00, [143.3125, 34, 143.328125, 13] 2016-09-13 03:00:00, [143.34375, 5, 143.359375, 79] 2016-09-13 04:00:00, [143.4375, 5, 143.453125, 64] 2016-09-13 05:00:00, [143.515625, 62, 143.53125, 8] 2016-09-13 06:00:00, [143.40625, 115, 143.421875, 15] 2016-09-13 07:00:00, [143.328125, 53, 143.34375, 24] 2016-09-13 08:00:00, [143.328125, 51, 143.34375, 65] 2016-09-13 09:00:00, [143.203125, 73, 143.21875, 167] 2016-09-13 10:00:00, [143.171875, 129, 143.1875, 63] 2016-09-13 11:00:00, [142.671875, 59, 142.6875, 83] 2016-09-13 12:00:00, [142.5, 16, 142.515625, 64] 2016-09-13 13:00:00, [142.4375, 117, 142.453125, 111] 2016-09-13 14:00:00, [142.40625, 130, 142.421875, 47] 2016-09-13 15:00:00, [142.578125, 60, 142.59375, 79] 2016-09-13 16:00:00, [142.46875, 1, 142.5, 84] B \ 2016-09-12 19:00:00, [166.9375, 61, 167.0, 80] 2016-09-12 20:00:00, [167.125, 62, 167.15625, 42] 2016-09-12 21:00:00, [167.21875, 20, 167.25, 51] 2016-09-12 22:00:00, [167.28125, 49, 167.3125, 42] 2016-09-12 23:00:00, [167.25, 45, 167.28125, 43] 2016-09-13 00:00:00, [167.1875, 69, 167.21875, 33] 2016-09-13 01:00:00, [167.125, 42, 167.15625, 34] 2016-09-13 02:00:00, [166.96875, 105, 167.0, 23] 2016-09-13 03:00:00, [167.09375, 49, 167.125, 137] 2016-09-13 04:00:00, [167.375, 47, 167.40625, 123] 2016-09-13 05:00:00, [167.53125, 71, 167.5625, 185] 2016-09-13 06:00:00, [167.28125, 128, 167.3125, 104] 2016-09-13 07:00:00, [167.09375, 124, 167.125, 155] 2016-09-13 08:00:00, [167.125, 175, 167.15625, 172] 2016-09-13 09:00:00, [166.78125, 218, 166.8125, 27] 2016-09-13 10:00:00, [166.65625, 100, 166.6875, 117] 2016-09-13 11:00:00, [165.625, 381, 165.65625, 84] 2016-09-13 12:00:00, [165.40625, 47, 165.4375, 34] 2016-09-13 13:00:00, [165.21875, 161, 165.25, 95] 2016-09-13 14:00:00, [165.28125, 318, 165.3125, 388] 2016-09-13 15:00:00, [165.4375, 208, 165.46875, 93] 2016-09-13 16:00:00, [165.21875, 16, 165.25, 42] C 2016-09-12 19:00:00, [130.578125, 96, 130.59375, 541] 2016-09-12 20:00:00, [130.640625, 493, 130.65625, 1146] 2016-09-12 21:00:00, [130.65625, 828, 130.671875, 115] 2016-09-12 22:00:00, [130.71875, 599, 130.734375, 417] 2016-09-12 23:00:00, [130.65625, 678, 130.671875, 409] 2016-09-13 00:00:00, [130.640625, 940, 130.65625, 656] 2016-09-13 01:00:00, [130.59375, 615, 130.609375, 59] 2016-09-13 02:00:00, [130.53125, 553, 130.546875, 292] 2016-09-13 03:00:00, [130.53125, 1028, 130.546875, 224] 2016-09-13 04:00:00, [130.59375, 1122, 130.609375, 320] 2016-09-13 05:00:00, [130.65625, 890, 130.671875, 600] 2016-09-13 06:00:00, [130.578125, 1166, 130.59375, 94] 2016-09-13 07:00:00, [130.546875, 330, 130.5625, 1169] 2016-09-13 08:00:00, [130.53125, 1109, 130.546875, 731] 2016-09-13 09:00:00, [130.453125, 987, 130.46875, 952] 2016-09-13 10:00:00, [130.46875, 220, 130.484375, 1780] 2016-09-13 11:00:00, [130.125, 1010, 130.140625, 1227] 2016-09-13 12:00:00, [130.015625, 139, 130.03125, 100] 2016-09-13 13:00:00, [129.984375, 1227, 130.0, 411] 2016-09-13 14:00:00, [129.96875, 1628, 129.984375, 1676] 2016-09-13 15:00:00, [130.09375, 1712, 130.109375, 408] 2016-09-13 16:00:00, [130.015625, 328, 130.03125, 205] </code></pre>
0
2016-09-15T04:24:29Z
39,503,902
<p>I am new to <code>pandas</code>. There may be a better way but this what I could manage:</p> <pre><code>for col in df: df[col] = df[col].str.extract(r'\[(.*)\]') </code></pre>
0
2016-09-15T05:48:42Z
[ "python", "csv" ]
Converting a List Into Float Variables
39,503,158
<p>I'm wanting to take an input as a list but use each variable as a float. Is there a simpler way to make this conversion other than explicitly like I do below, as a list is defined with strings, and I want to, for example, add rather than concatenate:</p> <pre><code>edges = input("Enter three edges: ").split(", ") print("The perimeter is", (float(edges[0]) + float(edges[1]) + float(edges[2]))) </code></pre>
0
2016-09-15T04:32:23Z
39,503,197
<p>You could use <code>map</code> to transform to <code>float</code>s and then <code>sum</code> to sum them up:</p> <pre><code>print("The perimeter is", sum(map(float, edges))) </code></pre> <p><code>map</code> takes a callable (<code>float</code> here), and applies it to every element of an iterable (<code>edges</code> here). This creates a <code>map</code> iterator (something that can be iterated through) that is then supplied to <code>sum</code> which sums it up.</p> <p>Then you print it.</p> <p>You could of course create an ugly little expression that combines them all together because both <code>input</code> and <code>split</code> return their results:</p> <pre><code>print("Sum is ", sum(map(float, input('Enter three edges ' ).split(",")))) </code></pre> <p>but don't, <em>it's ugly</em>.</p>
1
2016-09-15T04:36:53Z
[ "python", "list", "python-3.x", "floating-point" ]
Converting a List Into Float Variables
39,503,158
<p>I'm wanting to take an input as a list but use each variable as a float. Is there a simpler way to make this conversion other than explicitly like I do below, as a list is defined with strings, and I want to, for example, add rather than concatenate:</p> <pre><code>edges = input("Enter three edges: ").split(", ") print("The perimeter is", (float(edges[0]) + float(edges[1]) + float(edges[2]))) </code></pre>
0
2016-09-15T04:32:23Z
39,503,213
<p>map is your friend</p> <pre><code>sum(map(float, edges)) </code></pre> <p>or a generator expression</p> <pre><code>sum(float(f) for f in edges) </code></pre> <p>Have fun!</p>
1
2016-09-15T04:38:10Z
[ "python", "list", "python-3.x", "floating-point" ]
Converting a List Into Float Variables
39,503,158
<p>I'm wanting to take an input as a list but use each variable as a float. Is there a simpler way to make this conversion other than explicitly like I do below, as a list is defined with strings, and I want to, for example, add rather than concatenate:</p> <pre><code>edges = input("Enter three edges: ").split(", ") print("The perimeter is", (float(edges[0]) + float(edges[1]) + float(edges[2]))) </code></pre>
0
2016-09-15T04:32:23Z
39,503,235
<p>Since you probably want the edges only as numbers, you can convert them early:</p> <pre><code>edges = [float(edge) for edge in input("Enter three edges: ").split(", ")] print("The perimeter is", sum(edges)) </code></pre> <p>Sample run:</p> <pre><code>Enter three edges: 1.2, 3.4, 5.6 The perimeter is 10.2 </code></pre>
0
2016-09-15T04:39:26Z
[ "python", "list", "python-3.x", "floating-point" ]
List of list of words by Python:
39,503,172
<p>Having a long list of comments (50 by saying) such as this one: </p> <blockquote> <p>"this was the biggest disappointment of our trip. the restaurant had received some very good reviews, so our expectations were high. the service was slow even though the restaurant was not very full. I had the house salad which could have come out of any sizzler in the us. the keshi yena, although tasty reminded me of barbequed pulled chicken. this restaurant is very overrated".</p> </blockquote> <p>I want to create a list of list of words retaining sentence tokenization using python. </p> <p>After removing stopwords I want a result for all 50 comments in which sentence tokens are retained and word tokens are retained into each tokenized sentence. At the end I hope result being similar to: </p> <pre><code>list(c("disappointment", "trip"), c("restaurant", "received", "good", "reviews", "expectations", "high"), c("service", "slow", "even", "though", "restaurant", "full"), c("house", "salad", "come", "us"), c("although", "tasty", "reminded", "pulled"), "restaurant") </code></pre> <p>How could I do that in python? Is R a good option in this case? I really will appreciate your help.</p>
0
2016-09-15T04:34:11Z
39,503,353
<p>Not sure you want R for this or not, but based on your requirement, I think it can be done in a pure pythonic way as well. </p> <p>You basically want a list that contains small list of important words (that are not stop words) per sentence.</p> <p>So you can do something like</p> <pre><code>input_reviews = """ this was the biggest disappointment of our trip. the restaurant had received some very good reviews, so our expectations were high. the service was slow even though the restaurant was not very full. I had the house salad which could have come out of any sizzler in the us. the keshi yena, although tasty reminded me of barbequed pulled chicken. this restaurant is very overrated. """ # load your stop words list here stop_words_list = ['this', 'was', 'the', 'of', 'our', 'biggest', 'had', 'some', 'very', 'so', 'were', 'not'] def main(): sentences = input_reviews.split('.') sentence_list = [] for sentence in sentences: inner_list = [] words_in_sentence = sentence.split(' ') for word in words_in_sentence: stripped_word = str(word).lstrip('\n') if stripped_word and stripped_word not in stop_words_list: # this is a good word inner_list.append(stripped_word) if inner_list: sentence_list.append(inner_list) print(sentence_list) if __name__ == '__main__': main() </code></pre> <p>On my end, this outputs</p> <pre><code>[['disappointment', 'trip'], ['restaurant', 'received', 'good', 'reviews,', 'expectations', 'high'], ['service', 'slow', 'even', 'though', 'restaurant', 'full'], ['I', 'house', 'salad', 'which', 'could', 'have', 'come', 'out', 'any', 'sizzler', 'in', 'us'], ['keshi', 'yena,', 'although', 'tasty', 'reminded', 'me', 'barbequed', 'pulled', 'chicken'], ['restaurant', 'is', 'overrated']] </code></pre>
0
2016-09-15T04:54:12Z
[ "python", "word-list" ]
List of list of words by Python:
39,503,172
<p>Having a long list of comments (50 by saying) such as this one: </p> <blockquote> <p>"this was the biggest disappointment of our trip. the restaurant had received some very good reviews, so our expectations were high. the service was slow even though the restaurant was not very full. I had the house salad which could have come out of any sizzler in the us. the keshi yena, although tasty reminded me of barbequed pulled chicken. this restaurant is very overrated".</p> </blockquote> <p>I want to create a list of list of words retaining sentence tokenization using python. </p> <p>After removing stopwords I want a result for all 50 comments in which sentence tokens are retained and word tokens are retained into each tokenized sentence. At the end I hope result being similar to: </p> <pre><code>list(c("disappointment", "trip"), c("restaurant", "received", "good", "reviews", "expectations", "high"), c("service", "slow", "even", "though", "restaurant", "full"), c("house", "salad", "come", "us"), c("although", "tasty", "reminded", "pulled"), "restaurant") </code></pre> <p>How could I do that in python? Is R a good option in this case? I really will appreciate your help.</p>
0
2016-09-15T04:34:11Z
39,503,644
<p>This is one way to do it. You may need to initialize the <code>stop_words</code> as suits your application. I have assumed <code>stop_words</code> is in lowercase: hence, using <code>lower()</code> on the original sentences for comparison. <code>sentences.lower().split('.')</code> gives sentences. <code>s.split()</code> gives list of words in each sentence.</p> <pre><code>stokens = [list(filter(lambda x: x not in stop_words, s.split())) for s in sentences.lower().split('.')] </code></pre> <p>You may wonder why we use <code>filter</code> and <code>lambda</code>. An alternative is this but this will give a flat list and hence is not suitable:</p> <pre><code>stokens = [word for s in sentences.lower().split('.') for word in s.split() if word not in stop_words] </code></pre> <p><code>filter</code> is a functional programming construct. It helps us to process an entire list, in this case, via an anonymous function using the <code>lambda</code> syntax.</p>
0
2016-09-15T05:23:12Z
[ "python", "word-list" ]
List of list of words by Python:
39,503,172
<p>Having a long list of comments (50 by saying) such as this one: </p> <blockquote> <p>"this was the biggest disappointment of our trip. the restaurant had received some very good reviews, so our expectations were high. the service was slow even though the restaurant was not very full. I had the house salad which could have come out of any sizzler in the us. the keshi yena, although tasty reminded me of barbequed pulled chicken. this restaurant is very overrated".</p> </blockquote> <p>I want to create a list of list of words retaining sentence tokenization using python. </p> <p>After removing stopwords I want a result for all 50 comments in which sentence tokens are retained and word tokens are retained into each tokenized sentence. At the end I hope result being similar to: </p> <pre><code>list(c("disappointment", "trip"), c("restaurant", "received", "good", "reviews", "expectations", "high"), c("service", "slow", "even", "though", "restaurant", "full"), c("house", "salad", "come", "us"), c("although", "tasty", "reminded", "pulled"), "restaurant") </code></pre> <p>How could I do that in python? Is R a good option in this case? I really will appreciate your help.</p>
0
2016-09-15T04:34:11Z
39,504,381
<p>If you do not want to create a list of stop words by hand, I would recommend that you use the nltk library in python. It also handles sentence splitting (as opposed to splitting on every period). A sample that parses your sentence might look like this:</p> <pre><code>import nltk stop_words = set(nltk.corpus.stopwords.words('english')) text = "this was the biggest disappointment of our trip. the restaurant had received some very good reviews, so our expectations were high. the service was slow even though the restaurant was not very full. I had the house salad which could have come out of any sizzler in the us. the keshi yena, although tasty reminded me of barbequed pulled chicken. this restaurant is very overrated" sentence_detector = nltk.data.load('tokenizers/punkt/english.pickle') sentences = sentence_detector.tokenize(text.strip()) results = [] for sentence in sentences: tokens = nltk.word_tokenize(sentence) words = [t.lower() for t in tokens if t.isalnum()] not_stop_words = tuple([w for w in words if w not in stop_words]) results.append(not_stop_words) print results </code></pre> <p>However, note that this does not give the exact same output as listed in your question, but instead looks like this:</p> <pre><code>[('biggest', 'disappointment', 'trip'), ('restaurant', 'received', 'good', 'reviews', 'expectations', 'high'), ('service', 'slow', 'even', 'though', 'restaurant', 'full'), ('house', 'salad', 'could', 'come', 'sizzler', 'us'), ('keshi', 'yena', 'although', 'tasty', 'reminded', 'barbequed', 'pulled', 'chicken'), ('restaurant', 'overrated')] </code></pre> <p>You might need to add some stop words manually in your case if the output needs to look the same.</p>
0
2016-09-15T06:30:42Z
[ "python", "word-list" ]
depreciation warning when I use sklearn imputer
39,503,200
<p>My code is quite simple, but it always pops out the warning like this:</p> <pre><code>DeprecationWarning: Passing 1d arrays as data is deprecated in 0.17 and will raise ValueError in 0.19. Reshape your data either using X.reshape(-1, 1) if your data has a single feature or X.reshape(1, -1) if it contains a single sample. (DeprecationWarning) </code></pre> <p>I don't know why it does not work even if I add <code>s.reshape(-1,1)</code> in the parentheses of <code>fit_transforms</code>.</p> <p>The code is following:</p> <pre><code>import pandas as pd s = pd.Series([1,2,3,np.nan,5,np.nan,7,8]) imp = Imputer(missing_values='NAN', strategy='mean', axis=0) x = pd.Series(imp.fit_transform(s).tolist()[0]) x </code></pre>
0
2016-09-15T04:37:07Z
39,503,568
<p>Besides the warning, your snippet did not interpret by me due to missing <code>import</code>s, and an error (<code>ufunc: isnan not supported</code>) once I got some imports into place. </p> <p>This code runs without warnings or errors, though:</p> <pre><code>In [39]: import pandas as pd In [40]: import numpy as np In [41]: from sklearn import preprocessing In [42]: s = pd.Series([1,2,3,np.nan,5,np.nan,7,8]) In [43]: imp = preprocessing.Imputer(strategy='mean', axis=0) In [44]: x = pd.Series(imp.fit_transform(s.values.reshape(1, -1)).tolist()[0]) In [45]: x Out[45]: 0 1.0 1 2.0 2 3.0 3 5.0 4 7.0 5 8.0 dtype: float64 </code></pre> <p>Note the following:</p> <ol> <li><p><code>import</code>s</p></li> <li><p><code>preprocessing.Imputer(strategy='mean', axis=0)</code> omits your <code>NAN</code> specification (it should be <code>NaN</code>, but as <code>NaN</code> is the default, you can just erase it).</p></li> <li><p><code>x = pd.Series(imp.fit_transform(s.values.reshape(1, -1)).tolist()[0])</code> reshapes from a 1d array, to a 2d array.</p></li> </ol> <p>Your warning was about point 3 - this function wants a 2d matrix, not a 1d vector.</p>
0
2016-09-15T05:15:45Z
[ "python", "pandas", "scikit-learn" ]
TypeError: unsupported operand type(s) for /: 'float' and 'list', can't resolve
39,503,212
<p>I am trying to generate a plot in python to determine velocity of planets, V = sqrt(GM/r). My approach is this:</p> <p>I can generate few hundred points for 'r' :</p> <pre><code>r = range (57909227, 5906440628, 10000000) </code></pre> <p>using the largest and smallest values of 'r', which have already been given. the values of G and M are also given. my code looks like this :</p> <pre><code>import sys import os import numpy import matplotlib.pyplot as plt from pylab import * G=6.67*10**(-11) M=2.0*10**30 radial_distance = range (57909227, 5906440629, 10000000) for distance in radial_distance: plt.plot(radial_distance, ((G*M)/distance)**0.5, '*') plt.show() </code></pre> <p>which returns me the following error:</p> <pre><code>File "generate_list.py", line 20, in &lt;module&gt; plt.plot(radial_distance, ((G*M)/distance)**0.5, '*') File "/home/trina/anaconda2/lib/python2.7/site-packages/matplotlib/pyplot.py", line 3154, in plot ret = ax.plot(*args, **kwargs) File "/home/trina/anaconda2/lib/python2.7/site-packages/matplotlib/__init__.py", line 1812, in inner return func(ax, *args, **kwargs) File "/home/trina/anaconda2/lib/python2.7/site-packages/matplotlib/axes/_axes.py", line 1424, in plot for line in self._get_lines(*args, **kwargs): File "/home/trina/anaconda2/lib/python2.7/site-packages/matplotlib/axes/_base.py", line 386, in _grab_next_args for seg in self._plot_args(remaining, kwargs): File "/home/trina/anaconda2/lib/python2.7/site-packages/matplotlib/axes/_base.py", line 364, in _plot_args x, y = self._xy_from_xy(x, y) File "/home/trina/anaconda2/lib/python2.7/site-packages/matplotlib/axes/_base.py", line 223, in _xy_from_xy raise ValueError("x and y must have same first dimension") ValueError: x and y must have same first dimension </code></pre> <p>please help me fix the error.</p>
0
2016-09-15T04:38:06Z
39,503,382
<p>What you need is to apply an expression element-wise on the list and then pass the resultant list to plot.</p> <pre><code>y = [((G*M)/x)**0.5 for x in radial_distance] plt.plot(radial_distance, y) </code></pre>
2
2016-09-15T04:56:15Z
[ "python", "range" ]
python create list of dictionaries without reference
39,503,277
<p>I have a requirement in which I need create dictionary objects with duplicate keys embedded into a list object, something like this:</p> <pre><code>[{ "key": "ABC" },{ "key": "EFG" } ] </code></pre> <p>I decided to have a top level list initialized to empty like <code>outer_list=[]</code> and a placeholder dictionary object like <code>dict_obj= {}</code>. Next I keep adding elements to my list using the following steps:</p> <ol> <li>assign <code>{ "key": "ABC" }</code> to dict_obj using <code>dict_obj["key"]="ABC"</code></li> <li>Add this object to the list using <code>outer_list.append(dict_obj)</code></li> <li>Flush/pop the key/items in dictionary object using <code>dict_obj.clear()</code></li> <li>Repeat steps 1 to 3 based on the number of key/item combinations in my data</li> </ol> <p>Issue: the <code>outer_list</code> object maintains a reference to the original <code>dict_obj</code> and if the <code>dict_obj</code> is flushed or a new key/item is added it changes accordingly. So finally, I end up with this <code>[{ "key": "EFG" },{ "key": "EFG" } ]</code> instead of <code>[{ "key": "ABC" },{ "key": "EFG" } ]</code></p> <p>Please guide me with some workarounds if possible.</p>
0
2016-09-15T04:44:37Z
39,503,408
<p>I think there are two ways to avoid the duplicate references.</p> <p>The first is to <code>append</code> a copy of the dictionary, instead of a reference to it. <code>dict</code> instances have a <code>copy</code> method, so this is easy. Just change your current <code>append</code> call to:</p> <pre><code>outer_list.append(dict_obj.copy())` </code></pre> <p>The other option is to not always use the same <code>dict_obj</code> object, but rather create a separate dictionary object for each entry. In this version, you'd replace your call to <code>dict_obj.clear()</code> with:</p> <pre><code>dict_obj = {} </code></pre> <p>For the second approach, you might choose to reorder things rather than doing a straight one-line replacement. You could move the setup code to the start of the loop and get rid of the reset logic at the end of the loop.</p> <p>That is, change code that looks like this:</p> <pre><code>outer_list = [] dict_obj = {} for foo in whatever: # add stuff to dict_obj outer_list.append(dict_obj) dict_obj.clear() </code></pre> <p>To:</p> <pre><code>outer_list = [] for foo in whatever: dict_obj = {} # add stuff to dict_obj outer_list.append(dict_obj) </code></pre> <p>If the logic for creating the inner dictionaries is simple enough to compute, you might even turn the whole thing into a list comprehension:</p> <pre><code>outer_list = [{"key": value, "key2": value2} for value, value2 in some_sequence] </code></pre>
1
2016-09-15T04:58:36Z
[ "python", "list", "dictionary" ]
python create list of dictionaries without reference
39,503,277
<p>I have a requirement in which I need create dictionary objects with duplicate keys embedded into a list object, something like this:</p> <pre><code>[{ "key": "ABC" },{ "key": "EFG" } ] </code></pre> <p>I decided to have a top level list initialized to empty like <code>outer_list=[]</code> and a placeholder dictionary object like <code>dict_obj= {}</code>. Next I keep adding elements to my list using the following steps:</p> <ol> <li>assign <code>{ "key": "ABC" }</code> to dict_obj using <code>dict_obj["key"]="ABC"</code></li> <li>Add this object to the list using <code>outer_list.append(dict_obj)</code></li> <li>Flush/pop the key/items in dictionary object using <code>dict_obj.clear()</code></li> <li>Repeat steps 1 to 3 based on the number of key/item combinations in my data</li> </ol> <p>Issue: the <code>outer_list</code> object maintains a reference to the original <code>dict_obj</code> and if the <code>dict_obj</code> is flushed or a new key/item is added it changes accordingly. So finally, I end up with this <code>[{ "key": "EFG" },{ "key": "EFG" } ]</code> instead of <code>[{ "key": "ABC" },{ "key": "EFG" } ]</code></p> <p>Please guide me with some workarounds if possible.</p>
0
2016-09-15T04:44:37Z
39,503,757
<p>The following should be self-explanatory:</p> <pre><code># object reuse d = {} l = [] d['key'] = 'ABC' l.append(d) d.clear() print(l) # [{}] : cleared! d['key'] = 'EFG' l.append(d) print(l) # [{'key': 'EFG'}, {'key': 'EFG'}] # explicit creation of new objects d = {} l = [] d['key'] = 'ABC' l.append(d) print(l) d = {} d['key'] = 'EFG' l.append(d) print(l) </code></pre>
0
2016-09-15T05:34:24Z
[ "python", "list", "dictionary" ]
Django override model subclass create method
39,503,292
<p>I'm looking for right ways to override the <code>create()</code> method of a subclass.</p> <p>Basically I'm doing this:</p> <pre><code>class Base(models.Model): field1_base = models.IntegerField() def __init__(self, field1_base): # LOGICS self.field1_base = field1_base class A(Base): field2_sub = models.IntegerField() def __init__(self, field2_sub, field1_base): # LOGICS self.field2_sub = field2_sub super(A, self).__init__(field1_base) A(field2_sub=1, field1_base=2) </code></pre> <p>However we can't override the <code>__init__()</code> method of a model.</p> <p>I just want to leave some fields to be assigned in base class's methods.</p> <p>Is there a proper way to do this using <code>create()</code> method?</p> <p>Of course I can custom <code>create</code> method of Base class, however what I want is to invoke Base.create and A.create at the same time on the creation of A, which makes the situation different from <a href="http://stackoverflow.com/questions/843580">this question</a></p>
0
2016-09-15T04:46:39Z
39,503,855
<p>I would do something like this.</p> <pre><code>class Base(models.Model): field1_base = models.IntegerField() def initialize(self, *args, **kwargs): self.field1_base = kwargs['field1_base'] @classmethod def create(cls, *args, **kwargs): # LOGICS self = cls() self.initialize(*args, **kwargs) return self class A(Base): field2_sub = models.IntegerField() def initialize(self, *args, **kwargs): super(A, self).initialize(*args, **kwargs) self.field2_sub = kwargs['field1_base'] A.create(field2_sub=1, field1_base=2) </code></pre>
1
2016-09-15T05:44:27Z
[ "python", "django" ]
TypeError: randint() got an unexpected keyword argument 'low'
39,503,354
<pre><code>names = ['Bob', 'Jessica', 'Mary', 'John', 'Mel'] import random random.seed(500) random_names = [names[random.randint(low = 0, high = len(names))] for i in range(1000)] </code></pre> <p>Objective is to make a random list of 1,000 names using the five above. But the above code throws back the following error : </p> <pre><code>Traceback (most recent call last): File "&lt;pyshell#88&gt;", line 1, in &lt;module&gt; random_names = [names[random.randint(low = 0, high = len(names))] for i in range(1000)] TypeError: randint() got an unexpected keyword argument 'low' </code></pre>
0
2016-09-15T04:54:16Z
39,503,947
<p>Remove <code>low</code> and <code>high</code> and your code will work fine. i.e. <code>random.randint(0, len(names)-1)</code></p> <p>However, more efficient way to do it is using <a href="https://docs.python.org/2/library/random.html#random.choice" rel="nofollow"><code>random.choice()</code></a></p> <pre><code>&gt;&gt;&gt; [random.choice(names) for i in range(10)] ['Mel', 'Mary', 'Mary', 'John', 'Bob', 'Mel', 'John', 'Jessica', 'Jessica', 'John'] </code></pre>
2
2016-09-15T05:53:03Z
[ "python", "python-2.7", "random" ]
Need to access self.request.GET from main.py in lib.py
39,503,369
<p>I need to do calculations among other things within lib.py and I need to access the user input data within main.py for it, because it needs to be that way. How do I do this?</p> <p>doing from main import MainHandler in lib.py and then calling it "works" in the sense that it doesn't give any code errors, but displays a blank page when done that way and I get a log error saying that I cannot import it.</p> <p>main.py</p> <pre><code>import webapp2 from lib import FormData from pages import FormPage from pages import ResultsPage class MainHandler(webapp2.RequestHandler): def get(self): f = FormPage() s = ResultsPage() fd1 = FormData() if self.request.GET: fd1.name = self.request.GET['name'] fd1.email = self.request.GET['email'] fd1.weight = self.request.GET['weight'] fd1.height = self.request.GET['height'] self.response.write(s.second_page(fd1.name, fd1.email, fd1.weight, fd1.height)) else: self.response.write(f.form_page) app = webapp2.WSGIApplication([ ('/', MainHandler) ], debug=True) </code></pre> <p>lib.py</p> <pre><code>class FormData(object): def __init__(self): pass </code></pre> <p>I need to be able to access:</p> <pre><code>fd1.name = self.request.GET['name'] fd1.email = self.request.GET['email'] fd1.weight = self.request.GET['weight'] fd1.height = self.request.GET['height'] </code></pre> <p>In lib.py</p>
0
2016-09-15T04:55:13Z
39,504,590
<p>Your if/else statement is outside the <code>get</code> method, so it shouldn't even work properly.</p> <p>I think the most clean way would be to pass the request data to the <code>FormData</code> class already in the initialiser. So the code would look like this:</p> <p>main.py</p> <pre class="lang-py prettyprint-override"><code>import webapp2 from lib import FormData from pages import FormPage from pages import ResultsPage class MainHandler(webapp2.RequestHandler): def get(self): f = FormPage() s = ResultsPage() fd1 = FormData(data=self.request.GET) if fd1.name: # This is None, if form has not been submitted self.response.write(s.second_page(fd1.name, fd1.email, fd1.weight, fd1.height)) else: self.response.write(f.form_page) app = webapp2.WSGIApplication([ ('/', MainHandler) ], debug=True) </code></pre> <p>lib.py</p> <pre class="lang-py prettyprint-override"><code>class FormData(object): def __init__(self, data): self.name = data.get('name') self.email = data.get('email') self.weight = data.get('weight') self.height = data.get('height') </code></pre> <p>As a side note, I don't really know this webapp2 framework, so there might be a better way to do this.</p>
1
2016-09-15T06:44:45Z
[ "python", "webapp2" ]
Edit list of entries using Python
39,503,430
<p>My script so far:</p> <pre><code>#DogReg v1.0 import time Students = ['Mary', 'Matthew', 'Mark', 'Lianne' 'Spencer' 'John', 'Logan', 'Sam', 'Judy', 'Jc', 'Aj' ] print("1. Add Student") print("2. Delete Student") print("3. Edit Student") print("4. Show All Students") useMenu = input("What shall you do? ") if(useMenu != "1" and useMenu != "2" and useMenu != "3" and useMenu != "4"): print("Invalid request please choose 1, 2, 3, or 4.") elif(useMenu == "1"): newName = input("What is the students name? ") Students.append(newName) time.sleep(1) print(str(newName) + " added.") time.sleep(1) print(Students) elif(useMenu == "2"): remStudent = input("What student would you like to remove? ") Students.remove(remStudent) time.sleep(1) print(str(remStudent) + " has been removed.") time.sleep(1) print(Students) elif(useMenu == "3"): </code></pre> <p>So I'm trying to be able to let the user input a name they want to edit and change it. </p> <p>I tried looking up the function for editing list entries and I haven't found one I'm looking for.</p>
-1
2016-09-15T05:01:02Z
39,503,548
<p>Suppose the user wants to change <code>'Mary'</code> to <code>'Maria'</code>:</p> <pre><code>student_old = 'Mary' student_new = 'Maria' change_index = Students.index(student_old) Students[change_index] = student_new </code></pre> <p>Note that you will have to add proper error handling - for example, if the user asks for modifying <code>'Xavier'</code> who is not in your list, you will get a <code>ValueError</code>.</p>
0
2016-09-15T05:13:00Z
[ "python", "list" ]
Edit list of entries using Python
39,503,430
<p>My script so far:</p> <pre><code>#DogReg v1.0 import time Students = ['Mary', 'Matthew', 'Mark', 'Lianne' 'Spencer' 'John', 'Logan', 'Sam', 'Judy', 'Jc', 'Aj' ] print("1. Add Student") print("2. Delete Student") print("3. Edit Student") print("4. Show All Students") useMenu = input("What shall you do? ") if(useMenu != "1" and useMenu != "2" and useMenu != "3" and useMenu != "4"): print("Invalid request please choose 1, 2, 3, or 4.") elif(useMenu == "1"): newName = input("What is the students name? ") Students.append(newName) time.sleep(1) print(str(newName) + " added.") time.sleep(1) print(Students) elif(useMenu == "2"): remStudent = input("What student would you like to remove? ") Students.remove(remStudent) time.sleep(1) print(str(remStudent) + " has been removed.") time.sleep(1) print(Students) elif(useMenu == "3"): </code></pre> <p>So I'm trying to be able to let the user input a name they want to edit and change it. </p> <p>I tried looking up the function for editing list entries and I haven't found one I'm looking for.</p>
-1
2016-09-15T05:01:02Z
39,503,588
<p>How about this?</p> <pre><code>elif(useMenu == "3"): oldName = input("What student would you like to edit? ") if oldName in Students: index = Students.index(oldName) newName = input("What is the student's new name? ") Students[index] = newName time.sleep(1) print(str(oldName) + " has been edited to " + str(newName)) time.sleep(1) else: print('Student' + oldName + 'not found!') print(Students) </code></pre> <p>with output:</p> <pre><code>1. Add Student 2. Delete Student 3. Edit Student 4. Show All Students What shall you do? '3' What student would you like to edit? 'Mary' What is the student's new name? 'Marry' Mary has been edited to Marry ['Marry', 'Matthew', 'Mark', 'LianneSpencerJohn', 'Logan', 'Sam', 'Judy', 'Jc', 'Aj'] </code></pre>
0
2016-09-15T05:17:58Z
[ "python", "list" ]
Condional annotations on a class in python
39,503,649
<p>Below is the code snippet I want to accomplish. Please help!</p> <pre><code>try: from cinder import interface interface_available = True except ImportError: interface_available = False @interface.volumedriver class EMCCoprHDFCDriver(driver.FibreChannelDriver): </code></pre> <p>Now the above would give an error in case the 'interface' module is not available, i.e, interface_available = False. However, if the 'interface' module is available, the annotation should be used above the class.</p> <p>Is there any way, I can do this? Thanks. </p>
0
2016-09-15T05:23:34Z
39,503,782
<p>Yes there is. </p> <p>If the decorator does not exist then simply use the identity decorator to perform a no-op:</p> <pre><code>try: from cinder.interface import volumedriver except ImportError: def volumedriver(func): return func @volumedriver class EMCCoprHDFCDriver(driver.FibreChannelDriver): </code></pre> <hr> <p>Why this works:</p> <p>A python decorator:</p> <pre><code>@decorator def some_function: pass </code></pre> <p>is just syntactic sugar for calling:</p> <pre><code>some_function = decorator(some_function) </code></pre> <p>If we think about decorators this way, it is clear that if we want to apply a decorator that does nothing (the no-op decorator or identity decorator) we should make a decorator that returns the original function. </p> <pre><code>def identity(func): return func @identity def func(): pass </code></pre>
0
2016-09-15T05:36:01Z
[ "python", "class", "conditional", "python-decorators" ]
Python Client - C++ Server Connection Refused Error
39,503,712
<p>So I'm trying to run a client-server application using Python as the client and C++ as the server. </p> <p>The two are on separate machines - right now I'm running the python client on my macbook pro and the server is a linux desktop I have. </p> <p>I am able to ssh into my linux box with as following: </p> <pre><code>ssh username@address.hopto.org </code></pre> <p>And then entering my password </p> <p>Despite being able to ssh with no problem, I cannot get a port/socket connection to work. </p> <p>Here is my python code: </p> <pre><code>import socket, time client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) client.connect(('username@address.hopto.org', 9999)) print client.send('Hello world!'), 'bytes sent.' time.sleep(0.2) print 'Received message:', client.recv(1024) </code></pre> <p>And here is my C++ server (which has been borrowed from this site: <a href="http://www.cs.utah.edu/~swalton/listings/sockets/programs/part2/chap6/simple-server.c" rel="nofollow">http://www.cs.utah.edu/~swalton/listings/sockets/programs/part2/chap6/simple-server.c</a> )</p> <pre><code>#define MY_PORT 9999 #define MAXBUF 1024 int main(int Count, char *Strings[]) { int sockfd; struct sockaddr_in self; char buffer[MAXBUF]; /*---Create streaming socket---*/ if ( (sockfd = socket(AF_INET, SOCK_STREAM, 0)) &lt; 0 ) { perror("Socket"); exit(errno); } /*---Initialize address/port structure---*/ bzero(&amp;self, sizeof(self)); self.sin_family = AF_INET; self.sin_port = htons(MY_PORT); self.sin_addr.s_addr = INADDR_ANY; /*---Assign a port number to the socket---*/ if ( bind(sockfd, (struct sockaddr*)&amp;self, sizeof(self)) != 0 ) { perror("socket--bind"); exit(errno); } /*---Make it a "listening socket"---*/ if ( listen(sockfd, 20) != 0 ) { perror("socket--listen"); exit(errno); } /*---Forever... ---*/ while (1) { int clientfd; struct sockaddr_in client_addr; int addrlen=sizeof(client_addr); /*---accept a connection (creating a data pipe)---*/ clientfd = accept(sockfd, (struct sockaddr*)&amp;client_addr, &amp;addrlen); printf("%s:%d connected\n", inet_ntoa(client_addr.sin_addr), ntohs(client_addr.sin_port)); /*---Echo back anything sent---*/ send(clientfd, buffer, recv(clientfd, buffer, MAXBUF, 0), 0); /*---Close data connection---*/ close(clientfd); } /*---Clean up (should never get here!)---*/ close(sockfd); return 0; } </code></pre> <p>I've actually tried two separate things for the python/client side: </p> <p>If I write the following: </p> <pre><code>client.connect(('username@address.hopto.org', 9999)) </code></pre> <p>I get this error: <strong>socket.gaierror: [Errno 8] nodename nor servname provided, or not known</strong></p> <p>However if I do: </p> <pre><code>client.connect(('address.hopto.org', 9999)) </code></pre> <p>without the username part...I get this error: </p> <pre><code>socket.error: [Errno 61] Connection refused </code></pre> <p>I'm thinking it's because I have a password on my Linux box that is "blocking" the connection but I don't know how to include it here. </p> <p>I'm a beginner at networking code so a lot of this is very unfamiliar to me. </p>
-1
2016-09-15T05:30:13Z
39,505,671
<p>Connection refused usually means the host is reachable but the port is not opened.<br> May be your request is block by firewall or your server is not running correctly. </p> <p>To avoid the firewall issue. I suggest u can run your python script on same box as the server and use 127.0.0.1 to connect it first.</p>
0
2016-09-15T07:49:28Z
[ "python", "c++", "linux", "sockets", "networking" ]
Convert json using jq based on specific constraints
39,503,715
<p>I have a json file 'OpenEnded_mscoco_val2014.json'.The json file contains 121,512 questions.<br> Here is some sample :</p> <pre><code>"questions": [ { "question": "What is the table made of?", "image_id": 350623, "question_id": 3506232 }, { "question": "Is the food napping on the table?", "image_id": 350623, "question_id": 3506230 }, { "question": "What has been upcycled to make lights?", "image_id": 350623, "question_id": 3506231 }, { "question": "Is this an Spanish town?", "image_id": 8647, "question_id": 86472 } </code></pre> <p>]</p> <p>I used <code>jq -r '.questions | [map(.question), map(.image_id), map(.question_id)] | @csv' OpenEnded_mscoco_val2014_questions.json &gt;&gt; temp.csv</code> to convert json into csv. <br> But here output in csv is question followed by image_id which is what above code does.<br> The expected output is : </p> <pre><code>"What is table made of",350623,3506232 "Is the food napping on the table?",350623,3506230 </code></pre> <p>Also is it possible to filter only results having<code>image_id &lt;= 10000</code> and to <code>group questions having same image_id</code>? e.g. 1,2,3 result of json can be combined to have 3 questions, 1 image_id, 3 question_id.</p> <p>EDIT : The first problem is solved by <code>possible duplicate question</code>.I would like to know if is it possible to invoke comparison operator on command line in jq for converting json file. In this case get all fields from json if <code>image_id &lt;= 10000</code> only.</p>
0
2016-09-15T05:30:24Z
39,504,085
<p>1) Given your input (suitably elaborated to make it valid JSON), the following query generates the CSV output as shown:</p> <pre><code>$ jq -r '.questions[] | [.question, .image_id, .question_id] | @csv' "What is the table made of?",350623,3506232 "Is the food napping on the table?",350623,3506230 "What has been upcycled to make lights?",350623,3506231 "Is this an Spanish town?",8647,86472 </code></pre> <p>The key thing to remember here is that @csv requires a flat array, but as with all jq filters, you can feed it a stream.</p> <p>2) To filter using the criterion <code>.image_id &lt;= 10000</code>, just interpose the appropriate <code>select/1</code> filter:</p> <pre><code>.questions[] | select(.image_id &lt;= 10000) | [.question, .image_id, .question_id] | @csv </code></pre> <p>3) To sort by image_id, use sort_by(.image_id)</p> <pre><code>.questions | sort_by(.image_id) |.[] | [.question, .image_id, .question_id] | @csv </code></pre> <p>4) To group by <code>.image_id</code> you would pipe the output of the following pipeline into your own pipeline:</p> <pre><code>.questions | group_by(.image_id) </code></pre> <p>You will, however, have to decide exactly how you want to combine the grouped objects.</p>
0
2016-09-15T06:06:16Z
[ "python", "json", "csv", "filtering", "jq" ]
Why is my generator implementation incorrect in Python?
39,503,748
<p>So basically i am writing a program where i need to take in a file that contains uppercase letters, that may or may not be seperated by white space or new lines, and return a generator over the letters in the file.</p> <p>For example: </p> <pre><code>Z FM TM CC </code></pre> <p>Would return a generator with an output of "Z","F","M","T","M","C","C"</p> <p>The function should be a generator, so it will only load in letters at a time instead of the entire file.</p> <p>Anyways, here is what i have so far. ANyone tell me where i went wrong?</p> <pre><code>def buildGen: with open(filename) as sample: for word in sample: for ch in word: yield ch </code></pre>
1
2016-09-15T05:33:49Z
39,503,834
<p>You are using wrong indentation and a wrong variable name dna. You need write something like this:</p> <pre><code>def buildGen: with open(filename) as sample: for line in sample.read().splitlines(): for ch in line.split(): yield ch </code></pre>
0
2016-09-15T05:41:53Z
[ "python", "generator" ]
Why is my generator implementation incorrect in Python?
39,503,748
<p>So basically i am writing a program where i need to take in a file that contains uppercase letters, that may or may not be seperated by white space or new lines, and return a generator over the letters in the file.</p> <p>For example: </p> <pre><code>Z FM TM CC </code></pre> <p>Would return a generator with an output of "Z","F","M","T","M","C","C"</p> <p>The function should be a generator, so it will only load in letters at a time instead of the entire file.</p> <p>Anyways, here is what i have so far. ANyone tell me where i went wrong?</p> <pre><code>def buildGen: with open(filename) as sample: for word in sample: for ch in word: yield ch </code></pre>
1
2016-09-15T05:33:49Z
39,503,881
<p>There are a number of problems with your code:</p> <ol> <li><p>You're defining a function with the wrong syntax (<code>def buildGen:</code> &lt;- Parenthesis should follow).</p></li> <li><p>Your description of the output implies that you need to address whitespace characters.</p></li> </ol> <p>The following outputs the output in your example (assuming your file is <code>stuff.txt</code>):</p> <pre><code># Note `buildGen` takes now `filename`. def buildGen(filename): with open(filename) as sample: for word in sample: for ch in word: # Only yield non-whitespace. if ch.strip(): yield ch print list(buildGen('stuff.txt')) </code></pre>
2
2016-09-15T05:46:43Z
[ "python", "generator" ]
Why is my generator implementation incorrect in Python?
39,503,748
<p>So basically i am writing a program where i need to take in a file that contains uppercase letters, that may or may not be seperated by white space or new lines, and return a generator over the letters in the file.</p> <p>For example: </p> <pre><code>Z FM TM CC </code></pre> <p>Would return a generator with an output of "Z","F","M","T","M","C","C"</p> <p>The function should be a generator, so it will only load in letters at a time instead of the entire file.</p> <p>Anyways, here is what i have so far. ANyone tell me where i went wrong?</p> <pre><code>def buildGen: with open(filename) as sample: for word in sample: for ch in word: yield ch </code></pre>
1
2016-09-15T05:33:49Z
39,503,935
<p>your logic here is wrong, as according to my understanding you are trying to read the file and yield all the letters in the file by calling your <code>buildGen</code> function.</p> <p>As you are using a with statement it will close the file each time and you always end up with the first line only. Another point is you are opening the file as sample and using as dna that itself will throw an error.</p> <p>you can achieve the same using this</p> <pre><code>fp = open('sample.txt') # generator for the data data_generator = (c for c in fp.read()) for char in data_generator: print char def read_chars(fp): for line in fp </code></pre>
-1
2016-09-15T05:52:11Z
[ "python", "generator" ]
Why is my generator implementation incorrect in Python?
39,503,748
<p>So basically i am writing a program where i need to take in a file that contains uppercase letters, that may or may not be seperated by white space or new lines, and return a generator over the letters in the file.</p> <p>For example: </p> <pre><code>Z FM TM CC </code></pre> <p>Would return a generator with an output of "Z","F","M","T","M","C","C"</p> <p>The function should be a generator, so it will only load in letters at a time instead of the entire file.</p> <p>Anyways, here is what i have so far. ANyone tell me where i went wrong?</p> <pre><code>def buildGen: with open(filename) as sample: for word in sample: for ch in word: yield ch </code></pre>
1
2016-09-15T05:33:49Z
39,504,580
<p>Assume only <code>uppercase letters</code> will be included in the output and <code>only load in letters at a time instead of the entire file</code>:</p> <pre><code>def buildGen(): with open(filename) as sample: while True: ch = sample.read(1) if ch: if 'A' &lt;= ch &lt;= 'Z': yield ch else: break </code></pre>
0
2016-09-15T06:44:18Z
[ "python", "generator" ]
How do you sequentially flip each dimension in a NumPy array?
39,503,759
<p>I have encountered the following function in MATLAB that sequentially flips all of the dimensions in a matrix:</p> <pre><code>function X=flipall(X) for i=1:ndims(X) X = flipdim(X,i); end end </code></pre> <p>Where <code>X</code> has dimensions <code>(M,N,P) = (24,24,100)</code>. How can I do this in Python, given that <code>X</code> is a NumPy array?</p>
4
2016-09-15T05:34:39Z
39,503,993
<p>The equivalent to <code>flipdim</code> in MATLAB is <a href="http://docs.scipy.org/doc/numpy-dev/reference/generated/numpy.flip.html" rel="nofollow"><code>flip</code></a> in <code>numpy</code>. Be advised that this is only available in version 1.12.0.</p> <p>Therefore, it's simply:</p> <pre><code>import numpy as np def flipall(X): Xcopy = X.copy() for i in range(X.ndim): Xcopy = np.flip(Xcopy, i) return Xcopy </code></pre> <p>As such, you'd simply call it like so:</p> <pre><code>Xflip = flipall(X) </code></pre> <p>However, if you know <em>a priori</em> that you have only three dimensions, you can hard code the operation by simply doing:</p> <pre><code>def flipall(X): return X[::-1,::-1,::-1] </code></pre> <p>This flips each dimension one right after the other.</p> <hr> <p>If you don't have version 1.12.0 (thanks to user hpaulj), you can use <code>slice</code> to do the same operation:</p> <pre><code>import numpy as np def flipall(X): return X[[slice(None,None,-1) for _ in X.shape]] </code></pre>
4
2016-09-15T05:56:25Z
[ "python", "matlab", "numpy", "flip" ]
im trying to create a variable outside of a def, bring that variable into a def change it, then use the modified variable
39,503,811
<p>the code is going to be kind of long, but I'm still new and learning how to compress code. The gist of what im trying to do is</p> <pre><code>L1 = c def code(): let = d let = L1 code L1 = let print (let) </code></pre> <p>I have lots more code involved but the gist of what actually happens in <code>def code():</code> is whatever <code>let</code> equals (which will be a letter) will become the next letter. That all works if I do it for each letter but that makes the code extremely long since whats in code() is about 15 lines long.</p> <p>The point of the program is to code a word or small phrase. So if <code>L1=a</code> then <code>def code():</code> would bring it too the next letter in the alphabet unless it is the same as one of the letters in <code>key</code>. then it will keep going up one letter until it cant be the same as a letter in <code>key</code>. unless <code>L1</code> equals a letter in <code>key</code> from the start in which case, it will stay the same, then repeats that 14 more times.</p> <p>if you would like to see what i mean, this is my actual code.</p> <pre><code>key = ["r", "a", "b", "b", "i", "t"] #Enter word to code print("Welcome to Part 2") print("Type each letter of your word followed by enter") print("Type the 15 letters (or less) word to code.") print("(if word is shorter, leave those spaces blank.)") #Code Word L1 = input ("First Letter: ").lower() L2 = input ("Second Letter: ").lower() L3 = input ("Third Letter: ").lower() L4 = input ("Fourth Letter: ").lower() L5 = input ("Fifth Letter: ").lower() L6 = input ("Sixth Letter: ").lower() L7 = input ("Seventh Letter: ").lower() L8 = input ("Eighth Letter: ").lower() L9 = input ("Ninth Letter: ").lower() L10 = input ("Tenth Letter: ").lower() L11 = input ("Eleventh Letter: ").lower() L12 = input ("Twelfth Letter: ").lower() L13 = input ("Thirteenth Letter: ").lower() L14 = input ("Fourteenth Letter: ").lower() L15 = input ("Fifteenth Letter: ").lower() #combining all the letters into one word if you want to see the word before it codes #code = L1+L2+L3+L4+L5+L6+L7+L8+L9+L10+L11+L12+L13+L14+L15 #Coding the letters #making blank lines print() print() def code(): if let in key: let = let else: let = let.translate(bytes.maketrans(b"abcdefghijklmnopqrstuvwxyz",b"bcdefghijklmnopqrstuvwxyza")) if let in key: let=let.translate(bytes.maketrans(b"abcdefghijklmnopqrstuvwxyz",b"bcdefghijklmnopqrstuvwxyza")) if let in key: let=let.translate(bytes.maketrans(b"abcdefghijklmnopqrstuvwxyz",b"bcdefghijklmnopqrstuvwxyza")) if let in key: let=let.translate(bytes.maketrans(b"abcdefghijklmnopqrstuvwxyz",b"bcdefghijklmnopqrstuvwxyza")) if let in key: let=let.translate(bytes.maketrans(b"abcdefghijklmnopqrstuvwxyz",b"bcdefghijklmnopqrstuvwxyza")) if let in key: let=let.translate(bytes.maketrans(b"abcdefghijklmnopqrstuvwxyz",b"bcdefghijklmnopqrstuvwxyza")) if let in key: let=let.translate(bytes.maketrans(b"abcdefghijklmnopqrstuvwxyz",b"bcdefghijklmnopqrstuvwxyza")) else: let = let else: let = let else: let = let else: let = let else: let = let else: let = let let = L1 code L1= let let = L2 code L2 = let let = L3 code L3= let let = L4 code L4= let let = L5 code L5= let let = L6 code L6= let let = L7 code L7= let let = L8 code L8= let let = L9 code L9= let let = L10 code L10= let let = L11 code L11= let let = L12 code L12= let let = L13 code L13= let let = L14 code L14= let let = L15 code L15= let code = L1+L2+L3+L4+L5+L6+L7+L8+L9+L10+L11+L12+L13+L14+L15 print(code) </code></pre> <p>that's all my code. Now imagine whats in <code>def code():</code> was written for L1-L15 with <code>let</code> being L1-L15 respectively. </p> <p>I have a different version which works but it is the version with <code>code()</code> written out for L1-L15.</p> <p>I'm very sorry if i made no sense. i'm not very sure how to explain what i'm saying. Thanks for the help.</p>
-2
2016-09-15T05:38:43Z
39,504,759
<p>This is rather confusing, so I may not have the right answer here, but I'll take a shot. First, a couple of notes for you.</p> <p>This <code>def code()</code> is normally called a function. It sounds like you want to pass variables into and out from your function, which you can do with parameters. Here's an example:</p> <pre><code>def code(number, key): if number == key: number += 1 return number a_key = 5 a_number = 5 a_number = code(a_number, a_key) print(a_number) &gt;&gt;&gt; 6 </code></pre> <p>You can also clean up your function quite a bit. Those else statements seem to do nothing (just assign a variable to itself, so it doesn't change), so we can just remove them. Also, we can improve readability greatly by using another function as a helper, like so:</p> <pre><code>... # just imagine all your other code is up here def helper_function(letter): return letter.translate(bytes.maketrans(b"abcdefghijklmnopqrstuvwxyz",b"bcdefghijklmnopqrstuvwxyza")) def code(let, key): if let in key: let = let else: let = helper_function(let) if let in key: let=helper_function(let) if let in key: let=helper_function(let) if let in key: let=helper_function(let) if let in key: let=helper_function(let) if let in key: let=helper_function(let) if let in key: let=helper_function(let) return let let = L1 let = code(let, key) L1 = let </code></pre> <p>I may be wrong about what you're trying to do, but these last 3 lines here you might be able to change to</p> <pre><code>L1 = code(L1, key) </code></pre> <p>because it looks like you're only using <code>let</code> as a placeholder for a moment.</p> <p>I hope that helps. Keep working at it!</p>
0
2016-09-15T06:56:04Z
[ "python", "function", "variables" ]
How to export all pages from mediawiki into individual page files?
39,503,835
<p>Related to <a href="http://stackoverflow.com/questions/6739999/how-to-export-text-from-all-pages-of-a-mediawiki">How to export text from all pages of a MediaWiki?</a>, but I want the output be individual text files named using the page title.</p> <pre><code>SELECT page_title, page_touched, old_text FROM revision,page,text WHERE revision.rev_id=page.page_latest AND text.old_id=revision.rev_text_id; </code></pre> <p>works to dump it into stdout and all pages in one go.</p> <p>How to split them and dump into individual files?</p> <p><strong>SOLVED</strong></p> <p>First dump into one single file:</p> <pre><code>SELECT page_title, page_touched, old_text FROM revision,page,text WHERE revision.rev_id=page.page_latest AND text.old_id=revision.rev_text_id AND page_namespace!='6' AND page_namespace!='8' AND page_namespace!='12' INTO OUTFILE '/tmp/wikipages.csv' FIELDS TERMINATED BY '\n' ESCAPED BY '' LINES TERMINATED BY '\n@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@\n'; </code></pre> <p>Then split it into individual file, use python:</p> <pre><code>with open('wikipages.csv', 'rb') as f: alltxt = f.read().split('\n@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@\n') for row in alltxt: one = row.split('\n') name = one[0].replace('/','-') try: del one[0] del one[0] except: continue txt = '\n'.join(one) of = open('/tmp/wikipages/' + name + '.txt', 'w') of.write(txt) of.close() </code></pre>
0
2016-09-15T05:41:58Z
39,842,978
<p>In case you have some python knowledge you can utilize <code>mwclient</code> library to achieve this:</p> <ol> <li>install Python 2.7 <code>sudo apt-get install python2.7</code> ( see <a href="http://askubuntu.com/questions/101591/how-do-i-install-python-2-7-2-on-ubuntu">http://askubuntu.com/questions/101591/how-do-i-install-python-2-7-2-on-ubuntu</a> in case of troubles )</li> <li>install mwclient via <code>pip install mwclient</code></li> <li><p>run python script below</p> <pre><code>import mwclient wiki = mwclient.Site(('http', 'you-wiki-domain.com'), '/') for page in wiki.Pages: file = open(page.page_title, 'w') file.write(page.text()) file.close() </code></pre></li> </ol> <p>see mwclient page <a href="https://github.com/mwclient/mwclient" rel="nofollow">https://github.com/mwclient/mwclient</a> for reference</p>
1
2016-10-04T01:42:52Z
[ "python", "mysql", "mediawiki" ]
Getting size of JSON array and read it's elements Python
39,503,846
<p>I have an json array that looks like this:</p> <pre><code>{ "inventory": [ { "Name": "katt" }, { "Name": "dog" } ] } </code></pre> <p>And now I want to access this array in a program that I'm creating and remove a element, for example "Name": "dog". I'm not super familiar with how to work with json in python, but so far I have tried something like this:</p> <p>import json</p> <pre><code>jsonfile = open("viktor.json", "r") jsonObj = json.load(jsonfile) jsonfile.close() counter = 0 for item in range(len(jsonObj["inventory"])): print(jsonObj["inventory"][counter]) print(type(jsonObj["inventory"][counter])) if jsonObj["inventory"][counter] == argOne: print("hej") counter += 1 </code></pre> <p>So first I read from the json and stores the data in a variable. Then I want to loop through the whole variable and see if I can find any match, and if so, I want to remove it. I think I can use a pop() method here or something? But I can't seem to get my if-statement to work properly since the jsonObj["inventory"][counter] is a dict and argOne is a string.</p> <p>What can I do instead of this? Or what I'm missing?</p>
0
2016-09-15T05:42:57Z
39,503,954
<p>You can use <a href="https://docs.python.org/3/library/functions.html#filter" rel="nofollow">filter</a>:</p> <pre><code>In [11]: import json In [12]: with open("viktor.json", "r") as f: ...: jsonObj = json.load(f) ...: In [13]: argOne = 'katt' #Let's say In [14]: jsonObj['inventory'] = list(filter(lambda x: x['Name'] != argOne, jsonObj['inventory'])) In [15]: jsonObj Out[15]: {'inventory': [{'Name': 'dog'}]} </code></pre>
1
2016-09-15T05:53:25Z
[ "python", "python-3.x" ]
Getting size of JSON array and read it's elements Python
39,503,846
<p>I have an json array that looks like this:</p> <pre><code>{ "inventory": [ { "Name": "katt" }, { "Name": "dog" } ] } </code></pre> <p>And now I want to access this array in a program that I'm creating and remove a element, for example "Name": "dog". I'm not super familiar with how to work with json in python, but so far I have tried something like this:</p> <p>import json</p> <pre><code>jsonfile = open("viktor.json", "r") jsonObj = json.load(jsonfile) jsonfile.close() counter = 0 for item in range(len(jsonObj["inventory"])): print(jsonObj["inventory"][counter]) print(type(jsonObj["inventory"][counter])) if jsonObj["inventory"][counter] == argOne: print("hej") counter += 1 </code></pre> <p>So first I read from the json and stores the data in a variable. Then I want to loop through the whole variable and see if I can find any match, and if so, I want to remove it. I think I can use a pop() method here or something? But I can't seem to get my if-statement to work properly since the jsonObj["inventory"][counter] is a dict and argOne is a string.</p> <p>What can I do instead of this? Or what I'm missing?</p>
0
2016-09-15T05:42:57Z
39,504,152
<p>Making the change suggested by @arvindpdmn (to be more pythonic).</p> <pre><code>for index, item in enumerate(jsonObj["inventory"]): print(item) print(type(item)) # Here we have item is a dict object if item['Name'] == argOne: # So we can access their elements using item['key'] syntax print(index, "Match found") </code></pre> <p>The <code>for</code> loop is responsible to go through the array, which contains <code>dict</code> objects, and for each <code>dict</code> it will create a <code>item</code> variable that we use to try to get a match.</p> <p><strong>edit</strong> In order to remove the element if it is in the list, I suggest you to use this:</p> <pre><code>new_list = [] for item in jsonObj["inventory"]: if item['Name'] is not argOne: # add the item if it does not match new_list.append(item) </code></pre> <p>This way you will end with the list you want (new_list).</p> <pre><code># Or shorter.. and more pythonic with comprehensions lists. new_list = [item for item in jsonObj['inventory'] if item['Name'] is not argOne] </code></pre>
3
2016-09-15T06:11:49Z
[ "python", "python-3.x" ]
How to do an OR on a Django ManyToManyField without getting duplicates?
39,504,066
<p>I have the following two Django Classes <code>MyClassA</code> and <code>MyClassB</code>.</p> <p><code>MyClassB</code> has a many-to-many field of <code>MyClassA</code>s</p> <pre><code>from django.db import models class MyClassA(models.Model): name = models.CharField(max_length=50, null=False) def __str__(self): return "&lt;%s %s&gt;" % ( self.__class__.__name__, "; ".join(["ID: %s" % self.pk, "name: %s" % self.name, ])) class MyClassB(models.Model): name = models.CharField(max_length=50, null=False) my_class_as = models.ManyToManyField(MyClassA, related_name="MyClassB_my_class_as") def __str__(self): return "&lt;%s %s&gt;" % ( self.__class__.__name__, "; ".join(["ID: %s" % self.pk, "name: %s" % self.name, ])) </code></pre> <p>Then I seed the database with the following data:</p> <pre><code>&gt;&gt;&gt; a = MyClassA.objects.create(name="A") &gt;&gt;&gt; b = MyClassA.objects.create(name="B") &gt;&gt;&gt; c = MyClassA.objects.create(name="C") &gt;&gt;&gt; d = MyClassA.objects.create(name="D") &gt;&gt;&gt; e = MyClassA.objects.create(name="E") &gt;&gt;&gt; u = MyClassB.objects.create(name="U") &gt;&gt;&gt; u.my_class_as.add(c) &gt;&gt;&gt; u.my_class_as.add(d) &gt;&gt;&gt; u.save() </code></pre> <p>I want to find the (unique) list of MyClassBs that have a relationship with a instance <code>c</code> or <code>d</code> of MyClassA. How can I do it??</p> <p>My solution was to create the following static method on <code>MyClassB</code>:</p> <pre><code>@staticmethod def is_m2m_related_queryset(my_class_a_list): q = Q() for curr_a in my_class_a_list: q |= Q(my_class_as=curr_a) return q </code></pre> <p>...And then run the following query:</p> <pre><code>&gt;&gt;&gt; MyClassB.objects.filter(MyClassB.is_m2m_related_queryset([c, d])) [&lt;MyClassB: &lt;MyClassB ID: 11; name: U&gt;&gt;, &lt;MyClassB: &lt;MyClassB ID: 11; name: U&gt;&gt;] </code></pre> <p>But wait! Instead of returning to me a singleton list containing the <code>u</code> object as I expected, this queryset returns <code>[u, u]</code>. That's not what I want. Shouldn't this return <code>[u]</code>?? Why did it return what it did? </p> <p>How should I get what I want? Should I simply append a <code>.distinct()</code> to my queryset? Or is there a better/more efficient for me construct my queryset?? </p> <p><strong>EDIT:</strong></p> <p>I tried Andrey's solution suggested below (and a variant thereof), but that didn't work either:</p> <pre><code>&gt;&gt;&gt; MyClassB.objects.filter(my_class_as__pk__in=[c.pk, d.pk]) [&lt;MyClassB: &lt;MyClassB ID: 1; name: U&gt;&gt;, &lt;MyClassB: &lt;MyClassB ID: 1; name: U&gt;&gt;] &gt;&gt;&gt; MyClassB.objects.filter(my_class_as__in=[c, d]) [&lt;MyClassB: &lt;MyClassB ID: 1; name: U&gt;&gt;, &lt;MyClassB: &lt;MyClassB ID: 1; name: U&gt;&gt;] </code></pre>
0
2016-09-15T06:04:23Z
39,504,234
<p>Have you tried:</p> <pre><code>MyClassB.objects.filter(my_class_as__pk__in=[c.pk, d.pk])? </code></pre>
1
2016-09-15T06:18:22Z
[ "python", "django", "orm", "many-to-many", "django-queryset" ]
Take column of string data in pandas dataframe and split into separate columns
39,504,079
<p>I have a pandas dataframe from data I read from a CSV. One column is for the name of a group, while the other column contains a string (that looks like a list), like the following:</p> <pre><code>Group | Followers ------------------------------------------ biebers | u'user1', u'user2', u'user3' catladies | u'user4', u'user5' bkworms | u'user6', u'user7' </code></pre> <p>I'd like to try to split up the strings in the "Followers" column and make a separate dataframe where each row is for a user, as well as a column showing which group they're in. So for this example I'd like to get the following:</p> <pre><code>User | Group -------------------------------- user1 | biebers user2 | biebers user3 | biebers user4 | catladies user5 | catladies user6 | bkworms user7 | bkworms </code></pre> <p>Anyone have suggestions for the best way to approach this? Here's a screenshot of what it looks like:</p> <p><a href="http://i.stack.imgur.com/Os8Ke.png" rel="nofollow"><img src="http://i.stack.imgur.com/Os8Ke.png" alt="enter image description here"></a></p>
2
2016-09-15T06:05:07Z
39,504,462
<pre><code>df.Followers = df.Followers.str.replace(r"u'([^']*)'", r'\1') df.set_index('Group').Followers.str.split(r',\s*', expand=True) \ .stack().rename('User').reset_index('Group').set_index('User') </code></pre> <p><a href="http://i.stack.imgur.com/rZXWi.png" rel="nofollow"><img src="http://i.stack.imgur.com/rZXWi.png" alt="enter image description here"></a></p> <hr> <p>To keep <code>User</code> as a column.</p> <pre><code>df.Followers = df.Followers.str.replace(r"u'([^']*)'", r'\1') df.set_index('Group').Followers.str.split(r',\s*', expand=True) \ .stack().rename('User').reset_index('Group') \ .reset_index(drop=True)[['User', 'Group']] </code></pre>
3
2016-09-15T06:35:37Z
[ "python", "pandas" ]
How to print directly above another print after a series of subsecuent prints but without leaving a blank space in python 2?
39,504,088
<p>Thanks beforehand. I'm currently trying to get some values from an array in the format that another program requieres as input. I'm iterating over i rows and j columns since I need the value of i directly followed by the value of array[i,j] (if non-zero and i different than j) printed directly on the same line for each value on the first dimension. I also need to jump to the next line only for a new value of i. I've achieved it with a normal jump line "\n", but it leaves a blank line and I need the next line to be directly under the previous with no blank line. I know I could easily fix this in bash but I'd like to know a method to do it in python.</p> <p>This is what I'm trying and the result:</p> <pre><code>import numpy as np z=np.arange(100).reshape(10,10) z[5,4]=0 print z for i in xrange(1,10,1): for j in xrange(1,10,1): if not (i==j): if not z[i,j]==0: print j, z[i,j], print "\n" </code></pre> <hr> <pre><code>[[ 0 1 2 3 4 5 6 7 8 9] [10 11 12 13 14 15 16 17 18 19] [20 21 22 23 24 25 26 27 28 29] [30 31 32 33 34 35 36 37 38 39] [40 41 42 43 44 45 46 47 48 49] [50 51 52 53 0 55 56 57 58 59] [60 61 62 63 64 65 66 67 68 69] [70 71 72 73 74 75 76 77 78 79] [80 81 82 83 84 85 86 87 88 89] [90 91 92 93 94 95 96 97 98 99]] 2 12 3 13 4 14 5 15 6 16 7 17 8 18 9 19 1 21 3 23 4 24 5 25 6 26 7 27 8 28 9 29 1 31 2 32 4 34 5 35 6 36 7 37 8 38 9 39 1 41 2 42 3 43 5 45 6 46 7 47 8 48 9 49 1 51 2 52 3 53 6 56 7 57 8 58 9 59 1 61 2 62 3 63 4 64 5 65 7 67 8 68 9 69 1 71 2 72 3 73 4 74 5 75 6 76 8 78 9 79 1 81 2 82 3 83 4 84 5 85 6 86 7 87 9 89 1 91 2 92 3 93 4 94 5 95 6 96 7 97 8 98 </code></pre>
0
2016-09-15T06:06:27Z
39,504,224
<p>A call to print automatically adds a newline at the end of what it prints. You can suppress the newline by adding a comma at the end as you have done. However in your call to <code>print '\n'</code> at the end of the loop, you are adding two newlines because print adds a newline to the end of your '\n'. Either end this print statement with a comma or print the empty string, either will work:</p> <pre><code>import numpy as np z=np.arange(100).reshape(10,10) z[5,4]=0 print z for i in xrange(1,10,1): for j in xrange(1,10,1): if not (i==j): if not z[i,j]==0: print j, z[i,j], print "" # automatically adds newline to end of empty string. # print "\n", # &lt;---- could use this alternatively. Note the comma at the end </code></pre>
0
2016-09-15T06:17:35Z
[ "python", "blank-line" ]
Changing PyQT Table Item from QComboBox to QTableWidgetItem
39,504,283
<p>In my PyQT window, I have a table containing <code>QComboBox</code> in one column. How can the <code>QComboBox</code> later be changed to the regular <code>QTableWidgetItem</code> to display some text?</p> <p>I tried the following but the <code>QComboBox</code> was not replaced by text from <code>QTableWidgetItem</code>.</p> <pre><code>myTable= QTableWidget() myTable.setRowCount(6) myTable.setColumnCount(2) myTable.setHorizontalHeaderLabels(QString("Name;Age;").split(";")) myTable.horizontalHeader().setResizeMode(QHeaderView.Stretch) # Populate with QComboBox in column 1 for i, name in enumerate(nameList): myTable.setItem(i, 0, QTableWidgetItem(name )) ageCombo = QComboBox() for option in ageComboOptions: ageCombo.addItem(option) myTable.setCellWidget(i, 1, ageCombo) # Change column 1 to QTableWidgetItem for i, name in enumerate(nameList): myTable.setItem(i, 1, QTableWidgetItem(name)) </code></pre>
0
2016-09-15T06:21:49Z
39,508,337
<p>The short answer is that if you just <code>removeCellWidget</code> you'll get what you want. Example code below.</p> <p>But in more detail:</p> <p>The "Item" as set by <code>setItem</code> and the "Widget" as set by <code>setCellWidget</code> are different - they play different roles. The item carries the data for the cell: in the model view architecture it's in the model. The widget is doing the display: it's in the view. So, when you set the cell widget you might still expect it to use an item in the model behind it. However, the <code>QTableWidget</code> provides a simplified API to the full model view architecture as used in QT (e.g. see the <code>QTableView</code> and <code>QAbstractitemModel</code>). It provides its own default model which you access via an item for each cell. Then, when you replace the widget on a cell it dispenses with any item at all and just allows you to control the widget directly. Remove the widget and it goes back to using the item.</p> <p>Here's a working example:</p> <pre><code>class MainWindow(QtGui.QMainWindow): def __init__(self): super(MainWindow, self).__init__() self.initUI() def initUI(self): self.myTable= QtGui.QTableWidget() self.myTable.setRowCount(1) self.myTable.setColumnCount(2) item1 = QtGui.QTableWidgetItem("a") self.myTable.setItem(0, 0, item1) item2 = QtGui.QTableWidgetItem("b") self.myTable.setItem(0, 1, item2) self.setCentralWidget(self.myTable) menubar = QtGui.QMenuBar(self) self.setMenuBar(menubar) menu = QtGui.QMenu(menubar) menu.setTitle("Test") action = QtGui.QAction(self) action.setText("Test 1") action.triggered.connect(self.test1) menu.addAction(action) action = QtGui.QAction(self) action.setText("Test 2") action.triggered.connect(self.test2) menu.addAction(action) menubar.addAction(menu.menuAction()) self.show() def test1(self): self.myTable.removeCellWidget(0, 1) def test2(self): combo = QtGui.QComboBox() combo.addItem("c") combo.addItem("d") self.myTable.setCellWidget(0, 1, combo) def main(): app = QtGui.QApplication(sys.argv) mw = MainWindow() sys.exit(app.exec_()) if __name__ == '__main__': main() </code></pre>
2
2016-09-15T10:06:01Z
[ "python", "python-2.7", "pyqt", "pyqt4" ]
Python heapq heappush The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
39,504,333
<p>I'm running into a bug with the <code>heapq</code> library -- the <code>heappush</code> function in particular. The error code (below) gives me no help.</p> <pre><code>(Pdb) heapq.heappush(priority_queue, (f, depth, child_node_puzzle_state)) *** ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() </code></pre> <p>Here's the snippet that is causing the problem...</p> <pre><code>h = compute_heuristic(child_node_puzzle_state, solved_puzzle) depth = current_node[1] + 1 f = h + depth heapq.heappush(priority_queue, [f, depth, child_node_puzzle_state]) </code></pre> <p>I should note that <code>h</code> and <code>depth</code> are <code>int</code>'s and <code>child_node_puzzle_state</code> is a numpy array. Checkout out some of the debugging code...</p> <pre><code>(Pdb) child_node_puzzle_state array([[ 5., 4., 18., 15., 0., 0., 0., 0., 0., 0., 0., 99.], [ 99., 10., 6., 14., 12., 20., 0., 0., 0., 0., 99., 99.], [ 99., 99., 11., 19., 17., 16., 8., 0., 0., 99., 99., 99.], [ 99., 99., 99., 2., 3., 0., 0., 0., 99., 99., 99., 99.], [ 99., 99., 99., 99., 1., 21., 0., 99., 99., 99., 99., 99.], [ 99., 99., 99., 99., 99., 9., 13., 7., 0., 0., 0., 0.]]) (Pdb) child_node_puzzle_state.dtype dtype('float64') (Pdb) p h 3 (Pdb) depth 2 (Pdb) f 5 (Pdb) priority_queue [(5, 2, array([[ 9., 15., 0., 0., 0., 0., 0., 0., 0., 0., 0., 99.], [ 99., 10., 6., 14., 5., 4., 18., 0., 0., 0., 99., 99.], [ 99., 99., 11., 19., 17., 12., 20., 8., 0., 99., 99., 99.], [ 99., 99., 99., 16., 3., 0., 0., 0., 99., 99., 99., 99.], [ 99., 99., 99., 99., 2., 0., 0., 99., 99., 99., 99., 99.], [ 99., 99., 99., 99., 99., 1., 21., 13., 7., 0., 0., ... (Pdb) len(priority_queue) 9 </code></pre> <p>Here's what I cannot figure out... if I change one little thing it works -- but it is semantically wrong. Here's is the change ...</p> <pre><code>h = compute_heuristic(child_node_puzzle_state, solved_puzzle) depth = current_node[1] + 1 heapq.heappush(priority_queue, (h, depth, child_node_puzzle_state)) </code></pre> <p>Did you catch the difference? Instead of computing <code>f = h + depth</code> I just use <code>h</code>. And magically it works? </p> <p>This couldn't be the size, because as I showed in debugging...</p> <pre><code>(Pdb) len(priority_queue) 9 </code></pre> <hr> <p>This really doesn't make sense to me, so I'm going to include more code. First, here is everything needed to compute <code>h</code> there is nothing funky going on, so I really doubt this is the problem. All the functions return integers (although they use numpy arrays)...</p> <pre><code>def tubes_aligned(puzzle_state): current_index = 3 #test for index 3 blue_tube = puzzle_state[3,:] len_of_top_tube = len(blue_tube[blue_tube &lt; 99]) - 3 correct_index = 6 - len_of_top_tube found = False distance = 3 for i in range(3): if i == correct_index: distance = current_index - i found = True if not found: for i in range(5,2,-1): if i == correct_index: distance = i - current_index return distance def balls_in_top_half(puzzle_state): for i in range(6): full_tube = puzzle_state[i,:] num_balls = full_tube[full_tube &lt; 99] num_balls = len(num_balls[num_balls &gt; 0]) if (6 - i - num_balls) != 0: return 1 return 0 def balls_in_correct_place(puzzle_state, solved_puzzle): if is_solved(puzzle_state, solved_puzzle): return 0 else: return 1 def compute_heuristic(puzzle_state, solved_puzzle): # print "computing heuristic" # heuristic (sum all three): # 1. how many tubes is the puzzle state from tubes being aligned -- max is 3 # 2. is there balls in the top portion? 1 -- yes || 0 -- no # 3. are there balls in the wrong place in the bottom half? 1 -- yes || 0 -- no part_1 = tubes_aligned(puzzle_state) part_2 = balls_in_top_half(puzzle_state) part_3 = balls_in_correct_place(puzzle_state, solved_puzzle) return part_1 + part_2 + part_3 </code></pre>
0
2016-09-15T06:26:31Z
39,504,878
<p><code>heapq.heappush</code> will <em>compare</em> an array with other arrays in the heap, if the preceding elements in the tuple you push are otherwise equal.</p> <p>Here is a pure Python implementation of <code>heappush()</code>:</p> <pre><code>def heappush(heap, item): """Push item onto heap, maintaining the heap invariant.""" heap.append(item) _siftdown(heap, 0, len(heap)-1) def _siftdown(heap, startpos, pos): newitem = heap[pos] # Follow the path to the root, moving parents down until finding a place # newitem fits. while pos &gt; startpos: parentpos = (pos - 1) &gt;&gt; 1 parent = heap[parentpos] if newitem &lt; parent: heap[pos] = parent pos = parentpos continue break heap[pos] = newitem </code></pre> <p>The actual implementation will be in C, which is why you get the error without a deeper traceback.</p> <p>Note the <code>newitem &lt; parent</code> comparison; it is <em>that comparison</em> that is throwing the exception, as numpy <code>array</code> objects would be compared element by element and produce a boolean array with true and false results. If there is a state in your heap where <code>f</code> and <code>depth</code> are equal, that comparison must compare the arrays:</p> <pre><code>&gt;&gt;&gt; import numpy &gt;&gt;&gt; t1 = (5, 2, numpy.array([9., 15.])) &gt;&gt;&gt; t2 = (5, 2, numpy.array([10., 15.])) &gt;&gt;&gt; t1 &lt; t2 Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() </code></pre> <p>For you the problem 'disappeared' when you changed the value in the first position of the tuple, making the first two values unique again compared to what is already in your heap. But it doesn't actually solve the underlying problem.</p> <p>You can avoid this issue by inserting a unique count (using <a href="https://docs.python.org/3/library/itertools.html#itertools.count" rel="nofollow"><code>itertools.count()</code></a>) before the array:</p> <pre><code>from itertools import count # a global tiebreaker = count() # each time you push heapq.heappush(priority_queue, (f, depth, next(tiebreaker), child_node_puzzle_state)) </code></pre> <p>The counter ensures that the first three elements of your tuples are <em>always</em> unique. It also means that any later addition to the heap that matches an already-present state on the heuristic score <em>and</em> depth are sorted before older ones. You can use <code>count(step=-1)</code> if you want to inverse that relationship.</p>
6
2016-09-15T07:02:50Z
[ "python", "numpy", "heap" ]
Save pandas (string/object) column as VARCHAR in Oracle DB instead of CLOB (default behaviour)
39,504,351
<p>i am trying to transfer a dataframe to oracle database, but the transfer is taking too long, because the datatype of the variable is showing as <strong>clob</strong> in oracle. However i believe if i convert the datatype from <strong>clob</strong> to string of <strong>9 digits</strong> with <strong>padded 0's</strong> , it will not take that much time. data is </p> <pre><code>product 000012320 000234234 </code></pre> <p>is there a way to change the datatype of this variable to string of 9 digits. so that oracle does not think of it as CLOB object. i have tried the following.</p> <pre><code>df['product']=df['product'].astype(str) </code></pre> <p>or is there something else that might slow the transfer from python to oracle ?</p>
3
2016-09-15T06:27:53Z
39,504,563
<p>use <code>str.zfill</code></p> <pre><code>df['product'].astype(str).str.zfill(9) 0 000012320 1 000234234 Name: product, dtype: object </code></pre>
1
2016-09-15T06:42:54Z
[ "python", "python-3.x", "pandas", "dataframe" ]
Save pandas (string/object) column as VARCHAR in Oracle DB instead of CLOB (default behaviour)
39,504,351
<p>i am trying to transfer a dataframe to oracle database, but the transfer is taking too long, because the datatype of the variable is showing as <strong>clob</strong> in oracle. However i believe if i convert the datatype from <strong>clob</strong> to string of <strong>9 digits</strong> with <strong>padded 0's</strong> , it will not take that much time. data is </p> <pre><code>product 000012320 000234234 </code></pre> <p>is there a way to change the datatype of this variable to string of 9 digits. so that oracle does not think of it as CLOB object. i have tried the following.</p> <pre><code>df['product']=df['product'].astype(str) </code></pre> <p>or is there something else that might slow the transfer from python to oracle ?</p>
3
2016-09-15T06:27:53Z
39,514,888
<p>Here is a demo:</p> <pre><code>import cx_Oracle from sqlalchemy import types, create_engine engine = create_engine('oracle://user:password@host_or_scan_address:1521/ORACLE_SID') In [32]: df Out[32]: c_str c_int c_float 0 aaaaaaa 4 0.046531 1 bbb 6 0.987804 2 ccccccccccccc 7 0.931600 In [33]: df.to_sql('test', engine, index_label='id', if_exists='replace') </code></pre> <p>In Oracle DB:</p> <pre><code>SQL&gt; desc test Name Null? Type ------------------- -------- ------------- ID NUMBER(19) C_STR CLOB C_INT NUMBER(38) C_FLOAT FLOAT(126) </code></pre> <p>now let's specify an SQLAlchemy dtype: 'VARCHAR(max_length_of_C_STR_column)':</p> <pre><code>In [41]: df.c_str.str.len().max() Out[41]: 13 In [42]: df.to_sql('test', engine, index_label='id', if_exists='replace', ....: dtype={'c_str': types.VARCHAR(df.c_str.str.len().max())}) </code></pre> <p>In Oracle DB:</p> <pre><code>SQL&gt; desc test Name Null? Type --------------- -------- ------------------- ID NUMBER(19) C_STR VARCHAR2(13 CHAR) C_INT NUMBER(38) C_FLOAT FLOAT(126) </code></pre> <p>PS for padding your string with 0's please check <a href="http://stackoverflow.com/a/39504563/5741205">@piRSquared's answer</a></p>
1
2016-09-15T15:25:54Z
[ "python", "python-3.x", "pandas", "dataframe" ]
Load Spark RDD to Neo4j in Python
39,504,400
<p>I am working on a project where I am using <strong>Spark</strong> for Data processing. My data is now processed and I need to load the data into <strong>Neo4j</strong>. After loading into Neo4j, I will be using that to showcase the results.</p> <p>I wanted all the implementation to de done in <strong>Python</strong> Programming. But I could't find any library or example on net. Can you please help with links or the libraries or any example.</p> <p>My RDD is a PairedRDD. And in every tuple, I have to create a relationship.<br> <strong>PairedRDD</strong> </p> <pre><code>Key Value Jack [a,b,c] </code></pre> <p>For simplicity purpose, I transformed the RDD to</p> <pre><code> Key value Jack a Jack b Jack c </code></pre> <p>Then I have to create relationships between </p> <pre><code> Jack-&gt;a Jack-&gt;b Jack-&gt;c </code></pre> <p>Based on William Answer, I am able to load a list directly. But this data is throwing the cypher error.</p> <p>I tried like this: </p> <pre><code> def writeBatch(b): print("writing batch of " + str(len(b))) session = driver.session() session.run('UNWIND {batch} AS elt MERGE (n:user1 {user: elt[0]})', {'batch': b}) session.close() def write2neo(v): batch_d.append(v) for hobby in v[1]: batch_d.append([v[0],hobby]) global processed processed += 1 if len(batch) &gt;= 500 or processed &gt;= max: writeBatch(batch) batch[:] = [] max = userhobbies.count() userhobbies.foreach(write2neo) </code></pre> <p>b is the list of lists. Unwinded elt is a list of two elements elt[0],elt[1] as key and values.</p> <p><strong>Error</strong></p> <pre><code>ValueError: Structure signature must be a single byte value </code></pre> <p>Thanks Advance.</p>
0
2016-09-15T06:31:39Z
39,507,738
<p>You can do a <code>foreach</code> on your RDD, example : </p> <pre><code>from neo4j.v1 import GraphDatabase, basic_auth driver = GraphDatabase.driver("bolt://localhost", auth=basic_auth("",""), encrypted=False) from pyspark import SparkContext sc = SparkContext() dt = sc.parallelize(range(1, 5)) def write2neo(v): session = driver.session() session.run("CREATE (n:Node {value: {v} })", {'v': v}) session.close() dt.foreach(write2neo) </code></pre> <p>I would however improve the function to batch the writes, but this simple snippet is working for basic implementation</p> <p><strong>UPDATE WITH EXAMPLE OF BATCHING WRITES</strong></p> <pre><code>sc = SparkContext() batch = [] max = None processed = 0 def writeBatch(b): print("writing batch of " + str(len(b))) session = driver.session() session.run('UNWIND {batch} AS elt CREATE (n:Node {v: elt})', {'batch': b}) session.close() def write2neo(v): batch.append(v) global processed processed += 1 if len(batch) &gt;= 500 or processed &gt;= max: writeBatch(batch) batch[:] = [] dt = sc.parallelize(range(1, 2136)) max = dt.count() dt.foreach(write2neo) </code></pre> <p>- Which results with</p> <pre><code>16/09/15 12:25:47 INFO Executor: Running task 0.0 in stage 1.0 (TID 1) writing batch of 500 writing batch of 500 writing batch of 500 writing batch of 500 writing batch of 135 16/09/15 12:25:47 INFO PythonRunner: Times: total = 279, boot = -103, init = 245, finish = 137 16/09/15 12:25:47 INFO Executor: Finished task 0.0 in stage 1.0 (TID 1). 1301 bytes result sent to driver 16/09/15 12:25:47 INFO TaskSetManager: Finished task 0.0 in stage 1.0 (TID 1) in 294 ms on localhost (1/1) 16/09/15 12:25:47 INFO TaskSchedulerImpl: Removed TaskSet 1.0, whose tasks have all completed, from pool 16/09/15 12:25:47 INFO DAGScheduler: ResultStage 1 (foreach at /Users/ikwattro/dev/graphaware/untitled/writeback.py:36) finished in 0.295 s 16/09/15 12:25:47 INFO DAGScheduler: Job 1 finished: foreach at /Users/ikwattro/dev/graphaware/untitled/writeback.py:36, took 0.308263 s </code></pre>
2
2016-09-15T09:36:49Z
[ "python", "apache-spark", "neo4j", "cypher", "pyspark" ]
Gunicorn can't connect to socket error [Running in vagrant]
39,504,485
<p>I'm running my django app with gunicorn and ran into a weird issue.</p> <p>This command doesn't work -</p> <pre><code>(venv)-bash-4.1$ gunicorn myapp.wsgi -b unix:/opt/myapp/var/run/app.sock [2016-09-15 06:04:12 +0000] [10100] [INFO] Starting gunicorn 19.4.5 [2016-09-15 06:04:12 +0000] [10100] [ERROR] Retrying in 1 second. [2016-09-15 06:04:13 +0000] [10100] [ERROR] Retrying in 1 second. [2016-09-15 06:04:14 +0000] [10100] [ERROR] Retrying in 1 second. [2016-09-15 06:04:15 +0000] [10100] [ERROR] Retrying in 1 second. [2016-09-15 06:04:16 +0000] [10100] [ERROR] Retrying in 1 second. [2016-09-15 06:04:17 +0000] [10100] [ERROR] Can't connect to /opt/myapp/var/run/app.sock </code></pre> <p>This one works</p> <pre><code>(venv)-bash-4.1$ gunicorn myapp.wsgi -b unix:/tmp/myapp.sock [2016-09-15 06:04:58 +0000] [10105] [INFO] Starting gunicorn 19.4.5 [2016-09-15 06:04:58 +0000] [10105] [INFO] Listening at: unix:/tmp/myapp.sock (10105) [2016-09-15 06:04:58 +0000] [10105] [INFO] Using worker: sync [2016-09-15 06:04:58 +0000] [10110] [INFO] Booting worker with pid: 10110 [2016-09-15 06:05:01 +0000] [10105] [INFO] Handling signal: int </code></pre> <p>Provided, I have 777 permissions on /opt/myapp/var/run/ directory. The only difference is the location of socket file.</p> <p>Update : This app is running in a virtualbox VM started with vagrant and /opt/myapp is mapped using fileshare option. </p>
0
2016-09-15T06:36:55Z
39,506,309
<p>I just found that socket files can not be created on a virtualbox shared directory.</p> <p>This link helped me. <a href="https://github.com/burke/zeus/issues/231" rel="nofollow">https://github.com/burke/zeus/issues/231</a></p>
0
2016-09-15T08:23:48Z
[ "python", "django", "gunicorn", "django-wsgi" ]
How to Create a Python dictionary with multiple values from a list?
39,504,622
<p>I have a Python list like below:</p> <pre><code>['Phylum_C3.30', 'CDgu97FdFT6pyfQWZmquhFtiKrL1yp', 'pAnstdjgs3Dzzc8I0fOLERPeXNZIuT_legend', 'pAnstdjgs3Dzzc8I0fOLERPeXNZIuT', 'Family_E3.30', 'iKUmlH47RuphW3NbqXykn0ayizhztF', 'ZzTzTLMDCHIkPBo9waDG3lBZi6u2hG_legend', 'ZzTzTLMDCHIkPBo9waDG3lBZi6u2hG', 'Class_C2.60', 'D0RRB3F0dCl39KuEZNqfdD8q9jKzUu', 'MYe9hzd8BTeg1OW00TMQQ0qc60KWIH_legend', 'MYe9hzd8BTeg1OW00TMQQ0qc60KWIH'] </code></pre> <p>I wish to have a dictionary where keys would be any element that starts with 'Pylum' or 'Class' or 'Order' or 'Family' or 'Genus' and values will all values following that element until the next element with 'Pylum' or 'Class' or 'Order' or 'Family' or 'Genus'.</p> <p>For e.g:</p> <p>The final dictionary will look like:</p> <pre><code>{ "Phylum_C3.30": [ 'CDgu97FdFT6pyfQWZmquhFtiKrL1yp', 'pAnstdjgs3Dzzc8I0fOLERPeXNZIuT_legend', 'pAnstdjgs3Dzzc8I0fOLERPeXNZIuT' ], "Family_E3.30": [ 'iKUmlH47RuphW3NbqXykn0ayizhztF', 'ZzTzTLMDCHIkPBo9waDG3lBZi6u2hG_legend', 'ZzTzTLMDCHIkPBo9waDG3lBZi6u2hG' ], "Class_C2.60": [ 'D0RRB3F0dCl39KuEZNqfdD8q9jKzUu', 'MYe9hzd8BTeg1OW00TMQQ0qc60KWIH_legend', 'MYe9hzd8BTeg1OW00TMQQ0qc60KWIH' ], } </code></pre>
-3
2016-09-15T06:46:40Z
39,504,693
<p>Simply loop over the list, and if a value tests as a key store that as the most 'recent' key seen, and add a list to the dictionary for that key. Then for all other non-key values add to the list associated with the last-seen key:</p> <pre><code>prefixes = ('Pylum', 'Class', 'Order', 'Family', 'Genus') output = {} current_key = None for elem in inputlist: if any(elem.startswith(p) for p in prefixes): # this is a key, add it to the output current_key = elem if current_key not in output: output[current_key] = [] else: output[current_key].append(elem) </code></pre> <p>You can tweak the way a key is handled a bit; dropping the <code>if current_key not in output</code> would result in duplicate entries overwriting previous entries. Or you could raise an exception for the <code>if current_key in output</code> case if duplicate entries is supposed to be a bug.</p>
2
2016-09-15T06:51:12Z
[ "python", "python-2.7", "dictionary" ]
Python converting dictionary to dataframe fail
39,504,624
<p>When I try to convert the following dictionary to dataframe, python repeats each row twice.</p> <pre><code>a = [[[[130.578125, 96, 130.59375, 541], [130.5625, 635, 130.609375, 1055], [130.546875, 657, 130.625, 1917], [130.53125, 707, 130.640625, 1331], [130.515625, 1530, 130.65625, 2104]], [[130.578125, 96, 130.59375, 541], [130.5625, 635, 130.609375, 1055], [130.546875, 657, 130.625, 1917], [130.53125, 707, 130.640625, 1331], [130.515625, 1530, 130.65625, 2104]]], [[[143.34375, 5, 143.359375, 79], [143.328125, 142, 143.375, 129], [143.3125, 132, 143.390625, 137], [143.296875, 126, 143.40625, 118], [143.28125, 113, 143.421875, 125]], [[143.34375, 5, 143.359375, 79], [143.328125, 142, 143.375, 129], [143.3125, 132, 143.390625, 137], [143.296875, 126, 143.40625, 118], [143.28125, 113, 143.421875, 125]]]] b = ['Mini','on'] c = dict(zip(b,a)) d = pd.DataFrame.from_dict(c) print d </code></pre> <p>Python prints the following output:</p> <pre><code> Mini \ 0 [[130.578125, 96, 130.59375, 541], [130.5625, ... 1 [[130.578125, 96, 130.59375, 541], [130.5625, ... on 0 [[143.34375, 5, 143.359375, 79], [143.328125, ... 1 [[143.34375, 5, 143.359375, 79], [143.328125, ... </code></pre> <p>The desired output is:</p> <pre><code> Mini \ 0 [[130.578125, 96, 130.59375, 541], [130.5625, ... on 0 [[143.34375, 5, 143.359375, 79], [143.328125, ... </code></pre> <p>Can someone please suggest how I can fix this?</p>
2
2016-09-15T06:46:45Z
39,504,922
<p>Let's start with an example </p> <p>You're getting</p> <pre><code>pd.DataFrame({'Mini': [1, 1], 'on': [2, 2]}) </code></pre> <p><a href="http://i.stack.imgur.com/dS6Cv.png" rel="nofollow"><img src="http://i.stack.imgur.com/dS6Cv.png" alt="enter image description here"></a></p> <p>When you want</p> <pre><code>pd.DataFrame({'Mini': [1], 'on': [2]}) </code></pre> <p><a href="http://i.stack.imgur.com/Wi9jz.png" rel="nofollow"><img src="http://i.stack.imgur.com/Wi9jz.png" alt="enter image description here"></a></p> <hr> <p>You're definition of <code>a</code> is a 2x2x5x4 array in list form. The first dimension is getting zipped away into the values of the <code>dict</code>. The second dimension is a list of length 2 and I've just demonstrated what happens when you pass such a dictionary to <code>pd.DataFrame</code> </p> <p>To fix it, swap the following line with your previous definition of <code>d</code></p> <pre><code> d = pd.Series(c).to_frame().T </code></pre> <hr> <p><strong><em>Response to comment</em></strong><br> To print entire cell content</p> <pre><code>with pd.option_context('display.max_colwidth', -1): print d </code></pre>
2
2016-09-15T07:06:26Z
[ "python", "pandas", "dictionary", "dataframe" ]
What do you call the item of list when used as an iterator in a for loop?
39,504,872
<p>I'm not sure how you name the <code>n</code> in the following <code>for</code> loop. Is there are a term for it? </p> <pre><code>for n in [1,2,3,4,5]: print i </code></pre> <p>And, am I correct that the list itself is the <code>iterator</code> of the <code>for</code> loop ? </p>
-1
2016-09-15T07:02:38Z
39,505,086
<p>The example you gave is an <a href="https://en.wikipedia.org/wiki/For_loop#Iterator-based_for-loops" rel="nofollow">"iterator-based for-loop"</a></p> <p><code>n</code> is called the <code>loop variable</code>.</p> <p>The role that <code>list</code> plays is more troublesome to name.</p> <p>Indeed, after an interesting conversation with @juanpa.arrivillaga I've concluded that there simply isn't a "clearly correct formal name", nor a commonly used name, for that syntactic element.</p> <p>That being said, I do think that if you referred to it in context in a sentence as "the loop iterator" everyone would know what you meant.</p> <p>In doing so, you take the risk of confusing yourself or someone else with the fact that the syntactic element in that position is not in fact an iterator, its a collection or (loosely, but from the definition in the referenced article) an "iterable of some sort".</p> <p>I suspect that one reason why there isn't a name for this is that we hardly ever have to refer to it in a sentence. Another is that they types of element that can appear in that position vary widely, so it is hard to safely cover them all with a label. </p>
1
2016-09-15T07:16:10Z
[ "python", "terminology" ]
What do you call the item of list when used as an iterator in a for loop?
39,504,872
<p>I'm not sure how you name the <code>n</code> in the following <code>for</code> loop. Is there are a term for it? </p> <pre><code>for n in [1,2,3,4,5]: print i </code></pre> <p>And, am I correct that the list itself is the <code>iterator</code> of the <code>for</code> loop ? </p>
-1
2016-09-15T07:02:38Z
39,507,426
<p>While <code>n</code> is called a <em>loop variable</em> the list is absolutely <strong>not</strong> an iterator. It is iterable object, i.e. and <em>iterable</em>, but it is not an <em>iterator</em>. An iterable may be an iterator itself, but not always. That is to say, iterators are iterable, but not all iterables are iterators. In the case of a <code>list</code> it is simply an iterable. </p> <p>It is an iterable because it implements an <code>__iter__</code> method, which returns an iterator:</p> <p>From the <a href="https://docs.python.org/3/glossary.html#term-iterable" rel="nofollow">Python Glossary</a> an <strong>iterable</strong> is:</p> <blockquote> <p>An object capable of returning its members one at a time. Examples of iterables include all sequence types (such as list, str, and tuple) and some non-sequence types like dict, file objects, and objects of any classes you define with an <code>__iter__()</code> or <code>__getitem__()</code> method. Iterables can be used in a for loop and in many other places where a sequence is needed (zip(), map(), ...). <strong>When an iterable object is passed as an argument to the built-in function <code>iter()</code>, it returns an iterator for the object. This iterator is good for one pass over the set of values. When using iterables, it is usually not necessary to call iter() or deal with iterator objects yourself. The for statement does that automatically for you, creating a temporary unnamed variable to hold the iterator for the duration of the loop.</strong> </p> </blockquote> <p>So, observe: </p> <pre><code>&gt;&gt;&gt; x = [1,2,3] &gt;&gt;&gt; iterator = iter(x) &gt;&gt;&gt; type(iterator) &lt;class 'list_iterator'&gt; &gt;&gt;&gt; next(iterator) 1 &gt;&gt;&gt; next(iterator) 2 &gt;&gt;&gt; next(iterator) 3 &gt;&gt;&gt; next(iterator) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; StopIteration </code></pre> <p>It is illuminating to understand that a for-loop in Python such as the following:</p> <pre><code>for n in some_iterable: # do something </code></pre> <p>is equivalent to:</p> <pre><code>iterator = iter(some_iterable) while True: try: n = next(iterator) # do something except StopIteration as e: break </code></pre> <p>Iterators, which are returned by a call to an object's <code>__iter__</code> method, also implement the <code>__iter__</code> method (usually returning themselves) but they <strong>also</strong> implement a <code>__next__</code> method. Thus, an easy way to check if something is an iterable is to see if it implements a <strong>next</strong> method</p> <pre><code>&gt;&gt;&gt; next(x) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; TypeError: 'list' object is not an iterator </code></pre> <p>Again, from the <a href="https://docs.python.org/3/glossary.html#term-iterator" rel="nofollow">Python Glossary</a>, an <strong>iterator</strong> is:</p> <blockquote> <p>An object representing a stream of data. Repeated calls to the iterator’s <code>__next__()</code> method (or passing it to the built-in function <code>next()</code>) return successive items in the stream. When no more data are available a StopIteration exception is raised instead. At this point, the iterator object is exhausted and any further calls to its <code>__next__()</code> method just raise StopIteration again. <strong>Iterators are required to have an <code>__iter__()</code> method that returns the iterator object itself so every iterator is also iterable and may be used in most places where other iterables are accepted. One notable exception is code which attempts multiple iteration passes. A container object (such as a list) produces a fresh new iterator each time you pass it to the iter() function or use it in a for loop. Attempting this with an iterator will just return the same exhausted iterator object used in the previous iteration pass, making it appear like an empty container.</strong></p> </blockquote> <p>I've illustrated the bevahior of an iterator with the <code>next</code> function above, so now I want to concentrate on the bolded portion.</p> <p>Basically, an iterator can be used in the place of an iterable because iterators are always iterable. However, an iterator is good for only a single pass. So, if I use a non-iterator iterable, like a list, I can do stuff like this:</p> <pre><code>&gt;&gt;&gt; my_list = ['a','b','c'] &gt;&gt;&gt; for c in my_list: ... print(c) ... a b c </code></pre> <p>And this:</p> <pre><code>&gt;&gt;&gt; for c1 in my_list: ... for c2 in my_list: ... print(c1,c2) ... a a a b a c b a b b b c c a c b c c &gt;&gt;&gt; </code></pre> <p>An iterator behaves almost in the same way, so I can still do this:</p> <pre><code>&gt;&gt;&gt; it = iter(my_list) &gt;&gt;&gt; for c in it: ... print(c) ... a b c &gt;&gt;&gt; </code></pre> <p>However, iterators do not support multiple iteration (well, you can make your an iterator that does, but generally they do not):</p> <pre><code>&gt;&gt;&gt; it = iter(my_list) &gt;&gt;&gt; for c1 in it: ... for c2 in it: ... print(c1,c2) ... a b a c </code></pre> <p>Why is that? Well, recall what is happening with the iterator protocol which is used by a <code>for</code> loop under the hood, and consider the following:</p> <pre><code>&gt;&gt;&gt; my_list = ['a','b','c','d','e','f','g'] &gt;&gt;&gt; iterator = iter(my_list) &gt;&gt;&gt; iterator_of_iterator = iter(iterator) &gt;&gt;&gt; next(iterator) 'a' &gt;&gt;&gt; next(iterator) 'b' &gt;&gt;&gt; next(iterator_of_iterator) 'c' &gt;&gt;&gt; next(iterator_of_iterator) 'd' &gt;&gt;&gt; next(iterator) 'e' &gt;&gt;&gt; next(iterator_of_iterator) 'f' &gt;&gt;&gt; next(iterator) 'g' &gt;&gt;&gt; next(iterator) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; StopIteration &gt;&gt;&gt; next(iterator_of_iterator) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; StopIteration &gt;&gt;&gt; </code></pre> <p>When I used <code>iter()</code> on an iterator, it returned itself!</p> <pre><code>&gt;&gt;&gt; id(iterator) 139788446566216 &gt;&gt;&gt; id(iterator_of_iterator) 139788446566216 </code></pre>
1
2016-09-15T09:23:10Z
[ "python", "terminology" ]
python, pyspark : get sum of a pyspark dataframe column values
39,504,950
<p>say I have a dataframe like this</p> <pre><code>name age city abc 20 A def 30 B </code></pre> <p>i want to add a summary row at the end of the dataframe, so result will be like</p> <pre><code>name age city abc 20 A def 30 B All 50 All </code></pre> <p>So String 'All', I can easily put, but how to get sum(df['age']) ###column object is not iterable</p> <pre><code>data = spark.createDataFrame([("abc", 20, "A"), ("def", 30, "B")],["name", "age", "city"]) data.printSchema() #root #|-- name: string (nullable = true) #|-- age: long (nullable = true) #|-- city: string (nullable = true) res = data.union(spark.createDataFrame([('All',sum(data['age']),'All')], data.columns)) ## TypeError: Column is not iterable #Even tried with data['age'].sum() and got error. If i am using [('All',50,'All')], it is doing fine. </code></pre> <p>I usually work on Pandas dataframe and new to Spark. Might be my undestanding about spark dataframe is not that matured.</p> <p>Please suggest, how to get the sum over a dataframe-column in pyspark. And if there is any better way to add/append a row to end of a dataframe. Thanks.</p>
1
2016-09-15T07:08:21Z
39,530,864
<p>A dataframe is immutable, you need to create a new one. To get the sum of your age, you can use this function: <code>data.rdd.map(lambda x: float(x["age"])).reduce(lambda x, y: x+y)</code></p> <p>The way you add a row is fine, but why would you do such a thing? Your dataframe will be hard to manipulate and you wont be able to use aggregations functions unless you drop the last line.</p>
1
2016-09-16T11:54:01Z
[ "python", "pyspark", "pyspark-sql" ]
python, pyspark : get sum of a pyspark dataframe column values
39,504,950
<p>say I have a dataframe like this</p> <pre><code>name age city abc 20 A def 30 B </code></pre> <p>i want to add a summary row at the end of the dataframe, so result will be like</p> <pre><code>name age city abc 20 A def 30 B All 50 All </code></pre> <p>So String 'All', I can easily put, but how to get sum(df['age']) ###column object is not iterable</p> <pre><code>data = spark.createDataFrame([("abc", 20, "A"), ("def", 30, "B")],["name", "age", "city"]) data.printSchema() #root #|-- name: string (nullable = true) #|-- age: long (nullable = true) #|-- city: string (nullable = true) res = data.union(spark.createDataFrame([('All',sum(data['age']),'All')], data.columns)) ## TypeError: Column is not iterable #Even tried with data['age'].sum() and got error. If i am using [('All',50,'All')], it is doing fine. </code></pre> <p>I usually work on Pandas dataframe and new to Spark. Might be my undestanding about spark dataframe is not that matured.</p> <p>Please suggest, how to get the sum over a dataframe-column in pyspark. And if there is any better way to add/append a row to end of a dataframe. Thanks.</p>
1
2016-09-15T07:08:21Z
39,531,351
<p>Spark SQL has a dedicated module for column functions <a href="http://spark.apache.org/docs/latest/api/python/pyspark.sql.html#module-pyspark.sql.functions" rel="nofollow"><code>pyspark.sql.functions</code></a>.<br> So the way it works is:</p> <pre><code>from pyspark.sql import functions as F data = spark.createDataFrame([("abc", 20, "A"), ("def", 30, "B")],["name", "age", "city"]) res = data.unionAll( data.select([ F.lit('All').alias('name'), # create a cloumn named 'name' and filled with 'All' F.sum(data.age).alias('age'), # get the sum of 'age' F.lit('All').alias('city') # create a column named 'city' and filled with 'All' ])) res.show() </code></pre> <p>Prints:</p> <pre><code>+----+---+----+ |name|age|city| +----+---+----+ | abc| 20| A| | def| 30| B| | All| 50| All| +----+---+----+ </code></pre>
1
2016-09-16T12:19:00Z
[ "python", "pyspark", "pyspark-sql" ]
How to replace " (double quote) with space or remove space?
39,505,003
<p>It's a very simple and basic question that remove double quotes in python, I couldn't get it.</p> <pre><code>print text "'abc' : 'xyz'" </code></pre> <p>I want it to display as below</p> <pre><code>'abc' : 'xyz' </code></pre> <p>tried many ways but didn't get the required way</p> <pre><code>text.replace("\""," "); # but it display as it is. </code></pre> <p>Could someone tell me to correct syntax?</p>
-1
2016-09-15T07:11:45Z
39,505,077
<p>You don't specify how <code>text</code> was defined. Consider:</p> <pre><code>&gt;&gt;&gt; text = "'abc' : 'xyz'" &gt;&gt;&gt; print text 'abc' : 'xyz' </code></pre> <p>That prints as you want. So, maybe you defined <code>text</code> like this:</p> <pre><code>&gt;&gt;&gt; text = "\"'abc' : 'xyz'\"" &gt;&gt;&gt; print text "'abc' : 'xyz'" </code></pre> <p>That shows the print out that you see. To eliminate the <code>"</code>:</p> <pre><code>&gt;&gt;&gt; print text.replace('"', '') 'abc' : 'xyz' </code></pre>
0
2016-09-15T07:15:54Z
[ "python", "python-2.7" ]
How to replace " (double quote) with space or remove space?
39,505,003
<p>It's a very simple and basic question that remove double quotes in python, I couldn't get it.</p> <pre><code>print text "'abc' : 'xyz'" </code></pre> <p>I want it to display as below</p> <pre><code>'abc' : 'xyz' </code></pre> <p>tried many ways but didn't get the required way</p> <pre><code>text.replace("\""," "); # but it display as it is. </code></pre> <p>Could someone tell me to correct syntax?</p>
-1
2016-09-15T07:11:45Z
39,505,083
<p>The <code>replace</code> method does not modify the string in place, but it returns the new value. So you can try</p> <pre><code>text = text.replace('"', '') </code></pre>
0
2016-09-15T07:16:01Z
[ "python", "python-2.7" ]
How to replace " (double quote) with space or remove space?
39,505,003
<p>It's a very simple and basic question that remove double quotes in python, I couldn't get it.</p> <pre><code>print text "'abc' : 'xyz'" </code></pre> <p>I want it to display as below</p> <pre><code>'abc' : 'xyz' </code></pre> <p>tried many ways but didn't get the required way</p> <pre><code>text.replace("\""," "); # but it display as it is. </code></pre> <p>Could someone tell me to correct syntax?</p>
-1
2016-09-15T07:11:45Z
39,505,155
<p>There's even better <code>str</code> method for this:</p> <pre><code>&gt;&gt;&gt; print text.strip('"') </code></pre> <p>Or, if you want to make <code>strip</code> effect permanent:</p> <pre><code>&gt;&gt;&gt; text = text.strip('"') &gt;&gt;&gt; print text </code></pre>
1
2016-09-15T07:20:24Z
[ "python", "python-2.7" ]
Error in keras when compiling autoencoder?
39,505,059
<p>This is the model of my autoencoder: </p> <pre><code>input_img = Input(shape=(1, 32, 32)) x = Convolution2D(16, 3, 3, activation='relu', border_mode='same')(input_img) x = MaxPooling2D((2, 2), border_mode='same')(x) x = Convolution2D(8, 3, 3, activation='relu', border_mode='same')(x) x = MaxPooling2D((2, 2), border_mode='same')(x) x = Convolution2D(8, 2, 2, activation='relu', border_mode='same')(x) encoded = MaxPooling2D((2, 2), border_mode='same')(x) x = Convolution2D(8, 3, 3, activation='relu', border_mode='same')(encoded) x = UpSampling2D((2, 2))(x) x = Convolution2D(8, 3, 3, activation='relu', border_mode='same')(x) x = UpSampling2D((2, 2))(x) x = Convolution2D(16, 3, 3, activation='relu')(x) x = UpSampling2D((2, 2))(x) decoded = Convolution2D(1, 3, 3, activation='sigmoid', border_mode='same')(x) autoencoder = Model(input_img, decoded) autoencoder.compile(optimizer='adadelta', loss='binary_crossentropy') </code></pre> <p>This is my fit and predict function:</p> <pre><code>autoencoder.fit(X_train, X_train, nb_epoch=10, batch_size=128, shuffle=True, validation_data=(X_test, X_test)) decoded_imgs = autoencoder.predict(X_test) </code></pre> <p>When i try to compile this i get the following error. All the images of my dataset are 32x32 pixels. Why this error then ? </p> <pre><code>Exception: Error when checking model target: expected convolution2d_7 to have shape (None, 1, 28, 28) but got array with shape (4200, 1, 32, 32) </code></pre> <p>What change do i need to do in my model such that the input shape becomes (1,32,32) ? </p>
1
2016-09-15T07:14:32Z
39,507,343
<p>That was simple: </p> <pre><code>input_img = Input(shape=(1, 32, 32)) x = Convolution2D(16, 3, 3, activation='relu', border_mode='same')(input_img) x = MaxPooling2D((2, 2), border_mode='same')(x) x = Convolution2D(8, 3, 3, activation='relu', border_mode='same')(x) x = MaxPooling2D((2, 2), border_mode='same')(x) x = Convolution2D(8, 2, 2, activation='relu', border_mode='same')(x) encoded = MaxPooling2D((2, 2), border_mode='same')(x) x = Convolution2D(8, 3, 3, activation='relu', border_mode='same')(encoded) x = UpSampling2D((2, 2))(x) x = Convolution2D(8, 3, 3, activation='relu', border_mode='same')(x) x = UpSampling2D((2, 2))(x) x = Convolution2D(16, 3, 3, activation='relu', border_mode='same')(x) x = UpSampling2D((2, 2))(x) decoded = Convolution2D(1, 3, 3, activation='sigmoid', border_mode='same')(x) autoencoder = Model(input_img, decoded) autoencoder.compile(optimizer='adadelta', loss='binary_crossentropy') </code></pre> <p>You forgot about adding appropriate <code>border_mode='same'</code> in the 6th convolutional layer. </p>
1
2016-09-15T09:19:48Z
[ "python", "machine-learning", "neural-network", "keras", "autoencoder" ]
Create a permutation with same autocorrelation
39,505,153
<p>My question is similar to <a href="https://stackoverflow.com/questions/33898665/python-generate-array-of-specific-autocorrelation">this one</a>, but with the difference that I need an array of zeros and ones as output. I have an original time series of zeroes and ones with high autocorrelation (i.e., the ones are clustered). For some significance-testing I need to create random arrays with the same number of zeroes and ones. I.e. permutations of the original array, however, also the autocorrelation should stay the same/similar to the original so a simple <code>np.permutation</code> does not help me. </p> <p>Since I'm doing multiple realizations I would need a solution which is as fast as possible. Any help is much appreciated. </p>
4
2016-09-15T07:20:09Z
39,570,977
<p>According to the question to which you refer, you would like to permute <code>x</code> such that </p> <pre><code>np.corrcoef(x[0: len(x) - 1], x[1: ])[0][1] </code></pre> <p>doesn't change. </p> <p>Say the sequence <em>x</em> is composed of </p> <p><em>z<sub>1</sub> o<sub>1</sub> z<sub>2</sub> o<sub>2</sub> z<sub>3</sub> o<sub>3</sub> ... z<sub>k</sub> o<sub>k</sub></em>, </p> <p>where each <em>z<sub>i</sub></em> is a sequence of 0s, and each <em>o<sub>i</sub></em> is a sequence of 1s. (There are four cases, depending on whether the sequence starts with 0s or 1s, and whether it ends with 0s or 1s, but they're all the same in principle).</p> <p>Suppose <em>p</em> and <em>q</em> are each permutations of <em>{1, ..., k}</em>, and consider the sequence </p> <p><em>z<sub>p[1]</sub> o<sub>q[1]</sub> z<sub>p[2]</sub> o<sub>q[2]</sub> z<sub>p[3]</sub> o<sub>q[3]</sub> ... z<sub>p[k]</sub> o<sub>q[k]</sub></em>,</p> <p>that is, each of the run-length sub-sequences of 0s and 1s have been permuted internally. </p> <p>For example, suppose the original sequence is</p> <p><em>0, 0, 0, 1, 1, 0, 1</em>.</p> <p>Then </p> <p><em>0, 0, 0, 1, 0, 1, 1</em>, </p> <p>is such a permutation, as well as</p> <p><em>0, 1, 1, 0, 0, 0, 1</em>,</p> <p>and</p> <p><em>0, 1, 0, 0, 0, 1, 1</em>.</p> <p>Performing this permutation will not change the correlation:</p> <ul> <li>within each run, the differences are the same</li> <li>the boundaries between the runs are the same as before</li> </ul> <p>Therefore, this gives a way to generate permutations which do not affect the correlation. (Also, see at the end another far simpler and more efficient way which can work in many common cases.)</p> <p>We start with the function <code>preprocess</code>, which takes the sequence, and returns a tuple <code>starts_with_zero, zeros, ones</code>, indicating, respectively,</p> <ul> <li>whether <code>x</code> began with 0</li> <li>The 0 runs</li> <li>The 1 runs</li> </ul> <p>In code, this is</p> <pre><code>import numpy as np import itertools def preprocess(x): def find_runs(x, val): matches = np.concatenate(([0], np.equal(x, val).view(np.int8), [0])) absdiff = np.abs(np.diff(matches)) ranges = np.where(absdiff == 1)[0].reshape(-1, 2) return ranges[:, 1] - ranges[:, 0] starts_with_zero = x[0] == 0 run_lengths_0 = find_runs(x, 0) run_lengths_1 = find_runs(x, 1) zeros = [np.zeros(l) for l in run_lengths_0] ones = [np.ones(l) for l in run_lengths_1] return starts_with_zero, zeros, ones </code></pre> <p>(This function borrows from an answer to <a href="http://stackoverflow.com/questions/1066758/find-length-of-sequences-of-identical-values-in-a-numpy-array">this question</a>.)</p> <p>To use this function, you could do, e.g., </p> <pre><code>x = (np.random.uniform(size=10000) &gt; 0.2).astype(int) starts_with_zero, zeros, ones = preprocess(x) </code></pre> <p>Now we write a function to permute internally the 0 and 1 runs, and concatenate the results:</p> <pre><code>def get_next_permutation(starts_with_zero, zeros, ones): np.random.shuffle(zeros) np.random.shuffle(ones) if starts_with_zero: all_ = itertools.izip_longest(zeros, ones, fillvalue=np.array([])) else: all_ = itertools.izip_longest(ones, zeros, fillvalue=np.array([])) all_ = [e for p in all_ for e in p] x_tag = np.concatenate(all_) return x_tag </code></pre> <p>To generate another permutation (with same correlation), you would use</p> <pre><code>x_tag = get_next_permutation(starts_with_zero, zeros, ones) </code></pre> <p>To generate many permutations, you could do:</p> <pre><code>starts_with_zero, zeros, ones = preprocess(x) for i in range(&lt;number of permutations needed): x_tag = get_next_permutation(starts_with_zero, zeros, ones) </code></pre> <hr> <p><strong>Example</strong></p> <p>Suppose we run</p> <pre><code>x = (np.random.uniform(size=10000) &gt; 0.2).astype(int) print np.corrcoef(x[0: len(x) - 1], x[1: ])[0][1] starts_with_zero, zeros, ones = preprocess(x) for i in range(10): x_tag = get_next_permutation(starts_with_zero, zeros, ones) print x_tag[: 50] print np.corrcoef(x_tag[0: len(x_tag) - 1], x_tag[1: ])[0][1] </code></pre> <p>Then we get:</p> <pre><code>0.00674330566615 [ 1. 1. 1. 1. 1. 0. 0. 1. 1. 1. 1. 1. 1. 1. 1. 0. 1. 0. 1. 1. 0. 1. 1. 1. 1. 0. 1. 1. 0. 0. 1. 0. 1. 1. 1. 1. 0. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1.] 0.00674330566615 [ 1. 0. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 0. 1. 1. 0. 1. 1. 1. 1. 1. 1. 0. 0. 1. 0. 1. 1. 1. 1. 0. 0. 0. 1. 1. 1. 1. 1. 1. 1.] 0.00674330566615 [ 1. 1. 1. 1. 1. 0. 0. 1. 1. 1. 0. 0. 0. 0. 1. 0. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 0. 1. 1. 0. 1. 1. 1. 1. 1. 1. 1. 1. 0. 1. 0. 0. 1. 1. 1. 0.] 0.00674330566615 [ 1. 1. 1. 1. 0. 1. 0. 1. 1. 1. 1. 1. 1. 1. 0. 1. 1. 0. 1. 1. 1. 1. 1. 0. 0. 1. 1. 1. 1. 0. 1. 1. 1. 1. 1. 1. 1. 1. 1. 0. 1. 1. 1. 1. 1. 1. 1. 0. 0. 1.] 0.00674330566615 [ 1. 1. 1. 1. 0. 0. 0. 0. 1. 1. 0. 1. 1. 0. 0. 1. 0. 1. 1. 1. 0. 1. 0. 1. 1. 0. 1. 1. 1. 1. 1. 1. 1. 0. 0. 1. 0. 1. 1. 1. 1. 1. 1. 0. 1. 0. 1. 1. 1. 1.] 0.00674330566615 [ 1. 1. 0. 1. 1. 1. 0. 0. 1. 1. 0. 1. 1. 0. 0. 1. 1. 0. 1. 1. 1. 0. 1. 1. 1. 1. 0. 0. 0. 1. 1. 1. 1. 1. 1. 1. 0. 1. 1. 1. 1. 0. 1. 1. 0. 1. 0. 0. 1. 1.] 0.00674330566615 [ 1. 1. 0. 0. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 0. 1. 1. 1. 0. 1. 1. 1. 1. 1. 1. 1. 0. 1. 0. 1. 1. 0. 1. 0. 1. 1. 1. 1.] 0.00674330566615 [ 1. 1. 1. 1. 1. 1. 1. 0. 1. 1. 0. 1. 1. 0. 1. 0. 1. 1. 1. 1. 1. 0. 1. 0. 1. 1. 0. 1. 1. 1. 0. 1. 1. 1. 1. 0. 0. 1. 1. 1. 0. 1. 1. 0. 1. 1. 0. 1. 1. 1.] 0.00674330566615 [ 1. 1. 1. 0. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 0. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 0. 1. 1. 1. 0. 1. 1. 1. 0. 1. 1. 1. 1. 1. 1. 0. 1. 1. 0. 1. 1. 1.] 0.00674330566615 [ 1. 1. 0. 1. 1. 1. 1. 0. 1. 1. 1. 1. 1. 1. 0. 1. 0. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 0. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 0. 1. 0. 1. 0. 1. 1. 1. 1. 1. 1. 0.] </code></pre> <hr> <p>Note that there is a much simpler solution if </p> <ul> <li><p>your sequence is of length <em>n</em>, </p></li> <li><p>some number <em>m</em> has <em>m &lt;&lt; n</em>, and </p></li> <li><p><em>m!</em> is much larger than the number of permutations you need.</p></li> </ul> <p>In this case, simply divide your sequence into <em>m</em> (approximately) equal parts, and permute them randomly. As noted before, only the <em>m - 1</em> boundaries change in a way that potentially affects the correlations. Since <em>m &lt;&lt; n</em>, this is negligible.</p> <p>For some numbers, say you have a sequence with 10000 elements. It is known that <a href="https://en.wikipedia.org/wiki/Factorial" rel="nofollow">20! = 2432902008176640000</a>, which is far far more permutations than you need, probably. By dividing your sequence into 20 parts and permuting, you're affecting at most 19 / 10000 with might be small enough. For these sizes, this is the method I'd use.</p>
2
2016-09-19T10:30:08Z
[ "python", "numpy", "random", "permutation" ]
Django get context data across Views
39,505,184
<p>I know that there are several generic views like <code>ListView</code>, <code>DetailView</code>, or simply <code>View</code>. The thing is can I actually get the context data that are declared in a <code>BaseMixin</code>'s <code>get_context_data()</code> and use it in a View that doesn't have override <code>get_context_data()</code>? Example:</p> <pre><code> class BaseMixin(object): def get_context_data(self, *args, **kwargs): context = super(BaseMixin, self).get_context_data(**kwargs) context['test'] = 1 return context </code></pre> <p>And the view that extends this <code>BaseMixin</code>:</p> <pre><code>class FooView(BaseMixin, View): def foo(self, request): context = super(BaseMixin, self).get_context_data(**kwargs) # do something return </code></pre> <p>This is not working actually, even after put <code>**kwargs</code> as a parameter in <code>foo()</code>. The error is <code>'super' object has no attribute 'get_context_data'</code>. So is there a way to get context data which was set in <code>BaseMixin</code> in <code>FooView</code> ?</p> <p>Thanks for your answers :)</p>
0
2016-09-15T07:21:39Z
39,506,330
<p>Thanks to @Sayes and all answer posters, I finally solved this problem. From what I figured out, the problem is actually in <code>BaseMixin</code>, the inherited class of <code>BaseMixin</code>, which is <code>object</code>, doesn't have a <code>get_context_data()</code> function, just like @Sayes commented. After replace this <code>object</code> with <code>ContextMixin</code>, everything works perfectly, at least perfectly for now.</p> <p>Here is the modified <code>BaseMixin</code>:</p> <pre><code>class BaseMixin(ContextMixin): def get_context_data(self, *args, **kwargs): # do something return context </code></pre>
1
2016-09-15T08:25:10Z
[ "python", "django", "python-3.x" ]
list comprehension and item with chinese character
39,505,205
<p>I have the following code which will grab some data with Chinese character from a website.</p> <pre><code>import csv import requests from bs4 import BeautifulSoup url = "http://www.hkcpast.net/cpast_homepage/xyzbforms/BetMatchDetails.asp?tBetDate=2016/9/11" r = requests.get(url) soup = BeautifulSoup(r.content, "html.parser") for a in soup.find_all('html'): a.decompose() list = [] for row in soup.find_all('tr'): cols = row.find_all('td') for col in cols: if len(col) &gt; 0: list.append(col.text.encode('utf-8').strip()) </code></pre> <p>For now the result is like this:</p> <pre><code>[1, x, y, z, 2, x, y, z, 3, x, y, z] </code></pre> <p>My question is I want to create some sublists from the list, which the is separated by a number (1, 2, 3, 4 ,5 . .. . .)</p> <p>so that the result will be like this:</p> <pre><code>[1, x, y, z] [2, x, y, z] [3, x, y, z] </code></pre> <p>the ultimate goal of this is to write each sublist as a row in a csv file. Does it make sense to first separate the list into each entry and then write into a csv file? </p>
1
2016-09-15T07:22:53Z
39,506,227
<p>The literal translation of your code would look like:</p> <pre><code>list = [] for row in soup.find_all('tr'): cols = row.find_all('td') for col in cols: if len(col) = 0: continue # Save some indentation txt = col.text.encode('utf-8').strip() try: _ = int(txt) # txt is an int. Append new sub-list list.append( [txt] ) except ValueError: # txt is not an int, append it to the end of previous sub-list list[-1].append(txt) </code></pre> <p>(Note that this will fail horribly if the first entry is not an int!)</p> <p>However, I suspect you actually want to create a new sub-list for each row in the table.</p>
0
2016-09-15T08:19:14Z
[ "python", "list", "csv" ]
Opening IE explorere with Selenium in python 35 gives weird error
39,505,207
<p>After correcting zoom level IE now opens python.org but I still get lots of errors'</p> <pre><code>from selenium import webdriver Scripts\\drivers\\IEDriverServer.exe") driver = webdriver.Ie() driver.get("http://www.python.org") assert "Python" in driver.title elem = driver.find_element_by_name("q") elem.clear() elem.send_keys("pycon") elem.send_keys(Keys.RETURN) assert "No results found." not in driver.page_source driver.close() </code></pre> <p>I get these errors in python:</p> <blockquote> <blockquote> <blockquote> <blockquote> <blockquote> <blockquote> <blockquote> <blockquote> <blockquote> <blockquote> <blockquote> <blockquote> <p>Traceback (most recent call last): File "", line 1, in AssertionError Traceback (most recent call last): File "", line 1, in File "C:\Users\g14988\Documents\Anaconda\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 365, in find_element_by_name return self.find_element(by=By.NAME, value=name) File "C:\Users\g14988\Documents\Anaconda\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 752, in find_element 'value': value})['value'] File "C:\Users\g14988\Documents\Anaconda\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 236, in execute self.error_handler.check_response(response) File "C:\Users\g14988\Documents\Anaconda\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 192, in check_response raise exception_class(message, screen, stacktrace) selenium.common.exceptions.NoSuchElementException: Message: Unable to find element with name == q</p> </blockquote> </blockquote> </blockquote> </blockquote> </blockquote> </blockquote> </blockquote> </blockquote> </blockquote> <p>Traceback (most recent call last): File "", line 1, in NameError: name 'elem' is not defined Traceback (most recent call last): File "", line 1, in NameError: name 'elem' is not defined Traceback (most recent call last): File "", line 1, in NameError: name 'elem' is not defined</p> <blockquote> <blockquote> <blockquote> <p>Traceback (most recent call last): File "", line 1, in File "C:\Users\g14988\Documents\Anaconda\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 510, in close self.execute(Command.CLOSE) File "C:\Users\g14988\Documents\Anaconda\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 236, in execute self.error_handler.check_response(response) File "C:\Users\g14988\Documents\Anaconda\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 192, in check_response raise exception_class(message, screen, stacktrace) selenium.common.exceptions.NoSuchWindowException: Message: Unable to get browser</p> </blockquote> </blockquote> </blockquote> </blockquote> </blockquote> </blockquote>
-1
2016-09-15T07:22:55Z
39,506,452
<p>you can see in the exception:</p> <p>Browser zoom level was set to 112%. It should be set to 100%</p> <p>set the zoom to 100%</p> <p><a href="http://www.thewindowsclub.com/change-zoom-level-in-internet-explorer" rel="nofollow">http://www.thewindowsclub.com/change-zoom-level-in-internet-explorer</a></p>
1
2016-09-15T08:31:50Z
[ "python", "internet-explorer", "selenium" ]
AJAX call is triggered only in the first link and not in any other links inside a for loop
39,505,235
<p>I have an issue in implementing AJAX call for all the links inside for loop in Python Flask application.</p> <p>Only the first link triggers AJAX call and no other links triggers AJAX call.</p> <p>Below is the code of the respective .html and .js file I have implemented.</p> <p>.html</p> <pre><code>{% for article in articles %} {% if article._id in likes %} &lt;button data-toggle="tooltip" title="Unlike" id="unlike-button" value="{{article._id}}"&gt;&lt;span id="user-like-recommend" class="glyphicon glyphicon-heart" aria-hidden="true"&gt;&lt;/span&gt;&lt;/button&gt; {% else %} &lt;button data-toggle="tooltip" title="Like" id="like-button" value="{{article._id}}"&gt;&lt;span id="user-like-recommend" class="glyphicon glyphicon-heart-empty" aria-hidden="true"&gt;&lt;/span&gt;&lt;/button&gt; {% endif %} {% endfor %} </code></pre> <p>.js</p> <pre><code>document.getElementById("like-button").addEventListener("click", function(e) { e.preventDefault(); var article = $('#like-button').val(); var data = {"article": article}; console.log(data); if(data){ $.ajax({ type: 'POST', contentType: 'application/json', url: '/article_liked', dataType : 'json', data : JSON.stringify(data), success: function (response) { success("Article was successfully liked."); } </code></pre> <p>What should I do to fix this issue?</p>
0
2016-09-15T07:24:02Z
39,505,263
<p>Change the ids into classes, ids must be unique</p> <pre><code>{% for article in articles %} {% if article._id in likes %} &lt;button data-toggle="tooltip" title="Unlike" class="unlike-button" value="{{article._id}}"&gt;&lt;span id="user-like-recommend" class="glyphicon glyphicon-heart" aria-hidden="true"&gt;&lt;/span&gt;&lt;/button&gt; {% else %} &lt;button data-toggle="tooltip" title="Like" class="like-button" value="{{article._id}}"&gt;&lt;span id="user-like-recommend" class="glyphicon glyphicon-heart-empty" aria-hidden="true"&gt;&lt;/span&gt;&lt;/button&gt; {% endif %} {% endfor %} </code></pre> <p>js:</p> <pre><code>$(".like-button").on("click", function(e) { e.preventDefault(); var article = $(this).val(); var data = {"article": article}; console.log(data); if(data){ $.ajax({ type: 'POST', contentType: 'application/json', url: '/article_liked', dataType : 'json', data : JSON.stringify(data), success: function (response) { success("Article was successfully liked."); } </code></pre>
1
2016-09-15T07:25:41Z
[ "javascript", "jquery", "python", "ajax" ]
What's the type hint for "can be converted to" mean?
39,505,379
<p>Let's say I want to accept anything I can call <code>int()</code> on, or anything I can call <code>str()</code> on. How do I do that with the new type hints ?</p> <p>Annotating with <code>typing.SupportsInt</code> doesn't work, as mypy will warn against passing a string.</p>
2
2016-09-15T07:32:37Z
39,505,431
<p>You can't, not with type hinting. Type hinting can't say anything about the <em>contents</em> of a string, only that it must <em>be</em> a string.</p> <p>Note that <em>everything</em> in Python can be converted to a string (as <code>__repr__</code> is always available); so for 'can be converted to a string' can be handled by <code>typing.Any</code>.</p> <p>For <code>int()</code>, you can only specify specific hooks and types again; you can specify you'll accept objects that have a <a href="https://docs.python.org/3/reference/datamodel.html#object.__int__" rel="nofollow"><code>__int__()</code></a> method, but if you also accept strings, you can't specify what is <em>in</em> that string.</p> <p>So:</p> <pre><code>AcceptableToInt = Union[SupportsInt, str, bytes, bytearray] </code></pre> <p>would let you check on what types <code>int()</code> accepts, but not if they'll throw a <code>ValueError</code> exception when you actually try.</p>
3
2016-09-15T07:36:07Z
[ "python", "type-hinting" ]
ctypes CreateFile function not working properly
39,505,382
<p>creating new file with ctypes in python 3 doesnt seem to work properly, Here's how the code looks like: </p> <pre><code>ctypes.windll.kernel32.CreateFileA ( Filename, 0x10000000, 0x2, None, 1, 0x80, None ) </code></pre> <p><em>the same code works perfectly in py 2.x</em><br> I dont get any errors, and the file is created as well, only with no extension and name with only the first letter. for e.g, If I have filename as:</p> <pre><code>Filename = "File.txt" </code></pre> <p>It creates a file alright, but without "txt" extension and named as "F".<br> I know there are other ways to create file which works, but i just need to know why its not working with ctypes?</p>
1
2016-09-15T07:32:45Z
39,505,424
<p>You are calling the ANSI version of <code>CreateFile</code> while giving it Unicode string (The default string literal in python 3 are Unicode). To fix it :</p> <hr> <p>You can use <code>CreateFileA</code> and give it ANSI string.</p> <pre><code>Filename = b'file.txt' ctypes.windll.kernel32.CreateFileA ( Filename, 0x10000000, 0x2, None, 1, 0x80, None ) </code></pre> <hr> <p>You can use <code>CreateFileW</code>(The Unicode version of <code>CreateFile</code>)</p> <pre><code>Filename = 'file.txt' ctypes.windll.kernel32.CreateFileW ( Filename, 0x10000000, 0x2, None, 1, 0x80, None ) </code></pre> <hr>
1
2016-09-15T07:35:31Z
[ "python", "python-3.x", "ctypes" ]
Meaning of these arguments?
39,505,389
<p>I use a flashcard program called Anki, which is written in Python. I want to write my first add-on. I'm new to Python. I'm not a techie, but I have a few years experience of jumping around inside other people's code in Java, C++, C#, and so on.</p> <p>The flash card shows a question, for example "Capital of France?". When the "Show Answer" button is pressed, Anki displays the answer "Paris".</p> <p>I want to grab this text "Paris", before it's shown.</p> <p>I've arrived at this point in the Anki code. At this instant, the card shows "Capital of France?". The answer is still blank. I think I want to be able to grab "val" (which I think is "Paris") and use it in my add-on.</p> <pre><code>def _getTypedAnswer(self): self.web.evalWithCallback("typeans ? typeans.value : null", self._onTypedAnswer) def _onTypedAnswer(self, val): self.typedAnswer = val self._showAnswer() </code></pre> <p>I've been googling to try to find the meaning of this:</p> <pre><code>("typeans ? typeans.value : null", self._onTypedAnswer) </code></pre> <p>I have access to all the code, and I can provide any code that might be useful to responders.</p> <p>Thanks.</p> <hr> <p>Added: after questions from responders.</p> <p>Anki can be run on a computer or on the internet. All the results of studying cards are synced, so there's no difference between one method or the other as far as the end user is concerned.</p> <hr> <p>From the "webview" class:</p> <pre><code>def evalWithCallback(self, js, cb): self.page().runJavaScript(js, cb) </code></pre> <hr> <p>The "reviewer" class shows the questions and answers. The reviewer window is "mw" (for "main window")</p> <p>Here's the init statement for class "reviewer"</p> <pre><code>def __init__(self, mw): self.mw = mw self.web = mw.web </code></pre>
4
2016-09-15T07:33:15Z
39,505,483
<p><code>typeans ? typeans.value : null</code> is a <code>C/C++/C#</code> (and probably Java too, can't remember) code equivalent to (pseudo-code)</p> <pre><code>if typans: return typeans.value else: return null </code></pre> <p><code>("typeans ? typeans.value : null", self._onTypedAnswer)</code> is a tuple that contains this line of code as a string.</p>
1
2016-09-15T07:39:04Z
[ "python", "anki" ]
Meaning of these arguments?
39,505,389
<p>I use a flashcard program called Anki, which is written in Python. I want to write my first add-on. I'm new to Python. I'm not a techie, but I have a few years experience of jumping around inside other people's code in Java, C++, C#, and so on.</p> <p>The flash card shows a question, for example "Capital of France?". When the "Show Answer" button is pressed, Anki displays the answer "Paris".</p> <p>I want to grab this text "Paris", before it's shown.</p> <p>I've arrived at this point in the Anki code. At this instant, the card shows "Capital of France?". The answer is still blank. I think I want to be able to grab "val" (which I think is "Paris") and use it in my add-on.</p> <pre><code>def _getTypedAnswer(self): self.web.evalWithCallback("typeans ? typeans.value : null", self._onTypedAnswer) def _onTypedAnswer(self, val): self.typedAnswer = val self._showAnswer() </code></pre> <p>I've been googling to try to find the meaning of this:</p> <pre><code>("typeans ? typeans.value : null", self._onTypedAnswer) </code></pre> <p>I have access to all the code, and I can provide any code that might be useful to responders.</p> <p>Thanks.</p> <hr> <p>Added: after questions from responders.</p> <p>Anki can be run on a computer or on the internet. All the results of studying cards are synced, so there's no difference between one method or the other as far as the end user is concerned.</p> <hr> <p>From the "webview" class:</p> <pre><code>def evalWithCallback(self, js, cb): self.page().runJavaScript(js, cb) </code></pre> <hr> <p>The "reviewer" class shows the questions and answers. The reviewer window is "mw" (for "main window")</p> <p>Here's the init statement for class "reviewer"</p> <pre><code>def __init__(self, mw): self.mw = mw self.web = mw.web </code></pre>
4
2016-09-15T07:33:15Z
39,506,935
<p>Once you have found a place in the code that the variable you want is found, there are a number of ways of extracting this information to your own code.</p> <p>If direct manipulation of the source is allowed then you could assign val as an attribute to a different object within the methods you have shown in the question.</p> <p>For instance:</p> <pre><code>def _onTypedAnswer(self, val): self.typedAnswer = val myobj.answer = val # or call a method on myobj to break flow # myobj.method(val) self._showAnswer() </code></pre>
0
2016-09-15T08:58:17Z
[ "python", "anki" ]
Meaning of these arguments?
39,505,389
<p>I use a flashcard program called Anki, which is written in Python. I want to write my first add-on. I'm new to Python. I'm not a techie, but I have a few years experience of jumping around inside other people's code in Java, C++, C#, and so on.</p> <p>The flash card shows a question, for example "Capital of France?". When the "Show Answer" button is pressed, Anki displays the answer "Paris".</p> <p>I want to grab this text "Paris", before it's shown.</p> <p>I've arrived at this point in the Anki code. At this instant, the card shows "Capital of France?". The answer is still blank. I think I want to be able to grab "val" (which I think is "Paris") and use it in my add-on.</p> <pre><code>def _getTypedAnswer(self): self.web.evalWithCallback("typeans ? typeans.value : null", self._onTypedAnswer) def _onTypedAnswer(self, val): self.typedAnswer = val self._showAnswer() </code></pre> <p>I've been googling to try to find the meaning of this:</p> <pre><code>("typeans ? typeans.value : null", self._onTypedAnswer) </code></pre> <p>I have access to all the code, and I can provide any code that might be useful to responders.</p> <p>Thanks.</p> <hr> <p>Added: after questions from responders.</p> <p>Anki can be run on a computer or on the internet. All the results of studying cards are synced, so there's no difference between one method or the other as far as the end user is concerned.</p> <hr> <p>From the "webview" class:</p> <pre><code>def evalWithCallback(self, js, cb): self.page().runJavaScript(js, cb) </code></pre> <hr> <p>The "reviewer" class shows the questions and answers. The reviewer window is "mw" (for "main window")</p> <p>Here's the init statement for class "reviewer"</p> <pre><code>def __init__(self, mw): self.mw = mw self.web = mw.web </code></pre>
4
2016-09-15T07:33:15Z
39,507,029
<p>BTW, the exact (and valid) python equivalent of <em>typeans ? typeans.value : null</em> is:</p> <pre><code>typeans and typeans.value or null </code></pre>
0
2016-09-15T09:02:59Z
[ "python", "anki" ]
Meaning of these arguments?
39,505,389
<p>I use a flashcard program called Anki, which is written in Python. I want to write my first add-on. I'm new to Python. I'm not a techie, but I have a few years experience of jumping around inside other people's code in Java, C++, C#, and so on.</p> <p>The flash card shows a question, for example "Capital of France?". When the "Show Answer" button is pressed, Anki displays the answer "Paris".</p> <p>I want to grab this text "Paris", before it's shown.</p> <p>I've arrived at this point in the Anki code. At this instant, the card shows "Capital of France?". The answer is still blank. I think I want to be able to grab "val" (which I think is "Paris") and use it in my add-on.</p> <pre><code>def _getTypedAnswer(self): self.web.evalWithCallback("typeans ? typeans.value : null", self._onTypedAnswer) def _onTypedAnswer(self, val): self.typedAnswer = val self._showAnswer() </code></pre> <p>I've been googling to try to find the meaning of this:</p> <pre><code>("typeans ? typeans.value : null", self._onTypedAnswer) </code></pre> <p>I have access to all the code, and I can provide any code that might be useful to responders.</p> <p>Thanks.</p> <hr> <p>Added: after questions from responders.</p> <p>Anki can be run on a computer or on the internet. All the results of studying cards are synced, so there's no difference between one method or the other as far as the end user is concerned.</p> <hr> <p>From the "webview" class:</p> <pre><code>def evalWithCallback(self, js, cb): self.page().runJavaScript(js, cb) </code></pre> <hr> <p>The "reviewer" class shows the questions and answers. The reviewer window is "mw" (for "main window")</p> <p>Here's the init statement for class "reviewer"</p> <pre><code>def __init__(self, mw): self.mw = mw self.web = mw.web </code></pre>
4
2016-09-15T07:33:15Z
39,517,153
<pre><code>self.web.evalWithCallback("typeans ? typeans.value : null", self._onTypedAnswer) </code></pre> <p>This just calls the <code>evalWithCallback</code> method with two arguments: the string <code>"typeans ? typeans.value : null"</code> and the method object <code>self._onTypedAnswer</code>. You can see what <code>evalWithCallback</code> does with this from your posted code:</p> <pre><code>def evalWithCallback(self, js, cb): self.page().runJavaScript(js, cb) </code></pre> <p>So <code>evalWithCallback</code> takes the string and runs it as JavaScript. It's not clear from this exactly how the callback is called (for instance, what arguments it will be called with), but the essence of what the code does is it executes the string <code>typeans ? typeans.value : null</code> as JavaScript and then calls the function <code>self._onTypedAnswer</code>. My guess would be that the <code>val</code> argument passed to <code>_onTypedAnswer</code> will be the result of the evaluating the JS expression.</p> <p>Incidentally, judging from the name "typed answer", I would guess that <code>val</code> is not the correct answer to the question, but rather the user's guess (i.e., a value the user typed in).</p>
0
2016-09-15T17:36:50Z
[ "python", "anki" ]
Django update() to swap values of two fields in MySQL?
39,505,586
<p>The following does not work:</p> <pre><code>Car.objects.filters(&lt;filter&gt;).update(x=F('y'), y=F('x')) </code></pre> <p>as both <code>x</code> and <code>y</code> ends up being the same value. </p> <p>I need to use update() instead of save() due to performance (large set of records).</p> <p>Are there any other way of doing an update like the one above to mimic Python's <code>x, y = y, x</code>?</p> <p>The db is MySQL, <a href="http://dba.stackexchange.com/questions/31045/swap-columns-on-some-rows/31052#31052">which might explain why the resulting SQL statement doesn't work</a>.</p>
0
2016-09-15T07:44:59Z
39,505,755
<p>I don't think update can do that as it's basically an sql wrapper. What you could do, though, is use save(values=['x','y']). Hopefully it won't be as slow. Alternatively, you could use raw sql from django to perform the swap (see <a href="http://stackoverflow.com/questions/2758415/swap-values-for-two-rows-in-the-same-table-in-sql-server">Swap values for two rows in the same table in SQL Server</a>)</p>
-1
2016-09-15T07:53:43Z
[ "python", "mysql", "django" ]
Django update() to swap values of two fields in MySQL?
39,505,586
<p>The following does not work:</p> <pre><code>Car.objects.filters(&lt;filter&gt;).update(x=F('y'), y=F('x')) </code></pre> <p>as both <code>x</code> and <code>y</code> ends up being the same value. </p> <p>I need to use update() instead of save() due to performance (large set of records).</p> <p>Are there any other way of doing an update like the one above to mimic Python's <code>x, y = y, x</code>?</p> <p>The db is MySQL, <a href="http://dba.stackexchange.com/questions/31045/swap-columns-on-some-rows/31052#31052">which might explain why the resulting SQL statement doesn't work</a>.</p>
0
2016-09-15T07:44:59Z
39,506,222
<p>This should work correctly if you're using a proper standard-compliant SQL database. The query would expand to</p> <pre><code>UPDATE car SET x = y, y = x WHERE &lt;filter&gt; </code></pre> <p>It would work correctly at least on <a href="http://stackoverflow.com/a/37660/918959">PostgreSQL</a> (also below), SQLite3 (below), <a href="http://stackoverflow.com/questions/37649/swapping-column-values-in-mysql#comment17537164_37660">Oracle</a> and <a href="http://stackoverflow.com/questions/4198587/how-do-i-swap-column-values-in-sql-server-2008">MSSQL</a>, however the MySQL implementation is broken.</p> <p>PostgreSQL:</p> <pre><code>select * from car; x | y ---------+------ prefect | ford (1 row) test=&gt; update car set x = y, y = x; UPDATE 1 test=&gt; select * from car; x | y ------+--------- ford | prefect (1 row) </code></pre> <p>SQLite3</p> <pre><code>sqlite&gt; select * from foo; prefect|ford sqlite&gt; update foo set x = y, y = x; sqlite&gt; select * from foo; ford|prefect </code></pre> <p>However, MySQL violates the SQL standard,</p> <pre><code>mysql&gt; insert into car values ('prefect', 'ford'); Query OK, 1 row affected (0.01 sec) mysql&gt; select * from car; +---------+------+ | x | y | +---------+------+ | prefect | ford | +---------+------+ 1 row in set (0.00 sec) mysql&gt; update car set x = y, y = x; Query OK, 1 row affected (0.00 sec) Rows matched: 1 Changed: 1 Warnings: 0 mysql&gt; select * from car; +------+------+ | x | y | +------+------+ | ford | ford | +------+------+ 1 row in set (0.00 sec) </code></pre> <p>Thus there is a portable way to do this using a standard-compliant SQL database, but MySQL isn't one of them. If you cannot use the <code>for</code> ... <code>save</code> loop, then you must resort to some of the hacks from <a href="http://stackoverflow.com/questions/37649/swapping-column-values-in-mysql">Swapping column vales in MySQL</a>; the temporary variable seems to be the most generic one; though I am not sure whether you can use the temporary variables with <code>F</code> constructs of Django.</p>
3
2016-09-15T08:18:51Z
[ "python", "mysql", "django" ]
compare all adjacent columns in a dataframe
39,505,612
<p>I have the following dataframe</p> <pre><code>df = pd.DataFrame(np.random.choice(list('xyz'), (5, 4)), columns=list('ABCD')) print df A B C D 0 x z x z 1 y z x z 2 y z x x 3 y y y x 4 y x z z </code></pre> <p>I'd like to compare columns <code>A</code> with <code>B</code>, <code>B</code> with <code>C</code>, and <code>C</code> with <code>D</code>.<br> I know I can do <code>df.A == df.B</code>, but is there a way to easily compare all columns with their adjacent columns?</p> <p>I'd like to see</p> <pre><code> B C D 0 False False False 1 False False False 2 False False True 3 True True False 4 False False True </code></pre> <p>I've tried this</p> <pre><code>pd.concat([df.iloc[:, i] == df.iloc[:, i+1] for i in range(df.shape[1]-1)], axis=1, keys=df.columns.tolist()[1:]) </code></pre> <p>Which is how I got the desired output. Efficiency is important, so I feel my attempt is inadequate. If these were <code>float</code>s or <code>int</code>s, I could</p> <pre><code>df.diff(axis=1) == 0 </code></pre> <p>But they're strings</p>
1
2016-09-15T07:46:25Z
39,505,646
<p>Use <code>shift(axis=1)</code></p> <pre><code>(df == df.shift(axis=1)).iloc[:, 1:] </code></pre> <p><a href="http://i.stack.imgur.com/SuGe2.png" rel="nofollow"><img src="http://i.stack.imgur.com/SuGe2.png" alt="enter image description here"></a></p>
1
2016-09-15T07:48:00Z
[ "python", "pandas" ]
Scraping issues on a specific website
39,505,630
<p>This is my first question on stack overflow so bear with me, please. </p> <p>I am trying to download automatically (i.e. scrape) the text of some Italian laws from the website: <a href="http://www.normattiva.it" rel="nofollow">http://www.normattiva.it/</a></p> <p>I am using this code below (and similar permutations):</p> <pre><code>import requests, sys debug = {'verbose': sys.stderr} user_agent = {'User-agent': 'Mozilla/5.0', 'Connection':'keep-alive'} url = 'http://www.normattiva.it/atto/caricaArticolo?art.progressivo=0&amp;art.idArticolo=1&amp;art.versione=1&amp;art.codiceRedazionale=047U0001&amp;art.dataPubblicazioneGazzetta=1947-12-27&amp;atto.tipoProvvedimento=COSTITUZIONE&amp;art.idGruppo=1&amp;art.idSottoArticolo1=10&amp;art.idSottoArticolo=1&amp;art.flagTipoArticolo=0#art' r = requests.session() s = r.get(url, headers=user_agent) #print(s.text) print(s.url) print(s.headers) print(s.request.headers) </code></pre> <p>As you can see I am trying to load the "<strong>caricaArticolo</strong>" query. </p> <p>However, the output is a page saying that my search is invalid (<strong><em>"session is not valid or expired"</em></strong>) </p> <p>It seems that the page recognizes that I am not using a browser and loads a "breakout" javascript function. </p> <pre><code>&lt;body onload="javascript:breakout();"&gt; </code></pre> <p>I tried to use "browser" simulator python scripts such as <strong>selenium</strong> and <strong>robobrowser</strong> but the result is the same. </p> <p>Is there anyone who is willing to spend 10 minutes looking at the page output and give help?</p>
2
2016-09-15T07:47:14Z
39,511,974
<p>Once you click any link on the page with dev tools open, under the doc tab under Network:</p> <p><a href="http://i.stack.imgur.com/orZHr.png" rel="nofollow"><img src="http://i.stack.imgur.com/orZHr.png" alt="enter image description here"></a></p> <p>You can see three links, the first is what we click on, the second returns the html that allows you to jump to a specific <em>Article</em> and the last contains the article text.</p> <p>In the source returned from the firstlink, you can see two <em>iframe</em> tags:</p> <pre><code>&lt;div id="alberoTesto"&gt; &lt;iframe src="/atto/caricaAlberoArticoli?atto.dataPubblicazioneGazzetta=2016-08-31&amp;atto.codiceRedazionale=16G00182&amp;atto.tipoProvvedimento=DECRETO LEGISLATIVO" name="leftFrame" scrolling="auto" id="leftFrame" title="leftFrame" height="100%" style="width: 285px; float:left;" frameborder="0"&gt; &lt;/iframe&gt; &lt;iframe src="/atto/caricaArticoloDefault?atto.dataPubblicazioneGazzetta=2016-08-31&amp;atto.codiceRedazionale=16G00182&amp;atto.tipoProvvedimento=DECRETO LEGISLATIVO" name="mainFrame" id="mainFrame" title="mainFrame" height="100%" style="width: 800px; float:left;" scrolling="auto" frameborder="0"&gt; &lt;/iframe&gt; </code></pre> <p>The first is for the Article, the latter with <em>/caricaArticoloDefault</em> and the <em>id</em> <em>mainFrame</em> is what we want.</p> <p>You need to use the cookies from the initial requests so you can do it with the <em>Session</em> object and by parsing the pages using <a href="https://www.crummy.com/software/BeautifulSoup/bs4/doc/#find-all-next-and-find-next" rel="nofollow">bs4</a>:</p> <pre><code>import requests, sys import os from urlparse import urljoin import io user_agent = {'User-agent': 'Mozilla/5.0', 'Connection': 'keep-alive'} url = 'http://www.normattiva.it/atto/caricaArticolo?art.progressivo=0&amp;art.idArticolo=1&amp;art.versione=1&amp;art.codiceRedazionale=047U0001&amp;art.dataPubblicazioneGazzetta=1947-12-27&amp;atto.tipoProvvedimento=COSTITUZIONE&amp;art.idGruppo=1&amp;art.idSottoArticolo1=10&amp;art.idSottoArticolo=1&amp;art.flagTipoArticolo=0#art' with requests.session() as s: s.headers.update(user_agent) r = s.get("http://www.normattiva.it/") soup = BeautifulSoup(r.content, "lxml") # get all the links from the initial page for a in soup.select("div.testo p a[href^=http]"): soup = BeautifulSoup(s.get(a["href"]).content) # The link to the text is in a iframe tag retuened from the previous get. text_src_link = soup.select_one("#mainFrame")["src"] # Pick something to make the names unique with io.open(os.path.basename(text_src_link), "w", encoding="utf-8") as f: # The text is in pre tag that is in the div with the pre class text = BeautifulSoup(s.get(urljoin("http://www.normattiva.it", text_src_link)).content, "html.parser")\ .select_one("div.wrapper_pre pre").text f.write(text) </code></pre> <p>A snippet of the first text file:</p> <pre><code> IL PRESIDENTE DELLA REPUBBLICA Visti gli articoli 76, 87 e 117, secondo comma, lettera d), della Costituzione; Vistala legge 28 novembre 2005, n. 246 e, in particolare, l'articolo 14: comma 14, cosi' come sostituito dall'articolo 4, comma 1, lettera a), della legge 18 giugno 2009, n. 69, con il quale e' stata conferita al Governo la delega ad adottare, con le modalita' di cui all'articolo 20 della legge 15 marzo 1997, n. 59, decreti legislativi che individuano le disposizioni legislative statali, pubblicate anteriormente al 1° gennaio 1970, anche se modificate con provvedimenti successivi, delle quali si ritiene indispensabile la permanenza in vigore, secondo i principi e criteri direttivi fissati nello stesso comma 14, dalla lettera a) alla lettera h); comma 15, con cui si stabilisce che i decreti legislativi di cui al citato comma 14, provvedono, altresi', alla semplificazione o al riassetto della materia che ne e' oggetto, nel rispetto dei principi e criteri direttivi di cui all'articolo 20 della legge 15 marzo 1997, n. 59, anche al fine di armonizzare le disposizioni mantenute in vigore con quelle pubblicate successivamente alla data del 1° gennaio 1970; comma 22, con cui si stabiliscono i termini per l'acquisizione del prescritto parere da parte della Commissione parlamentare per la semplificazione; Visto il decreto legislativo 30 luglio 1999, n. 300, recante riforma dell'organizzazione del Governo, a norma dell'articolo 11 della legge 15 marzo 1997, n. 59 e, in particolare, gli articoli da 20 a 22; </code></pre>
1
2016-09-15T13:13:19Z
[ "python", "web-scraping", "python-requests" ]
Scraping issues on a specific website
39,505,630
<p>This is my first question on stack overflow so bear with me, please. </p> <p>I am trying to download automatically (i.e. scrape) the text of some Italian laws from the website: <a href="http://www.normattiva.it" rel="nofollow">http://www.normattiva.it/</a></p> <p>I am using this code below (and similar permutations):</p> <pre><code>import requests, sys debug = {'verbose': sys.stderr} user_agent = {'User-agent': 'Mozilla/5.0', 'Connection':'keep-alive'} url = 'http://www.normattiva.it/atto/caricaArticolo?art.progressivo=0&amp;art.idArticolo=1&amp;art.versione=1&amp;art.codiceRedazionale=047U0001&amp;art.dataPubblicazioneGazzetta=1947-12-27&amp;atto.tipoProvvedimento=COSTITUZIONE&amp;art.idGruppo=1&amp;art.idSottoArticolo1=10&amp;art.idSottoArticolo=1&amp;art.flagTipoArticolo=0#art' r = requests.session() s = r.get(url, headers=user_agent) #print(s.text) print(s.url) print(s.headers) print(s.request.headers) </code></pre> <p>As you can see I am trying to load the "<strong>caricaArticolo</strong>" query. </p> <p>However, the output is a page saying that my search is invalid (<strong><em>"session is not valid or expired"</em></strong>) </p> <p>It seems that the page recognizes that I am not using a browser and loads a "breakout" javascript function. </p> <pre><code>&lt;body onload="javascript:breakout();"&gt; </code></pre> <p>I tried to use "browser" simulator python scripts such as <strong>selenium</strong> and <strong>robobrowser</strong> but the result is the same. </p> <p>Is there anyone who is willing to spend 10 minutes looking at the page output and give help?</p>
2
2016-09-15T07:47:14Z
39,519,081
<p>wonderful, wonderful, wonderful Padraic. It works. Just had to edits slightly to clear imports but it's works wonderfully. Thanks very much. I am just discovering python's potential and you have made my journey much easier with this specific task. I would have not solved it alone. </p> <pre><code>import requests, sys import os from urllib.parse import urljoin from bs4 import BeautifulSoup import io user_agent = {'User-agent': 'Mozilla/5.0', 'Connection': 'keep-alive'} url = 'http://www.normattiva.it/atto/caricaArticolo?art.progressivo=0&amp;art.idArticolo=1&amp;art.versione=1&amp;art.codiceRedazionale=047U0001&amp;art.dataPubblicazioneGazzetta=1947-12-27&amp;atto.tipoProvvedimento=COSTITUZIONE&amp;art.idGruppo=1&amp;art.idSottoArticolo1=10&amp;art.idSottoArticolo=1&amp;art.flagTipoArticolo=0#art' with requests.session() as s: s.headers.update(user_agent) r = s.get("http://www.normattiva.it/") soup = BeautifulSoup(r.content, "lxml") # get all the links from the initial page for a in soup.select("div.testo p a[href^=http]"): soup = BeautifulSoup(s.get(a["href"]).content) # The link to the text is in a iframe tag retuened from the previous get. text_src_link = soup.select_one("#mainFrame")["src"] # Pick something to make the names unique with io.open(os.path.basename(text_src_link), "w", encoding="utf-8") as f: # The text is in pre tag that is in the div with the pre class text = BeautifulSoup(s.get(urljoin("http://www.normattiva.it", text_src_link)).content, "html.parser")\ .select_one("div.wrapper_pre pre").text f.write(text) </code></pre>
0
2016-09-15T19:39:14Z
[ "python", "web-scraping", "python-requests" ]
Merge list concating unique values as comma seperated retaining original order from csv
39,505,658
<p>Here is my data:</p> <p>data.csv</p> <pre><code>id,fname,lname,education,gradyear,attributes 1,john,smith,mit,2003,qa 1,john,smith,harvard,207,admin 1,john,smith,ft,212,master 2,john,doe,htw,2000,dev </code></pre> <p>Here is the code:</p> <pre><code>from itertools import groupby import csv import pprint t = csv.reader(open('data.csv')) t = list(t) def join_rows(rows): return [(e[0] if i &lt; 3 else ','.join(e)) for (i, e) in enumerate(zip(*rows))] for name, rows in groupby(sorted(t), lambda x:x[0]): print join_rows(rows) </code></pre> <p>It works, but while merging it doest not retain original order, instead it works from concating last to first</p> <p>Output is:</p> <pre><code>['1', 'john', 'smith', 'ft,harvard,mit', '212,207,2003', 'master,admin,qa'] ['2', 'john', 'doe', 'htw', '2000', 'dev'] ['id', 'fname', 'lname', 'education', 'gradyear', 'attributes'] </code></pre> <p>Instead of:</p> <pre><code>['1', 'john', 'smith', 'mit,harvard,ft', '2003,207,212', 'qa,admin,master'] ['2', 'john', 'doe', 'htw', '2000', 'dev'] ['id', 'fname', 'lname', 'education', 'gradyear', 'attributes'] </code></pre> <p>as it is listed in the CSV file (original order)</p> <p>My approach to fix this would be to rerun though values and try to reverse it. Is there any cleverer approach? </p>
0
2016-09-15T07:48:47Z
39,505,975
<p>The problem is sorting, which is not required. Change as:</p> <pre><code>groupby(t, lambda x:x[0]) </code></pre>
0
2016-09-15T08:04:43Z
[ "python" ]
Reading CSV File and Deciding on a Data Structure
39,505,682
<p>I'm working with a rather basic CSV file depicting four cities and the distances between them. As such, the goal is to retrieve the information from said file, and use Python for further operations.</p> <p><strong>Excel File</strong></p> <p>The file is built up as follows in Excel:</p> <p><a href="http://i.stack.imgur.com/MUx9J.png" rel="nofollow"><img src="http://i.stack.imgur.com/MUx9J.png" alt="cities.csv file"></a> </p> <p><strong>CSV File</strong></p> <p>When exported as CSV, the file is represented as follows:</p> <pre><code>,OSL,CPH,LDN,TKO OSL,0,2,4,10 CPH,2,0,2,9 LDN,4,2,0,12 TKO,10,9,12,0 </code></pre> <p><strong>Getting the Cities</strong></p> <p>Evidently, the first row contains all cities, as well as the first blank cell. I have done the following to retrieve the cities, excluding the blank cell: </p> <pre><code>def get_cities(file): reader = csv.reader(file) cities = [] row1 = next(reader) cities.extend(row1[1:]) #exclude first cell (blank) print cities </code></pre> <p>Yielding: </p> <pre><code>['OSL', 'CPH', 'LDN', 'TKO'] </code></pre> <p><strong>Mapping Cities and Distances between Them</strong></p> <p>Having done so, I can now read the rest of the file, in order to retrieve the distances between the cities. </p> <p><strong>However</strong>, I am finding it hard to come up with a good way of representing this information as a data structure. Optimally, I want to be able to check the distance between any two cities. </p> <p>Any suggestions on how I can go about implementing this, would be highly appreciated. </p> <p>That is, <strong>how can I best represent this information</strong> for easy distance lookup?</p>
1
2016-09-15T07:49:59Z
39,505,810
<p>it seems like your data directly represents an adjacency matrix for a graph.Store it as a adjacency matrix and just do simple lookup for (city1, city2) for the distance. For implementation you enumerate on the city.</p>
1
2016-09-15T07:56:30Z
[ "python", "csv", "data-structures", "types" ]
Reading CSV File and Deciding on a Data Structure
39,505,682
<p>I'm working with a rather basic CSV file depicting four cities and the distances between them. As such, the goal is to retrieve the information from said file, and use Python for further operations.</p> <p><strong>Excel File</strong></p> <p>The file is built up as follows in Excel:</p> <p><a href="http://i.stack.imgur.com/MUx9J.png" rel="nofollow"><img src="http://i.stack.imgur.com/MUx9J.png" alt="cities.csv file"></a> </p> <p><strong>CSV File</strong></p> <p>When exported as CSV, the file is represented as follows:</p> <pre><code>,OSL,CPH,LDN,TKO OSL,0,2,4,10 CPH,2,0,2,9 LDN,4,2,0,12 TKO,10,9,12,0 </code></pre> <p><strong>Getting the Cities</strong></p> <p>Evidently, the first row contains all cities, as well as the first blank cell. I have done the following to retrieve the cities, excluding the blank cell: </p> <pre><code>def get_cities(file): reader = csv.reader(file) cities = [] row1 = next(reader) cities.extend(row1[1:]) #exclude first cell (blank) print cities </code></pre> <p>Yielding: </p> <pre><code>['OSL', 'CPH', 'LDN', 'TKO'] </code></pre> <p><strong>Mapping Cities and Distances between Them</strong></p> <p>Having done so, I can now read the rest of the file, in order to retrieve the distances between the cities. </p> <p><strong>However</strong>, I am finding it hard to come up with a good way of representing this information as a data structure. Optimally, I want to be able to check the distance between any two cities. </p> <p>Any suggestions on how I can go about implementing this, would be highly appreciated. </p> <p>That is, <strong>how can I best represent this information</strong> for easy distance lookup?</p>
1
2016-09-15T07:49:59Z
39,505,947
<p>Use dict of dicts. This is not very memory efficient but is the simplest solution using built in python containers.</p> <pre><code> map = {'OSL' : { 'OSL' : 0, 'CPH' : 2, ... }, 'CPH' : { ... }, ... } </code></pre> <p>Then you can look up the distance just like map['OSL']['CPH'].</p>
0
2016-09-15T08:03:17Z
[ "python", "csv", "data-structures", "types" ]
How to return the random key and use it to call next value in array list JSON?
39,505,766
<p>I have a small problem. Here is my code:</p> <pre><code>random_key = random.randrange(0, len(product['products'])+1, 2) if product['products'][0]['images'][3]['url'] is None: _send_to_fb( fbid, product['products'] [random_key]['title'], product['products']['key_of_random_title']['urls'][0]['value'], product['products'][0]['summary']) </code></pre> <p>So I have <code>title</code>, <code>url</code> and <code>summary</code>. What I actually want here is to get a random product of the product array list. What I get now is only the random value of product's title.</p> <p>I want to know how can I get that random_key and use it to get the right url and summary as well. (<code>'title.random_key'</code>) for example. Or get 1 random product and return all its title, url, summary,..</p> <p>This is how my json array list looks like</p> <pre><code>"products": [ { "id": "9200000059237726", "ean": "5035223116370", "gpc": "games", "title": "FIFA 17 - PS4", "specsTag": "Electronic Arts", "summary": "PlayStation 4 | PEGI-leeftijd: 3 | Sport|Actie | 29 september 2016", "rating": 0, "shortDescription": "&lt;h3 style=\"display:inline;\"&gt;Reserveer nu FIFA 17 en ontvang een halfjaar gratis VI Premium* &lt;\/h3&gt;&lt;br /&gt;&lt;b&gt;Daarnaast ontvang je ook nog de volgende pre-order DLC*:&lt;\/b&gt;&lt;br /&gt;&lt;ul class=\"default_listitem\" style=\"display: inline;\"&gt;&lt;li style=\"display:inline;\"&gt;5 FUT Draft-tokens, 1 per week gedurende 5 weken &lt;\/li&gt;&lt;br /&gt;&lt;li style=\"display:inline;\"&gt;FUT-leenspeler voor 8 wedstrijden, keuze uit Hazard, Martial, Reus of Rodriguez&lt;\/li&gt;&lt;br /&gt;&lt;li style=\"display:inline;\"&gt;Special Edition FUT-tenues&lt;\/li&gt;&lt;\/ul&gt;&lt;br /&gt;&lt;br /&gt;&lt;i&gt;* De VI Premium code + de DLC codes worden op dag van release voor 18.00 per email verstuurd. Iedereen die al gereserveerd heeft ontvangt ook een halfjaar VI Premium + de Pre-order DLC!&lt;\/i&gt;&lt;br /&gt;&lt;br /&gt;&lt;h3 style=\"display:inline;\"&gt;Informatie over de aanbieding:&lt;\/h3&gt;&lt;br /&gt;Je ontvangt...", "longDescription": "&lt;h3 style=\"display:inline;\"&gt;Reserveer nu FIFA 17 en ontvang een halfjaar gratis VI Premium* &lt;\/h3&gt;&lt;br /&gt;&lt;b&gt;Daarnaast ontvang je ook nog de volgende pre-order DLC*:&lt;\/b&gt;&lt;br /&gt;&lt;ul class=\"default_listitem\" style=\"display: inline;\"&gt;&lt;li style=\"display:inline;\"&gt;5 FUT Draft-tokens, 1 per week gedurende 5 weken &lt;\/li&gt;&lt;br /&gt;&lt;li style=\"display:inline;\"&gt;FUT-leenspeler voor 8 wedstrijden, keuze uit Hazard, Martial, Reus of Rodriguez&lt;\/li&gt;&lt;br /&gt;&lt;li style=\"display:inline;\"&gt;Special Edition FUT-tenues&lt;\/li&gt;&lt;\/ul&gt;&lt;br /&gt;&lt;br /&gt;&lt;i&gt;* De VI Premium code + de DLC codes worden op dag van release voor 18.00 per email verstuurd. Iedereen die al gereserveerd heeft ontvangt ook een halfjaar VI Premium + de Pre-order DLC!&lt;\/i&gt;&lt;br /&gt;&lt;br /&gt;&lt;h3 style=\"display:inline;\"&gt;Informatie over de aanbieding:&lt;\/h3&gt;&lt;br /&gt;Je ontvangt de volledige FIFA 17-game samen met maximaal 5 FUT Draft-tokens, een FUT-leenspeler voor 8 wedstrijden en Special Edition FUT-tenues.&lt;br /&gt;&lt;br /&gt;&lt;h3 style=\"display:inline;\"&gt;Wat is FIFA Ultimate Team (FUT)?&lt;\/h3&gt;&lt;br /&gt;EA SPORTS FIFA 17 Ultimate Team is een gigantische online community van fans die in FIFA 17 hun ultieme voetbalteam samenstellen met de beste spelers ter wereld, hun team coachen en er het veld mee opgaan. Sluit je aan bij meer dan 15 miljoen fans en ga de uitdaging aan om voetbalteams samen te stellen met de beste spelers ter wereld door spelers te verdienen, kopen, verkopen en te verhandelen met de community van Ultimate Team. Betreed het veld met je dreamteam en speel wanneer je maar wilt tegen de teams van je vrienden. Stel meerdere selecties samen, beheer ze en doe mee aan online en singleplayertoernooien. Al deze toernooien worden wekelijks dynamisch bijgewerkt.&lt;br /&gt;&lt;br /&gt;&lt;h3 style=\"display:inline;\"&gt;Wat is een FIFA Ultimate Team-leenspeler? &lt;\/h3&gt;&lt;br /&gt;Heb je je ooit afgevraagd hoe het zou zijn om een topvoetballer in je team te hebben? Je kunt enkele van de meest gewilde spelers uit FIFA Ultimate Team gedurende een beperkt aantal wedstrijden uitproberen.&lt;br /&gt;&lt;br /&gt;&lt;h3 style=\"display:inline;\"&gt;Wat is een FIFA Ultimate Team Draft?&lt;\/h3&gt;&lt;br /&gt;FUT Draft is een nieuwe manier om FIFA Ultimate Team te spelen! Stel een selectie samen en daag tegenstanders uit in een toernooi om pakketten, munten en nog veel meer te verdienen. Test je vaardigheden als teambouwer en selecteer uit 5 spelers de beste speler voor elke positie. Maak belangrijke keuzes gebaseerd op de kwaliteiten van spelers of teamgeest. Win grotere prijzen naarmate je verder komt; win alle 4 de wedstrijden op rij voor de beste beloningen!&lt;br /&gt;&lt;br /&gt;&lt;h3 style=\"display:inline;\"&gt;Wat is de EA SPORTS Football Club (EAS FC)?&lt;\/h3&gt;&lt;br /&gt;Ervaar het sociale netwerk van voetbal. Verdien beloningen, stijg in niveau, doe mee aan live Uitdagingen en maak verbinding met je vrienden. Alles in FIFA 17 wordt beoordeeld en gecommuniceerd via EA SPORTS Football Club. Fans kunnen beloningen verdienen waarmee ze items uit de Football Club-catalogus kunnen ontgrendelen en hun status vergroten door te proberen niveau 100 te halen. Verhaallijnen uit de echte wereld schotelen je in EA SPORTS Football Club regelmatig uitdagingen voor, waardoor FIFA 17 aanvoelt, speelt en er uitziet als het echte voetbalseizoen. ", "urls": [ { "key": "DESKTOP", "value": "https://www.bol.com/nl/p/fifa-17-ps4/9200000059237726/" }, { "key": "MOBILE", "value": "https://m.bol.com/nl/p/fifa-17-ps4/9200000059237726/" } ], "images": [], "media": [], "offerData": {}, "promotions": [], "parentCategoryPaths": [] }, { "id": "9200000059241692", "ean": "5030949121820", "gpc": "games", "title": "FIFA 17 - Deluxe Edition - PS4", "specsTag": "Electronic Arts", "summary": "PlayStation 4 | PEGI-leeftijd: 3 | Sport|Actie | 29 september 2016", "rating": 0, "shortDescription": "&lt;h3 style=\"display:inline;\"&gt;Reserveer nu FIFA 17 en ontvang een halfjaar gratis VI Premium* &lt;\/h3&gt;&lt;br /&gt;&lt;b&gt;In de Deluxe edition zit ook nog de volgende DLC bijgesloten:&lt;\/b&gt;&lt;br /&gt;&lt;ul class=\"default_listitem\" style=\"display: inline;\"&gt;&lt;li style=\"display:inline;\"&gt;20 FIFA Ultimate Team™ Premium Jumbo Goud-pakketten, 1 per week gedurende 20 weken&lt;\/li&gt;&lt;br /&gt;&lt;li style=\"display:inline;\"&gt;Team van de week FUT-leenspelers voor 3 wedstrijden, maximaal 1 per week gedurende 20 weken&lt;\/li&gt;&lt;br /&gt;&lt;li style=\"display:inline;\"&gt;FUT-leenspeler voor 8 wedstrijden, keuze uit Hazard, Martial, Reus of Rodriguez&lt;\/li&gt;&lt;br /&gt;&lt;li style=\"display:inline;\"&gt;Special Edition FUT-tenues&lt;\/li&gt;&lt;\/ul&gt;&lt;br /&gt;&lt;br /&gt;&lt;i&gt;* De VI Premium code wordt op dag van release voor 18.00 per email verstuurd. Iedereen die al ger...&lt;\/i&gt;", "longDescription": "&lt;h3 style=\"display:inline;\"&gt;Reserveer nu FIFA 17 en ontvang een halfjaar gratis VI Premium* &lt;\/h3&gt;&lt;br /&gt;&lt;b&gt;In de Deluxe edition zit ook nog de volgende DLC bijgesloten:&lt;\/b&gt;&lt;br /&gt;&lt;ul class=\"default_listitem\" style=\"display: inline;\"&gt;&lt;li style=\"display:inline;\"&gt;20 FIFA Ultimate Team™ Premium Jumbo Goud-pakketten, 1 per week gedurende 20 weken&lt;\/li&gt;&lt;br /&gt;&lt;li style=\"display:inline;\"&gt;Team van de week FUT-leenspelers voor 3 wedstrijden, maximaal 1 per week gedurende 20 weken&lt;\/li&gt;&lt;br /&gt;&lt;li style=\"display:inline;\"&gt;FUT-leenspeler voor 8 wedstrijden, keuze uit Hazard, Martial, Reus of Rodriguez&lt;\/li&gt;&lt;br /&gt;&lt;li style=\"display:inline;\"&gt;Special Edition FUT-tenues&lt;\/li&gt;&lt;\/ul&gt;&lt;br /&gt;&lt;br /&gt;&lt;i&gt;* De VI Premium code wordt op dag van release voor 18.00 per email verstuurd. Iedereen die al gereserveerd heeft ontvangt ook een halfjaar VI Premium. DLC Deluxe edition zit bijgesloten in de verpakking!&lt;\/i&gt;&lt;br /&gt;&lt;br /&gt;&lt;h3 style=\"display:inline;\"&gt;Informatie over de aanbieding:&lt;\/h3&gt;&lt;br /&gt;Je ontvangt de volledige FIFA 17-game samen met maximaal 20 FUT Premium Jumbo Goud-pakketten, Team van de week leenspelers voor 3 wedstrijden, een FUT-leenspeler voor 8 wedstrijden en Special Edition FUT-tenues.&lt;br /&gt;&lt;br /&gt;&lt;h3 style=\"display:inline;\"&gt;Wat is FIFA Ultimate Team (FUT)?&lt;\/h3&gt;&lt;br /&gt;EA SPORTS FIFA 17 Ultimate Team is een gigantische online community van fans die in FIFA 17 hun ultieme voetbalteam samenstellen met de beste spelers ter wereld, hun team coachen en er het veld mee opgaan. Sluit je aan bij meer dan 15 miljoen fans en ga de uitdaging aan om voetbalteams samen te stellen met de beste spelers ter wereld door spelers te verdienen, kopen, verkopen en te verhandelen met de community van Ultimate Team. Betreed het veld met je dreamteam en speel wanneer je maar wilt tegen de teams van je vrienden. Stel meerdere selecties samen, beheer ze en doe mee aan online en singleplayertoernooien. Al deze toernooien worden wekelijks dynamisch bijgewerkt.&lt;br /&gt;&lt;br /&gt;&lt;h3 style=\"display:inline;\"&gt;Wat is een FIFA Ultimate Team Premium Jumbo Goud-pakket?&lt;\/h3&gt;&lt;br /&gt;Ervaar hoe spannend het is om pakketten te openen. Elk pakket is een combinatie van 24 items, die kunnen bestaan uit spelers, contracten, stadions, managers, personeel, conditie-items, genezende items, ballen, tenues, badges en teamgeeststijlen. Goud-pakketten bestaan uit spelers die in het spel een beoordeling van minimaal 75 hebben en bevatten minstens zeven zeldzame items. Zeldzame items zijn onder meer verbeterde eigenschappen voor spelers, langere contracten en de meest gewilde spelers.&lt;br /&gt;&lt;br /&gt;&lt;h3 style=\"display:inline;\"&gt;Wat is een FIFA Ultimate Team-leenspeler?&lt;\/h3&gt; &lt;br /&gt;Heb je je ooit afgevraagd hoe het zou zijn om een topvoetballer in je team te hebben? Je kunt enkele van de meest gewilde spelers uit FIFA Ultimate Team gedurende een beperkt aantal wedstrijden uitproberen.&lt;br /&gt;&lt;br /&gt;&lt;h3 style=\"display:inline;\"&gt;Wat is de EA SPORTS Football Club (EAS FC)?&lt;\/h3&gt;&lt;br /&gt;Ervaar het sociale netwerk van voetbal. Verdien beloningen, stijg in niveau, doe mee aan live Uitdagingen en maak verbinding met je vrienden. Alles in FIFA 17 wordt beoordeeld en gecommuniceerd via EA SPORTS Football Club. Fans kunnen beloningen verdienen waarmee ze items uit de Football Club-catalogus kunnen ontgrendelen en hun status vergroten door te proberen niveau 100 te halen. Verhaallijnen uit de echte wereld schotelen je in Football Club regelmatig uitdagingen voor, waardoor FIFA 17 aanvoelt, speelt en er uitziet als het echte voetbalseizoen. ", "urls": [ { "key": "DESKTOP", "value": "https://www.bol.com/nl/p/fifa-17-deluxe-edition-ps4/9200000059241692/" }, { "key": "MOBILE", "value": "https://m.bol.com/nl/p/fifa-17-deluxe-edition-ps4/9200000059241692/" } ], "images": [], "media": [], "offerData": {}, "promotions": [], "parentCategoryPaths": [] }, { "id": "9200000058463485", "ean": "5030933113763", "gpc": "games", "title": "Battlefield 1 - PS4", "specsTag": "Electronic Arts", "summary": "PlayStation 4 | PEGI-leeftijd: 18 | Actie|Shooter | oktober 2016", "rating": 40, "shortDescription": "&lt;h3 style=\"display:inline;\"&gt;&lt;b&gt;Pre-order actie&lt;\/b&gt;&lt;\/h3&gt;&lt;br /&gt;Reserveer Battlefield™ 1 en maak kans op een jaar lang gratis paintballen met je vrienden! Daarnaast geven wij nog 10 keer een los paintball jaarabonnement weg.&lt;br /&gt;&lt;br /&gt;Ook ontvang je het Battlefield™ 1 Hellfighter Pack en krijg je 7 dagen eerder toegang tot een map die later in 2016 wordt uitgebracht. De Harlem Hellfighters waren een van de sterkste infanterieregimenten in de Grote Oorlog. Dit pakket bevat unieke unlocks die zijn geïnspireerd door hun heldendaden.&lt;br /&gt;&lt;br /&gt;&lt;b&gt;Inhoud&lt;\/b&gt;&lt;br /&gt;• &lt;b&gt;Hellfighter Trenc...&lt;\/b&gt;", "longDescription": "&lt;h3 style=\"display:inline;\"&gt;&lt;b&gt;Pre-order actie&lt;\/b&gt;&lt;\/h3&gt;&lt;br /&gt;Reserveer Battlefield™ 1 en maak kans op een jaar lang gratis paintballen met je vrienden! Daarnaast geven wij nog 10 keer een los paintball jaarabonnement weg.&lt;br /&gt;&lt;br /&gt;Ook ontvang je het Battlefield™ 1 Hellfighter Pack en krijg je 7 dagen eerder toegang tot een map die later in 2016 wordt uitgebracht. De Harlem Hellfighters waren een van de sterkste infanterieregimenten in de Grote Oorlog. Dit pakket bevat unieke unlocks die zijn geïnspireerd door hun heldendaden.&lt;br /&gt;&lt;br /&gt;&lt;b&gt;Inhoud&lt;\/b&gt;&lt;br /&gt;• &lt;b&gt;Hellfighter Trench Shotgun&lt;\/b&gt; – Een door de strijd gehavend jachtgeweer gegraveerd met het Hellfighter-insigne en “Men of Bronze” op de receiver en het nummer van de eenheid 369th op de loop, samen met het reliëf “Go Forward or Die France 1918” op de houten kolf.&lt;br /&gt;• &lt;b&gt;Hellfighter M1911&lt;\/b&gt; – Betrouwbaar en tijdloos reservewapen dat vandaag de dag nog steeds wordt gebruikt. Heeft als koosnaam \"old slabsides\" en is gegraveerd met het Hellfighter-insigne op het staartstuk en \"Men of Bronze\" op de vuurmond.&lt;br /&gt;• &lt;b&gt;Hellfighter Bolo Knife&lt;\/b&gt; – Angstaanjagend mes, gegraveerd met het nummer van het Hellfighter-regiment 369th, waardoor de vijand meteen heimwee krijgt.&lt;br /&gt;• &lt;b&gt;Hellfighter Insignia&lt;\/b&gt; – Draag dit embleem om aan te geven dat je bij de elite-eenheid Hellfighter hoort en angst inboezemt op het strijdveld.&lt;br /&gt;&lt;br /&gt;&lt;h3 style=\"display:inline;\"&gt;Battlefield 1&lt;\/h3&gt;&lt;br /&gt;Ervaar het begin van totale oorlog in Battlefield™ 1. Baan je een weg door epische gevechten, variërend van krappe belegerde Franse steden tot zwaar verdedigde bergforten in de Italiaanse Alpen, en aanschouw waanzinnige veldslagen in de woestijn van Arabië. Ontdek een nieuwe wereld in oorlog via een avontuurlijke campagne, of doe mee aan epische multiplayer gevechten met maximaal 64 spelers. Stem je tactiek af op de adembenemende omgevingen en totale verwoesting. Strijd als infanterie of bestuur ongelooflijke voertuigen te land, ter zee en in de lucht (variërend van tanks en motoren op de grond tot dubbeldekkers en gigantische oorlogsschepen), en stem je speelstijl af op de meest dynamische gevechten in de geschiedenis van Battlefield. &lt;br /&gt;&lt;br /&gt;&lt;h3 style=\"display:inline;\"&gt;Belangrijkste kenmerken:&lt;\/h3&gt;&lt;br /&gt;• Epische multiplayer gevechten met 64 spelers - Vorm een squad met vrienden en doe mee aan de meest epische multiplayer gevechten in de geschiedenis van FPS met maximaal 64 spelers als infanteristen of bestuurders van voertuigen, variërend van tanks en motoren in het veld tot dubbeldekkers en gigantische oorlogsschepen. &lt;br /&gt;• Ervaar het begin van totale oorlog – Maak deel uit van de grootste veldslagen in de geschiedenis van de mensheid. Van de zwaar verdedigde Alpen tot de verzengende woestijnen van Arabië, de oorlog raast op epische schaal te land, ter zee en in de lucht terwijl je getuige bent van de geboorte van moderne oorlogvoering.&lt;br /&gt;• Adembenemende intuïtieve verwoesting - Met intuïtieve verwoesting is geen strijd ooit dezelfde. Vernietig grote en kleine voertuigen, en maak hele gebouwen met de grond gelijk. Van kleine houten huizen tot enorme stenen forten, zelfs de grond waarop je vecht kan uiteen worden gereten.&lt;br /&gt;• Oorlogsverhalen van de andere kant van de wereld - Ontdek een wereld in oorlog via een avontuurlijke campagne en bekijk een wereldwijd conflict door de ogen van diverse personages, die worden verenigd door deze eerste moderne oorlog. ", "urls": [], "images": [], "media": [], "offerData": {}, "promotions": [], "parentCategoryPaths": [] }, { "id": "9200000061342591", "ean": "3391891989886", "gpc": "games", "title": "The Witcher 3: Wild Hunt - Game of The Year Edition - PS4", "specsTag": "Bandai Namco", "summary": "PlayStation 4 | PEGI-leeftijd: 18 | Avontuur|Role Playing Game (RPG)", "rating": 50, "shortDescription": "&lt;b&gt;About the GAME OF THE YEAR Edition&lt;\/b&gt;&lt;br /&gt;Word een monsterslachter en stort je in het avontuur! Al bij de release was The Witcher 3: Wild Hunt een klassieker, met meer dan 250 Game of the Year-prijzen. Geniet nu van dit enorme, meer dan 100 uur durende avontuur in een open wereld, inclusief beide uitbreidingen en meer dan 50 uur aan extra gameplay. Deze editie bevat alle aanvullende content – nieuw(e) wapens, pantsers, partneroutfits, speltype en missies.&lt;br /&gt; &lt;br /&gt;&lt;b&gt;About the GAME OF THE YEAR&lt;\/b&gt;&lt;br /&gt;De meest bekroonde gam...", "longDescription": "&lt;b&gt;About the GAME OF THE YEAR Edition&lt;\/b&gt;&lt;br /&gt;Word een monsterslachter en stort je in het avontuur! Al bij de release was The Witcher 3: Wild Hunt een klassieker, met meer dan 250 Game of the Year-prijzen. Geniet nu van dit enorme, meer dan 100 uur durende avontuur in een open wereld, inclusief beide uitbreidingen en meer dan 50 uur aan extra gameplay. Deze editie bevat alle aanvullende content – nieuw(e) wapens, pantsers, partneroutfits, speltype en missies.&lt;br /&gt; &lt;br /&gt;&lt;b&gt;About the GAME OF THE YEAR&lt;\/b&gt;&lt;br /&gt;De meest bekroonde game van 2015!&lt;br /&gt;Word een monsterslachter en stort je in een episch avontuur om het kind uit de voorspelling te zoeken, een levend wapen van verwoesting.&lt;br /&gt;INCLUSIEF ALLE UITBREIDINGEN EN AANVULLENDE CONTENT.&lt;br /&gt; &lt;br /&gt;&lt;b&gt;Features:&lt;\/b&gt;&lt;br /&gt; &lt;br /&gt;Speel als een sterk getrainde professionele monsterslachter&lt;br /&gt;Witchers worden van kinds af aan getraind en gemuteerd om bovennatuurlijke vaardigheden, kracht en reflexen te ontwikkelen. Ze vallen sociaal buiten alle groepen en vormen de contrabalans voor de met monsters geïnfecteerde wereld waarin ze wonen.&lt;br /&gt; &lt;br /&gt;•Vernietig vijanden als professionele monsterjager op gruwelijke wijze, gewapend met een reeks upgradebare wapens, muterende drankjes en vechtmagie.&lt;br /&gt;•Jaag op een diversiteit aan exotische monsters, van wilde beesten die zich ophouden in de bergpassen tot sluwe bovennatuurlijke roofdieren die schuilen in de donkere steegjes van dichtbevolkte steden.&lt;br /&gt;•Investeer je beloningen om je wapens te upgraden en aangepaste pantsers te kopen, of geef ze uit aan paardenrennen, kaartspellen, vuistgevechten en andere leuke dingen in het leven.&lt;br /&gt; &lt;br /&gt;Zoek het kind uit de voorspelling in een open fantasywereld met een dubbele moraal&lt;br /&gt;De enorme open wereld van The Witcher is gemaakt voor eindeloos avontuur en zet nieuwe normen op het gebied van formaat, diepte en complexiteit. &lt;br /&gt;•Doorkruis een open fantasywereld: verken vergeten ruïnes, grotten en scheepswrakken, handel met kooplieden en dwergensmeden in de steden, en ga op jacht op open vlakten tussen de bergen en de zee.&lt;br /&gt;•Zoek in oorlogstijd het kind uit de voorspelling, een levend wapen van grote macht dat werd aangekondigd in oude elfenlegenden.&lt;br /&gt;•Maak keuzes die verdergaan dan goed en kwaad, en ervaar de verstrekkende consequenties.&lt;br /&gt; &lt;br /&gt;&lt;b&gt;Game of the Year EDITION&lt;\/b&gt;&lt;br /&gt;The Witcher 3: Wild Hunt Game of the Year-edition is een combinatie van de basisgame en alle aanvullende content die tot nu is uitgebracht.&lt;br /&gt; &lt;br /&gt;•Inclusief de Hearts of Stone- en Blood &amp; Wine-uitbreidingen, die 50 uur aan extra verhaal bieden, plus nieuwe functies en nieuwe gebieden die de verkenbare wereld met meer dan een derde uitbreiden!&lt;br /&gt;•Biedt toegang tot alle aanvullende content tot nu toe, inclusief wapens, pantsers, zijdelingse missies, speltypen en nieuwe GWENT-kaarten!&lt;br /&gt;•Inclusief alle technische en visuele updates, plus een nieuwe gebruikersinterface die volledig opnieuw is ontworpen op basis van feedback van leden van de Witcher-community.", "urls": [], "images": [], "media": [], "offerData": {}, "parentCategoryPaths": [] }, </code></pre>
0
2016-09-15T07:54:07Z
39,506,213
<p>First of all, you're aware that the "2" in the <code>randrange</code> function skips all the odd-numbered elements, right?</p> <p>That aside, the most natural way to solve this is tho first get a random product, then do whatever you need with its data/fields. Also, as another poster said, the ordering of getting the <code>summary</code> field is wrong. I think you copied/pasted that line--watch out for copy/paste when trying to write code.</p> <pre><code>products = product['products'] random_product = products[random.randrange(0, len(products)+1, 2)] if products[0]['images'][3]['url'] is None: _send_to_fb(fbid, random_product['title'], random_product['urls'][0]['value'], random_product['summary']) </code></pre> <p>Finally, I wonder whether you really meant to check whether the first product's fourth image URL is <code>None</code>. If the image list is shorter than four elements, that check will cause an error. What is it you're really looking to find out?</p>
0
2016-09-15T08:18:28Z
[ "python", "arrays", "json", "list", "random" ]
Selecting only columns of a numpy array where value of a specific row < x
39,505,802
<p>I have a numpy array similar to following structure:</p> <pre><code>my_array = numpy.array([[1,1,1,2,2,2,3,3,3], [1,2,3,1,2,3,1,2,3], [1,1,32,4,15,63,763,23,0], [1,1,2,3,1,2,3,1,1], [1,1,1,1,1,1,1,1,1]]) </code></pre> <p>Now I'd like to get subset this array to get only those columns where the value in the 3rd row is &lt; 15.</p> <p>I can get a boolean list of that as:</p> <pre><code>list(my_array[2,:]&gt;15) </code></pre> <p>However I cannot use that boolean list for indexing like:</p> <pre><code>my_array[:,list(my_array[2,:]&gt;15)] </code></pre> <p>Probably I have to transform that list to a list of indices and use that to subset the array, but maybe there is an in-built function or straight forward way for selecting the specific columns of the array?</p>
0
2016-09-15T07:56:01Z
39,505,933
<p>You should not call <code>list()</code>. The input to <code>[...]</code> are supposed to be numpy arrays.</p> <pre><code>&gt;&gt;&gt; my_array[:, my_array[2,:]&gt;15] array([[ 1, 2, 3, 3], [ 3, 3, 1, 2], [ 32, 63, 763, 23], [ 2, 2, 3, 1], [ 1, 1, 1, 1]]) </code></pre>
1
2016-09-15T08:02:14Z
[ "python", "arrays", "numpy", "indexing" ]
how to add an ordered score table with names
39,505,970
<pre><code>import random number_correct = 0 def scorer(): global number_correct if attempt == answer: print("Correct.") number_correct = number_correct + 1 else: print('Incorrect. The correct answer is ' + str(answer)) name = input("Enter your name: ") for i in range(10): num1 = random.randrange(1, 100) num2 = random.randrange(1, 100) operation = random.choice(["*", "-", "+", "%", "//"]) print("What is the answer?", num1, operation, num2) attempt = int(input(" ")) if operation == "+": answer = num1 + num2 scorer() elif operation == "-": answer = num1 - num2 scorer() elif operation == "*": answer = num1 * num2 scorer() elif operation == "%": answer = num1 % num2 scorer() elif operation == "//": answer = num1 // num2 scorer() print(name + ", you got " + str(number_correct) + " out of 10.") </code></pre> <p>I have made the quiz above and now want it to make a high-score table with the names and scores next to each other from highest to smallest.</p> <p>I am trying to sort the scores first and this is what I have come up with:</p> <pre><code>scores = [] names = [] file = open("scores.txt","a") addedline = number_correct file.write('%d' % addedline) file.close() file = open("scores.txt","r") for eachline in file: scores.append(eachline) x = scores.sort() print(x) file.close() </code></pre> <p>I don't think this works and am not sure how i will combine the names and scores at the end (making sure that the correct score is next to the correct name). Please help. thanks</p>
0
2016-09-15T08:04:29Z
39,506,122
<p>I would recommend storing the names and scores as a csv, then you could read the names with the scores and then sort with the score as a key.</p> <pre><code>with open("scores.txt", "a") as file: file.write("%s, %s\n" % (name, number_correct)) with open("scores.txt", "r") as file: data = [line.split(", ") for line in file.read().split("\n")] data = sorted(data, key = lambda x: -int(x[1])) print("\n".join(["%s\t%s" % (i[0], i[1]) for i in data])) </code></pre>
0
2016-09-15T08:13:01Z
[ "python" ]
how to add an ordered score table with names
39,505,970
<pre><code>import random number_correct = 0 def scorer(): global number_correct if attempt == answer: print("Correct.") number_correct = number_correct + 1 else: print('Incorrect. The correct answer is ' + str(answer)) name = input("Enter your name: ") for i in range(10): num1 = random.randrange(1, 100) num2 = random.randrange(1, 100) operation = random.choice(["*", "-", "+", "%", "//"]) print("What is the answer?", num1, operation, num2) attempt = int(input(" ")) if operation == "+": answer = num1 + num2 scorer() elif operation == "-": answer = num1 - num2 scorer() elif operation == "*": answer = num1 * num2 scorer() elif operation == "%": answer = num1 % num2 scorer() elif operation == "//": answer = num1 // num2 scorer() print(name + ", you got " + str(number_correct) + " out of 10.") </code></pre> <p>I have made the quiz above and now want it to make a high-score table with the names and scores next to each other from highest to smallest.</p> <p>I am trying to sort the scores first and this is what I have come up with:</p> <pre><code>scores = [] names = [] file = open("scores.txt","a") addedline = number_correct file.write('%d' % addedline) file.close() file = open("scores.txt","r") for eachline in file: scores.append(eachline) x = scores.sort() print(x) file.close() </code></pre> <p>I don't think this works and am not sure how i will combine the names and scores at the end (making sure that the correct score is next to the correct name). Please help. thanks</p>
0
2016-09-15T08:04:29Z
39,507,567
<p>I'm not sure how exactly your textfile looks but I would suggest using a dictionary (as long as you do not have the same score more than once). Like this you could make the key your score and the value could be the name and the dictionary would automatically sort itself in order of the keys. </p>
0
2016-09-15T09:29:30Z
[ "python" ]
range() keeps returning empty list
39,506,048
<p>long time lurker first time poster. This is really stumping me. So I have a function:</p> <pre><code>def button_pressed(): first_day = int(daterangeT1.get("1.0","end-1c")) last_day = int(daterangeT1.get("1.0","end-1c")) days = range(first_day, last_day) </code></pre> <p>So i have tried many different ways but the range() call doesn't seem to like the two variables above it. They are both integers. It is always returning an empty list when i do a print command. Simply: "[]"</p> <p>Any help greatly appreciated thanks :)</p>
-2
2016-09-15T08:08:58Z
39,506,079
<p>It seems like <code>first_day</code> and <code>last_day</code> are equal (you are getting the same key from the <code>daterangeT1</code> dictionary/object), and <code>range(x, x)</code> returns an empty list.</p> <p>Also note that if <code>daterangeT1</code> is indeed a dictionary, if the <code>'1.0'</code> key doesn't exist then <code>get</code> will return the string <code>'end-1c'</code> which will cause a <code>ValueError</code> when trying to convert to <code>int</code>. </p>
2
2016-09-15T08:10:39Z
[ "python", "list", "range" ]