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
Python Flask wt forms ventilator check if password is matching database
39,506,137
<p>I am trying to create a from where before updating records the user must type in their password for validation.</p> <p>I was thinking of useing something like this.</p> <pre><code>class AccountSettingsForm(Form): password_proof= TextField("Password:",[validators.EqualTo(current_user.password, message='Pass...
-1
2016-09-15T08:13:51Z
39,506,421
<p>You need to create a validator method with the syntax <code>validate_{field_name}</code>. Also, as you are using other data (the user instance, which contains their password), you need to initialize the form with that user instance.</p> <p>Something like this should work for your example:</p> <pre><code>from wtfor...
1
2016-09-15T08:29:51Z
[ "python", "flask", "flask-sqlalchemy", "flask-wtforms", "flask-security" ]
pandas drop_duplicates using comparison function
39,506,438
<p>Is it somehow possible to use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.drop_duplicates.html" rel="nofollow">pandas.drop_duplicates</a> with a comparison operator which compares two objects in a particular column in order to identify duplicates? If not, what is the alternative?<...
3
2016-09-15T08:31:04Z
39,506,753
<p><strong><em>Option 1</em></strong></p> <pre><code>df[~pd.DataFrame(df.A.values.tolist()).duplicated()] </code></pre> <p><a href="http://i.stack.imgur.com/pQ4BD.png" rel="nofollow"><img src="http://i.stack.imgur.com/pQ4BD.png" alt="enter image description here"></a></p> <p><strong><em>Option 2</em></strong></p> <...
3
2016-09-15T08:49:26Z
[ "python", "pandas" ]
pandas drop_duplicates using comparison function
39,506,438
<p>Is it somehow possible to use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.drop_duplicates.html" rel="nofollow">pandas.drop_duplicates</a> with a comparison operator which compares two objects in a particular column in order to identify duplicates? If not, what is the alternative?<...
3
2016-09-15T08:31:04Z
39,506,999
<p>IIUC, your question is how to use an <em>arbitrary</em> function to determine what is a duplicate. To emphasize this, let's say that two lists are duplicates if the sum of the first item, plus the square of the second item, is the same in each case</p> <pre><code>In [59]: In [118]: df = pd.DataFrame( {'A': [[1,2],[...
3
2016-09-15T09:01:47Z
[ "python", "pandas" ]
pandas drop_duplicates using comparison function
39,506,438
<p>Is it somehow possible to use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.drop_duplicates.html" rel="nofollow">pandas.drop_duplicates</a> with a comparison operator which compares two objects in a particular column in order to identify duplicates? If not, what is the alternative?<...
3
2016-09-15T08:31:04Z
39,507,103
<p><code>Lists</code> are unhashable in nature. Try converting them to hashable types such as <code>tuples</code> and then you can continue to use <code>drop_duplicates</code>:</p> <pre><code>df['A'] = df['A'].map(tuple) df.drop_duplicates('A').applymap(list) </code></pre> <p><a href="http://i.stack.imgur.com/Ge4NF.p...
3
2016-09-15T09:06:42Z
[ "python", "pandas" ]
How to test function, that has two or more input()'s inside?
39,506,572
<p>I need to test some python 3 code, and I got stuck testing function with few input()'s.</p> <p>Example:</p> <pre><code>def two_answers(): if input("Input 'go' to proceed") != "go": return two_answers() else: while input("Input 'bananas' to proceed") != "bananas": print("What?!")...
2
2016-09-15T08:39:18Z
39,507,214
<p>What you want is to simulate the user inputs.</p> <p>You have to use a <a href="https://docs.python.org/3/library/unittest.mock.html" rel="nofollow"><strong>unittest.mock</strong></a> and patch the <code>input</code> function.</p> <p>See the <a href="https://docs.python.org/3/library/unittest.mock.html#quick-guide...
0
2016-09-15T09:13:08Z
[ "python", "unit-testing", "python-3.x", "python-unittest" ]
How to test function, that has two or more input()'s inside?
39,506,572
<p>I need to test some python 3 code, and I got stuck testing function with few input()'s.</p> <p>Example:</p> <pre><code>def two_answers(): if input("Input 'go' to proceed") != "go": return two_answers() else: while input("Input 'bananas' to proceed") != "bananas": print("What?!")...
2
2016-09-15T08:39:18Z
39,507,282
<p>Here is my solution:</p> <pre><code>class SimulatedInput: def __init__(self,*args): self.args = iter(args) def __call__(self,x): try: return next(self.args) except StopIteration: raise Exception("No more input") </code></pre> <p>Then you could use it like ...
0
2016-09-15T09:16:53Z
[ "python", "unit-testing", "python-3.x", "python-unittest" ]
How to test function, that has two or more input()'s inside?
39,506,572
<p>I need to test some python 3 code, and I got stuck testing function with few input()'s.</p> <p>Example:</p> <pre><code>def two_answers(): if input("Input 'go' to proceed") != "go": return two_answers() else: while input("Input 'bananas' to proceed") != "bananas": print("What?!")...
2
2016-09-15T08:39:18Z
39,507,428
<p>A minimalistic example with no dependencies. Play with it to extend it as you wish:</p> <pre><code>import sys import io def two_answers(): if input("Input 'go' to proceed") != "go": return two_answers() else: while input("Input 'bananas' to proceed") != "bananas": print("What?!"...
-1
2016-09-15T09:23:15Z
[ "python", "unit-testing", "python-3.x", "python-unittest" ]
How to test function, that has two or more input()'s inside?
39,506,572
<p>I need to test some python 3 code, and I got stuck testing function with few input()'s.</p> <p>Example:</p> <pre><code>def two_answers(): if input("Input 'go' to proceed") != "go": return two_answers() else: while input("Input 'bananas' to proceed") != "bananas": print("What?!")...
2
2016-09-15T08:39:18Z
39,537,628
<p>I would wrap the input in to a function.</p> <pre><code>def input_wrap(prompt): return input(prompt) </code></pre> <p>Then you can inject it.</p> <pre><code>def two_answers(input_func): if input_func('...') != 'go': return two_answers(input_func) ... </code></pre> <p>Now when you want to test it you ca...
0
2016-09-16T18:05:11Z
[ "python", "unit-testing", "python-3.x", "python-unittest" ]
How to get match result by given range using regular expression?
39,506,578
<p>I'm stucking with my code to get all return match by given range. My data sample is:</p> <pre><code> comment 0 [intj74, you're, whipping, people, is, a, grea... 1 [home, near, kcil2, meniaga, who, intj47, a, l... 2 [thematic, budget, kasi, smooth, sweep] 3 [budget, 2, intj69, most, pe...
1
2016-09-15T08:39:36Z
39,506,752
<p>you could replace <code>[t for t in x if t=='intj74']</code> with, e.g.,</p> <pre><code>[t for t in x if re.match('intj[0-9]+$', t)] </code></pre> <p>or even</p> <pre><code>[t for t in x if re.match('intj[0-9]+$', t)] or [np.nan] </code></pre> <p>which would also handle the case if there are no matches (so that ...
1
2016-09-15T08:49:26Z
[ "python", "pandas" ]
How to get match result by given range using regular expression?
39,506,578
<p>I'm stucking with my code to get all return match by given range. My data sample is:</p> <pre><code> comment 0 [intj74, you're, whipping, people, is, a, grea... 1 [home, near, kcil2, meniaga, who, intj47, a, l... 2 [thematic, budget, kasi, smooth, sweep] 3 [budget, 2, intj69, most, pe...
1
2016-09-15T08:39:36Z
39,506,867
<p>I am new to <code>pandas</code> as well. You might have initialized your DataFrame differently. Anyway, this is what I have:</p> <pre><code>import pandas as pd data = { 'comment': [ "intj74, you're, whipping, people, is, a", "home, near, kcil2, meniaga, who, intj47, a", "thematic, budge...
0
2016-09-15T08:55:00Z
[ "python", "pandas" ]
Django 1.10 full text search by UUIDField returns DataError
39,506,717
<p>I have the following model:</p> <pre><code>class Show(models.Model): cid = models.UUIDField( default=uuid.uuid4, editable=False, verbose_name="Content ID", help_text="Unique Identifier" ) title_short = models.CharField( max_length=60, blank=True, v...
0
2016-09-15T08:47:29Z
39,507,224
<p>You may want to file a bug-report.</p> <p>The Django code creates a COALESCE() statement, assuming that the final fallback value of an empty string (<code>''</code>) is acceptable for fields given. I don't see a way to specify the fallback value through the official API, and since UUID fields are translated to Post...
0
2016-09-15T09:13:30Z
[ "python", "django", "postgresql", "full-text-search", "uuid" ]
See stacktrace of hanging Python in futex(..., FUTEX_WAIT_BITSET_PRIVATE|...)
39,506,737
<p>A Python process hangs in futex():</p> <pre><code>root@pc:~# strace -p 9042 strace: Process 9042 attached futex(0x1e61900, FUTEX_WAIT_BITSET_PRIVATE|FUTEX_CLOCK_REALTIME, 0, NULL, ffffffff </code></pre> <p>I want to see the stacktrace if the hanging process.</p> <p>Unfortunately ctrl-c does not work :-(</p> <p>H...
3
2016-09-15T08:48:22Z
39,507,648
<ol> <li>install the gdb python extensions if needed for your system (see <a href="https://wiki.python.org/moin/DebuggingWithGdb" rel="nofollow">here</a> for example, or look at your distro documentation)</li> <li>attach gdb to your hung process</li> <li><p>run</p> <pre><code>(gdb) py-bt </code></pre> <p>instead of r...
3
2016-09-15T09:32:45Z
[ "python", "debugging", "hang", "futex" ]
PyQt display 1 widget in 2 layouts?
39,506,856
<p>I'd like to add QLineEdit/checkbox/button in 2 layouts. So no matter which one I press in which ever window they both do the same thing, update each other as I type and so on.</p> <p>Is it possible or do I need to create second set of controls and then signal link each other?</p> <p>Regards Dariusz</p>
1
2016-09-15T08:54:37Z
39,506,951
<p>A widget can only exist in one place at a time. You will need to link the two unfortunately. Do yourself a favor and do it properly via a model.</p> <p>If it were possible for a widget to exist in multiple places, this would lead to a whole lot of problems: cyclic trees, multiple parents, etc.</p>
1
2016-09-15T08:59:14Z
[ "python", "pyqt", "pyqt4" ]
Random sampling without replacement when more needs to be sampled than there are samples
39,507,118
<p>I need to generate samples from a list of numbers in a scenario where I might have the situation that I need to sample more numbers than I have. More explicitly, this is what I need to do: </p> <ul> <li><p>Let the total number of elements in my list be N.</p></li> <li><p>I need to sample randomly without replacemen...
2
2016-09-15T09:07:18Z
39,507,484
<p>I would just wrap numpy's <code>random.choice()</code> like so:</p> <pre><code>L = [1, 2, 3, 4, 5] def wrap_choice(list_to_sample, no_samples): list_size = len(list_to_sample) takes = no_samples // list_size samples = list_to_sample * (no_samples // list_size) + list(np.random.choice(list_to_sample, no...
2
2016-09-15T09:25:56Z
[ "python", "numpy", "sampling" ]
Random sampling without replacement when more needs to be sampled than there are samples
39,507,118
<p>I need to generate samples from a list of numbers in a scenario where I might have the situation that I need to sample more numbers than I have. More explicitly, this is what I need to do: </p> <ul> <li><p>Let the total number of elements in my list be N.</p></li> <li><p>I need to sample randomly without replacemen...
2
2016-09-15T09:07:18Z
39,507,620
<p>You can <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.concatenate.html" rel="nofollow"><code>concatenate</code></a> the results of <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.repeat.html" rel="nofollow"><code>repeat</code></a> and <a href="http://docs.scipy.org/doc/numpy/r...
3
2016-09-15T09:31:38Z
[ "python", "numpy", "sampling" ]
Random sampling without replacement when more needs to be sampled than there are samples
39,507,118
<p>I need to generate samples from a list of numbers in a scenario where I might have the situation that I need to sample more numbers than I have. More explicitly, this is what I need to do: </p> <ul> <li><p>Let the total number of elements in my list be N.</p></li> <li><p>I need to sample randomly without replacemen...
2
2016-09-15T09:07:18Z
39,507,782
<p>Here is what might be a solution for the <strong>case where 0 &lt; M-N &lt; max(L)</strong> :</p> <pre><code>import numpy as np from numpy.random import random l = np.array([1, 2, 3, 4, 5]) rand = [ i for i in l[np.argsort(np.amax(l))[:M-N]] ] new_l = np.concatenate(l,rand) </code></pre> <p>Here is an example :<...
1
2016-09-15T09:39:02Z
[ "python", "numpy", "sampling" ]
Random sampling without replacement when more needs to be sampled than there are samples
39,507,118
<p>I need to generate samples from a list of numbers in a scenario where I might have the situation that I need to sample more numbers than I have. More explicitly, this is what I need to do: </p> <ul> <li><p>Let the total number of elements in my list be N.</p></li> <li><p>I need to sample randomly without replacemen...
2
2016-09-15T09:07:18Z
39,507,924
<p>Use <code>divmod()</code> to get the number of repetitions of the list and the remainder/shortfall. The shortfall can then be randomly selected from the list using <code>numpy.random.choice()</code>.</p> <pre><code>import numpy as np def get_sample(l, n): samples, shortfall = divmod(n, len(l)) return np.co...
1
2016-09-15T09:45:27Z
[ "python", "numpy", "sampling" ]
Curses Programming with Python
39,507,305
<p>So I have start working with Curses in Python. I have got this source code to start with and slowly I will make some updates to it:</p> <pre><code> #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Testing out the curses lib. """ import curses def main(scr): """ Draw a border around the screen, move...
0
2016-09-15T09:17:35Z
39,508,038
<p>You know the valid range. From <code>0</code> to to <code>y1</code> inclusive. (0 to <code>x1</code> respectively). So just add tests to ensure the coordinates stay within the range:</p> <pre><code> elif key == 'KEY_UP': if y &gt; 0: y -= 1 elif key == 'KEY_DOWN': if y &lt; y1: y ...
1
2016-09-15T09:50:46Z
[ "python", "python-3.x", "curses" ]
How to unpack variables from tuple and give them names from another tuple?
39,507,350
<p>I have two tuples - one with the keys and another one with a collection of variables of different types (list, float64, int and array) generate with the help of the following formula from a dictionary:</p> <pre><code>keys, values = zip(*[(key, value) for (key, value) in data_dict.items()]) </code></pre> <p>Now I w...
0
2016-09-15T09:20:03Z
39,508,015
<p>If it's really not possible to store your key/value pairs in a <code>dict</code> and serialise them to data file in that format, you can use <a href="https://docs.python.org/3/library/functions.html#exec" rel="nofollow"><code>exec</code></a> to dynamically construct assignment statements</p> <pre><code>&gt;&gt;&gt;...
1
2016-09-15T09:49:16Z
[ "python" ]
How to unpack variables from tuple and give them names from another tuple?
39,507,350
<p>I have two tuples - one with the keys and another one with a collection of variables of different types (list, float64, int and array) generate with the help of the following formula from a dictionary:</p> <pre><code>keys, values = zip(*[(key, value) for (key, value) in data_dict.items()]) </code></pre> <p>Now I w...
0
2016-09-15T09:20:03Z
39,508,083
<p>If you want to create variables in the global scope from your dictionary, perhaps you could update it like this:</p> <pre><code>globals().update(data_dict) </code></pre> <p>without unpacking the dict.</p> <p>I'm not sure if this is what you're looking for.</p>
0
2016-09-15T09:52:57Z
[ "python" ]
The recursive implementation with python for a mathematical puzzle of hailstone sequence or Collatz conjecture?
39,507,395
<p>There is a mathematical puzzle:</p> <ol> <li>Pick a positive integer n as start. </li> <li>If n is even, then divide it by 2.</li> <li>If n is odd, multiply it by 3, and add 1. </li> <li>continue this process until n is 1.</li> </ol> <p>I want to write a recursive function, that takes the n as parameter, and then ...
0
2016-09-15T09:22:01Z
39,507,961
<p>You can use an accumulator:</p> <pre><code>def hailstone(n): """ return a tuple that includes the hailstone sequence starting at n, and the length of sequence. 1) Pick a positive integer n as start. 2) If n is even, then divide it by 2. 3) If n is odd, multiply it by 3, and add 1. 4) con...
2
2016-09-15T09:46:57Z
[ "python", "algorithm", "recursion" ]
The recursive implementation with python for a mathematical puzzle of hailstone sequence or Collatz conjecture?
39,507,395
<p>There is a mathematical puzzle:</p> <ol> <li>Pick a positive integer n as start. </li> <li>If n is even, then divide it by 2.</li> <li>If n is odd, multiply it by 3, and add 1. </li> <li>continue this process until n is 1.</li> </ol> <p>I want to write a recursive function, that takes the n as parameter, and then ...
0
2016-09-15T09:22:01Z
39,509,530
<p>First, you need to decide whether to use an iterative or recursive process - in Python it doesn't matter much (since Python doesn't employ tail call optimization), but in languages it could. For a more in-depth explanation of iterative/recursive process see <a href="http://stackoverflow.com/q/17254240/106471" title=...
1
2016-09-15T11:06:14Z
[ "python", "algorithm", "recursion" ]
How can I find one tag between two other tags?
39,507,399
<p>I have a document with structure like this:</p> <pre><code>&lt;tag1&gt;some_text_1&lt;/tag1&gt; &lt;tag2&gt;text_1&lt;/tag2&gt; &lt;tag3&gt;....&lt;/tag3&gt; &lt;tag2&gt;text_2&lt;/tag2&gt; &lt;tag1&gt;some_text_2&lt;/tag1&gt; &lt;tag2&gt;text_3&lt;/tag2&gt; ... </code></pre> <p>And I need to get all <code>tag2</c...
0
2016-09-15T09:22:19Z
39,507,574
<p>You should explain better what you need to find because is hard understand exactly what you want.</p> <p>A good way to do it is using a regular expressions.</p> <p><strong>Re Library Documentation:</strong> <a href="https://docs.python.org/2/library/re.html" rel="nofollow">https://docs.python.org/2/library/re....
-2
2016-09-15T09:29:49Z
[ "python", "python-3.x", "beautifulsoup" ]
How can I find one tag between two other tags?
39,507,399
<p>I have a document with structure like this:</p> <pre><code>&lt;tag1&gt;some_text_1&lt;/tag1&gt; &lt;tag2&gt;text_1&lt;/tag2&gt; &lt;tag3&gt;....&lt;/tag3&gt; &lt;tag2&gt;text_2&lt;/tag2&gt; &lt;tag1&gt;some_text_2&lt;/tag1&gt; &lt;tag2&gt;text_3&lt;/tag2&gt; ... </code></pre> <p>And I need to get all <code>tag2</c...
0
2016-09-15T09:22:19Z
39,508,232
<pre><code>from bs4 import BeautifulSoup html = '''&lt;tag1&gt;some_text_1&lt;/tag1&gt; &lt;tag2&gt;text_1&lt;/tag2&gt; &lt;tag3&gt;....&lt;/tag3&gt; &lt;tag2&gt;text_2&lt;/tag2&gt; &lt;tag1&gt;some_text_2&lt;/tag1&gt; &lt;tag2&gt;text_3&lt;/tag2&gt;''' soup = BeautifulSoup(html,"html.parser"...
0
2016-09-15T10:00:29Z
[ "python", "python-3.x", "beautifulsoup" ]
How can I find one tag between two other tags?
39,507,399
<p>I have a document with structure like this:</p> <pre><code>&lt;tag1&gt;some_text_1&lt;/tag1&gt; &lt;tag2&gt;text_1&lt;/tag2&gt; &lt;tag3&gt;....&lt;/tag3&gt; &lt;tag2&gt;text_2&lt;/tag2&gt; &lt;tag1&gt;some_text_2&lt;/tag1&gt; &lt;tag2&gt;text_3&lt;/tag2&gt; ... </code></pre> <p>And I need to get all <code>tag2</c...
0
2016-09-15T09:22:19Z
39,510,675
<p>Your description <em>I need to get all tag2 instances that are after tag1 with some_text_1 and before the next tag2.</em> basically equates to getting the first <code>tag2</code> after any tag1 with the text <code>some_text_</code>.</p> <p>So find the <code>tag1's</code> with the certain text and check if the next...
1
2016-09-15T12:08:48Z
[ "python", "python-3.x", "beautifulsoup" ]
TensorFlow, Python, Sharing Variables, initialize at top
39,507,405
<p>I'm having an issue in TensorFlow with Sharing Variables with the Python API.</p> <p>I've read the official documentation (<a href="https://www.tensorflow.org/versions/r0.10/how_tos/variable_scope/index.html" rel="nofollow">https://www.tensorflow.org/versions/r0.10/how_tos/variable_scope/index.html</a>), but I stil...
0
2016-09-15T09:22:33Z
39,513,649
<p>It seems like the call to tf.variable_scope() finds the variable scope/w even if you run it in an empty session. I have cleaned up your code to demonstrate.</p> <pre><code>import tensorflow as tf import numpy as np def shared_layer(x, output_size, non_linearity, name): with tf.variable_scope(name): in...
0
2016-09-15T14:25:58Z
[ "python", "tensorflow" ]
Identify cells containing specific strings and overwrite content with numbers using Python
39,507,417
<p>I have a dataframe which looks like this:</p> <p><a href="http://i.stack.imgur.com/qe7Y2.png" rel="nofollow"><img src="http://i.stack.imgur.com/qe7Y2.png" alt="enter image description here"></a></p> <p>My goal is to identify for each cell of every column if the following strings are contained: <code>'KSS'</code>, ...
0
2016-09-15T09:22:52Z
39,507,870
<p>If you create a dict with your lookup and replacement values then you can call <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.map.html#pandas.Series.map" rel="nofollow"><code>map</code></a> on this column, additionally you need to pass <code>na_action='ignore'</code> to <code>map</code>...
3
2016-09-15T09:43:17Z
[ "python", "pandas", "replace", "substitution" ]
Fill missing values from another Pandas dataframe with different shape
39,507,433
<p>I have 2 tables of different sizes which I would like to merge in the following way in Python using Pandas:</p> <pre><code>UID Property Date 1 A 10/02/2016 2 B NaN 3 A 10/02/2016 4 C NaN 5 C NaN 6 A 10/02/2016 </code></pre> <p>Table 1 conta...
0
2016-09-15T09:23:19Z
39,507,621
<p>First let's merge the two datasets: we don't overwrite the original date:</p> <pre><code>df_merge = pandas.merge(T1, T2, on='Property') </code></pre> <p>then we replace the missing values copying them from the 'DateProxy' field:</p> <pre><code>df_merge.Date = df_merge.apply( lambda x: x['Date'] + ' (kept from...
1
2016-09-15T09:31:39Z
[ "python", "pandas", "merge" ]
YAML key consisting of a list of elements
39,507,595
<p>I need to have a list of elements as a key, so that I can check if several conditions are met. Example (don't know if this is possible and if the syntax is correct):</p> <pre><code>mapping: c_id: [pak, gb]: '4711' [pak, ch]: '4712' [pak]: '4713' d_id: . . . </code></pre> <p>Now I need ...
0
2016-09-15T09:30:37Z
39,507,713
<p>The syntax for your YAML is correct. The only trick is that because in Python a key has to be immutable you need to specify access to the complex key as a tuple:</p> <pre><code>import ruamel.yaml yaml_str = """\ mapping: c_id: [pak, gb]: '4711' [pak, ch]: '4712' [pak]: '4713' """ data = ruamel.yaml....
2
2016-09-15T09:35:36Z
[ "python", "yaml", "pyyaml" ]
YAML key consisting of a list of elements
39,507,595
<p>I need to have a list of elements as a key, so that I can check if several conditions are met. Example (don't know if this is possible and if the syntax is correct):</p> <pre><code>mapping: c_id: [pak, gb]: '4711' [pak, ch]: '4712' [pak]: '4713' d_id: . . . </code></pre> <p>Now I need ...
0
2016-09-15T09:30:37Z
39,510,765
<p>In addition to Anthon's answer, here is how you can do it with PyYaml:</p> <pre><code>mapping: c_id: !!python/tuple [pak, gb]: '4711' !!python/tuple [pak, ch]: '4712' !!python/tuple [pak]: '4713' </code></pre> <p>The trick is to tell PyYaml that you want to load the keys into a tuple (since a list ca...
1
2016-09-15T12:13:33Z
[ "python", "yaml", "pyyaml" ]
Python pandas nonzero cumsum
39,507,774
<p>I want to apply <code>cumsum</code> on dataframe in <code>pandas</code> in <code>python</code>, but withouth zeros. Simply I want to leave zeros and do <code>cumsum</code> on dataframe. Suppose I have dataframe like this:</p> <pre><code>import pandas as pd df = pd.DataFrame({'a' : [1,2,0,1], ...
2
2016-09-15T09:38:41Z
39,507,811
<p>You can mask the df so that you only overwrite the non-zero cells:</p> <pre><code>In [173]: df[df!=0] = df.cumsum() df Out[173]: a b c 0 1 2 0 1 3 7 1 2 0 0 3 3 4 0 8 </code></pre>
5
2016-09-15T09:40:19Z
[ "python", "pandas" ]
OR-tools routing fails to find 'trivial' optimal solution in the presence of order-constraints
39,507,824
<p>In order to better understand the constraint-programming behind or-tools routing, I created a toy example of a depot and 4 other nodes configured to allow for two routes.</p> <p><a href="http://i.stack.imgur.com/SiZj1.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/SiZj1.jpg" alt="enter image description her...
0
2016-09-15T09:41:01Z
39,718,730
<p><strong>@furnon</strong> On github answered my question via the github-issues list: <a href="https://github.com/google/or-tools/issues/252#issuecomment-249646587" rel="nofollow">https://github.com/google/or-tools/issues/252#issuecomment-249646587</a></p> <p>First, constraint programming performs better on tighter...
0
2016-09-27T07:33:17Z
[ "python", "or-tools" ]
Make unittest.mock.Mock() return list of dicts
39,507,864
<p>I'm trying to mock a call of method <code>extra_get()</code> which usually returns a list of dicts. As far as I understand from the Mock <a href="https://docs.python.org/3/library/unittest.mock.html#unittest.mock.Mock" rel="nofollow">docs</a>, if I want to return iterable, I should set side_effect param.</p> <pre><...
0
2016-09-15T09:43:03Z
39,537,404
<pre><code>with mock.patch.object(client, 'extra_get', return_value=[{...}, {...}]) as mock_get: # fill in the rest </code></pre>
1
2016-09-16T17:47:41Z
[ "python", "unit-testing", "python-unittest" ]
Calling functions
39,507,903
<p>this may sound proper nooby, but I'm having some trouble with python functions.</p> <p>i do a level computer science and I'm making a currency converter using a dictionary to define the exchange rates of the currencies.</p> <p>for each conversion, i have made a function that does all the calculations etc for the c...
-2
2016-09-15T09:44:28Z
39,508,139
<p><code>return</code> is used to return variables from a <a href="https://docs.python.org/3/tutorial/controlflow.html#defining-functions" rel="nofollow">function definition</a>. </p> <p>To call a function you have simply to write the name of the function with the input parameters in the round brackets. In your case <...
2
2016-09-15T09:55:51Z
[ "python", "dictionary", "python-3.5.2" ]
Creating a list of lists and appending lists
39,507,943
<pre><code>a=[[2,3],[3,4]] b=[[5,6],[7,8],[9,10]] c=[[11,12],[13,14],[15,16],[17,18]] c1=[[11,12],[13,14],[15,16],[17,18]] listr=[] for number in range(96): listr.append(number) list = [[]]*96 for e in a: for f in b: for g in c: for h in d: for i in listr: ...
-1
2016-09-15T09:46:17Z
39,508,432
<p>You may want to use <a href="https://docs.python.org/2/library/itertools.html#itertools.product" rel="nofollow"><code>itertools.product</code></a> to solve this.</p> <p>Assuming you want combinations from <code>a</code>, <code>b</code>, <code>c</code> and <code>d</code> in groups of 4 (and based on your expected ou...
2
2016-09-15T10:10:14Z
[ "python", "list", "append" ]
pandas: rename axis in df
39,508,001
<p>I have a df which looks like this:</p> <pre><code> Column 1 Channel Apples 1.0 Oranges 2.0 Puppies 3.0 Ducks 4.0 </code></pre> <p>I would like to rename the axis so it looks like this:</p> <pre><code>Channel Column 1 Apples ...
1
2016-09-15T09:48:49Z
39,509,360
<p>This is kind of a hack to get you what you eventually wanted it to look like.</p> <pre><code>df = pd.read_csv(data, sep='\s{2,}', index_col='Channel', engine='python') df </code></pre> <p><a href="http://i.stack.imgur.com/CLcCU.png" rel="nofollow"><img src="http://i.stack.imgur.com/CLcCU.png" alt="Image"></a></p> ...
1
2016-09-15T10:57:55Z
[ "python", "pandas", "dataframe" ]
Pandas: Set variable to value in cell, if another cell on same row contains string
39,508,021
<p>Let's say my Pandas <code>DataFrame</code> contains the following:</p> <pre><code>Row Firstname Middlename Lastname … 10 Roy G. Biv 11 Cnyder M. Uk 12 Pan T. One … </code></pre> <p>If a cell in <code>["Lastname"]</code> contains <code>"Biv"</cod...
1
2016-09-15T09:49:38Z
39,508,189
<p>If you want just the scalar value then you can access the first value in the result array and assign this:</p> <pre><code>firstname = df.loc[df['Lastname'].str.contains('Biv'), 'Firstname'][0] </code></pre> <p>Note that really you should check if it's not empty though:</p> <pre><code>if len(df.loc[df['Lastname']....
1
2016-09-15T09:57:56Z
[ "python", "pandas" ]
Use scrapy as an item generator
39,508,095
<p>I have an existing script (main.py) that requires data to be scraped.</p> <p>I started a scrapy project for retrieving this data. Now, is there any way main.py can retrieve the data from scrapy as an Item generator, rather than persisting data using the Item pipeline?</p> <p>Something like this would be really con...
0
2016-09-15T09:53:20Z
39,508,698
<p>You could send json data out from the crawler and grab the results. It can be done as follows:</p> <p>Having the spider:</p> <pre><code>class MySpider(scrapy.Spider): # some attributes accomulated=[] def parse(self, response): # do your logic here page_text = response.xpath('//text()')...
0
2016-09-15T10:23:04Z
[ "python", "scrapy", "scrapy-pipeline" ]
Use scrapy as an item generator
39,508,095
<p>I have an existing script (main.py) that requires data to be scraped.</p> <p>I started a scrapy project for retrieving this data. Now, is there any way main.py can retrieve the data from scrapy as an Item generator, rather than persisting data using the Item pipeline?</p> <p>Something like this would be really con...
0
2016-09-15T09:53:20Z
39,517,256
<p>You can do it this way in a Twisted or Tornado app:</p> <pre><code>import collections from twisted.internet.defer import Deferred from scrapy.crawler import Crawler from scrapy import signals def scrape_items(crawler_runner, crawler_or_spidercls, *args, **kwargs): """ Start a crawl and return an object (...
0
2016-09-15T17:43:47Z
[ "python", "scrapy", "scrapy-pipeline" ]
Python list from .txt file
39,508,166
<p>I`m trying to create primitive dictionary (or list) in Python with basic functions that I learned from book (Mark Summerfield).</p> <p>Here is my question.</p> <p>All works as I need, but I had a problem with writing strings to the file.</p> <p>This is a piece of my code:</p> <pre><code> word = input("New word ...
3
2016-09-15T09:57:04Z
39,508,466
<p>The issue is created in this line:</p> <pre><code>word = word[:x] + ",\n" # =adding shift to the end of str </code></pre> <p>You need to remember that variable <code>word</code> isn't contain your word any more. You have there for example "0. word" there.</p> <p>So you have to update <code>x</code> - line count t...
0
2016-09-15T10:11:50Z
[ "python" ]
Python list from .txt file
39,508,166
<p>I`m trying to create primitive dictionary (or list) in Python with basic functions that I learned from book (Mark Summerfield).</p> <p>Here is my question.</p> <p>All works as I need, but I had a problem with writing strings to the file.</p> <p>This is a piece of my code:</p> <pre><code> word = input("New word ...
3
2016-09-15T09:57:04Z
39,508,470
<p>The length of word has increased after inserting <code>numeration</code>, so <code>x</code> holds the value of the old length before the update. You should move the line where <code>x</code> is assigned after the update:</p> <pre><code>numeration = str(count) + ". " word = numeration + word[0:] # length of word ch...
0
2016-09-15T10:12:02Z
[ "python" ]
Python list from .txt file
39,508,166
<p>I`m trying to create primitive dictionary (or list) in Python with basic functions that I learned from book (Mark Summerfield).</p> <p>Here is my question.</p> <p>All works as I need, but I had a problem with writing strings to the file.</p> <p>This is a piece of my code:</p> <pre><code> word = input("New word ...
3
2016-09-15T09:57:04Z
39,508,476
<p>Your problem is that you set <code>x</code> to be the length of the input word, but then add <code>numeration</code> to the string, making it several characters longer (three characters, in the case of a single-digit <code>count</code>). If you were to change</p> <pre><code>word = word[:x] + ",\n" # =adding shift t...
0
2016-09-15T10:12:27Z
[ "python" ]
BeautifulSoup use unique CSS Selector
39,508,252
<p>From this <a href="https://www.placetel.de/status" rel="nofollow">page</a>, I need to get the status from "Anbindung an das Telefonnetz". </p> <p>I identified 2 ways to get it: </p> <ol> <li>If the status contains the sentence "Das System arbeitet einwandfrei";</li> <li>If the color of the background is green. </l...
1
2016-09-15T10:01:07Z
39,509,270
<p>As far as I know <a href="http://stackoverflow.com/a/24720912/4241180">nth-of-child</a> is still not implemented in <code>BeautifulSoup4</code>. Also if you investigate the website's CSS (namely <code>_system.scss</code> file), you'll find out that there are 3 statuses:</p> <ol> <li><code>system-item-green</code> <...
1
2016-09-15T10:53:04Z
[ "python", "html", "css", "beautifulsoup" ]
BeautifulSoup use unique CSS Selector
39,508,252
<p>From this <a href="https://www.placetel.de/status" rel="nofollow">page</a>, I need to get the status from "Anbindung an das Telefonnetz". </p> <p>I identified 2 ways to get it: </p> <ol> <li>If the status contains the sentence "Das System arbeitet einwandfrei";</li> <li>If the color of the background is green. </l...
1
2016-09-15T10:01:07Z
39,509,738
<p>You can use the text to find the h6 for <code>Anbindung an das Telefonnetz</code> and get the p sibling:</p> <pre><code>import requests import re r = requests.get("https://www.placetel.de/status").content soup = BeautifulSoup(r, "lxml") h6 = soup.find("h6", text=re.compile(ur"Anbindung an das Telefonnetz", re.I)...
1
2016-09-15T11:16:56Z
[ "python", "html", "css", "beautifulsoup" ]
reading all the file content in directory
39,508,469
<p>I have directory <code>poem</code> which contains 50 files and I want to read them all.</p> <pre><code>for file in os.listdir("/home/ubuntu/Desktop/temp/poem"): print file f = open(file, 'r') print f.read() f.close() </code></pre> <p>This code reads file name of all the files in directory. But it ...
0
2016-09-15T10:11:59Z
39,508,529
<p><code>os.listdir</code> only returns filenames, to get the full path you need to join that filename with the folder you're reading:</p> <pre><code>folder = "/home/ubuntu/Desktop/temp/poem" for file in os.listdir(folder): print file filepath = os.path.join(folder, file) f = open(filepath, 'r') print ...
5
2016-09-15T10:14:45Z
[ "python", "io" ]
reading all the file content in directory
39,508,469
<p>I have directory <code>poem</code> which contains 50 files and I want to read them all.</p> <pre><code>for file in os.listdir("/home/ubuntu/Desktop/temp/poem"): print file f = open(file, 'r') print f.read() f.close() </code></pre> <p>This code reads file name of all the files in directory. But it ...
0
2016-09-15T10:11:59Z
39,508,643
<p>you are searching file in current join file path with directory folder.</p> <pre><code>import os for i in os.listdir("/home/ubuntu/Desktop/temp/poem"): if os.path.isfile(os.path.join("/home/ubuntu/Desktop/temp/poem",i)): print os.path.join("/home/ubuntu/Desktop/temp/poem",i) f=open(os.path.join...
1
2016-09-15T10:20:22Z
[ "python", "io" ]
Repeating code 3 times, and making sure input is only a number in Python 2.7
39,508,667
<p>I am trying to find out how to make my code repeat its self 3 times at the end of the set of questions and also I'm trying to make sure my validation is correct so that the input to the questions is only a number. </p> <p><strong>This is my code...</strong></p> <pre><code>import random correct = 0 name = raw_inp...
0
2016-09-15T10:21:22Z
39,510,953
<p>Your <code>answer != int</code> should be <code>if not isinstance(answer, int)</code> Furthermore, you will get <code>ValueError</code> each time user tries to insert characters.</p> <p>Because of this, you should edit your code to look like this:</p> <pre><code>from __future__ import division import random for i...
0
2016-09-15T12:23:51Z
[ "python", "python-2.7" ]
What's the equivalent of MatLab/Octave filt/bode in scipy?
39,508,726
<p>To create a digital system that could be used e.g. in bode or spectrum in matlab or octave I could use:</p> <pre><code>b = [1,0.1,0.2,0.3] a = [1,-1] sys = filt(b,a) bode(sys) spectrum(sys) </code></pre> <p>What will be the scipy equivalent for this command(s)?</p>
1
2016-09-15T10:24:34Z
39,529,035
<p>There are a few options, you can use <a href="http://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.signal.bode.html" rel="nofollow"><code>scipy.signal.bode</code></a> or <a href="http://python-control.readthedocs.io/en/latest/generated/control.bode.html#control.bode" rel="nofollow"><code>python-control.b...
0
2016-09-16T10:19:02Z
[ "python", "matlab", "scipy", "signal-processing" ]
Numpy efficient indexing with varied size arrays
39,508,846
<p>Take a look at this piece of code:</p> <pre><code>import numpy as np a = np.random.random(10) indicies = [ np.array([1, 4, 3]), np.array([2, 5, 8, 7, 3]), np.array([1, 2]), np.array([3, 2, 1]) ] result = np.zeros(2) result[0] = a[indicies[0]].sum() result[1] = a[indicies[2]].sum() </code></pre> ...
1
2016-09-15T10:31:01Z
39,509,169
<p>If your array <strong>a</strong> is very large you might have <strong>memory issues</strong> if your array of indices contains many arrays of many indices when looping through it.</p> <p>To avoid this issue use an iterator instead of a list :</p> <pre><code>indices = iter(indices) </code></pre> <p>and then loop t...
-1
2016-09-15T10:46:54Z
[ "python", "arrays", "numpy" ]
Numpy efficient indexing with varied size arrays
39,508,846
<p>Take a look at this piece of code:</p> <pre><code>import numpy as np a = np.random.random(10) indicies = [ np.array([1, 4, 3]), np.array([2, 5, 8, 7, 3]), np.array([1, 2]), np.array([3, 2, 1]) ] result = np.zeros(2) result[0] = a[indicies[0]].sum() result[1] = a[indicies[2]].sum() </code></pre> ...
1
2016-09-15T10:31:01Z
39,515,877
<p>With your <code>a</code> and <code>indicies</code> list:</p> <pre><code>In [280]: [a[i].sum() for i in indicies] Out[280]: [1.3986792680307709, 2.6354365193743732, 0.83324677494990895, 1.8195179021311731] </code></pre> <p>Which of course could wrapped in <code>np.array()</code>.</p> <p>For a subset of the <co...
0
2016-09-15T16:17:29Z
[ "python", "arrays", "numpy" ]
Grouping dictionary items by attribute
39,508,956
<p>I am trying to group the items in a dictionary by a particular key, let's say we have the following dictionary:</p> <pre><code>[{'type': 'animal', 'name': 'rabbit'}, {'type': 'animal', 'name': 'cow'}, {'type': 'plant', 'name': 'orange tree'}, {'type': 'animal', 'name': 'coyote'}] </code></pre> <p>And I wanted to g...
0
2016-09-15T10:36:29Z
39,508,993
<p>use <code>defaultdict(list)</code>, not <code>defaultdict()</code>. Read the docs for defaultdict to find out more.</p> <p>Also, you cannot use some_dict.a_key (in your case: .type) - you must use some_dict['a_key'] (in your case ['type'])</p>
2
2016-09-15T10:38:38Z
[ "python", "dictionary" ]
Grouping dictionary items by attribute
39,508,956
<p>I am trying to group the items in a dictionary by a particular key, let's say we have the following dictionary:</p> <pre><code>[{'type': 'animal', 'name': 'rabbit'}, {'type': 'animal', 'name': 'cow'}, {'type': 'plant', 'name': 'orange tree'}, {'type': 'animal', 'name': 'coyote'}] </code></pre> <p>And I wanted to g...
0
2016-09-15T10:36:29Z
39,509,221
<p>You can also use a normal dictionary and its <a href="https://docs.python.org/2/library/stdtypes.html#dict.setdefault" rel="nofollow"><code>setdefault</code></a> method:</p> <pre><code>l = [{'type': 'animal', 'name': 'rabbit'}, {'type': 'animal', 'name': 'cow'}, {'type': 'plant', 'name': 'orange tree'}, {'type': 'a...
0
2016-09-15T10:50:23Z
[ "python", "dictionary" ]
Grouping dictionary items by attribute
39,508,956
<p>I am trying to group the items in a dictionary by a particular key, let's say we have the following dictionary:</p> <pre><code>[{'type': 'animal', 'name': 'rabbit'}, {'type': 'animal', 'name': 'cow'}, {'type': 'plant', 'name': 'orange tree'}, {'type': 'animal', 'name': 'coyote'}] </code></pre> <p>And I wanted to g...
0
2016-09-15T10:36:29Z
39,509,441
<pre><code>from collections import defaultdict animals=[{'type': 'animal', 'name': 'rabbit'}, {'type': 'animal', 'name': 'cow'}, {'type': 'plant', 'name': 'orange tree'}, {'type': 'animal', 'name': 'coyote'}] animal_by_type = defaultdict(list) for animal in animals: animal_by_type[animal['type']].append(animal['...
0
2016-09-15T11:02:15Z
[ "python", "dictionary" ]
SVM Scikit-Learn : Why prediction time decrease with SVC when increasing parameter C?
39,509,080
<p>I’m trying to evaluate the influence of the # of features &amp; parameter C (SVM regularization) on the prediction time. I am using a modified version of <a href="http://scikit-learn.org/stable/auto_examples/applications/plot_prediction_latency.html#example-applications-plot-prediction-latency-py" rel="nofollow">c...
1
2016-09-15T10:42:54Z
39,513,160
<p>Having a larger C will lead to smaller values for the slack variables. This means that the number of support vectors will decrease. When you run the prediction, it will need to calculate the indicator function for each support vector. </p> <p>Thus; smaller C -> more support vectors -> more calculations -> slower pr...
0
2016-09-15T14:03:53Z
[ "python", "machine-learning", "scikit-learn", "svm", "latency" ]
Nearest neighbour in pyspark using euclidean distance or similar
39,509,095
<p>So I need to find nearest neighbors of a given row in pyspark DF using euclidean distance or anything. the data that I have 20+ columns, more than thousand rows and all the values are numbers.</p> <p>I am trying to oversample some data in pyspark, as mllib doesn't have inbuilt support for it, i decided to create it...
0
2016-09-15T10:43:38Z
39,530,374
<p>Not tried but Ive found this script: <a href="https://github.com/jakac/spark-python-knn/blob/master/python/gaussalgo/knn/knn.py" rel="nofollow">https://github.com/jakac/spark-python-knn/blob/master/python/gaussalgo/knn/knn.py</a></p> <p>If your data are dataframe, you should first merge your column into a vector wi...
1
2016-09-16T11:28:16Z
[ "python", "pyspark", "nearest-neighbor", "knn" ]
Progress bar in tkinter not working
39,509,185
<p>I am writing a small app to copy some files. I have made almost everything that I wanted but 3 things:</p> <p>1) Progress-bar to move while the copy option is in motion. I can display it but it won't react. </p> <p>I am using this to show it:</p> <pre><code>self.p = ttk.Progressbar(self, orient=HORIZONTAL, length...
0
2016-09-15T10:48:05Z
39,667,184
<p>I compacted the loading bar I got working in an older project of mine. The only way I had figured it out was to call the progress bar handling calls in a new thread and call the work-intensive functions from this thread into another new thread. </p> <p>It is bad practice to have a separate threads handling UI el...
0
2016-09-23T18:17:08Z
[ "python", "tkinter", "progress-bar" ]
Progress bar in tkinter not working
39,509,185
<p>I am writing a small app to copy some files. I have made almost everything that I wanted but 3 things:</p> <p>1) Progress-bar to move while the copy option is in motion. I can display it but it won't react. </p> <p>I am using this to show it:</p> <pre><code>self.p = ttk.Progressbar(self, orient=HORIZONTAL, length...
0
2016-09-15T10:48:05Z
39,775,063
<p>So I have used your code to make the improvements in mine and it works :) Unfortunately there is a "but". So the progress bar is nicely moving while files are being copied. What is still not perfect that after the button is pressed to execute the coping there is quite substantial delay time before the copying start....
0
2016-09-29T16:02:02Z
[ "python", "tkinter", "progress-bar" ]
Full blocking generator in twisted thread that runs forever
39,509,254
<p>Let's assume we have a <em>blackbox</em> generator that is fully blocking and runs forever. We're running Twisted, so standard way to handle blocking things is use <code>defers</code> or <code>defers + threads</code>.</p> <pre><code># some very naive example from twisted.internet import reactor def aSillyBlockingM...
0
2016-09-15T10:52:07Z
39,518,362
<p>I took the answer provided from <a href="http://stackoverflow.com/a/2244899/2172464">this post</a> and added example code. Also keep in mind it's always best to have well defined start and end points for threads. As you can see, it can cause some pretty sticky situations if a thread runs forever in an uncontrolled f...
0
2016-09-15T18:50:55Z
[ "python", "multithreading", "twisted" ]
Django not creating database table after deleting migrations files and migration table
39,509,392
<p>I have created two tables profile and details through django model and mistakenly i have deleted both these tables. Further when i tried to create table using</p> <pre><code>python2.7 manage.py makemigrations </code></pre> <p>and </p> <pre><code>python2.7 manage.py migrate </code></pre> <p>then it was not creat...
0
2016-09-15T10:59:49Z
39,509,767
<p>Run following command:</p> <pre><code>python manage.py migrate --fake-initial </code></pre>
0
2016-09-15T11:18:02Z
[ "python", "django" ]
Django not creating database table after deleting migrations files and migration table
39,509,392
<p>I have created two tables profile and details through django model and mistakenly i have deleted both these tables. Further when i tried to create table using</p> <pre><code>python2.7 manage.py makemigrations </code></pre> <p>and </p> <pre><code>python2.7 manage.py migrate </code></pre> <p>then it was not creat...
0
2016-09-15T10:59:49Z
39,509,790
<p>You need to first fake migrations for each of those built-in apps</p> <p><strong>python manage.py migrate --fake auth</strong><br> <strong>python manage.py migrate --fake contenttypes</strong></p> <p>the run fake initial</p> <p><strong>python manage.py migrate --fake-initial</strong></p> <p>This most probably sh...
0
2016-09-15T11:19:22Z
[ "python", "django" ]
Reducing rows in a column for a panda DataFrame for plotting
39,509,404
<p>So I have a csv table of data which I have read into a panda DataFrame, however one of the columns has the same string in multiple rows, which is correct as its a classification data, but when I plot this column against another of values, it treats each cell in this column as separate rather than combining them.</p>...
0
2016-09-15T11:00:28Z
39,510,033
<p>I presume you want a stacked bar plot, so starting with your dataframe looking like this </p> <pre><code>Classification Value 0 MIR-weak 0.089657 1 MIR-weak 0.199028 2 MIR-bright 0.285053 3 MIR-bright 0.080708 4 FIR-dark/MIR-bright 1.761086 5 ...
0
2016-09-15T11:32:53Z
[ "python", "pandas", "plot", "dataframe" ]
KD Tree gives different results to brute force method
39,509,562
<p>I have an array of 1000 random 3D points &amp; I am interested in the closest 10 points to any given point. <a href="http://stackoverflow.com/questions/2486093/millions-of-3d-points-how-to-find-the-10-of-them-closest-to-a-given-point">In essence the same as this post.</a></p> <p>I checked the 2 solutions offered by...
0
2016-09-15T11:07:38Z
39,512,661
<p><code>KDTree</code> algorithm is computing the nearest points based on the square-root of the same distance used by <code>Brute-force</code> algorithm.</p> <p>Basically KDtree uses: <code>sqrt(x^2+y^2+z^2)</code> and Brute-force algorithm uses: <code>x^2+y^2+z^2</code></p>
1
2016-09-15T13:43:03Z
[ "python", "numpy", "scipy", "kdtree" ]
KD Tree gives different results to brute force method
39,509,562
<p>I have an array of 1000 random 3D points &amp; I am interested in the closest 10 points to any given point. <a href="http://stackoverflow.com/questions/2486093/millions-of-3d-points-how-to-find-the-10-of-them-closest-to-a-given-point">In essence the same as this post.</a></p> <p>I checked the 2 solutions offered by...
0
2016-09-15T11:07:38Z
39,513,237
<p>distances = ((a-point)**2).sum(axis=1) **0.5<a href="http://i.stack.imgur.com/3idkJ.png" rel="nofollow"><img src="http://i.stack.imgur.com/3idkJ.png" alt="enter image description here"></a></p>
0
2016-09-15T14:07:04Z
[ "python", "numpy", "scipy", "kdtree" ]
python speech to text and voice level differences visualisation
39,509,624
<p>Hi am using pyttsx for converting text to speech and then vise versa making a sort of automatic call replying system. Where one will ask questions and then python will convert it into text and reply with voice(Like SIRI in apple) Now what i want is to have a tool which will show different values of bar when the syst...
0
2016-09-15T11:11:26Z
39,510,471
<p>A tool to make that is the standard <a href="https://docs.python.org/2/library/turtle.html" rel="nofollow"><code>turtle</code> library</a> for output, the necessary calculations (how much the bar must go up) can be done without any library.</p>
0
2016-09-15T11:58:06Z
[ "python", "text-to-speech" ]
Python or LibreOffice Save xlsx file encrypted with password
39,509,741
<p>I am trying to save an Excel file <em>encrypted</em> with password. I have tried following the guide on <a href="https://help.libreoffice.org/Common/Protecting_Content_in" rel="nofollow">https://help.libreoffice.org/Common/Protecting_Content_in</a> - and works perfectly. However, this is in the GUI, but I am looking...
1
2016-09-15T11:16:59Z
39,898,408
<p>There is solution using <a href="http://jython.org" rel="nofollow">Jython</a> and <a href="https://poi.apache.org/" rel="nofollow">Apache POI</a>. If you want like to use it from CPython/PyPy, you can use <a href="https://docs.python.org/3/library/subprocess.html" rel="nofollow">subprocess</a> module to call externa...
1
2016-10-06T14:15:05Z
[ "python", "excel", "encryption", "ubuntu-14.04", "libreoffice-calc" ]
Does python perform tasks on lists in parallel by itself?
39,509,770
<p>I stumbled upon this piece of work:</p> <pre><code>def getChild(self, childName): for child in self.children : if(childName == child.data['name']): return child return None </code></pre> <p>As far as ranting is concerned this code implies everything there is to say and know about this l...
-2
2016-09-15T11:18:14Z
39,510,146
<p>No, there is no automatic parallelization. Python is about writing your code efficiently, but not about making it computationally efficient. And there is a bigger problem: the GIL - Global Interpreter Lock. That means that only one thread at a time is executed. So there is no big point in parallelization of CPU inte...
2
2016-09-15T11:39:51Z
[ "python", "list", "dictionary", "parallel-processing" ]
Pandas: KeyError when attempting to print value from df.loc in Excel file
39,509,803
<p>I'm attempting to parse an Excel-file using Pandas.</p> <pre><code>import pandas as pd import xlrd xl_file = pd.ExcelFile("file.xlsx") df = xl_file.parse("Sheet1") </code></pre> <p>Now, if I get a value (<code>name</code>) from the sheet:</p> <pre><code>if len(df.loc[df["Col A"].str.contains("John"), "Col B"]) ...
2
2016-09-15T11:20:15Z
39,510,639
<p><code>name</code> is a series, and <code>0</code> is not in the series' index (check <code>name.index</code>). This explains the error message.</p> <p>If you want to select the first element in the series, do:</p> <pre><code>name.iloc[0] </code></pre>
3
2016-09-15T12:06:35Z
[ "python", "excel", "python-2.7", "pandas" ]
Python unique values per column in csv file row
39,509,824
<p>Crunching on this for a long time. Is there an easy way using Numpy or Pandas or fixing my code to get the unique values for the column in a row separated by "|"</p> <p>I.e the data:</p> <pre><code>"id","fname","lname","education","gradyear","attributes" "1","john","smith","mit|harvard|ft|ft|ft","2003|207|212|212|...
0
2016-09-15T11:21:14Z
39,510,014
<p>If you don't care about the order when you have many items separated with <code>|</code>, this will work:</p> <pre><code>lst = ["id","fname","lname","education","gradyear","attributes", "1","john","smith","mit|harvard|ft|ft|ft","2003|207|212|212|212","qa|admin,co|master|NULL|NULL", "2","john","doe","htw","2000","de...
0
2016-09-15T11:31:30Z
[ "python", "pandas", "numpy" ]
Python unique values per column in csv file row
39,509,824
<p>Crunching on this for a long time. Is there an easy way using Numpy or Pandas or fixing my code to get the unique values for the column in a row separated by "|"</p> <p>I.e the data:</p> <pre><code>"id","fname","lname","education","gradyear","attributes" "1","john","smith","mit|harvard|ft|ft|ft","2003|207|212|212|...
0
2016-09-15T11:21:14Z
39,510,118
<p><code>numpy</code>/<code>pandas</code> is a bit overkill for what you can achieve with <code>csv.DictReader</code> and <code>csv.DictWriter</code> with a <code>collections.OrderedDict</code>, eg:</p> <pre><code>import csv from collections import OrderedDict # If using Python 2.x - use `open('output.csv', 'wb') ins...
2
2016-09-15T11:38:31Z
[ "python", "pandas", "numpy" ]
Python write multiline data in a column of a single row in csv
39,509,837
<p>I have a json response similar to as dt1 and i'm writing the json data into CSV with fieldnames NAME, Total and details , below is my code.</p> <pre><code>dt1 = { u'Name': ABC, u'total': 6 , u'Details':{ u'Subject1': {u'Opted': False, u'value': u'100'}, u'Subject2': {u'Opted...
0
2016-09-15T11:22:01Z
39,537,872
<p>try something like this:</p> <pre><code>import csv dt1 = { u'Name': 'ABC', u'Total': 6 , u'Details':{ u'Subject1': {u'Opted': False, u'value': u'100'}, u'Subject2': {u'Opted': True, u'value': u'200'}, u'Subject3': {u'Opted': True, u'value': u'200'} } } with open('fi...
0
2016-09-16T18:22:56Z
[ "python", "json", "csv", "dictionary" ]
Can I save a list in Memcache in Google-AppEngine in Python?
39,509,956
<p>I want to save a list in MemCache in AppEngine with Python and I am having the next error : </p> <p>TypeError: <strong>new</strong>() takes exactly 4 arguments (1 given).</p> <p>This is the link of the image with the error : <a href="http://i.stack.imgur.com/we3VU.png" rel="nofollow">http://i.stack.imgur.com/we3V...
1
2016-09-15T11:28:26Z
39,515,702
<p>You are not storing a list. You are storing a query object. To store a list, use <code>.fetch()</code>:</p> <pre><code>list_version = WikiPostVersion.query().filter(WikiPostVersion.r_post == postobj.key).fetch() </code></pre> <p>You can store a simple query object, but when you add <code>.order()</code> or <code...
3
2016-09-15T16:07:52Z
[ "python", "google-app-engine", "memcached" ]
How to set the "chunk size" of read lines from file read with Python subprocess.Popen() or open()?
39,509,959
<p>I have a fairly large text file which I would like to run in chunks. In order to do this with the <code>subprocess</code> library, one would execute following shell command:</p> <pre><code>"cat hugefile.log" </code></pre> <p>with the code:</p> <pre><code>import subprocess task = subprocess.Popen("cat hugefile.log...
0
2016-09-15T11:28:34Z
39,510,102
<p>Using a file, you can iterate on the file handle (no need for subprocess to open <code>cat</code>):</p> <pre><code>with open('hugefile.log', 'r') as f: for read_line in f: print(read_line) </code></pre> <p>Python reads a line by reading all the chars up to <code>\n</code>. To simulate the line-by-line...
1
2016-09-15T11:37:35Z
[ "python", "bash", "shell", "subprocess", "chunking" ]
In Python subprocess, what is the difference between using Popen() and check_output()?
39,510,029
<p>Take the shell command "cat file.txt" as an example. </p> <p>With Popen, this could be run with</p> <pre><code>import subprocess task = subprocess.Popen("cat file.txt", shell=True, stdout=subprocess.PIPE) data = task.stdout.read() </code></pre> <p>With check_output, one could run</p> <pre><code>import subproces...
1
2016-09-15T11:32:29Z
39,510,073
<p>From <a href="https://docs.python.org/3/library/subprocess.html#exceptions" rel="nofollow">the documentation</a>:</p> <blockquote> <p><code>check_call()</code> and <code>check_output()</code> will raise <code>CalledProcessError</code> if the called process returns a non-zero return code.</p> </blockquote>
1
2016-09-15T11:35:33Z
[ "python", "bash", "shell", "subprocess" ]
In Python subprocess, what is the difference between using Popen() and check_output()?
39,510,029
<p>Take the shell command "cat file.txt" as an example. </p> <p>With Popen, this could be run with</p> <pre><code>import subprocess task = subprocess.Popen("cat file.txt", shell=True, stdout=subprocess.PIPE) data = task.stdout.read() </code></pre> <p>With check_output, one could run</p> <pre><code>import subproces...
1
2016-09-15T11:32:29Z
39,510,272
<p><code>Popen</code> is the class that defines an object used to interact with an external process. <code>check_output()</code> is just a wrapper around an instance of <code>Popen</code> to examine its standard output. Here's the definition from Python 2.7 (sans docstring):</p> <pre><code>def check_output(*popenargs,...
1
2016-09-15T11:47:44Z
[ "python", "bash", "shell", "subprocess" ]
Concatenate/stack unpacked numpy array in certain axis to other arrays
39,510,084
<p>I want to create a numpy array <code>variables</code> with a certain structure, as in the example below, consisting of the variables <code>X</code> and <code>Y</code> for a meshgrid and additional parameters <code>params</code>. I need this in the context of plotting a 3D surface plot for a function <code>f(variable...
0
2016-09-15T11:36:05Z
39,512,379
<p>You can't get there from here.</p> <p>Numpy arrays are for storing cuboidal grids of data, where each entry is the same shape as every other entry.</p> <p>The best you can do here is have a <code>(5,)</code>-grid, containing <code>object</code>s, where each of the first two objects is itself a numpy array:</p> <p...
1
2016-09-15T13:30:53Z
[ "python", "arrays", "numpy" ]
Gather rows under the same key in Cassandra/Python
39,510,113
<p>I was working through the <a href="https://academy.datastax.com/resources/getting-started-time-series-data-modeling" rel="nofollow">Pattern 1</a> and was wondering if there is a way, in python or otherwise to "gather" all the rows with the same id into a row with dictionaries.</p> <pre><code>CREATE TABLE temperatur...
0
2016-09-15T11:38:12Z
39,514,436
<p>Alex, you will have to do some post execution data processing to get this format. The driver returns row by row, no matter what row_factory you use. </p> <p>One of the reasons the driver cannot accomplish the format you suggest is that there is pagination involved internally (default fetch_size is 5000). So the res...
1
2016-09-15T15:04:17Z
[ "python", "cassandra" ]
skype4py PlaceCall doesn't work on OSX
39,510,212
<p>I'm trying to write a python script which calls skype numbers for a music project. For some reason although the script can connect to the skype instance, when I make a call the app just waits and the call never goes through to the calling device. </p> <p>I've tried this in my own script, and the example record.py s...
0
2016-09-15T11:43:38Z
39,531,246
<p>I tried this on windows 8, and osx the API seems to be broken. On ubuntu trusty, the code works exactly as expected. </p>
1
2016-09-16T12:12:59Z
[ "python", "osx", "skype", "skype4py" ]
Django Auth user date_joined field datetime to string
39,510,274
<p>When i am fetching the stored datetime value from auth user in django the value comes as below is there a way to convert this into normal date time format may be like <code>"dd:mm:yyyy hh:mm:ss"</code> or some string value that can be displayed in better(other) format</p> <pre><code> date_joined = request.user.dat...
0
2016-09-15T11:47:50Z
39,511,082
<p>You can format a datetime object using its <a href="https://docs.python.org/2/library/datetime.html#strftime-strptime-behavior" rel="nofollow"><code>strftime()</code></a> method, for example like this:</p> <pre><code> date_joined = request.user.date_joined date_joined.strftime("%d:%m:%y %H:M:S") </code></pre> <p>...
1
2016-09-15T12:30:11Z
[ "python", "django", "datetime" ]
Django project template loader setup
39,510,368
<p>Is it possible to set the django project template loading priority so that first of all it loads the apps' "templates" folder and after that the project "templates". If the template exists in the app folder, then use it. If it does not exist in the app folder, then try load from project folder.</p> <p>Or it is not...
0
2016-09-15T11:53:46Z
39,510,662
<p>Update your <code>TEMPLATES</code> setting, and put the <code>app_directories</code> loader before the <code>filesystem</code> loader.</p> <p>If you currently have <code>'APP_DIRS': True</code>, you will have to remove this, and add the <code>loaders</code> option.</p> <p>For example, you could change your <code>T...
1
2016-09-15T12:08:13Z
[ "python", "django", "django-templates" ]
Producing a sorted football league table in Python
39,510,399
<p>I have created a program which simulates an entire football season between teams. The user inputs the teams' names and their skill ratings. It then uses the Poisson distribution to compare their skill ratings and calculate the result between the two teams. After each match, the relevant lists are updated: the winnin...
2
2016-09-15T11:54:46Z
39,511,038
<p>While your current approach is (barely) workable, it makes it very difficult to (for example) change the information you want to store about each team. You might consider defining a Team class instead, each instance of which stores all the information about a specific team.</p> <pre><code>class Team: def __init...
3
2016-09-15T12:28:07Z
[ "python", "list", "sorting" ]
Django combine different tables in separate table
39,510,526
<p>I have 2 tables and wanted to <code>combine</code> 1st and 2nd table and show it in 3rd table</p> <pre><code> class Date(models.Model): name = models.CharField(max_length=50) def __unicode__(self): return self.name class Month(models.Model): name = models.CharField(max_len...
0
2016-09-15T12:00:54Z
39,511,339
<p>To get 1st and 2nd table content into 3rd table you need to write separate foreign keys for each model. We should not assign a single foreign key for both models.</p> <pre><code>class Group(models.Model): date = models.ForeignKey(Date) month = models.ForeignKey(Month) def __unicode__(self): ret...
2
2016-09-15T12:42:13Z
[ "python", "django", "django-models" ]
How to do regression using tensorflow with series output?
39,510,597
<p>I want to build a regression model with 2 output nodes using tensorflow. I search a code which can build regression model but with 1 output nodes.</p> <p><a href="https://github.com/tensorflow/tensorflow/blob/master/tensorflow/examples/skflow/boston.py" rel="nofollow">https://github.com/tensorflow/tensorflow/blob/m...
0
2016-09-15T12:04:29Z
39,528,834
<p>Actually, I find a workable code using DNNRegressor:</p> <pre><code>import numpy as np from sklearn.cross_validation import train_test_split from tensorflow.contrib import learn import tensorflow as tf import logging #logging.getLogger().setLevel(logging.INFO) #Some fake data N=200 X=np.array(range(N),dtype=np.fl...
0
2016-09-16T10:07:19Z
[ "python", "output", "tensorflow", "regression" ]
Convert list of list of integers into a list of strings
39,510,778
<p>I have a list of strings:</p> <pre><code>['[2, 8]', '[8, 2]', '[2, 5, 3]', '[2, 5, 3, 0]', '[5, 3, 0, 2]'] </code></pre> <p>I want output to look like </p> <pre><code>['28','82','253',2530',5302'] </code></pre> <p>I've tried using </p> <pre><code>string1= ''.join(str(e) for e in list[0]) </code></pre> <p>I...
2
2016-09-15T12:14:01Z
39,510,804
<p>You actually don't have a <code>list</code> of <code>list</code>, you have a <code>list</code> of <code>str</code>. Therefore you can use <a href="https://docs.python.org/3/library/ast.html#ast.literal_eval" rel="nofollow"><code>ast.literal_eval</code></a> to interpret each string as a list, then convert to <code>st...
4
2016-09-15T12:16:01Z
[ "python", "string", "list" ]
Convert list of list of integers into a list of strings
39,510,778
<p>I have a list of strings:</p> <pre><code>['[2, 8]', '[8, 2]', '[2, 5, 3]', '[2, 5, 3, 0]', '[5, 3, 0, 2]'] </code></pre> <p>I want output to look like </p> <pre><code>['28','82','253',2530',5302'] </code></pre> <p>I've tried using </p> <pre><code>string1= ''.join(str(e) for e in list[0]) </code></pre> <p>I...
2
2016-09-15T12:14:01Z
39,510,866
<p>If you want to use built-in functions only (without imports), you can define a function that parses only the numbers and map that function to your list.</p> <pre><code>def remove_non_digits(z): return "".join(k if k.isdigit() else "" for k in z) &gt;&gt;&gt; map(remove_non_digits, a) ['28', '82', '253', '2530'...
2
2016-09-15T12:19:12Z
[ "python", "string", "list" ]
Mean or max pooling with masking support in Keras
39,510,809
<pre><code>... print('Build model...') model = Sequential() model.add(Embedding(max_features, 128)) model.add(LSTM(size, return_sequences=True, dropout_W=0.2 dropout_U=0.2)) model.add(GlobalAveragePooling1D()) model.add(Dense(1)) model.add(Activation('sigmoid')) .... </code></pre> <p>I need to be able to take the mea...
1
2016-09-15T12:16:22Z
39,534,110
<p>Since average pooling is only doing a mean over one axis, you just need to correct the number of elements in the mean since loss masking is handled at the end, not here. You can do this probably with something like this:</p> <pre><code>class GlobalAveragePooling1DMasked(GlobalAveragePooling1D): def call(self, x...
0
2016-09-16T14:35:28Z
[ "python", "masking", "keras", "lstm", "pooling" ]
Process each line of text file using Python
39,510,824
<p>I am fairly new to Python. I have a text file containing many blocks of data in following format along with other unnecessary blocks.</p> <pre><code> NOT REQUIRED :: 123 Connected Part-1:: A ~$ Connected Part-3:: B ~$ Connector Location:: 100 200 300 ~$ NOT REQUIRED :: 456 Connected ...
0
2016-09-15T12:17:14Z
39,512,204
<p>I will try to make it clear, and show how I would do it without <code>regex</code>. First of all, the biggest issue with the code presented is that when using the <code>string.strip</code> function the entire content list is being read:</p> <pre><code>connected_part_1 = [s.strip(' \n ~ $ Connected Part -1 ::') for ...
0
2016-09-15T13:24:02Z
[ "python", "python-3.x" ]
How to copy a .bin file to a text file in Python
39,510,827
<p>I'm trying to take a file with .bin suffix, encode it and then to send it to someone(sending it as .bin is not supported)...the problem is that when i use the command :</p> <pre><code>with open('myfile.bin','r') as fileToCopy: </code></pre> <p>I got an error messages </p> <pre><code>'charmap' codec can't decode b...
0
2016-09-15T12:17:19Z
39,511,331
<p>It's not clear what you are trying to do. Either you are trying to copy an existing file <code>myfile.bin</code> to a new file <code>newfile.txt</code> or you're trying to convert the binary file to a human readable format.</p> <p>Assuming it's your goal to copy the file <code>myfile.bin</code> to <code>newfile.txt...
2
2016-09-15T12:41:36Z
[ "python", "file", "text", "binary", "bin" ]
extract data from website using python
39,510,830
<p>I recently started learning python and one of the first projects I did was to scrap updates from my son's classroom web page and send me notifications that they updated the site. This turned out to be an easy project so I wanted to expand on this and create a script that would automatically check if any of our lott...
0
2016-09-15T12:17:31Z
39,511,176
<p>If you look closely at the source of the page (I just used <code>curl</code>) you can see this block</p> <pre><code>&lt;script type="text/javascript"&gt; // &lt;![CDATA[ var dataPath = '../../'; var json_filename = 'data/json/games/lottery/recent.json'; var games = new Array(); var sessions = ne...
0
2016-09-15T12:34:02Z
[ "python", "python-3.x" ]
lambda python function in reversing list
39,511,011
<pre><code>scores = [] with open("scores.txt") as f: for line in f: name, score = line.split(',') score = int(score) scores.append((name, score)) scores.sort(key=lambda s: s[1]) for name, score in scores: print(name + ", " + str(score)) </code></pre> <p>This code can be used to ...
0
2016-09-15T12:26:40Z
39,511,040
<p>Use the <a href="https://docs.python.org/3/library/functions.html#sorted" rel="nofollow"><code>reverse</code></a> argument to <code>list.sort()</code>:</p> <pre><code>scores.sort(key=lambda s: s[1], reverse=True) </code></pre> <p>From the documentation:</p> <blockquote> <p><em>reverse</em> is a boolean value. I...
1
2016-09-15T12:28:12Z
[ "python" ]
lambda python function in reversing list
39,511,011
<pre><code>scores = [] with open("scores.txt") as f: for line in f: name, score = line.split(',') score = int(score) scores.append((name, score)) scores.sort(key=lambda s: s[1]) for name, score in scores: print(name + ", " + str(score)) </code></pre> <p>This code can be used to ...
0
2016-09-15T12:26:40Z
39,511,066
<p>Just use <code>scores[::-1]</code> instead of <code>scores</code> in the last for-loop. Here's a small illustration of this behaviour:</p> <pre><code>a=list(range(10)) print(a[::-1]) </code></pre>
1
2016-09-15T12:29:28Z
[ "python" ]
lambda python function in reversing list
39,511,011
<pre><code>scores = [] with open("scores.txt") as f: for line in f: name, score = line.split(',') score = int(score) scores.append((name, score)) scores.sort(key=lambda s: s[1]) for name, score in scores: print(name + ", " + str(score)) </code></pre> <p>This code can be used to ...
0
2016-09-15T12:26:40Z
39,511,311
<p>Use <code>reverse</code> when you sort: </p> <pre><code>&gt;&gt;&gt; l = [('a', 1), ('c',5), ('a', 2), ('b', 1)] &gt;&gt;&gt; l.sort(key=lambda i: i[1], reverse=True) &gt;&gt;&gt; l [('c', 5), ('a', 2), ('a', 1), ('b', 1)] </code></pre> <p>You can use it with <code>sorted</code>: </p> <pre><code>&gt;&gt;&gt; l...
0
2016-09-15T12:40:29Z
[ "python" ]
Resample xarray Dataset to annual frequency using only winter data
39,511,062
<p>I have a dataset which consists of daily x,y gridded meteorological data for several years. I am interested in calculating annual means of winter data only, ie. not including the summer data as well.</p> <p>I think that I need to use the <code>resample</code> command with, e.g. a frequency of <code>AS-OCT</code> to...
1
2016-09-15T12:29:15Z
39,516,454
<p>The trick is to create a mask for the dates you wish to exclude. You can do this by using groupby to extract the month.</p> <pre class="lang-python prettyprint-override"><code>import xarray as xr import pandas as pd import numpy as np # create some example data at daily resolution that also has a space dimension t...
3
2016-09-15T16:51:52Z
[ "python", "python-xarray" ]
Extract nested tags with other text data as string in scrapy
39,511,122
<p>I am trying to extract data. Here is the specific part of the html-</p> <pre><code> &lt;div class="readable"&gt; &lt;span id="freeTextContainer2123443890291117716"&gt;I write because I need to. &lt;br&gt;I review because I want to. &lt;br&gt;I pay taxes because I have to. &lt;br&gt;&lt;br&gt;...
0
2016-09-15T12:31:51Z
39,513,567
<p>As per my comment, you can use xpath with <code>//text()</code> to get all the children's text content.</p>
0
2016-09-15T14:22:16Z
[ "python", "scrapy" ]
Python NetworkX creating graph from incidence matrix
39,511,179
<p>I have an incidence matrix (where the rows are nodes and the columns are edges) as follows (it is read from a text file into a NumPy array):</p> <pre><code>[[1 1 1 1 1 1 1 1 1 1] [1 1 1 1 1 1 1 0 0 0] [1 1 1 1 1 0 1 1 0 0] [0 0 1 1 1 0 1 0 0 0] [1 1 1 1 1 1 0 0 0 0] [1 1 0 1 1 0 0 0 0 0] [1 0 1 0 0 1 0 1 0 0]...
2
2016-09-15T12:34:09Z
39,515,259
<p>Networkx has a handy <a href="http://networkx.github.io/documentation/networkx-1.7/reference/generated/networkx.convert.from_numpy_matrix.html" rel="nofollow"><code>nx.from_numpy_matrix</code> function</a> taking an adjacency matrix, so once we convert the incidence matrix to an adjacency matrix, we're good.</p> <p...
2
2016-09-15T15:44:59Z
[ "python", "networkx" ]
Python - Add checkbox to every row in QTableWidget
39,511,181
<p>I am trying to add a checkbow to every row in a QTableWidget, unfortunately it only seems to appear in the first row. Here is my code:</p> <pre><code>data = ['first_row', 'second_row', 'third_row'] nb_row = len(data) nb_col = 2 qTable = self.dockwidget.tableWidget qTable.setRowCount(nb_row) qTable.setColumnCount(n...
0
2016-09-15T12:34:10Z
39,511,449
<p>Ok, I just had to put <code>chkBoxItem = QTableWidgetItem()</code> inside the last loop (<em>I guess it has to create a new <code>QTableWidgetItem()</code> item for each row</em>...):</p> <pre><code>for col in [1]: chkBoxItem = QTableWidgetItem() chkBoxItem.setFlags(QtCore.Qt.ItemIsUserCheckable | QtCore.Qt...
0
2016-09-15T12:48:59Z
[ "python", "pyqt", "qtablewidget", "qcheckbox" ]
SQLAlchemy can't join two tables with two foreign keys between them
39,511,232
<p>The code below does not work due to this line <code>owner_id = Column(Integer, ForeignKey('employees.employee_id'))</code> in Manager class. SQLAlchemy generates error message:</p> <blockquote> <p>AmbiguousForeignKeysError: Can't determine join between 'employees' and > 'managers'; tables have more than one fore...
0
2016-09-15T12:36:46Z
39,514,965
<p>You are both extending parent model as well as defining relationship to the same parent model.</p> <p>simply use one way, you could simply created relations and have all your models extend base class</p> <pre><code>class Employee(Base): __tablename__ = 'employees' employee_id = Column(Integer, primary_key...
0
2016-09-15T15:29:51Z
[ "python", "sqlalchemy" ]
SQLAlchemy can't join two tables with two foreign keys between them
39,511,232
<p>The code below does not work due to this line <code>owner_id = Column(Integer, ForeignKey('employees.employee_id'))</code> in Manager class. SQLAlchemy generates error message:</p> <blockquote> <p>AmbiguousForeignKeysError: Can't determine join between 'employees' and > 'managers'; tables have more than one fore...
0
2016-09-15T12:36:46Z
39,518,177
<p>SQLAlchemy is confused about how to join <code>Manager</code> to <code>Employee</code> because you have multiple foreign keys between the two tables, <code>employee_id</code> and <code>owner_id</code>. In this case, you need to specify the <code>inherit_condition</code> to the mapper explicitly:</p> <pre><code>clas...
1
2016-09-15T18:39:16Z
[ "python", "sqlalchemy" ]
Filtering a pandas data frame with a variable
39,511,378
<p>I'm stuck on something simple but I can't see it despite reading the docs and relevant SO questions. This involves filtering records from data that comes out of a WordPress database. </p> <p>Create some data:</p> <pre><code>import pandas as pd data = {'number': [1,2,3],\ 'field': ['billing_last_name', 'sh...
0
2016-09-15T12:44:24Z
39,511,431
<p>Maybe you should create match as:</p> <pre><code>match = str(choice['name'][0]) </code></pre> <p>cause <strong>choice['name']</strong> is Series</p>
0
2016-09-15T12:47:59Z
[ "python", "pandas" ]
Filtering a pandas data frame with a variable
39,511,378
<p>I'm stuck on something simple but I can't see it despite reading the docs and relevant SO questions. This involves filtering records from data that comes out of a WordPress database. </p> <p>Create some data:</p> <pre><code>import pandas as pd data = {'number': [1,2,3],\ 'field': ['billing_last_name', 'sh...
0
2016-09-15T12:44:24Z
39,511,457
<p>The problem is that <code>str(choice.name)</code> will not do what you think. The type is</p> <pre><code>In [205]: type(choice.name) Out[205]: pandas.core.series.Series </code></pre> <p>so <code>str</code> just finds the string representation of the Series.</p> <p>In order to access it the way you want, you can u...
1
2016-09-15T12:49:20Z
[ "python", "pandas" ]
Filtering a pandas data frame with a variable
39,511,378
<p>I'm stuck on something simple but I can't see it despite reading the docs and relevant SO questions. This involves filtering records from data that comes out of a WordPress database. </p> <p>Create some data:</p> <pre><code>import pandas as pd data = {'number': [1,2,3],\ 'field': ['billing_last_name', 'sh...
0
2016-09-15T12:44:24Z
39,511,539
<p><code>match</code> is actually a <code>pandas</code> <code>series</code>, not the <code>string</code> variable "jones". In this case, you need to access the <code>string</code> values within the <code>series</code>:</p> <pre><code>field_filter = 'billing_last_name' number_filter = 1 choice = dframe[(dframe['field'...
2
2016-09-15T12:52:49Z
[ "python", "pandas" ]