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 won...
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...
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...
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>...
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...
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 ...
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 ar...
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([(...
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...
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_intr...
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):...
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 ov...
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 erro...
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 pa...
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.st...
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') ...
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.st...
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...
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 the...
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> <pr...
-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)() </c...
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" ce...
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 PrintIE6...
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 initi...
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="nofoll...
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 initi...
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 verbos...
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 initi...
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) ...
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 initi...
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;...
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 initi...
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 initi...
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 initi...
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...
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 initi...
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="no...
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 pla...
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="no...
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 ...
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="h...
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="h...
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 i...
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]...
-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 &l...
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]...
-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 t...
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)): din...
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("e...
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)): din...
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): di...
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> unsuccessfu...
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(", ") ...
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</co...
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(", ") ...
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(", ") ...
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><...
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 sala...
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 = """ th...
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 sala...
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()</c...
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 sala...
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.stopwor...
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 s...
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 ...
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....
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 diction...
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_l...
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 diction...
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...
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): f...
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.ini...
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...
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...
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 display...
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...
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") useMen...
-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 as...
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") useMen...
-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(s...
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...
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): <...
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>...
-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": 3506...
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 u...
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 o...
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 o...
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 output...
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 o...
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 ...
-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 o...
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;= ...
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 ...
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 ...
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(...
-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 exam...
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,p...
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...
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 eleme...
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(filt...
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 eleme...
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(in...
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__...
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 ...
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/rZ...
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 ...
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 t...
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</...
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 f...
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 ...
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...
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</stron...
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</stron...
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 ccccccccccc...
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...
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):...
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...
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', 'D...
-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 = {} ...
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]...
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>p...
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 intere...
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 ...
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 ...
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...
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 ...
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.createDat...
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("\""," ...
-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;...
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("\""," ...
-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("\""," ...
-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), borde...
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 ...
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 cl...
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<...
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_cont...
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 r...
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, "h...
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)...
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() ...
-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 articl...
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;...
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 ...
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 fi...
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 ( Filen...
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?...
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 tha...
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?...
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 que...
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?...
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?...
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 <c...
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 othe...
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-sam...
-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 othe...
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 ...
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>...
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 permutation...
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 secon...
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 permutation...
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, s...
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 = cs...
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....
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....
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>...
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_...
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 th...
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 ...
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]]) </c...
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): num...
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(", ") fo...
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): num...
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 w...
-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 doe...
2
2016-09-15T08:10:39Z
[ "python", "list", "range" ]