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
Flask, MySQL and SQLAlchemy quering ID error
39,186,521
<p>I get a weird error when I try to query an item by id. I have tried all suggestion I have found and only when doing raw query I get a proper result.</p> <p>Part of the Traceback:</p> <pre><code> File "C:\Users\pgsid\Envs\xo\lib\site-packages\flask\app.py", line 1988, in wsgi_app response = self.full_dispatch_...
0
2016-08-27T22:55:47Z
39,214,729
<p>Change your id type as such:</p> <pre><code>id = db.Column('id', db.Integer(), primary_key=True) </code></pre>
0
2016-08-29T20:32:58Z
[ "python", "mysql", "flask", "sqlalchemy" ]
Read data from text file, into numpy array in python
39,186,610
<p>I want to read the file of below format into numpy array in python. </p> <pre><code>ADIDGoogle#8a65c466-****-4a7e-****-0836c8884dae 2016-06-01 17:55:53 ADIDGoogle#8a65c466-****-4a7e-****-0836c8884dae 2016-06-01 17:55:53 ADIDGoogle#8a65c466-****-4a7e-****-0836c8884dae 2016-06-01 17:55:53 ADIDGoogle#8a664a70-****-...
2
2016-08-27T23:09:40Z
39,186,697
<p>First of all, the <code>#</code> character in your file will make <code>numpy</code> think everything after "ADIDGoogle" in each line is a comment. It appears you can change the comment character using the <code>comments</code> kwarg in <code>np.loadtxt</code>. This will solve the <code>IndexError</code>, leaving th...
2
2016-08-27T23:28:11Z
[ "python", "arrays", "numpy" ]
Read data from text file, into numpy array in python
39,186,610
<p>I want to read the file of below format into numpy array in python. </p> <pre><code>ADIDGoogle#8a65c466-****-4a7e-****-0836c8884dae 2016-06-01 17:55:53 ADIDGoogle#8a65c466-****-4a7e-****-0836c8884dae 2016-06-01 17:55:53 ADIDGoogle#8a65c466-****-4a7e-****-0836c8884dae 2016-06-01 17:55:53 ADIDGoogle#8a664a70-****-...
2
2016-08-27T23:09:40Z
39,186,880
<p>You can read via <code>genfromtxt</code> line-by-line</p> <pre><code>import numpy as np fname = "./data.txt" with open(fname, 'r') as f: data = np.genfromtxt(f,comments="!",dtype="string",usecols=(1,2)) print data </code></pre>
1
2016-08-28T00:09:01Z
[ "python", "arrays", "numpy" ]
Set vertical size for the pop-up menu of a GtkComboBox
39,186,665
<p>I created a GtkComboBox with dozens of items. When I perform I see that the pop-up menu containing the items is very vertically large. How do I set a maximum size? I checked the documentation and I not found a method to define it.</p> <p>Example:</p> <pre><code>#!/usr/bin/env python3 import gi gi.require_version(...
2
2016-08-27T23:23:04Z
39,257,099
<p>As far as I know (and can find), it is impossible to set the number of rows in a GtkComboBox drop down menu.</p> <p>If you insist on using <code>Gtk.ComboBox()</code>, you can however reduce the height in case of large amounts of entries by using:</p> <pre><code>combobox.set_wrap_width(5) </code></pre> <p>Which w...
1
2016-08-31T19:00:02Z
[ "python", "gtk", "gtk3" ]
How to make a proxy object behave like the integer it wraps?
39,186,692
<p>I want to create a proxy class that wraps an <code>int</code> for thread-safe access. In contrast to the built-in type, the proxy class is mutable, so that it can be incremented in-place. Now, I want to use that class just as a normal integer from the outside. Usually, Python's <code>__getattr__</code> makes it very...
2
2016-08-27T23:27:34Z
39,190,081
<p>The blog post linked by <a href="http://stackoverflow.com/users/5378816/vpfb">@VPfB</a> in the <a href="http://stackoverflow.com/questions/39186692/how-to-make-a-proxy-object-behave-like-the-integer-it-wraps/39190081#comment65719596_39186692">comments</a> has a more generic and thorough solution to proxying dunder m...
2
2016-08-28T09:58:25Z
[ "python", "python-3.x", "proxy" ]
Internal C++ object already deleted (pyside)
39,186,716
<p>The aim of this program is to show the tradeWindow as a QWidget and then show a QDialog each time doStuff is called (via button) if there are results. The code works first time, but second time i get error messages:</p> <pre class="lang-none prettyprint-override"><code>Traceback (most recent call last): File "GUI...
0
2016-08-27T23:31:01Z
39,190,134
<p>After your <code>Dialog</code> is closed, and the <code>popup</code> variable referencing it goes out of scope, Python will garbage-collect it. This causes the entire underlying C++ object, including all of its sub-widgets and layouts, to be deleted. However, you're keeping a reference to a layout used by the dialo...
1
2016-08-28T10:04:30Z
[ "python", "qt", "pyside" ]
get both unique count and max in group-by of pandas dataframe
39,186,843
<p>Using Pandas data frame group by feature and I want to group by column <code>c_b</code> and (1) calculate unique count for column <code>c_a</code> and column <code>c_c</code>, (2) and get the max value of column c_d. Wondering if there is any solution to write one line of group by code to achieve both goals? I tried...
2
2016-08-28T00:01:23Z
39,187,330
<p>You can pass a dict to <code>agg()</code>:</p> <pre><code>df.groupby('c_b').agg({'c_a':'nunique', 'c_c':'nunique', 'c_d':'max'}) </code></pre> <p>If you don't want <code>c_b</code> as index, you can pass <code>as_index=False</code> to <code>groupby</code>:</p> <pre><code>df.groupby('c_b', as_index=False).agg({'c_...
3
2016-08-28T01:50:19Z
[ "python", "python-2.7", "pandas", "dataframe", "group-by" ]
import hooks (custom module loaders) for pypy do not work
39,186,850
<p>I'm successfully able to create import hooks to load files directly from memory in python2.7. The example I used was the accepted response to this question:</p> <p><a href="http://stackoverflow.com/questions/14191900/pythonimport-module-from-memory">python:Import module from memory</a></p> <p>However; when applyi...
0
2016-08-28T00:02:29Z
39,188,737
<p>The problem is that in both of the examples you point to, <code>load_module()</code> does not add the loaded module to <code>sys.modules</code>. Normally, it should do so (and then PyPy works like CPython).</p> <p>If <code>load_module()</code> does not add the module to <code>sys.modules</code>, then every single ...
1
2016-08-28T06:55:23Z
[ "python", "pypy" ]
Max and min value in list of dicts where each dict key has a value
39,186,852
<p>All the answers I found to this seem to make you have to <a href="http://stackoverflow.com/questions/5320871/in-list-of-dicts-find-min-value-of-a-common-dict-field">specify which key</a> you want to find the max/min for e.g. <a href="http://stackoverflow.com/questions/19759374/finding-minimum-values-in-a-list-of-dic...
0
2016-08-28T00:03:01Z
39,186,865
<p>You can flatten the values, then find the min and max:</p> <pre><code>from itertools import chain flattened = list(chain(*(d.values() for d in list_of_dicts))) print(min(flattened)) print(max(flattened)) </code></pre>
1
2016-08-28T00:07:03Z
[ "python", "list", "dictionary", "max", "min" ]
Max and min value in list of dicts where each dict key has a value
39,186,852
<p>All the answers I found to this seem to make you have to <a href="http://stackoverflow.com/questions/5320871/in-list-of-dicts-find-min-value-of-a-common-dict-field">specify which key</a> you want to find the max/min for e.g. <a href="http://stackoverflow.com/questions/19759374/finding-minimum-values-in-a-list-of-dic...
0
2016-08-28T00:03:01Z
39,186,878
<p>You can use a list comprehension or generator expression.</p> <pre><code>max([max(d.values()) for d in data]) </code></pre>
2
2016-08-28T00:08:44Z
[ "python", "list", "dictionary", "max", "min" ]
filling individual frames in tkinter notebook Tabs with widgets (after automatic tab generation)
39,186,863
<p>I found a way makeing it easy to automatically generate multiple Tabs with the ttk notebook. As a "solution" to: <a href="http://stackoverflow%20-%20Automatic%20multiple%20Tab%20generation%20with%20tkinter%20notebook">http://stackoverflow.com/questions/39175898/automatic-multiple-tab-generation-with-tkinter-notebook...
-3
2016-08-28T00:05:14Z
39,472,023
<p>The rule is quite simple: to place a widget in another widget, you need a reference to the other widget. In your case, the simple thing to do is create a dictionary to hold references to your frames:</p> <pre><code>tabs = {} for i in range(0, len(tab_names)): tab = MyTab(self.notebook, tab_names[i]) self.no...
0
2016-09-13T14:02:37Z
[ "python", "tkinter", "tabs", "widget", "ttk" ]
Logging for multiple objects: IOError
39,186,906
<p>I have a class called <code>Job</code> which has a logger</p> <pre><code>class MyFileHandler(logging.FileHandler): def __init__(self, filename): self.filename = filename super(MyFileHandler, self).__init__(filename) def emit(self, record): log_text = self.format(record) try:...
0
2016-08-28T00:12:55Z
39,186,991
<p>Guess your operating system is running out of file handles.</p>
0
2016-08-28T00:30:42Z
[ "python", "python-2.7", "logging" ]
Logging for multiple objects: IOError
39,186,906
<p>I have a class called <code>Job</code> which has a logger</p> <pre><code>class MyFileHandler(logging.FileHandler): def __init__(self, filename): self.filename = filename super(MyFileHandler, self).__init__(filename) def emit(self, record): log_text = self.format(record) try:...
0
2016-08-28T00:12:55Z
39,187,435
<p>Fyi, instead of executing <code>self.logger.info(msg)</code> directly, i just wrapped it around the following code which opens filehandler and closes it each time im writing to a log..</p> <p>rewrite <code>self.logger.info(msg)</code> to <code>self.write_to_log(msg)</code></p> <p>where:</p> <pre><code>def write_t...
0
2016-08-28T02:11:51Z
[ "python", "python-2.7", "logging" ]
Cygwin Setup does not install gdb.exe
39,186,984
<p>I'm trying to use NetBeans 8.1 with Cygwin to write, compile and debug a C program. I knew nothing about C when I started this, and somehow found my way to fixing all the compiler errors. But when it came time to debug there was no debugger! Long story short, there's no gdb.exe in the Cygwin/bin directory and even ...
0
2016-08-28T00:28:26Z
39,187,596
<p>(I wrote this before I saw matzeri's response. I still may try extending python to run code from the C library, but getting the C code I've already written to work would be vastly preferable.)</p> <p>I have no idea what's going on with Cygwin's gdb, but after getting over my frustration I answered my alternative qu...
0
2016-08-28T02:51:32Z
[ "python", "c", "netbeans", "gdb", "cygwin" ]
Cygwin Setup does not install gdb.exe
39,186,984
<p>I'm trying to use NetBeans 8.1 with Cygwin to write, compile and debug a C program. I knew nothing about C when I started this, and somehow found my way to fixing all the compiler errors. But when it came time to debug there was no debugger! Long story short, there's no gdb.exe in the Cygwin/bin directory and even ...
0
2016-08-28T00:28:26Z
39,188,541
<p>Cygwin setup can install ~ 4000 packages.GDB is one of them.<br> Why do you think GDB should be installed by default ?</p> <p>Please read:<br> <a href="https://cygwin.com/cygwin-ug-net/setup-net.html#setup-packages" rel="nofollow">https://cygwin.com/cygwin-ug-net/setup-net.html#setup-packages</a></p>
1
2016-08-28T06:20:53Z
[ "python", "c", "netbeans", "gdb", "cygwin" ]
TensorFlow: how to name operations for tf.get_variable
39,187,009
<p>My question is related to this <a href="http://stackoverflow.com/questions/36612512/tensorflow-how-to-get-a-tensor-by-name">Tensorflow: How to get a tensor by name?</a></p> <p>I can give names to operations. But actually they named differently. For example:</p> <pre><code>In [11]: with tf.variable_scope('test_scop...
1
2016-08-28T00:35:16Z
39,189,462
<p><code>tf.get_variable()</code> won't work to get an operation. Therefore, I would define a new variable storing <code>tf.maximum(1,2)</code> to retrieve it later:</p> <pre><code>import tensorflow as tf with tf.variable_scope('test_scope') as scope: a1 = tf.get_variable('a', [1]) b1 = tf.get_variable('b', i...
1
2016-08-28T08:43:08Z
[ "python", "tensorflow" ]
TensorFlow: how to name operations for tf.get_variable
39,187,009
<p>My question is related to this <a href="http://stackoverflow.com/questions/36612512/tensorflow-how-to-get-a-tensor-by-name">Tensorflow: How to get a tensor by name?</a></p> <p>I can give names to operations. But actually they named differently. For example:</p> <pre><code>In [11]: with tf.variable_scope('test_scop...
1
2016-08-28T00:35:16Z
39,189,727
<p>I disagree with @rvinas answer, you don't need to create a Variable to hold the value of a tensor you want to retrieve. You can just use <code>graph.get_tensor_by_name</code> with the correct name to retrieve your tensor:</p> <pre class="lang-py prettyprint-override"><code>with tf.variable_scope('test_scope') as sc...
1
2016-08-28T09:18:11Z
[ "python", "tensorflow" ]
Python: Line break after every nth line split
39,187,012
<p>I want to force a line break after every 10 numbers or 9 nine splits on a txt file in python? How would I go about this? So say i have </p> <pre><code>Input would be something like: 40 20 30 50 40 40 40 40 40 40 20 40 20 30 50 40 40 40 20 40 20 30 50 40 40 40 40 20 20 20 20 20 20 </code></pre> <p>int a txt.fi...
0
2016-08-28T00:36:04Z
39,187,045
<p>How about using [count] to count the occurrences of an item in the list?</p> <pre><code>list == [40, 20, 30, 50, 40, 40, 40, 40, 40, 40, 20] for i in list: if list.count(i) &gt; 10: # Do Stuff </code></pre>
0
2016-08-28T00:45:01Z
[ "python" ]
Python: Line break after every nth line split
39,187,012
<p>I want to force a line break after every 10 numbers or 9 nine splits on a txt file in python? How would I go about this? So say i have </p> <pre><code>Input would be something like: 40 20 30 50 40 40 40 40 40 40 20 40 20 30 50 40 40 40 20 40 20 30 50 40 40 40 40 20 20 20 20 20 20 </code></pre> <p>int a txt.fi...
0
2016-08-28T00:36:04Z
39,187,233
<p>It looks like everything below the <code>with</code> statement should be indented one more level. Your method seems like a good start, but it will not work if there are more than 2 groups on one line. The following code takes care of that and simplifies things a bit:</p> <pre><code>with open('practice.txt') as f: ...
2
2016-08-28T01:24:02Z
[ "python" ]
Python list slicing
39,187,018
<p>I'm not able understand what to do here. Can someone help.</p> <p>I've a few lists:</p> <pre><code>array = [7,8,2,3,4,10,5,6,7,10,8,9,10,4,5,12,13,14,1,2,15,16,17] slice = [2, 4, 6, 8, 10, 12, 15, 17, 20, 22] intervals = [12, 17, 22] output = [] intermediate = [] </code></pre> <p><code>slice</code> is a list of i...
1
2016-08-28T00:36:49Z
39,187,334
<p>A straightforward solution:</p> <pre><code>array_ = [7,8,2,3,4,10,5,6,7,10,8,9,10,4,5,12,13,14,1,2,15,16,17] slice_ = [2, 4, 6, 8, 10, 12, 15, 17, 20, 22] intervals = [12, 17, 22] output = [] intermediate = [] for i in range(0, len(slice_), 2): intermediate.extend(array_[slice_[i]:slice_[i+1]+1]) if slice_...
3
2016-08-28T01:50:53Z
[ "python", "list" ]
Python list slicing
39,187,018
<p>I'm not able understand what to do here. Can someone help.</p> <p>I've a few lists:</p> <pre><code>array = [7,8,2,3,4,10,5,6,7,10,8,9,10,4,5,12,13,14,1,2,15,16,17] slice = [2, 4, 6, 8, 10, 12, 15, 17, 20, 22] intervals = [12, 17, 22] output = [] intermediate = [] </code></pre> <p><code>slice</code> is a list of i...
1
2016-08-28T00:36:49Z
39,187,609
<p>Here is a recursive solution which goes through the index once and dynamically check if the index is within the intervals and append the sliced results to a list accordingly:</p> <pre><code>def slicing(array, index, stops, sliced): # if the length of index is smaller than two, stop if len(index) &lt; 2: ...
2
2016-08-28T02:54:19Z
[ "python", "list" ]
What is the difference between table level operation and record-level operation?
39,187,032
<p>While going through the documentation of django to muster the detailed knowledge, i endured the word 'table level operation' and 'record level operation'. What is the difference in between them? Could anyone please explain me this 2 word with example? Does they have other name too? </p> <p>P.S I am not asking their...
0
2016-08-28T00:41:26Z
39,187,633
<p>I do not know specifically how Django people use the terms, but 'record-level operation' should mean an operation on 1 or more records while a 'table-level operation' should mean an operation of the table as a whole. I am not quite sure what an operation on all rows should be -- perhaps both, perhaps it depends on ...
0
2016-08-28T02:58:44Z
[ "python", "django", "database", "django-models" ]
What is the difference between table level operation and record-level operation?
39,187,032
<p>While going through the documentation of django to muster the detailed knowledge, i endured the word 'table level operation' and 'record level operation'. What is the difference in between them? Could anyone please explain me this 2 word with example? Does they have other name too? </p> <p>P.S I am not asking their...
0
2016-08-28T00:41:26Z
39,194,511
<p>In the context of Django, record level operations are those that on a single records. An example is when you define custom methods in a model:</p> <pre><code>class Person(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) birth_date = models.DateField...
1
2016-08-28T18:31:24Z
[ "python", "django", "database", "django-models" ]
python multi inheritance with parent classes have different __init__()
39,187,040
<p>Here both <code>B</code> and <code>C</code> are derived from <code>A</code>, but with different <code>__init__()</code> parameters. My question is how to write the correct/elegant code here to initialize self.a,self.b,self.c1,self.c2 in the following example? Maybe another question is--is it a good coding practice t...
0
2016-08-28T00:44:02Z
39,188,237
<p>Multiple inheritance in Python requires that all the classes cooperate to make it work. In this case, you can make them cooperate by having the <code>__init__</code> method in each class accept arbitrary <code>**kwargs</code> and pass them on when they call <code>super().__init__</code>.</p> <p>For your example cla...
1
2016-08-28T05:15:20Z
[ "python", "multiple-inheritance" ]
NLTK CFG recursion depth error
39,187,042
<pre><code>import nltk from nltk.parse.generate import generate,demo_grammar from nltk import CFG grammar = CFG.fromstring(""" ROOT -&gt; S S -&gt; NP VP NP -&gt; NP PP NP -&gt; DT NN DT -&gt; 'The' NN -&gt; 'work' PP -&gt; IN NP IN -&gt; 'of' NP -&gt; DT NN DT -&gt; 'the' NN -&gt; 'painter' VP -&gt; VBZ AD...
0
2016-08-28T00:44:11Z
39,191,332
<p>The function <code>generate</code>, as its docstring states, "Generates an iterator of all sentences from a CFG." Clearly it does so by choosing alternative expansions in the order they are listed in the grammar. So, the first time is sees an <code>NP</code>, it expands it with the rule <code>NP -&gt; NP PP</code>. ...
3
2016-08-28T12:34:44Z
[ "python", "nltk" ]
NLTK CFG recursion depth error
39,187,042
<pre><code>import nltk from nltk.parse.generate import generate,demo_grammar from nltk import CFG grammar = CFG.fromstring(""" ROOT -&gt; S S -&gt; NP VP NP -&gt; NP PP NP -&gt; DT NN DT -&gt; 'The' NN -&gt; 'work' PP -&gt; IN NP IN -&gt; 'of' NP -&gt; DT NN DT -&gt; 'the' NN -&gt; 'painter' VP -&gt; VBZ AD...
0
2016-08-28T00:44:11Z
39,196,885
<p>I tried to number the repeating occurrence of NP NN DT etc. It seems to solve the problem due to unique identification( I presume). What wonders me is it should have been like this at first place i.e the tree production thrown out should have serialized the parts of speech. </p> <pre><code>import nltk from n...
-1
2016-08-28T23:57:48Z
[ "python", "nltk" ]
How to set environment variables for current Command Prompt session from Python
39,187,043
<p>I've been stumped for far too long. Hoping someone can assist.</p> <p>I am writing a Python CLI application that needs to set a temporary environment variable (PATH) for the current command prompt session (Windows). The application already sets the environment variables permanently for all future sessions, using ...
1
2016-08-28T00:44:53Z
39,187,084
<p>Brute-force but straightforward is to emit your assignments as a batch script on stdout, and execute that script in the existing interpreter (akin to <code>source</code> in bash):</p> <pre><code>python myscript &gt;%TEMP%\myscript-vars.bat call %TEMP%\myscript-vars.bat del %TEMP%\myscript-vars.bat </code></pre>
2
2016-08-28T00:52:57Z
[ "python", "windows", "environment-variables" ]
Failure to reproduce GridSearch from sklearn in python
39,187,055
<p>I am trying to do something similar to GridSearch in sklearn: I want to get a list of three models, where all parameters are fixed except for C corresponding to the 1, 10, and 100 in each model. I have the following two functions. </p> <pre><code>def params_GridSearch(dic_params): keys, values = dic_params.keys...
0
2016-08-28T00:47:20Z
39,188,223
<p><code>model</code> refers to the same object throughout each iteration of the list comprehension in <code>model_GridSearch</code>, so you're just assigning a <code>C</code> value 3 times to the same object. You can do a few different things to fix this: you could a copy of the object using the <code>copy</code> mod...
2
2016-08-28T05:12:22Z
[ "python", "scikit-learn", "grid-search" ]
TDSVersion keeps defaulting to 7.1 pymssql
39,187,089
<p>IMPORTANT CHANGE:</p> <p>The following command also works and gets me the correct prompt. There must then be an issue with pymssql.</p> <pre><code>sudo TDSVER=7.1 tsql -H asdf.database.windows.net -p 1433 -U adf@ad -P adsf#adf -D adf </code></pre> <p>So I'm fighting with my pymssql and freetds drivers.</p> <p>P...
0
2016-08-28T00:53:43Z
39,190,882
<p>Unfortunately you don't tell us:</p> <ul> <li>Which TDS version you wish to actually use.</li> <li>Which pymssql version you are using and how you've installed it</li> </ul> <p>If you are trying to use TDS 8.0 and see pymssql+FreeTDS is using 7.1 then you </p> <p>a) Don't need to worry as they are the same thing....
2
2016-08-28T11:42:23Z
[ "python", "database", "sql-azure", "freetds", "pymssql" ]
TDSVersion keeps defaulting to 7.1 pymssql
39,187,089
<p>IMPORTANT CHANGE:</p> <p>The following command also works and gets me the correct prompt. There must then be an issue with pymssql.</p> <pre><code>sudo TDSVER=7.1 tsql -H asdf.database.windows.net -p 1433 -U adf@ad -P adsf#adf -D adf </code></pre> <p>So I'm fighting with my pymssql and freetds drivers.</p> <p>P...
0
2016-08-28T00:53:43Z
39,193,758
<p>It appears that freetds v0.95 is not compatible with Ubuntu 16.04 and neither is the latest version of pymssql since it ships with v0.95 and it appears there isn't much you can do to swap the version it uses out.</p> <p>I was able to get this to work by doing the following:</p> <pre><code>sudo apt-get install free...
0
2016-08-28T17:05:45Z
[ "python", "database", "sql-azure", "freetds", "pymssql" ]
Efficient ways to iterate over several numpy arrays and process current and previous elements?
39,187,149
<p>I've read a lot about different techniques for iterating over numpy arrays recently and it seems that consensus is not to iterate at all (for instance, see <a href="http://stackoverflow.com/questions/38207528/what-are-the-efficient-ways-to-loop-over-vectors-along-a-specified-axis-in-numpy">a comment here</a>). There...
2
2016-08-28T01:06:35Z
39,187,490
<p>The <code>numpy.where()</code> version is fast enough, you can speedup it a little by <code>method3()</code>. If the <code>&gt;</code> condition can change to <code>&gt;=</code>, you can also use <code>method4()</code>.</p> <pre><code>import numpy as np a = np.random.randn(100000) def method1(a): idx = [] ...
3
2016-08-28T02:24:16Z
[ "python", "arrays", "performance", "numpy", "itertools" ]
Efficient ways to iterate over several numpy arrays and process current and previous elements?
39,187,149
<p>I've read a lot about different techniques for iterating over numpy arrays recently and it seems that consensus is not to iterate at all (for instance, see <a href="http://stackoverflow.com/questions/38207528/what-are-the-efficient-ways-to-loop-over-vectors-along-a-specified-axis-in-numpy">a comment here</a>). There...
2
2016-08-28T01:06:35Z
39,187,539
<p>I'll need to read your post in more detail, but will start with some general observations (from previous iteration questions).</p> <p>There isn't an efficient way of iterating over arrays in Python, though there are things that slow things down. I like to distinguish between the iteration mechanism (<code>nditer</...
3
2016-08-28T02:35:54Z
[ "python", "arrays", "performance", "numpy", "itertools" ]
Alphabetical pairing of CSV elements while keeping first element constant in python
39,187,192
<p>How is it possible to take a CSV file with rows of varying lengths (up to 12 in practice) as input and then output a new CSV file where new rows consist of the 0th element of each row + each unique pair of elements (>0th) in alphabetical order?</p> <p>The original row elements are not in alphabetical order.</p> <...
0
2016-08-28T01:16:31Z
39,187,305
<p>You can use <a href="https://docs.python.org/3/library/csv.html#module-csv" rel="nofollow"><code>csv</code></a> for reading &amp; writing and <a href="https://docs.python.org/3.5/library/itertools.html#itertools.combinations" rel="nofollow"><code>itertools.combinations</code></a> for generating the pairs:</p> <pre>...
1
2016-08-28T01:43:12Z
[ "python", "python-3.x", "sorting", "csv", "itertools" ]
Brute-force search algorithm in arithmetic operations
39,187,275
<p>Since I'm a Python beginner, I'm trying to study some codes from some websites. I found in GitHub an algorithm which does a <a href="https://en.wikipedia.org/wiki/Brute-force_search" rel="nofollow">Bruteforce search</a> for arithmetic expressions. The code is:</p> <pre><code>#!python import operator import itertool...
2
2016-08-28T01:36:27Z
39,187,572
<p>The recursion terminates by yielding str(num[0]) if num[0] equals target and nothing otherwise. If something is yielded, the string expression is built on successive yields. To get all expressions, something must always be yielded. I choose to also yield whether the target was reached. Instead, the expression cou...
2
2016-08-28T02:44:19Z
[ "python", "algorithm", "math" ]
How to add a new line after each loop?
39,187,327
<p>Currently getting this output</p> <pre><code>[1, 1, 3, '\n'] [1, 1, 3, '\n', 7, 7, 7, '\n'] </code></pre> <p>looking for this output</p> <pre><code>[1, 1, 3] [7, 7, 7] </code></pre> <p>Code:</p> <pre><code> import random my_list=[] n = 3 m = 1 while m &lt; 10: for i in range(n): # repeats...
1
2016-08-28T01:49:45Z
39,187,371
<pre><code>import random n = 3 m = 0 my_list = [] while m &lt; 10: my_list.append([]) for i in range(n): my_list[m].append(random.randrange(0, 9)) print(my_list[m]) m = m + 1 </code></pre> <p>This code creates sublists inside <code>my_list</code>, and prints out each sublist every iteration. So...
1
2016-08-28T01:58:47Z
[ "python", "python-3.x", "while-loop" ]
How to add a new line after each loop?
39,187,327
<p>Currently getting this output</p> <pre><code>[1, 1, 3, '\n'] [1, 1, 3, '\n', 7, 7, 7, '\n'] </code></pre> <p>looking for this output</p> <pre><code>[1, 1, 3] [7, 7, 7] </code></pre> <p>Code:</p> <pre><code> import random my_list=[] n = 3 m = 1 while m &lt; 10: for i in range(n): # repeats...
1
2016-08-28T01:49:45Z
39,187,412
<p>I agree with @Neil It looks like you want a 2d array. Here's another way to do it.</p> <pre><code>from random import randint my_list = [[randint(1, 11) for i in xrange(10)] for j in xrange(randint(5, 10))] </code></pre> <p>This will create a 0 - 9 number object 5 to 9 times. e.g [[2,3,4,5...], [1,2,2,3...]...]</...
1
2016-08-28T02:06:36Z
[ "python", "python-3.x", "while-loop" ]
How to add a new line after each loop?
39,187,327
<p>Currently getting this output</p> <pre><code>[1, 1, 3, '\n'] [1, 1, 3, '\n', 7, 7, 7, '\n'] </code></pre> <p>looking for this output</p> <pre><code>[1, 1, 3] [7, 7, 7] </code></pre> <p>Code:</p> <pre><code> import random my_list=[] n = 3 m = 1 while m &lt; 10: for i in range(n): # repeats...
1
2016-08-28T01:49:45Z
39,187,415
<p>Put the my_list=[] inside the outer loop to reinitialize it each time. Also, if you don't want the newline, don't append it to my_list. If you want all the output on the same line use the optional arg <code>end</code> to the print function.</p> <pre><code>import random n = 3 m = 1 while m &lt; 10: my_list = [] ...
1
2016-08-28T02:07:43Z
[ "python", "python-3.x", "while-loop" ]
Porting, Python to C# - How can I iterate a tuple over a tuple?
39,187,360
<p>I'm port a Python project over to C#.</p> <p>So far I've run into this problem, is there any way I could port this to C#?</p> <pre><code>verts = (-1,-1,-1),(1,-1,-1),(1,1,-1),(-1,1,-1),(-1,-1,1),(1,-1,1),(1,1,1),(-1,1,1) edges = (0,1),(1,2),(2,3),(3,0),(4,5),(5,6),(6,7),(7,4),(0,4),(1,5),(2,6),(3,7) for edge in e...
0
2016-08-28T01:57:18Z
39,187,742
<p>This is one way you could go about doing it...</p> <pre><code> var verts = new[] { new Tuple&lt;int,int,int&gt; (-1,-1,-1 ), new Tuple&lt;int,int,int&gt; (1,-1,-1 ), new Tuple&lt;int,int,int&gt; (1,1,-1 ), new Tuple&lt;int,int,int&gt; (-1,1,-1 ), ...
1
2016-08-28T03:22:38Z
[ "c#", "python", "3d", "port" ]
How to serialize 2 models with custom relationship in django-rest-framework?
39,187,365
<p>I have 2 existing tables in database and i haven't permission to alter them. Show as models below.</p> <pre><code>class Prenames(models.Model): typ = models.DecimalField(max_digits=1, decimal_places=0, db_column='tprpretyp') code = models.DecimalField(max_digits=3, decimal_places=0, db_column='tprprecod') ...
1
2016-08-28T01:57:59Z
39,189,721
<p>Try this:</p> <pre><code>prenames = PrenameSerializer(source="how_you_get_this_field, many=True, read_only=True) </code></pre>
1
2016-08-28T09:17:29Z
[ "python", "django", "django-rest-framework" ]
How to serialize 2 models with custom relationship in django-rest-framework?
39,187,365
<p>I have 2 existing tables in database and i haven't permission to alter them. Show as models below.</p> <pre><code>class Prenames(models.Model): typ = models.DecimalField(max_digits=1, decimal_places=0, db_column='tprpretyp') code = models.DecimalField(max_digits=3, decimal_places=0, db_column='tprprecod') ...
1
2016-08-28T01:57:59Z
39,190,687
<p>Thanks @Aison for giving me an inspiration. This solution is not exactly what I want. But it save my life for now. From <a href="http://www.django-rest-framework.org/api-guide/fields/#serializermethodfield" rel="nofollow">SerializerMethodField</a>. I decided to modify ProfileSerializer to</p> <pre><code>class Patie...
0
2016-08-28T11:14:53Z
[ "python", "django", "django-rest-framework" ]
How to correctly uninstall numpy on MacOSX?
39,187,374
<p>I'm on a Mac, and I installed <code>numpy</code> and <code>sklearn</code> in that order. Now, I'm faced with these errors that have already been mentioned on SO several times: </p> <p><a href="http://stackoverflow.com/questions/38197086/sklearn-numpy-dtype-has-the-wrong-size-try-recompiling-in-both-pycharm-and-te...
0
2016-08-28T01:59:05Z
39,188,275
<p>If you're using the brew version of python</p> <pre><code>brew uninstall numpy </code></pre> <p>If you're using the mac version of python:</p> <p>python 2.7</p> <pre><code>pip uninstall numpy </code></pre> <p>python 3</p> <pre><code>pip3 uninstall numpy </code></pre>
1
2016-08-28T05:24:34Z
[ "python", "osx", "python-2.7", "numpy" ]
How to correctly uninstall numpy on MacOSX?
39,187,374
<p>I'm on a Mac, and I installed <code>numpy</code> and <code>sklearn</code> in that order. Now, I'm faced with these errors that have already been mentioned on SO several times: </p> <p><a href="http://stackoverflow.com/questions/38197086/sklearn-numpy-dtype-has-the-wrong-size-try-recompiling-in-both-pycharm-and-te...
0
2016-08-28T01:59:05Z
39,323,756
<p>To solve this, I did the following: (note that it is not entirely clear to me which of these solved the problem, since I didn't test thoroughly).</p> <p>1) Installed python at Python.org instead of Mac's stupid version</p> <p>2) re-installed all of the modules like <code>numpy</code>, <code>scipy</code>, <co...
1
2016-09-05T03:59:50Z
[ "python", "osx", "python-2.7", "numpy" ]
Installed app in Django not found when running tests
39,187,382
<p>I have a pretty simple Django app, that I am trying to run unit tests on. In my tests.py file I am trying to import the parent apps views file. I tried 'from . import views' but got an error:</p> <pre><code>SystemError: Parent module '' not loaded, cannot perform relative import </code></pre> <p>I read that when a...
2
2016-08-28T02:01:24Z
39,188,059
<p>It's not much information you gave us.. but when I take a look at the Traceback it says <code>File 'menu/tests.py'</code>. So if the views.py is also inside the menu Folder you just can write:</p> <pre><code>import views </code></pre> <p>If the views.py is in the main folder you could write:</p> <pre><code>from ....
2
2016-08-28T04:36:25Z
[ "python", "django", "testing", "module" ]
how rsync_project to run on the remote server
39,187,394
<p>Here is my scenario:</p> <p><img src="https://cloud.githubusercontent.com/assets/759107/18025282/f5ba497a-6c5f-11e6-86be-b7324f109192.png" alt="fabric-question"> </p> <p>I want to execute local fab command to rsync code in the bastion server to the web server parallel, but I find <code>rsync_project</code> can on...
0
2016-08-28T02:03:31Z
39,252,618
<p>I think your best bet would be to install fabric and rsync_project on 'bastion' and use fabrics "run" to call rsync_project on bastion.</p> <p>Another option would be to use "get" to receive a copy from bastion and run rsync_project locally. But this approach will not match your picture.</p>
0
2016-08-31T14:40:10Z
[ "python", "fabric" ]
Django error with ViewSet using SimpleRouter
39,187,408
<p>views.py</p> <pre><code>from rest_framework import viewsets from rest_framework.response import Response from rest_framework import generics from ticker.serializers import PriceSerializer from ticker.models import Price import datetime from nexchange.settings import DEFAULT_HOUR_RANGE class LastPricesViewSet(view...
0
2016-08-28T02:05:27Z
39,187,711
<p>Solution: You must inherit from <code>viewsets.ViewSetMixin</code> to implement the methods that are required by a ViewSetClass to be registered with the DRF router, otherwise it is possible to use the simple Django <code>urlconf</code> notation.</p> <p><code>views.py:</code></p> <pre><code>class PriceHistoryViewS...
0
2016-08-28T03:14:47Z
[ "python", "django-rest-framework" ]
Trying to automate voucher code input with Selenium Python
39,187,438
<p>Ok so, I'm 16 and am new to Python. I need projects to do to help me learn, so I came up with a PlayStation Plus code generator as a project and so far it does:</p> <p>-Generates a code -Logs in to Account Management at Sony's site -Enters code at redeem section -Checks if error occurred</p> <pre><code>voucher_box...
0
2016-08-28T02:12:16Z
39,187,667
<p>This is an idea of what I mentioned in the comment</p> <pre><code>while i &lt; amount: try: counter = 0 # make sure that the elements can be found # try ten times and then break out of loop while counter &lt; 10: try: voucher_box = driver.find_element_by_id("voucherCode...
0
2016-08-28T03:06:45Z
[ "python", "python-3.x", "selenium" ]
Am I crazy or is it actually going this fast? (MultiThreading)
39,187,449
<pre><code>from tornado import httpclient import time start = time.time() for x in range(1000): httpclient.AsyncHTTPClient().fetch("https://www.google.com", method="GET") print ('{0} seconds'.format(time.time() - start)) </code></pre> <p>Result <code>1.11500000954 seconds</code></p> <p>I wrote this to see how ...
4
2016-08-28T02:14:48Z
39,187,486
<p>Well, yes, you spun off 1000 <em>asynchronous</em> requests to Google and timed that. You did not, however, time the overhead of actually making the HTTP call. That would require a <a href="http://www.tornadoweb.org/en/stable/httpclient.html#tornado.httpclient.AsyncHTTPClient">callback-type</a> of handler.</p>
5
2016-08-28T02:24:01Z
[ "python", "multithreading", "tornado" ]
Am I crazy or is it actually going this fast? (MultiThreading)
39,187,449
<pre><code>from tornado import httpclient import time start = time.time() for x in range(1000): httpclient.AsyncHTTPClient().fetch("https://www.google.com", method="GET") print ('{0} seconds'.format(time.time() - start)) </code></pre> <p>Result <code>1.11500000954 seconds</code></p> <p>I wrote this to see how ...
4
2016-08-28T02:14:48Z
39,187,493
<p>I haven't run this yet, so I could be wrong, but fetch() is an asynchronous method that takes a callback, and the callback is what handles the response from the server when it comes. In other words, I'm pretty sure all you're doing here in this ~1 second is creating the representations of the requests — you're def...
0
2016-08-28T02:24:55Z
[ "python", "multithreading", "tornado" ]
Am I crazy or is it actually going this fast? (MultiThreading)
39,187,449
<pre><code>from tornado import httpclient import time start = time.time() for x in range(1000): httpclient.AsyncHTTPClient().fetch("https://www.google.com", method="GET") print ('{0} seconds'.format(time.time() - start)) </code></pre> <p>Result <code>1.11500000954 seconds</code></p> <p>I wrote this to see how ...
4
2016-08-28T02:14:48Z
39,275,759
<p>As the other answers already pointed out, <code>tornado</code> works asynchronously. You have to run the requests in an <a href="http://www.tornadoweb.org/en/stable/ioloop.html#ioloop-objects" rel="nofollow"><code>IOLoop</code></a>. Please note that this has nothing to do with multithreading. The requests are execut...
0
2016-09-01T15:38:50Z
[ "python", "multithreading", "tornado" ]
Can Python's functool's reduce work with functions in the iterable?
39,187,477
<p>I'm trying to figure out how to return a function in Python. However, I don't know if the issue is with <code>reduce</code> or with my code. What I currently have is this:</p> <h3>Code:</h3> <pre><code>def combine(*args): from functools import reduce def closure(val): return reduce( (lambda x, f: f...
0
2016-08-28T02:21:19Z
39,187,508
<p>As it is defined in your question, <code>fifth(x)</code> is the same as:</p> <pre><code>fifth(x) = shift(shift(shift(shift(first(x))))) </code></pre> <p>Now, if <code>x = [1,2,3,4,5,6,7,8,9]</code>, then</p> <pre><code>first(x) = 1 </code></pre> <p>But that means that</p> <pre><code>shift(first(x)) = first(x)[1...
3
2016-08-28T02:28:45Z
[ "python", "reduce" ]
Scraping ASP Page with Python
39,187,532
<p>I'm trying to access an asp page to get data from a website but it always redirects my to its main page. I've tried setting allow_redirect to false but that throws an error, saying "the object has moved and can be found at href=main.htm". The website requires basic auth.</p> <p>-The url I want the data from is:</p>...
0
2016-08-28T02:34:56Z
39,188,252
<p>I was able to access the .asp page by first loading a primary asp page </p> <pre><code>s.get(example.com.au/blah/menu.asp) </code></pre> <p>then loading the asp page I wanted</p> <pre><code>r = s.get(example.com.au/blah/webpage.asp) </code></pre> <p>under the same session.</p>
0
2016-08-28T05:17:51Z
[ "python", "asp.net" ]
Regular Expressions re.findall()
39,187,726
<p>I have a function which takes a count and a string as input. It should return a list of all words in that string of length count, and greater. Python however doesn't recognise my variable and returns an empty list.</p> <pre><code>def word_number(count, string): return re.findall(r'\w{count,}', string) </code></...
3
2016-08-28T03:18:10Z
39,187,732
<p>You can use <a href="https://docs.python.org/2/library/string.html#format-examples" rel="nofollow">str.format</a> to achieve your goal.</p> <pre><code>def word_number(count, string): return re.findall(r'\w{{{0},}}'.format(count), string) </code></pre>
2
2016-08-28T03:19:11Z
[ "python", "regex" ]
Regular Expressions re.findall()
39,187,726
<p>I have a function which takes a count and a string as input. It should return a list of all words in that string of length count, and greater. Python however doesn't recognise my variable and returns an empty list.</p> <pre><code>def word_number(count, string): return re.findall(r'\w{count,}', string) </code></...
3
2016-08-28T03:18:10Z
39,187,753
<p>You can use <code>printf</code> style formatting:</p> <pre><code>re.findall(r'\w{%s,}' % count, string) </code></pre>
5
2016-08-28T03:25:29Z
[ "python", "regex" ]
Inheritance vs. Composition in Python for this specific case?
39,187,738
<p>Assume I have a series of classes as follows: </p> <pre><code>class A(object): __init__(self,a): self.a=a class B(A): __init__(self,a,b): super(B,self).__init__(a) self.b=b class C(A): __init__(self,a,c1,c2): super(C,self).__init__(a) self.c1=c1 self.c2=c2...
0
2016-08-28T03:21:55Z
39,187,786
<p>You're bound to get some level of opinion on a question like this -- My answer is to use inheritance <em>iff</em> your classes are designed to be inherited. Use composition in all the other cases. In practice, this usually means that if the code that you are extending exists in a realm out of your control, don't s...
1
2016-08-28T03:32:49Z
[ "python", "inheritance", "combinations" ]
tensorflow: efficient feeding of eval/train data using queue runners
39,187,764
<p>I'm trying to run a tensorflow graph to train a model and periodically evaluate using a separate evaluation dataset. Both training and evaluation data is implemented using queue runners.</p> <p>My current solution is to create both inputs in the same graph and use a <code>tf.cond</code> dependent on an <code>is_tra...
2
2016-08-28T03:27:25Z
39,196,611
<p>After some experimentation, my current best solution is to have a main graph featuring training inputs and a separate graph with just evaluation data operations. I open a separate session to get evaluation data and feed this to the training graph when I want to evaluate. Highly inelegant (and evaluation runs take lo...
0
2016-08-28T23:11:01Z
[ "python", "tensorflow" ]
models Django invalid literal for int() with base 10: 'None'
39,187,765
<p>I am new to Django, I am tring to make a Blog here is my models </p> <pre><code>from django.db import models from django.contrib.auth.models import User class UserProfile(models.Model): name = models.OneToOneField(User) def __unicode__(self): return self.user.user_name class Category(models.Mod...
3
2016-08-28T03:27:43Z
39,187,801
<p>Instead of <code>default="None"</code>, specify <code>null=True</code> to allow null for foreign key:</p> <pre><code>category = models.ForeignKey(Category, null=True) </code></pre>
5
2016-08-28T03:35:49Z
[ "python", "django", "django-models" ]
Find rows with non zero values in a subset of columns in pandas dataframe
39,187,788
<p>I have a datframe with 4 columns of strings and others as integers. Now I need to find out those rows of data where at least one of the column is a non-zero value (or > 0).</p> <pre><code>manwra,sahAyaH,T7,0,0,0,0,T manwra, akriti,T5,0,0,1,0,K awma, prabrtih,B6, 0,1,1,0,S </code></pre> <p>My output should be</p> ...
4
2016-08-28T03:33:08Z
39,187,821
<p>assume your dataframe is <code>df</code></p> <pre><code>df.loc[(df.loc[:, df.dtypes != object] != 0).any(1)] </code></pre> <p><a href="http://i.stack.imgur.com/A6MMx.png" rel="nofollow"><img src="http://i.stack.imgur.com/A6MMx.png" alt="enter image description here"></a></p>
3
2016-08-28T03:41:50Z
[ "python", "pandas", "dataframe" ]
Find rows with non zero values in a subset of columns in pandas dataframe
39,187,788
<p>I have a datframe with 4 columns of strings and others as integers. Now I need to find out those rows of data where at least one of the column is a non-zero value (or > 0).</p> <pre><code>manwra,sahAyaH,T7,0,0,0,0,T manwra, akriti,T5,0,0,1,0,K awma, prabrtih,B6, 0,1,1,0,S </code></pre> <p>My output should be</p> ...
4
2016-08-28T03:33:08Z
39,188,088
<p>You were close: </p> <pre><code> #your's KT[KT.ix[:,3:-2] != 0] #works KT[(KT.ix[:,3:6] &gt; 0).any(1)] 0 1 2 3 4 5 6 7 1 manwra akriti T5 0 0 1 0 K 2 awma prabrtih B6 0 1 1 0 S #key diff (KT.ix[:,3:6] &gt; 0) 3 4 5 6 0 False False F...
2
2016-08-28T04:44:10Z
[ "python", "pandas", "dataframe" ]
Find rows with non zero values in a subset of columns in pandas dataframe
39,187,788
<p>I have a datframe with 4 columns of strings and others as integers. Now I need to find out those rows of data where at least one of the column is a non-zero value (or > 0).</p> <pre><code>manwra,sahAyaH,T7,0,0,0,0,T manwra, akriti,T5,0,0,1,0,K awma, prabrtih,B6, 0,1,1,0,S </code></pre> <p>My output should be</p> ...
4
2016-08-28T03:33:08Z
39,190,492
<p>Here is an alternative solution which uses <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.select_dtypes.html" rel="nofollow">select_dtypes()</a> method:</p> <pre><code>In [41]: df[(df.select_dtypes(include=['number']) != 0).any(1)] Out[41]: 0 1 2 3 4 5 6 7 1 ...
2
2016-08-28T10:50:09Z
[ "python", "pandas", "dataframe" ]
How to I get python2.7 to be the default option when I call python on terminal?
39,187,797
<p>I recently installed the anaconda package while following a tutorial on data science from the guys at dataquest.io and after my install when I type "python" on the terminal I start Python 3 instead of 2.7.</p> <p>How do I get "python" to open up python 2.7 again?</p> <p>When I type</p> <pre><code>which python </c...
1
2016-08-28T03:35:11Z
39,187,820
<p>I was playing around with this some time ago and seem to remember that in my PATH variable in Windows (assuming Windows) - the PATH variable will be read such that the first python key is taken as the default. So in Win 10, I pushed the one I want to the very top of the list and that worked for me.</p>
0
2016-08-28T03:41:24Z
[ "python", "python-2.7" ]
How to I get python2.7 to be the default option when I call python on terminal?
39,187,797
<p>I recently installed the anaconda package while following a tutorial on data science from the guys at dataquest.io and after my install when I type "python" on the terminal I start Python 3 instead of 2.7.</p> <p>How do I get "python" to open up python 2.7 again?</p> <p>When I type</p> <pre><code>which python </c...
1
2016-08-28T03:35:11Z
39,188,641
<p>Seems has been updated your default anaconda and python folder to python 3.</p> <p>Easy way is to remove <code>anaconda</code> folder listed and download python 2.7.11 from anaconda and reinstall.</p> <p>In case you have anaconda and anaconda3 in your system than you can update the path according with your needs: ...
0
2016-08-28T06:38:33Z
[ "python", "python-2.7" ]
How to I get python2.7 to be the default option when I call python on terminal?
39,187,797
<p>I recently installed the anaconda package while following a tutorial on data science from the guys at dataquest.io and after my install when I type "python" on the terminal I start Python 3 instead of 2.7.</p> <p>How do I get "python" to open up python 2.7 again?</p> <p>When I type</p> <pre><code>which python </c...
1
2016-08-28T03:35:11Z
39,191,907
<p>You can create a <em>soft link</em> from <code>python</code> to <code>python2.7,</code> namely:</p> <pre><code>$ pushd /bin &amp;&amp; ln -s /bin/python python2.7 $ ls -ls `which python` 1 lrwxrwxrwx 1 Administrator None 13 Feb 25 2016 /bin/python -&gt; python2.7 </code></pre>
0
2016-08-28T13:43:15Z
[ "python", "python-2.7" ]
url_for() paramater was ignored in flask
39,187,809
<p>My route method is:</p> <pre><code>@app.route('/movie/') def movie(page_num=1): #...detail skiped... </code></pre> <p>And my template is:</p> <pre><code>&lt;li&gt;&lt;a href="{{ url_for('movie',page_num=page_num) }}"&gt;{{ page_num }}&lt;/a&gt;&lt;/li&gt; </code></pre> <p>When I click the link,the address bar sh...
0
2016-08-28T03:38:02Z
39,189,804
<p>Since you skipped the code of your function it's hard to say what's wrong. But I suspect that you just don't catch GET parameters correctly. To do this you can either use <a href="http://flask.pocoo.org/docs/0.11/quickstart/#variable-rules" rel="nofollow">variable rules</a> with dynamic name component in your route;...
1
2016-08-28T09:26:02Z
[ "python", "flask", "url-for" ]
Scikit-learn script giving vastly different results than the tutorial, and gives an error when I change the dataframes
39,187,875
<p>I'm working through a tutorial that has this section:</p> <pre><code>&gt;&gt;&gt; import numpy as np &gt;&gt;&gt; import pandas as pd &gt;&gt;&gt; from sklearn.feature_extraction.text import TfidfVectorizer &gt;&gt;&gt; from sklearn.linear_model.logistic import LogisticRegression &gt;&gt;&gt; from sklearn.cross_val...
0
2016-08-28T03:58:18Z
39,197,222
<p>The error at the end of the stacktrace is the key to understand what's going on here.</p> <blockquote> <p>ValueError: pos_label=1 is not a valid label: array(['ham', 'spam'], dtype='|S4')</p> </blockquote> <p>You're trying to score your model with precision and recall. Recall that these scoring methods...
1
2016-08-29T01:02:30Z
[ "python", "csv", "pandas", "dataframe", "scikit-learn" ]
What is the difference between subprocess.popen and subprocess.run
39,187,886
<p>I'm new to the <code>subprocess</code> module and the ducumentation leaves me wondering what the difference is between <code>subprocess.popen</code> and <code>subprocess.run</code>. Is there a difference in what the command does? Is one just newer? Which is better to use? </p>
0
2016-08-28T04:00:30Z
39,187,984
<p><code>subprocess.run</code> <a href="https://docs.python.org/3/library/subprocess.html#subprocess.run" rel="nofollow">was added in Python 3.5</a> as a simplification over <code>subprocess.Popen</code> when you just want to execute a command and wait until it finishes, but you don't want to do anything else meanwhile...
1
2016-08-28T04:23:27Z
[ "python" ]
HackerRank Project Puler #1
39,187,952
<p>What is wrong with this code? It is not passing case 2 &amp; 3 on HackerRank.</p> <pre><code>T=long(input()) while T&gt;0: N=long(input()) sum=0 for i in range (1,N): if i%3==0 or i%5==0: sum+=i print (sum) T-=1 </code></pre> <p>I'm new in programming and can't figure out wh...
-2
2016-08-28T04:17:15Z
39,188,199
<p>There are couple of issues with the code. First since you're using <code>long</code> I guess you're running it on Python 2. On Python 2 <a href="https://docs.python.org/2/library/functions.html#range" rel="nofollow"><code>range</code></a> will generate a <code>list</code> and you'll run out of memory since problem d...
0
2016-08-28T05:08:00Z
[ "python" ]
How to select Python Tuple/Dictionary Values where Index > x
39,187,958
<p>How do you select python Tuple/Dictionary values where the index is greater than some number. I would think the code should look similar to the following assuming we create a Tuple:</p> <p><code>dt = (100, 200, 300,400) dt[dt.index &gt; 1] </code></p>
0
2016-08-28T04:18:56Z
39,187,993
<p>You could just slice the tuple. </p> <pre><code>&gt;&gt;&gt; dt = (100, 200, 300,400) &gt;&gt;&gt; dt[2:] (300, 400) </code></pre>
3
2016-08-28T04:24:22Z
[ "python" ]
How to select Python Tuple/Dictionary Values where Index > x
39,187,958
<p>How do you select python Tuple/Dictionary values where the index is greater than some number. I would think the code should look similar to the following assuming we create a Tuple:</p> <p><code>dt = (100, 200, 300,400) dt[dt.index &gt; 1] </code></p>
0
2016-08-28T04:18:56Z
39,188,083
<p>You have to use : instead of > in tuples. like the answer ahsanul haque provided. thumbs up for him.</p>
1
2016-08-28T04:43:13Z
[ "python" ]
Python Conjecture
39,188,001
<p>recently I have been trying to make a spin-off of Collatz conjecture using python 3.0. The program works as it should with positive integers, but it will not work with negative integers. In the program I check if the number is negative and if so I square it, and then proceed with collatz, rules. Unfortuanitly it giv...
-1
2016-08-28T04:25:46Z
39,189,170
<p>In the mapping used by the Collatz conjecture, a positive value always maps to another positive value. So you only need to check for negative values as part of your initialisation:</p> <pre><code>number = input("Enter any integer: ") count = 0 try: number = int(number) except ValueError: print("Invalid Inpu...
1
2016-08-28T08:01:32Z
[ "python", "python-3.x", "sys" ]
How to break out of function and back into loop?
39,188,042
<p>I am currently making a web builder where it will generate a random gif based on the GIPHY API. I am having a problem where I test a case on when the api returns with 0 results.</p> <pre><code>def get_image_link(link): global flag set_count = 0 r = requests.get(link) api_response = json.loads(r.text) response = api...
1
2016-08-28T04:32:41Z
39,188,060
<p>You can move catching exception outside the function i.e:</p> <pre><code>while not flag: try: get_image_link(get_random_query()) except TypeError: flag = False print('TypeError... rerunning application...') pass </code></pre>
2
2016-08-28T04:36:26Z
[ "python" ]
How to break out of function and back into loop?
39,188,042
<p>I am currently making a web builder where it will generate a random gif based on the GIPHY API. I am having a problem where I test a case on when the api returns with 0 results.</p> <pre><code>def get_image_link(link): global flag set_count = 0 r = requests.get(link) api_response = json.loads(r.text) response = api...
1
2016-08-28T04:32:41Z
39,188,142
<p>Reset flag to false! </p> <pre><code>try: flag = True return response[random_gif_num]['images']['original']['url'] except TypeError: flag = false print(TypeError + '... rerunning application...') pass </code></pre>
2
2016-08-28T04:55:46Z
[ "python" ]
Turn list of JSON objects into Django model isntances
39,188,070
<p>I have a huge array of JSON objects in a json file. some objects have more keys than others, but they are all keys that are fields in a model class that I have. I am wondering, what is the best way to iterate over each JSON object to create a model instance with the data from that object, creating null values for an...
1
2016-08-28T04:38:39Z
39,188,527
<p><code>hasattr</code> and <code>setattr</code> can be very useful to solve your problem. (<a href="https://docs.python.org/3/library/functions.html#hasattr" rel="nofollow">docs</a>)</p> <pre><code>def convert(jsonObject, model): modelObject = model() for key in jsonObject: if hasattr(modelObject, key...
2
2016-08-28T06:18:09Z
[ "python", "json", "django", "model" ]
Running Flask with Gunicorn raises TypeError: index() takes 0 positional arguments but 2 were given
39,188,136
<p>I'm trying to run a Flask app with Gunicorn. When I run <code>gunicorn app:index</code>, I get the error <code>TypeError: index() takes 0 positional arguments but 2 were given</code>. None of the examples I've seen show <code>index</code> needing two parameters. What does this error mean? How do I run Flask with...
1
2016-08-28T04:54:21Z
39,190,113
<p>You have to pass a Flask instance to <code>gunicorn</code>, not a function name like you did with <code>index</code>. So if your app saved as <code>app.py</code>, then you have to run <code>gunicorn</code> as follows:</p> <pre><code>$ gunicorn --bind 127.0.0.1:8000 app:app </code></pre>
1
2016-08-28T10:02:17Z
[ "python", "flask", "gunicorn" ]
Get weekend timestamp in python
39,188,137
<p>I have to convert get weekend timestamp from php to python. I google many times but couldn't find the answer. in php I can do</p> <pre><code>endOfWeek = strtotime('next saturday, 11:59:59pm America/Los_Angeles'); </code></pre> <p>Do you guys know how to do the thing like that in python pls help me out</p>
-1
2016-08-28T04:54:23Z
39,188,928
<p>You can use the <a href="https://dateutil.readthedocs.io/en/stable/" rel="nofollow">dateutil</a> package. </p> <pre><code>from dateutil.relativedelta import * from datetime import * from dateutil.tz import * today = datetime.now(tzutc()) new_time = today+relativedelta(weekday=FR, hours=11, minutes=59, seconds=00) n...
0
2016-08-28T07:24:33Z
[ "python", "timestamp" ]
Get weekend timestamp in python
39,188,137
<p>I have to convert get weekend timestamp from php to python. I google many times but couldn't find the answer. in php I can do</p> <pre><code>endOfWeek = strtotime('next saturday, 11:59:59pm America/Los_Angeles'); </code></pre> <p>Do you guys know how to do the thing like that in python pls help me out</p>
-1
2016-08-28T04:54:23Z
39,199,473
<p>@Jose Yeah Thank you. I seen work in local for me. But we plan to use Python on Google App Engine and It not allow use extend library. But I find how to do it use standard date, time modules</p> <blockquote> <pre><code> year_no = datetime.datetime.utcnow().isocalendar(0) week_no = datetime.datetime.utcnow()....
0
2016-08-29T06:04:55Z
[ "python", "timestamp" ]
only rotate part of image python
39,188,198
<p>Can someone tell me how to rotate only part of an image like this:</p> <p><a href="http://i.stack.imgur.com/8MEVW.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/8MEVW.jpg" alt="this"></a></p> <p>How to find coordinate / center of this image:</p> <p><a href="http://i.stack.imgur.com/PxGtN.png" rel="nofollo...
2
2016-08-28T05:07:45Z
39,188,320
<p>You can solve this problem as such. Say you have <code>img = Image.open("nime1.png")</code></p> <ol> <li>Create a copy of the image using img2 = img.copy()</li> <li>Create a crop of img2 at the desired location using img2.crop(). You can read how to do this <a href="http://stackoverflow.com/questions/890051/how-do-...
0
2016-08-28T05:35:34Z
[ "python", "image", "rotation", "python-imaging-library", "python-3.4" ]
only rotate part of image python
39,188,198
<p>Can someone tell me how to rotate only part of an image like this:</p> <p><a href="http://i.stack.imgur.com/8MEVW.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/8MEVW.jpg" alt="this"></a></p> <p>How to find coordinate / center of this image:</p> <p><a href="http://i.stack.imgur.com/PxGtN.png" rel="nofollo...
2
2016-08-28T05:07:45Z
39,188,324
<p>You can crop an area of the picture as a new variable. In this case, I cropped a 120x120 pixel box out of the original image. It is rotated by 90 and then pasted back on the original. </p> <pre><code>from PIL import Image img = Image.open('./image.jpg') sub_image = img.crop(box=(200,0,320,120)).rotate(90) img.pa...
0
2016-08-28T05:37:07Z
[ "python", "image", "rotation", "python-imaging-library", "python-3.4" ]
Python program with arguments on Windows
39,188,406
<p>How to run this program saved in the file test.py on Windows XP with python 2.7 installed.</p> <pre><code>import argparse parser = argparse.ArgumentParser(description='Process some integers.') parser.add_argument('integers', metavar='N', type=int, nargs='+',help='an integer for the accumulator') parser.add_argument...
0
2016-08-28T05:56:38Z
39,188,473
<p>This is just me being naive, but considering the short error message you posted...</p> <p>Any chance you're getting this code off some book and try to run this on a command line?</p> <p>The book uses <code>$</code> to mark command line/terminal commands, but the character is actually not part of the syntax or comm...
0
2016-08-28T06:10:10Z
[ "python", "argparse" ]
Python program with arguments on Windows
39,188,406
<p>How to run this program saved in the file test.py on Windows XP with python 2.7 installed.</p> <pre><code>import argparse parser = argparse.ArgumentParser(description='Process some integers.') parser.add_argument('integers', metavar='N', type=int, nargs='+',help='an integer for the accumulator') parser.add_argument...
0
2016-08-28T05:56:38Z
39,188,523
<p>I tried running your script at the command line and it works perfectly:</p> <pre><code>$ python arg.py 1 2 3 4 --sum 10 </code></pre> <p>In the above, the <code>$</code> is the shell's prompt. What I entered is <code>python arg.py 1 2 3 4 --sum</code>. It works.</p> <p>Now, let's do what I suspect that you are ...
3
2016-08-28T06:17:34Z
[ "python", "argparse" ]
Python program with arguments on Windows
39,188,406
<p>How to run this program saved in the file test.py on Windows XP with python 2.7 installed.</p> <pre><code>import argparse parser = argparse.ArgumentParser(description='Process some integers.') parser.add_argument('integers', metavar='N', type=int, nargs='+',help='an integer for the accumulator') parser.add_argument...
0
2016-08-28T05:56:38Z
39,193,793
<p>Your <code>test</code> script is the first example on the Python argparse documentation. <a href="https://docs.python.org/3/library/argparse.html" rel="nofollow">https://docs.python.org/3/library/argparse.html</a></p> <p>Your comment with new lines added is</p> <pre><code>Python 2.7.8 (default, Jun 30 2014, 16:0...
0
2016-08-28T17:09:21Z
[ "python", "argparse" ]
Speech recognition not working in ubuntu
39,188,531
<p>I am starting a work which needs to convert audio into text. I am using the speechrecognition library of python. I saw a tutorial on github on how to use it. The program is not bale to recognise my voice through microphone.</p> <p>I am using python 2.7 on ubuntu 16.04.</p> <p>Code:</p> <pre><code>import speech_re...
4
2016-08-28T06:19:00Z
39,232,186
<p>I couldn't get <code>PocketSphinx</code> module installed , running into issues. But if I switch <code>recognize_sphinx</code> with <code>recognize_google</code>, its working for me.</p> <p>Here is your modified code.</p> <pre><code>import speech_recognition as sr # obtain audio from the microphone r = sr.Recogni...
1
2016-08-30T15:58:09Z
[ "python", "speech-recognition", "speech-to-text" ]
precision and recall on biased data set
39,188,687
<p>Suppose a two class classification problem. One class has more than 95% of labelled data, and the other class has 5% of labelled data. The two class are very biased.</p> <p>I am doing class validation to evaluate different classifiers, I found if a classifier intentionally to predict to the class which has majority...
0
2016-08-28T06:45:56Z
39,188,751
<p>This is a common problem in statistics, thus you will find plenty of resources in the internet. Check, e.g., <a href="http://machinelearningmastery.com/tactics-to-combat-imbalanced-classes-in-your-machine-learning-dataset/" rel="nofollow">8 Tactics To Combat Imbalanced Training Data</a>.</p> <p>The probably easie...
3
2016-08-28T06:57:49Z
[ "python", "python-2.7", "machine-learning", "scikit-learn", "precision-recall" ]
Trying to understand Python loop using underscore and input
39,188,827
<p>One more tip - if anyone is learning Python on HackerRank, knowing this is critical for starting out.</p> <p>I'm trying to understand this code:</p> <pre><code> stamps = set() for _ in range(int(raw_input())): print 'underscore is', _ stamps.add(raw_input().strip()) print stamps </co...
2
2016-08-28T07:10:21Z
39,188,897
<p><a href="http://stackoverflow.com/a/5893946/918959">ngoghlan's answer</a> lists 3 conventional uses for <code>_</code> in Python:</p> <blockquote> <ol> <li>To hold the result of the last executed statement in an interactive interpreter session. This precedent was set by the standard CPython interpreter, and...
3
2016-08-28T07:20:54Z
[ "python", "loops", "input" ]
Trying to understand Python loop using underscore and input
39,188,827
<p>One more tip - if anyone is learning Python on HackerRank, knowing this is critical for starting out.</p> <p>I'm trying to understand this code:</p> <pre><code> stamps = set() for _ in range(int(raw_input())): print 'underscore is', _ stamps.add(raw_input().strip()) print stamps </co...
2
2016-08-28T07:10:21Z
39,188,899
<p>The underscore is like a normal variable in your program.</p>
1
2016-08-28T07:21:04Z
[ "python", "loops", "input" ]
Trying to understand Python loop using underscore and input
39,188,827
<p>One more tip - if anyone is learning Python on HackerRank, knowing this is critical for starting out.</p> <p>I'm trying to understand this code:</p> <pre><code> stamps = set() for _ in range(int(raw_input())): print 'underscore is', _ stamps.add(raw_input().strip()) print stamps </co...
2
2016-08-28T07:10:21Z
39,217,043
<p>For anyone that is trying to understand how underscore and input works in a loop - after spending quite sometime debugging and printing - here's the code that made me understand what was going on.</p> <pre><code> for _ in range(int(raw_input())): print raw_input() </code></pre> <p>User input:</p> <pre>...
0
2016-08-30T00:16:32Z
[ "python", "loops", "input" ]
Check if a process is still running
39,188,869
<p>I have the following problem:</p> <p>I need my Python script run a bash script. In case the bash script is running more than let's say 10 seconds, I need to kill it. This is what I have so far:</p> <pre><code>cmd = ["bash", "script.sh", self.get_script_path()] process = subprocess.Popen(cmd) time.sleep(10) # pro...
1
2016-08-28T07:16:43Z
39,188,887
<p>I am using command stop process_name on ubuntu for stop my process. May it will helpful.</p>
-3
2016-08-28T07:19:54Z
[ "python", "linux", "bash", "process", "psutil" ]
Check if a process is still running
39,188,869
<p>I have the following problem:</p> <p>I need my Python script run a bash script. In case the bash script is running more than let's say 10 seconds, I need to kill it. This is what I have so far:</p> <pre><code>cmd = ["bash", "script.sh", self.get_script_path()] process = subprocess.Popen(cmd) time.sleep(10) # pro...
1
2016-08-28T07:16:43Z
39,189,189
<p>I think the <a href="http://linux.die.net/man/1/timeout" rel="nofollow"><code>timeout</code></a> command is perfect for you. From the doc page:</p> <blockquote> <h2>Synopsis</h2> <p><strong>timeout</strong> <em>[OPTION] NUMBER[SUFFIX] COMMAND [ARG]...</em><br/> <strong>timeout</strong> <em>[OPTION]</em></p...
0
2016-08-28T08:03:28Z
[ "python", "linux", "bash", "process", "psutil" ]
Check if a process is still running
39,188,869
<p>I have the following problem:</p> <p>I need my Python script run a bash script. In case the bash script is running more than let's say 10 seconds, I need to kill it. This is what I have so far:</p> <pre><code>cmd = ["bash", "script.sh", self.get_script_path()] process = subprocess.Popen(cmd) time.sleep(10) # pro...
1
2016-08-28T07:16:43Z
39,189,276
<p>Since you are already using <code>psutil</code> I suggest you replace the calls to the <code>subprocess</code> module with calls to <a href="http://pythonhosted.org/psutil/#psutil.Popen" rel="nofollow"><code>psutil.Popen</code></a>. This class has the same interface of <code>subprocess.Popen</code> but provides all ...
2
2016-08-28T08:15:52Z
[ "python", "linux", "bash", "process", "psutil" ]
TFRecordReader in data input pipeline
39,188,951
<p>I'm currently stuck with an implementation problem of <code>TFRecordReader</code></p> <p>This is the setup : </p> <pre><code>trainQ = tf.train.string_input_producer(fileList) RecReader = tf.TFRecordReader() batch_strings = RecReader.read(trainQ) con,seq=tf.parse_single_sequence_example(batch_strings.value,context_...
1
2016-08-28T07:29:12Z
39,189,797
<p>If you want to evaluate an intermediate layer (call it <code>conv3</code>) that depends on the batch input every 100 iterations, you can do the following:</p> <pre class="lang-py prettyprint-override"><code>for step in range(100000): if step % 100 != 0: # only run the training operation sess.run...
0
2016-08-28T09:25:12Z
[ "python", "queue", "tensorflow" ]
Sublime Text build system for input/output in python
39,189,125
<p>I want to use Sublime Text in Ubuntu for python programming and want to write a build system that takes input from a mentioned file and prints output to other mentioned file. I have done same for c++ using this code :</p> <pre><code>{ "cmd": ["g++ -std=c++11 ${file} -o ${file_path}/${file_base_name} &amp;&amp; ...
0
2016-08-28T07:52:15Z
39,243,853
<p>Tushar found the solution for himself by modifying the above code like below:</p> <pre><code>{ "cmd": ["python ${file}&lt;${file_path}/inputf.in&gt;${file_path}/outputf.in"], "shell":true } </code></pre>
0
2016-08-31T07:57:29Z
[ "python", "ubuntu", "sublimetext3" ]
Python 2.7, i want to get values between = and , in a string without using multiple split.
39,189,172
<p>Ex: "name=sam,city=london, age=24,location=abc" I want to get sam, london, 24 and abc in seperate variables. Without using split because it results in many useless variables. Will regular expression help? Note: The last value will not have , In this case no , after abc. Thank you</p>
-7
2016-08-28T08:01:43Z
39,189,196
<p>What's the useless info obtained with split?</p> <pre><code>In [365]: a = "name=sam,city=london, age=24,location=abc" In [366]: [x.split('=')[1] for x in a.split(',')] Out[366]: ['sam', 'london', '24', 'abc'] </code></pre> <p>Using regex:</p> <pre><code>In [368]: [x[1] for x in re.findall(r'(\w+=(\w+))', a)] Out...
2
2016-08-28T08:04:11Z
[ "python" ]
Python List comprehension and JSON parsing
39,189,272
<p>I'm new to Python and trying to figure out the best way to parse the values of a JSON object into an array, using a list comprehension. </p> <p>Here is my code - I'm querying the publicly available iNaturalist API and would like to take the JSON object that it returns, so that I take specific parts of the JSON obje...
0
2016-08-28T08:15:22Z
39,189,305
<p>You can iterate over the list of results directly:</p> <pre><code>print([tuple(result['location'].split(',')) for result in obSet['results']]) &gt;&gt; [('9.5142456535', '-83.8011438905'), ('10.2335478381', '-84.8517773638'), ... ] </code></pre>
2
2016-08-28T08:20:14Z
[ "python", "json", "list-comprehension" ]
Python List comprehension and JSON parsing
39,189,272
<p>I'm new to Python and trying to figure out the best way to parse the values of a JSON object into an array, using a list comprehension. </p> <p>Here is my code - I'm querying the publicly available iNaturalist API and would like to take the JSON object that it returns, so that I take specific parts of the JSON obje...
0
2016-08-28T08:15:22Z
39,189,311
<pre><code>[tuple(obSet['results'][i]['location'].split(',')) for i in range(n)] </code></pre> <p>This will return a list of tuple, elements of the tuples are <code>unicode</code>.</p> <p>If you want that the elements of tuples as floats, do the following:</p> <pre><code>[tuple(map(float,obSet['results'][i]['locatio...
2
2016-08-28T08:20:51Z
[ "python", "json", "list-comprehension" ]
Python List comprehension and JSON parsing
39,189,272
<p>I'm new to Python and trying to figure out the best way to parse the values of a JSON object into an array, using a list comprehension. </p> <p>Here is my code - I'm querying the publicly available iNaturalist API and would like to take the JSON object that it returns, so that I take specific parts of the JSON obje...
0
2016-08-28T08:15:22Z
39,189,338
<p>Another way to get list of [long, lat] without list comprehension:</p> <pre><code>In [14]: map(lambda x: obSet['results'][x]['location'].split(','), range(obSet['total_results'])) Out[14]: [[u'9.5142456535', u'-83.8011438905'], [u'10.2335478381', u'-84.8517773638'], [u'10.3358965682', u'-84.9964271008'], [u'10....
2
2016-08-28T08:25:45Z
[ "python", "json", "list-comprehension" ]
Python List comprehension and JSON parsing
39,189,272
<p>I'm new to Python and trying to figure out the best way to parse the values of a JSON object into an array, using a list comprehension. </p> <p>Here is my code - I'm querying the publicly available iNaturalist API and would like to take the JSON object that it returns, so that I take specific parts of the JSON obje...
0
2016-08-28T08:15:22Z
39,189,350
<p>The direct translation of your code into a list comprehension is:</p> <pre><code>positions = [obSet['results'][i]['location'] for i in range(obSet['total_results'])] </code></pre> <p>The <code>obSet['total_results']</code> is informative but not needed, you could just loop over <code>obSet['results']</code> direct...
2
2016-08-28T08:27:52Z
[ "python", "json", "list-comprehension" ]
Python List comprehension and JSON parsing
39,189,272
<p>I'm new to Python and trying to figure out the best way to parse the values of a JSON object into an array, using a list comprehension. </p> <p>Here is my code - I'm querying the publicly available iNaturalist API and would like to take the JSON object that it returns, so that I take specific parts of the JSON obje...
0
2016-08-28T08:15:22Z
39,189,361
<p>To correct way to get <strong>a list of tuples</strong> using list comprehensions would be:</p> <pre><code>def to_tuple(coords_str): return tuple(coords_str.split(',')) output_list = [to_tuple(obSet['results'][i]['location']) for i in range(obSet['total_results'])] </code></pre> <p>You can of course replace <...
1
2016-08-28T08:29:18Z
[ "python", "json", "list-comprehension" ]
Python List comprehension and JSON parsing
39,189,272
<p>I'm new to Python and trying to figure out the best way to parse the values of a JSON object into an array, using a list comprehension. </p> <p>Here is my code - I'm querying the publicly available iNaturalist API and would like to take the JSON object that it returns, so that I take specific parts of the JSON obje...
0
2016-08-28T08:15:22Z
39,189,369
<p><code>obSet['results']</code> is a list, no need to use <code>range</code> to iterate over it:</p> <pre><code>for item in obSet['results']: print(item['location']) </code></pre> <p>To make this into list comprehension you can write:</p> <pre><code>[item['location'] for item in obSet['results']] </code></pre> ...
1
2016-08-28T08:30:56Z
[ "python", "json", "list-comprehension" ]
Python List comprehension and JSON parsing
39,189,272
<p>I'm new to Python and trying to figure out the best way to parse the values of a JSON object into an array, using a list comprehension. </p> <p>Here is my code - I'm querying the publicly available iNaturalist API and would like to take the JSON object that it returns, so that I take specific parts of the JSON obje...
0
2016-08-28T08:15:22Z
39,189,407
<p>Let's try to give this a shot, starting with just 1 location: </p> <p><code>&gt;&gt;&gt; (long, lat) = obSet['results'][0]['location']</code> </p> <pre><code>Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; ValueError: too many values to unpack </code></pre> <p>Alright, so th...
1
2016-08-28T08:35:55Z
[ "python", "json", "list-comprehension" ]
Read block Text of a text file python
39,189,324
<p><strong>Input File - input.csv</strong></p> <pre><code>#######A Result:######### 2016-07-27 bar 51 14 2015-06-27 roujri 30 86 #######B Result:######### 2016-08-26 foo 34 83 2016-08-26 foo 34 83 ######################### </code></pre> <p><strong>Output result</strong> ...
-2
2016-08-28T08:23:33Z
39,189,538
<p>Throw in a little bit of regex:</p> <pre><code>$ cat a #######A Result:######### 2016-07-27 bar 51 14 2015-06-27 roujri 30 86 #######B Result:######### 2016-08-26 foo 34 83 2016-08-26 foo 34 83 ######################### $ cat a.py import re col_names = ['abc', 'xyz'] w...
1
2016-08-28T08:55:02Z
[ "python", "file", "text", "block" ]
pandas plot automatically assigning color to categories
39,189,368
<p>I want to do a bar plot my dataframe such that the categorical column ('ad') defines the colors of my bar charts. This is my data:</p> <pre><code>"date","shown","clicked","converted","avg_cost_per_click","total_revenue","ad" 2015-10-01,65877,2339,43,0.9,641.62,"ad_group_1" 2015-10-02,65100,2498,38,0.94,756.37,"ad_g...
0
2016-08-28T08:30:52Z
39,189,874
<p>You could get distinct colours for each group present in the <code>ad</code> column as shown:</p> <pre><code>df.set_index(['date'],inplace=True) # Empty list to append later grouped_list = [] label_list = [] # Iterating through each group key grouped by ad for label, key in df.groupby(['ad'])['clicked']: gro...
0
2016-08-28T09:33:46Z
[ "python", "pandas", "matplotlib" ]