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
How to automatically fill a one2many field values to another one2many field in odoo
39,524,632
<p>I have two one2many field which is reffering to a single model, existing in different models.</p> <p>ie,</p> <pre><code> class modelA(models.Model): _name = 'modela' fila = fields.One2many('main','refa') class moddelB(models.Model): _name = 'modelb' filb = fields.One2many('main',...
0
2016-09-16T05:59:43Z
39,533,425
<p>You need to use <a href="http://odoo-development.readthedocs.io/en/latest/dev/py/x2many.html#x2many-values-filling" rel="nofollow">One2manu values filling</a></p> <p><strong>XML code</strong> </p> <pre><code>&lt;button name="copy2b" type="object" string="COPY"/&gt; </code></pre> <p><strong>Python code</strong>...
1
2016-09-16T14:01:27Z
[ "python", "odoo-8" ]
Linear Search using python
39,524,718
<p>Hi I am new to python and I am trying to learn it by writing linear search in python here is the code and this is the code I have written so far. </p> <pre><code>a = [100] n = int(raw_input("Enter the no. of elements: ")) print "Enter the elements: " for i in range(0,n): print i item = int(raw_input("Enter t...
-1
2016-09-16T06:05:47Z
39,524,899
<p>You have one element in your list. The second look tries to access elements 1 though 9, which are out of bounds. </p> <p>I'd recommend using <code>enumerate</code>, which returns pairs of (index, element) up to the length of the iterable </p> <pre><code>for i, x in enumerate(a): if x == item: # found i...
1
2016-09-16T06:19:32Z
[ "python" ]
Linear Search using python
39,524,718
<p>Hi I am new to python and I am trying to learn it by writing linear search in python here is the code and this is the code I have written so far. </p> <pre><code>a = [100] n = int(raw_input("Enter the no. of elements: ")) print "Enter the elements: " for i in range(0,n): print i item = int(raw_input("Enter t...
-1
2016-09-16T06:05:47Z
39,525,107
<p>There are some errors in your code, I have tried to rearrange it:</p> <pre><code>a = [] n = int(raw_input("Enter the no. of elements: ")) print "Enter the elements: " for i in range(0,n): a.append(i) print (i) item = int(raw_input("Enter the item to be searched: ")) found = False for i in range(0,len(a)...
0
2016-09-16T06:33:48Z
[ "python" ]
Linear Search using python
39,524,718
<p>Hi I am new to python and I am trying to learn it by writing linear search in python here is the code and this is the code I have written so far. </p> <pre><code>a = [100] n = int(raw_input("Enter the no. of elements: ")) print "Enter the elements: " for i in range(0,n): print i item = int(raw_input("Enter t...
-1
2016-09-16T06:05:47Z
39,529,873
<p>slightly different (the sort algorithm)</p> <pre><code>a = [] n = int(input("enter number of elements: ")) print("appending elements: ") for i in range(0, n): a.append(i) print(i) item = int(input("enter the item to be searched: ")) # for python2.x please use raw_input for i in range(len(a)): print...
0
2016-09-16T11:01:34Z
[ "python" ]
C++ and Python 3 memory leak using PyArg_ParseTuple
39,524,724
<p>I'm not a C++ developer so i don't really know what I'm doing. Unfortunately I have to debug the following code but I'm not making any progress.</p> <pre><code>static PyObject* native_deserialize(PyObject *self, PyObject *args){ PyObject * pycontent; int len; PyObject * props = NULL; PyArg_ParseTuple(args,...
1
2016-09-16T06:05:55Z
39,615,048
<p>It turns out the solution was to Py_XDECREF the reference count for al the created objects. I still don't know exactly how, why and were as many of this still doesn't make sense to me.</p> <p>I found this page that points out some of the pitfalls of these macros.</p> <p><a href="https://wingware.com/psupport/pytho...
0
2016-09-21T11:16:54Z
[ "python", "c++" ]
Reading CSV with multiprocessing pool is taking longer than CSV reader
39,524,744
<p>From one of our client's requirement, I have to develop an application which should be able to process huge CSV files. File size could be in the range of 10 MB - 2GB in size.</p> <p>Depending on size, module decides whether to read the file using <code>Multiprocessing pool</code> or by using normal <code>CSV reader...
1
2016-09-16T06:07:42Z
39,525,703
<blockquote> <p>Is this correct behaviour? </p> </blockquote> <p>Yes - it may not be what you expect, but it is consistent with the way you implemented it and how <code>multiprocessing</code> works. </p> <blockquote> <p>Why Async mode is taking longer?</p> </blockquote> <p>The way your example works is perhaps b...
2
2016-09-16T07:12:19Z
[ "python", "csv", "python-multiprocessing" ]
How to turn decimals into hex without prefix `0x`
39,524,943
<pre><code>def tohex(r, g, b): #your code here :) def hex1(decimal): if decimal &lt; 0: return '00' elif decimal &gt; 255: return 'FF' elif decimal &lt; 17: return '0'+ hex(decimal)[2:] else: return inthex(decimal)[2:] return (...
1
2016-09-16T06:22:32Z
39,525,045
<p>You have an extra zero because the line should be <code>elif decimal &lt; 16</code> not <code>17</code>. </p> <p>Use format strings<sup>1</sup>:</p> <pre><code>def rgb(r,g,b): def hex1(d): return '{:02X}'.format(0 if d &lt; 0 else 255 if d &gt; 255 else d) return hex1(r)+hex1(g)+hex1(b) print rgb...
4
2016-09-16T06:29:41Z
[ "python", "python-2.7", "hex" ]
How to use/import PyCrypto in Django?
39,524,978
<p>I am trying to use PyCrypto with Django. I import it like this:</p> <pre><code>from Crypto.Cipher import AES </code></pre> <p>But it says:</p> <pre><code>ImportError: No module named 'Crypto' </code></pre> <p>But when I try it using the Command Prompt, it is working.</p> <p>Other details (if it can help):</p> ...
0
2016-09-16T06:24:44Z
39,530,336
<p>By using pip you can install pycrypto in virtualenv of your django project.</p> <pre><code>pip install pycrypto </code></pre> <p>And then import <code>from Crypto.Cipher import AES</code>in your required views.py file. It will support for <code>Django==1.9</code> and <code>python &lt;=3.4</code></p>
0
2016-09-16T11:26:13Z
[ "python", "django" ]
Configurate Spark by given Cluster
39,525,214
<p>I have to send some applications in python to a Apache Spark cluster. There is given a Clustermanager and some worker nodes with the addresses to send the Application to.</p> <p>My question is, how to setup and to configure Spark on my local computer to send those requests with the data to be worked out to the clus...
0
2016-09-16T06:41:49Z
39,530,209
<p>your question is unclear. If the data are on your local machine, you should first copy your data to the cluster on HDFS filesystem. Spark can works in 3 modes with YARN (are u using YARN or MESOS ?): cluster, client and standalone. What you are looking for is client-mode or cluster mode. But if you want to start the...
0
2016-09-16T11:19:52Z
[ "java", "python", "scala", "apache-spark", "pyspark" ]
Configurate Spark by given Cluster
39,525,214
<p>I have to send some applications in python to a Apache Spark cluster. There is given a Clustermanager and some worker nodes with the addresses to send the Application to.</p> <p>My question is, how to setup and to configure Spark on my local computer to send those requests with the data to be worked out to the clus...
0
2016-09-16T06:41:49Z
39,535,098
<p>i assume you remote cluster is running and you are able to submit jobs on it from remote server itself. what you need is ssh tuneling. Keep in mind that it does not work with aws.</p> <pre><code>ssh -f [email protected] -L 2000:personal-server.com:7077 -N </code></pre> <p>read more here: <a href="http://www...
0
2016-09-16T15:25:17Z
[ "java", "python", "scala", "apache-spark", "pyspark" ]
Searching and reading from file with python
39,525,334
<p>I am trying to search for a specific words in a file and print it.</p> <p>Here is my code:</p> <pre><code>import os # os directory library # Searching for a keyword Name and returning the name if found def scanName(file): name = 'Fake' with open('file.txt', 'r') as file1: for line in file1: ...
0
2016-09-16T06:49:23Z
39,525,389
<p>Replace <code>'name'.lower()</code> with <code>name.lower()</code>, because you are now checking with the <em>string</em> <code>name</code>, instead of the <em>variable</em> <code>name</code>.</p>
1
2016-09-16T06:53:29Z
[ "python", "python-2.7" ]
Searching and reading from file with python
39,525,334
<p>I am trying to search for a specific words in a file and print it.</p> <p>Here is my code:</p> <pre><code>import os # os directory library # Searching for a keyword Name and returning the name if found def scanName(file): name = 'Fake' with open('file.txt', 'r') as file1: for line in file1: ...
0
2016-09-16T06:49:23Z
39,527,072
<p>It might be easier not to check, line by line and word by word, instead simply check for the word with <code>if (word) in</code>:</p> <pre><code>import os # os directory library # Searching for a keyword Name and returning the name if found def scanName(file): name = 'larceny' with open(file, 'r') as file1...
0
2016-09-16T08:37:10Z
[ "python", "python-2.7" ]
Neural network accuracy optimization
39,525,358
<p>I have constructed an ANN in keras which has 1 input layer(3 inputs), one output layer (1 output) and two hidden layers with with 12 and 3 nodes respectively.</p> <p><a href="http://i.stack.imgur.com/PkYfu.png" rel="nofollow"><img src="http://i.stack.imgur.com/PkYfu.png" alt="enter image description here"></a></p> ...
3
2016-09-16T06:51:05Z
39,525,717
<p>You could try the following things. I have written this roughly in the order of importance - i.e. the order I would try things to fix the accuracy problem you are seeing:</p> <ol> <li><p>Normalise your input data. Usually you would take mean and standard deviation of training data, and use them to offset+scale all ...
4
2016-09-16T07:13:20Z
[ "python", "neural-network", "theano", "keras" ]
Neural network accuracy optimization
39,525,358
<p>I have constructed an ANN in keras which has 1 input layer(3 inputs), one output layer (1 output) and two hidden layers with with 12 and 3 nodes respectively.</p> <p><a href="http://i.stack.imgur.com/PkYfu.png" rel="nofollow"><img src="http://i.stack.imgur.com/PkYfu.png" alt="enter image description here"></a></p> ...
3
2016-09-16T06:51:05Z
39,526,036
<p>Neil Slater already provided a long list of helpful general advices.</p> <p>In your specific examaple, normalization is the important thing. If you add the following lines to your code</p> <pre><code>... X = dataset[:,0:3] from sklearn.preprocessing import StandardScaler scaler = StandardScaler() X = scaler.fit_tr...
3
2016-09-16T07:30:20Z
[ "python", "neural-network", "theano", "keras" ]
Is there a way of getting an item from a list by searching its position in python
39,525,375
<p>If I have a list of items e.g words=['Hi','I'm','a','computer']. Is there any way I can get the item with the index so it would look something like this...</p> <p>Input:</p> <blockquote> <p>print(words.index(2))</p> </blockquote> <p>Output:</p> <blockquote> <p>I'm</p> </blockquote> <p>So in conclusion i am ...
-3
2016-09-16T06:52:18Z
39,525,416
<p>Lists in python are like arrays in Java, C or other languages. Just index them.</p> <pre><code>words[1] </code></pre>
1
2016-09-16T06:55:34Z
[ "python", "indexing" ]
Is there a way of getting an item from a list by searching its position in python
39,525,375
<p>If I have a list of items e.g words=['Hi','I'm','a','computer']. Is there any way I can get the item with the index so it would look something like this...</p> <p>Input:</p> <blockquote> <p>print(words.index(2))</p> </blockquote> <p>Output:</p> <blockquote> <p>I'm</p> </blockquote> <p>So in conclusion i am ...
-3
2016-09-16T06:52:18Z
39,525,421
<p>You could just use the following syntax to access a certain element of your list:</p> <pre><code>words[1] </code></pre> <p>Output:</p> <pre><code>I'm </code></pre> <p>Note that the index starts with 0.</p>
3
2016-09-16T06:55:40Z
[ "python", "indexing" ]
How to print csv rows in ascending order Python
39,525,469
<p>I am trying to read a csv file, and parse the data and return on row (start_date) only if the date is before September 6, 2010. Then print the corresponding values from row (words) in ascending order. I can accomplish the first half using the following: </p> <pre><code>import csv with open('sample_data.csv', 'rb')...
0
2016-09-16T06:58:03Z
39,525,636
<p>Just read the list, filter the list according to the <code>&lt; date</code> criteria and sort it according to the 13th row <em>as integer</em></p> <p>Note that the common mistake would be to filter as ASCII (which may appear to work), but integer conversion is relaly required to avoid sort problems.</p> <pre><code...
0
2016-09-16T07:07:41Z
[ "python", "sorting", "csv" ]
UnicodeDecodeError while reading a custom created corpus in NLTK
39,525,684
<p>I made custom corpus for detecting polarity of sentences using nltk module. Here is the hierarchy of the corpus:</p> <p>polar<br> --polar<br> ----polar_tweets.txt<br> --nonpolar<br> ----nonpolar_tweets.txt<br></p> <p>And here is how I am importing that corpus in my source code:</p> <pre><code>polarity = LazyCorpu...
0
2016-09-16T07:11:02Z
39,538,326
<p>You need to understand that in Python's model, <code>unicode</code> is a kind of data but <code>utf-8</code> is an <em>encoding.</em> They're not the same thing at all. You're reading your raw text, which is apparently in <code>utf-8</code>; cleaning it, then writing it out to your new corpus <em>without specifying ...
1
2016-09-16T18:50:07Z
[ "python", "character-encoding", "nltk" ]
Unable to install pyOpenSSL
39,525,704
<p>I dual booted a Windows 10 partition on a Macbook Pro: Mac: El Capitan (64-bit) Windows: Windows 10 64-bit, formatted with the fat file system</p> <p>On Windows, I installed cygwin and Python 2.7. Through cygwin, I installed pip and gcc.</p> <p>I also tried installing cffi with <a href="http://www.lfd.uci.edu/~goh...
0
2016-09-16T07:12:26Z
40,136,918
<p>I had a similar issue and installed the libssl header files so I could compile the python module:</p> <pre><code>sudo apt-get install libssl-dev </code></pre>
0
2016-10-19T16:28:25Z
[ "python", "windows", "python-2.7", "windows-10", "pyopenssl" ]
DecisionTreeRegressor 'tree_' attribute documentation (Tree class)
39,525,716
<p>I am trying to find the documentation on the 'Tree' class which is the class of the 'tree_' parameter of a 'DecisionTreeRegressor' but no success.</p> <p>Would anybody know if this class is documented anywhere please ?</p> <p>Thanks, Yoann</p>
0
2016-09-16T07:13:18Z
39,525,895
<p>I ended up looking in the following file but I am still interested to know if the Tree class is part of the documentation.</p> <p><a href="https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tree/tree.py" rel="nofollow">https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tree/tree.py</a></...
0
2016-09-16T07:23:39Z
[ "python", "scikit-learn" ]
change specific field value in serializer class
39,525,754
<p>I have a model like this</p> <pre><code>class ProjectTemplate(models.Model): project_template_id = models.AutoField(primary_key=True) name = models.CharField(max_length=64) description = models.TextField(max_length=255) created_date = models.DateTimeField(auto_now_add=True) modified_date = model...
0
2016-09-16T07:15:30Z
39,529,285
<p>Just like Sayse said, you'd better make a foreign key to a user like this:</p> <pre><code>create_by = models.ForeignKey("User", related_name="project_user") </code></pre> <p>Then you can access the info from user like user_name or something by:</p> <pre><code>class UserSerializer(serializers.ModelSerializer): ...
0
2016-09-16T10:31:18Z
[ "python", "django", "django-rest-framework" ]
Extract data by pages one by one using single scrapy spider
39,525,828
<p>I am trying to extract data from <a href="https://www.goodreads.com/list/show/19793.I_Marked_My_Calendar_For_This_Book_s_Release?page=1" rel="nofollow">goodreads.</a></p> <p>I want to crawl pages one by one using some time delay.</p> <p>My spider looks like:</p> <pre><code>import scrapy import unidecode from scra...
0
2016-09-16T07:19:53Z
39,529,450
<p>I make changes in my code and it works. change is -</p> <pre><code>request = scrapy.Request(url=next_page_url) </code></pre> <p>should be</p> <pre><code>request = scrapy.Request(next_page_url, self.parse) </code></pre> <p>When I comment <code>allowed_domains = ["https://www.goodreads.com"]</code> It works well o...
0
2016-09-16T10:39:40Z
[ "python", "web", "scrapy", "scrapy-spider" ]
Extract data by pages one by one using single scrapy spider
39,525,828
<p>I am trying to extract data from <a href="https://www.goodreads.com/list/show/19793.I_Marked_My_Calendar_For_This_Book_s_Release?page=1" rel="nofollow">goodreads.</a></p> <p>I want to crawl pages one by one using some time delay.</p> <p>My spider looks like:</p> <pre><code>import scrapy import unidecode from scra...
0
2016-09-16T07:19:53Z
39,532,937
<p>Looks like <code>allowed_domains</code> needs a better explanation in <a href="http://doc.scrapy.org/en/latest/topics/spiders.html#scrapy.spiders.Spider.allowed_domains" rel="nofollow">the documentation</a> but if you check the examples, the structure of the domains there should be like <code>domain.com</code>, so a...
0
2016-09-16T13:38:05Z
[ "python", "web", "scrapy", "scrapy-spider" ]
trying all combinations of operations on list of variables
39,525,993
<p>I have a list of values like:</p> <pre><code>values = [1, 2, 3, 4] </code></pre> <p>and I want to try all combinations on this list like:</p> <pre><code>1 + 2 1 + 3 1 + 4 1 * 2 1 * 3 1 * 4 1 + 2 * 3 1 + 2 * 4 1 + 3 * 4 </code></pre> <p>etc.</p> <p>What would be the most straightforward way to get all these poss...
4
2016-09-16T07:28:36Z
39,526,322
<p>Here's a recursive solution that builds the expression from numbers &amp; operators and then uses <a href="https://docs.python.org/3.4/library/functions.html#eval"><code>eval</code></a> to calculate it:</p> <pre><code>vals = [1, 2, 3] operators = ['+', '*', '-', '/'] def expressions(values): # Base case, only ...
5
2016-09-16T07:50:10Z
[ "python", "combinations" ]
trying all combinations of operations on list of variables
39,525,993
<p>I have a list of values like:</p> <pre><code>values = [1, 2, 3, 4] </code></pre> <p>and I want to try all combinations on this list like:</p> <pre><code>1 + 2 1 + 3 1 + 4 1 * 2 1 * 3 1 * 4 1 + 2 * 3 1 + 2 * 4 1 + 3 * 4 </code></pre> <p>etc.</p> <p>What would be the most straightforward way to get all these poss...
4
2016-09-16T07:28:36Z
39,526,691
<p>How about this one (since order of the operands and operators does matter, we must use permutation) ?</p> <pre><code>from itertools import chain, permutations def powerset(iterable): xs = list(iterable) return chain.from_iterable(permutations(xs,n) for n in range(len(xs)+1) ) lst_expr = [] for operands in map...
2
2016-09-16T08:13:51Z
[ "python", "combinations" ]
trying all combinations of operations on list of variables
39,525,993
<p>I have a list of values like:</p> <pre><code>values = [1, 2, 3, 4] </code></pre> <p>and I want to try all combinations on this list like:</p> <pre><code>1 + 2 1 + 3 1 + 4 1 * 2 1 * 3 1 * 4 1 + 2 * 3 1 + 2 * 4 1 + 3 * 4 </code></pre> <p>etc.</p> <p>What would be the most straightforward way to get all these poss...
4
2016-09-16T07:28:36Z
39,526,839
<p>Below is the simpler and cleaner code to achieve this using <a href="https://docs.python.org/2/library/operator.html" rel="nofollow"><code>operator</code></a> and <a href="https://docs.python.org/2/library/itertools.html" rel="nofollow"><code>itertools</code></a>.</p> <p>Also check regarding why not to use <code>ev...
0
2016-09-16T08:22:57Z
[ "python", "combinations" ]
trying all combinations of operations on list of variables
39,525,993
<p>I have a list of values like:</p> <pre><code>values = [1, 2, 3, 4] </code></pre> <p>and I want to try all combinations on this list like:</p> <pre><code>1 + 2 1 + 3 1 + 4 1 * 2 1 * 3 1 * 4 1 + 2 * 3 1 + 2 * 4 1 + 3 * 4 </code></pre> <p>etc.</p> <p>What would be the most straightforward way to get all these poss...
4
2016-09-16T07:28:36Z
39,528,917
<p>My solution consumes a list of values and thus applies operations on the order with which arguments are given, as an alternative to normal arithmetic evaluation order. For example, <code>1 + 3 + 5 + 7</code>, would be <code>(((1 + 3) +5) + 7)</code>. However, it takes all possible permutations of values, so all poss...
1
2016-09-16T10:11:54Z
[ "python", "combinations" ]
How to groupby time series data
39,526,134
<p>I have a dataframe below,column B's dtype is datetime64.</p> <pre><code> A B 0 a 2016-09-13 1 b 2016-09-14 2 b 2016-09-15 3 a 2016-10-13 4 a 2016-10-14 </code></pre> <p>I would like to groupby according to month(or in general year and day...)</p> <p>so I would like to get count result ...
1
2016-09-16T07:37:07Z
39,526,402
<p>Say you start with</p> <pre><code>In [247]: df = pd.DataFrame({'A': ['a', 'b', 'b', 'a', 'a'], 'B': ['2016-09-13', '2016-09-14', '2016-09-15', '2016-10-13', '2016-10-14']}) In [248]: df.B = pd.to_datetime(df.B) </code></pre> <p>Then you can <code>groupby</code>-<code>size</code>, then <code>unstack</code>:</p> <...
3
2016-09-16T07:55:36Z
[ "python", "pandas" ]
How to groupby time series data
39,526,134
<p>I have a dataframe below,column B's dtype is datetime64.</p> <pre><code> A B 0 a 2016-09-13 1 b 2016-09-14 2 b 2016-09-15 3 a 2016-10-13 4 a 2016-10-14 </code></pre> <p>I would like to groupby according to month(or in general year and day...)</p> <p>so I would like to get count result ...
1
2016-09-16T07:37:07Z
39,527,634
<p>If you set the index to the datetime you can use pd.TimeGrouper to sort by various time ranges. Example code:</p> <pre><code># recreate dataframe df = pd.DataFrame({'A': ['a', 'b', 'b', 'a', 'a'], 'B': ['2016-09-13', '2016-09-14', '2016-09-15', '2016-10-13', '...
3
2016-09-16T09:08:41Z
[ "python", "pandas" ]
Converting hexadecimal to IEEE 754
39,526,356
<p>If I use a website like <a href="http://www.h-schmidt.net/FloatConverter/IEEE754.html" rel="nofollow">http://www.h-schmidt.net/FloatConverter/IEEE754.html</a> to convert the hex string <code>'424E4B31'</code> into float32, I get 51.57343.</p> <p>I need to use Python to convert the string, however, using solutions o...
1
2016-09-16T07:52:35Z
39,526,566
<p>Because endianness is a thing.</p> <pre><code>&gt;&gt;&gt; struct.unpack('&gt;f',hexbytes) (51.573429107666016,) </code></pre>
2
2016-09-16T08:05:55Z
[ "python", "ieee-754" ]
requests module : post data to remote host, wrong value is sent
39,526,416
<p>I have string like:</p> <pre><code>{ 'singleQuesResponses': { '28': '', '14': '', '27': '', '26': '' }, 'org_apache_struts_taglib_html_TOKEN': 'a1553f25303435076412b5ca7299b936', 'quesResponses': { 'some': 'data' } } </code></pre> <p>when i post it in py...
0
2016-09-16T07:56:42Z
39,527,426
<p>That's how it's supposed to work. The setting the data params as a dict will make the requests module attempt to send it with: </p> <pre><code>Content-Type: application/x-www-form-urlencoded </code></pre> <p>It will only take the first level of the dictionary and encode it in the body as x=data&amp;y=other_data.</...
0
2016-09-16T08:56:24Z
[ "python" ]
requests module : post data to remote host, wrong value is sent
39,526,416
<p>I have string like:</p> <pre><code>{ 'singleQuesResponses': { '28': '', '14': '', '27': '', '26': '' }, 'org_apache_struts_taglib_html_TOKEN': 'a1553f25303435076412b5ca7299b936', 'quesResponses': { 'some': 'data' } } </code></pre> <p>when i post it in py...
0
2016-09-16T07:56:42Z
39,591,764
<p>In this case, only way is sending your data with <code>Get</code> instead of posting them with data; you can use params in requests module.</p>
0
2016-09-20T10:28:19Z
[ "python" ]
Python tkinter button returns to black while pressed
39,526,427
<p>I'm using Tkinter and I've noticed that my buttons become black while mouse button is held down irrespective of what color I have stated when declaring the button.</p> <p>Does anyone know if this can be controlled?</p> <p>Kind regards,¨</p> <p>Daniel</p>
0
2016-09-16T07:57:14Z
39,526,759
<p>You're looking for the <code>activebackground</code> and <code>activeforeground</code> properties.<br> Read more about them <a href="http://effbot.org/tkinterbook/button.htm" rel="nofollow">here</a>.</p>
4
2016-09-16T08:17:53Z
[ "python", "button", "tkinter", "colors" ]
Django form: restore predefined field value in clean method
39,526,462
<p>In my Django form I need to perform different field values comparisons (+ some additional checks). If all of these conditions are met I want to raise error and inform user that he can't perform this operation. Right now I'm doing it in <code>clean</code> method and code looks like these: </p> <pre><code> if ...
0
2016-09-16T07:59:29Z
39,528,069
<p>It turned out that you can access fields' values via <code>self.data</code>. So I ended up doing <code>self.data['foo'] = self.instance.foo</code> and it's working now.</p>
0
2016-09-16T09:30:10Z
[ "python", "django", "django-forms" ]
Python (Kivy) - How to resize tabs of a TabbedPanel
39,526,499
<p>I'm using the <code>Kivy</code> library for the first time and I'm trying to develop a simple UI with a <code>TabbedPanel</code>. I would set the size (<code>x</code>) of each tab (in the code <code>TabbedPanelItem</code>) to fit at the entire <code>TabbedPanel</code>'s width but if I use <code>height</code> or <cod...
0
2016-09-16T08:01:52Z
39,527,010
<p>I have experimented a bit with your code and after reading the TabbedPanel Docs i found out that <code>tab_width</code> specifies the width of the tab header (as tab_height is for the height). To use it in your kivy file you have to add the following line:</p> <pre><code>&lt;Tabba&gt;: do_default_tab: False ...
1
2016-09-16T08:33:23Z
[ "python", "user-interface", "layout", "kivy", "kivy-language" ]
Circular imports and annotations
39,526,742
<p>If I want to use annotations in both classes in the different modules is cross?</p> <pre><code>from BModule import B class A: def method(self, b: B): pass </code></pre> <p>~</p> <pre><code>from AModule import A class B: def method(self, a: A): pass </code></pre> <p>I got a <code>ImportError: cann...
1
2016-09-16T08:16:56Z
39,526,853
<p>What is forcing the dependency? It seems to me that in this case, any method of <code>A</code> that takes a <code>B</code> could be implemented as a method on <code>B</code> that takes an <code>A</code>, so make one of the classes the "main" class and use that class to operate on objects of the other class, if that ...
0
2016-09-16T08:23:33Z
[ "python", "import", "annotations", "python-import", "circular-dependency" ]
Gaining information from the form data in form_valid
39,526,785
<p>I have to get some information from the form that has just been submitted. The form is a to put an event on a calendar.</p> <p>I need to get the "Category" field, this is basically a name of the person the event includes.</p> <p>From there I need to split the name into last and first and get their email from the u...
-2
2016-09-16T08:19:12Z
39,527,006
<p>Well, you've just created a new Event instance with that data. So the data is in that Event, naturally.</p> <p>You could also get it from the <code>form.cleaned_data</code> dict.</p>
0
2016-09-16T08:32:58Z
[ "python", "django", "django-forms" ]
Multiprocessing python function for numerical calculations
39,526,831
<p>Hoping to get some help here with parallelising my python code, I've been struggling with it for a while and come up with several errors in whichever way I try, currently running the code will take about 2-3 hours to complete, The code is given below; </p> <pre><code>import numpy as np from scipy.constants import B...
0
2016-09-16T08:22:11Z
39,527,968
<p>This is not an answer to the question, but if I may, I would propose how to speed up the code using simple numpy array operations. Have a look at the following code:</p> <pre><code>import numpy as np from scipy.constants import Boltzmann, elementary_charge as kb, e import time Tc = 9.2 RAM = 4*1024**2 # 4GB def De...
1
2016-09-16T09:25:44Z
[ "python", "multithreading", "numpy", "multiprocessing" ]
Multiprocessing python function for numerical calculations
39,526,831
<p>Hoping to get some help here with parallelising my python code, I've been struggling with it for a while and come up with several errors in whichever way I try, currently running the code will take about 2-3 hours to complete, The code is given below; </p> <pre><code>import numpy as np from scipy.constants import B...
0
2016-09-16T08:22:11Z
39,528,015
<p>I haven't tested your code, but you can do several things to improve it.</p> <p>First of all, don't create arrays unnecessarily. <code>sum_elements</code> creates three array-like objects when it can use just one generator. First, <code>np.arange</code> creates a numpy array, then the <code>list</code> function cre...
1
2016-09-16T09:27:49Z
[ "python", "multithreading", "numpy", "multiprocessing" ]
Copying (efficiently) dataframe content inside of another dataframe using Python
39,526,886
<p>I have one dataframe (<code>df1</code>):</p> <p><a href="http://i.stack.imgur.com/eXEeG.png" rel="nofollow"><img src="http://i.stack.imgur.com/eXEeG.png" alt="enter image description here"></a></p> <p>I then create a new dataframe (<code>df2</code>) which has twice as many rows as <code>fd1</code>. My goal is to c...
2
2016-09-16T08:26:44Z
39,527,551
<p>You could do it this way:</p> <pre><code>df2['XXX'] = np.repeat(df1['A'].values, 2) # Repeat elements in A twice df2.loc[::2, 'YYY'] = df1['B'].values # Fill even rows with B values df2.loc[1::2, 'YYY'] = df1['C'].values # Fill odd rows with C values XXX YYY ZZZ 0 pinco lollo NaN 1 pinc...
4
2016-09-16T09:04:01Z
[ "python", "pandas", "dataframe", "copy" ]
Copying (efficiently) dataframe content inside of another dataframe using Python
39,526,886
<p>I have one dataframe (<code>df1</code>):</p> <p><a href="http://i.stack.imgur.com/eXEeG.png" rel="nofollow"><img src="http://i.stack.imgur.com/eXEeG.png" alt="enter image description here"></a></p> <p>I then create a new dataframe (<code>df2</code>) which has twice as many rows as <code>fd1</code>. My goal is to c...
2
2016-09-16T08:26:44Z
39,534,662
<p>Working from Nickil Maveli's answer, there's a faster (if somewhat more arcane) solution if you interleave B and C into a single array first. <a href="http://stackoverflow.com/questions/5347065/interweaving-two-numpy-arrays">(c. f. this question).</a></p> <pre><code># Repeat elements in A twice df2['XXX'] = np.repe...
2
2016-09-16T15:02:31Z
[ "python", "pandas", "dataframe", "copy" ]
Url list problems
39,526,953
<p>I have a problem with url patterns, you can see them below.</p> <p>I can connect to the only one category called "Python" (<code>slug = 'python'</code>). Others like "Django", "Other categories", "Myown" links are not working, they're showing me 404 errors like below.</p> <pre><code>Page not found (404) Request Me...
0
2016-09-16T08:30:18Z
39,528,399
<p>Your URL pattern <code>^category/(?P&lt;category_name_slug&gt;[\w\-]+)/$</code> has a trailing slash. </p> <p>Therefore, you should use the URL <code>http://127.0.0.1:8000/rango/category/myown/</code> instead of <code>http://127.0.0.1:8000/rango/category/myown/</code> to view the category.</p> <p>If you the <a hre...
0
2016-09-16T09:46:09Z
[ "python", "django" ]
Secure deployment of client secrets in python
39,527,151
<p>I'm planning to write a <code>Kodi (former XBMC)</code> plugin for <code>Spotify</code> using <code>Python</code>. Some time ago, Spotify deprecated their old library <code>libspotify</code> and introduced a new <code>ReST</code> based <code>WebAPI</code>. I would like to use this api to request data like the playli...
2
2016-09-16T08:41:22Z
39,527,202
<p>In this case, you can use the <a href="https://developer.spotify.com/web-api/authorization-guide/#implicit_grant_flow" rel="nofollow">Implicit Grant Flow</a>, which is designed for client-side applications where storing the secret is impractical for security reasons.</p>
2
2016-09-16T08:44:18Z
[ "python", "rest", "security", "oauth", "spotify" ]
Iterating over only a part of list in Python
39,527,176
<p>I have a list in python, that consists of both alphabetic and numeric elements, say something like <code>list = ["a", 1, 2, 3, "b", 4, 5, 6]</code> and I want to slice it into 2 lists, containing numbers that follow the alphabetic characters, so <code>list1 = [1, 2, 3]</code> and <code>list2 = [4, 5, 6]</code>. <cod...
0
2016-09-16T08:42:41Z
39,527,499
<p>Here you have a functional aproach:</p> <pre><code>&gt;&gt;&gt; l = ["a", 1, 2, 3, "b", 4, 5, 6] &gt;&gt;&gt; dig = [x for (x, y) in enumerate(l) if type(y) is str] + [len(l)] &gt;&gt;&gt; dig [0, 4, 8] &gt;&gt;&gt; slices = zip(map(lambda x:x+1, dig), dig[1:]) &gt;&gt;&gt; slices [(1, 4), (5, 8)] &gt;&gt;&gt; list...
3
2016-09-16T09:00:31Z
[ "python", "iteration" ]
Iterating over only a part of list in Python
39,527,176
<p>I have a list in python, that consists of both alphabetic and numeric elements, say something like <code>list = ["a", 1, 2, 3, "b", 4, 5, 6]</code> and I want to slice it into 2 lists, containing numbers that follow the alphabetic characters, so <code>list1 = [1, 2, 3]</code> and <code>list2 = [4, 5, 6]</code>. <cod...
0
2016-09-16T08:42:41Z
39,527,521
<p>Something like this, maybe?</p> <pre><code>&gt;&gt;&gt; import itertools &gt;&gt;&gt; import numbers &gt;&gt;&gt; lst = ["a", 1, 2, 3, "b", 4, 5, 6] &gt;&gt;&gt; groups = itertools.groupby(lst, key=lambda x: isinstance(x, numbers.Number)) &gt;&gt;&gt; result = [[x for x in group_iter] for is_number, group_iter in g...
4
2016-09-16T09:01:55Z
[ "python", "iteration" ]
Iterating over only a part of list in Python
39,527,176
<p>I have a list in python, that consists of both alphabetic and numeric elements, say something like <code>list = ["a", 1, 2, 3, "b", 4, 5, 6]</code> and I want to slice it into 2 lists, containing numbers that follow the alphabetic characters, so <code>list1 = [1, 2, 3]</code> and <code>list2 = [4, 5, 6]</code>. <cod...
0
2016-09-16T08:42:41Z
39,527,537
<p>You can use slices:</p> <pre><code>list = ["a", 1, 2, 3, "b", 4, 5, 6] lista = list[list.index('a')+1:list.index('b')] listb = list[list.index('b')+1:] </code></pre>
0
2016-09-16T09:03:09Z
[ "python", "iteration" ]
Iterating over only a part of list in Python
39,527,176
<p>I have a list in python, that consists of both alphabetic and numeric elements, say something like <code>list = ["a", 1, 2, 3, "b", 4, 5, 6]</code> and I want to slice it into 2 lists, containing numbers that follow the alphabetic characters, so <code>list1 = [1, 2, 3]</code> and <code>list2 = [4, 5, 6]</code>. <cod...
0
2016-09-16T08:42:41Z
39,527,735
<p>Another approach (Python 3 only):</p> <pre><code>def chunks(values, idx=0): ''' Yield successive integer values delimited by a character. ''' tmp = [] for idx, val in enumerate(values[1:], idx): if not isinstance(val, int): yield from chunks(values[idx + 1:], idx) break ...
0
2016-09-16T09:14:08Z
[ "python", "iteration" ]
How to load remote database in cache, in python?
39,527,206
<p>I want to load a database from a remote server to my memory/cache, so that I don't have to make network calls every time I want to use the database. </p> <p>I am doing this in Python and the database is <code>cassandra</code>. How should I do it? I have heard about <code>memcached</code> and <code>beaker</code>. Wh...
0
2016-09-16T08:44:39Z
39,527,394
<p>If you are trying to get some data from a database, use the <a href="https://mkleehammer.github.io/pyodbc/" rel="nofollow">pyodbc</a> module. This module can be used to download data from a given table in a database. Answers can also be found in <a href="http://stackoverflow.com/questions/11451101/retrieving-data-fr...
0
2016-09-16T08:54:28Z
[ "python", "database", "caching", "cassandra", "memcached" ]
How to get the json from a text file in python
39,527,267
<pre><code>def calculateStats(): pattern = "Online_R*.txt" for root, dirs, files in os.walk("."): for name in files: if fnmatch.fnmatch(name, pattern): if(fName in root): fileName = os.path.join(root, name) intializeCSV(fileName) data = [...
-2
2016-09-16T08:48:23Z
39,527,451
<p>It seems that your line is not 100% json. It looks like the line was created by a "print (container)" statement in a previous python script and the output was redirected to create this line, hence the telltale 'u' in front of the strings.</p> <p>The solution is easy, go back to your previous python script and do th...
0
2016-09-16T08:57:57Z
[ "python", "json", "file" ]
'module' object has no attribute 'py' when running from cmd
39,527,284
<p>I'm currently learning unittesting, and I have stumbled upon a strange error:</p> <p>If I run my script from inside PyCharm, everything works perfectly. If I run it from my <code>cmd.exe</code> (as administrator), I get the following error:</p> <p><a href="http://i.stack.imgur.com/Q2oDm.png" rel="nofollow"><img sr...
0
2016-09-16T08:49:24Z
39,528,330
<p>Just remove the <code>.py</code> extension.</p> <p>You are running your tests using the <code>-m</code> command-line flag. The Python documentation will tell you more about it, just check out this <a href="http://docs.python.org/2/using/cmdline.html#cmdoption-m" rel="nofollow">link</a>.</p> <p>In a word, the <code...
1
2016-09-16T09:42:50Z
[ "python", "unit-testing", "cmd" ]
Associating users with models django
39,527,289
<p>I have a lot of models in model.py -</p> <pre><code>class Portfolio(models.Model): company = models.TextField(null=True) volume = models.IntegerField(blank=True) date = models.DateField(null=True) isin = models.TextField(null=True) class Endday(models.Model): company = models.TextField(null=True) isin ...
-1
2016-09-16T08:49:39Z
39,527,550
<p>This has nothing to do with permissions.</p> <p>If you want to associate your model with a user, use a ForeignKey to the user model.</p>
0
2016-09-16T09:03:59Z
[ "python", "django" ]
Associating users with models django
39,527,289
<p>I have a lot of models in model.py -</p> <pre><code>class Portfolio(models.Model): company = models.TextField(null=True) volume = models.IntegerField(blank=True) date = models.DateField(null=True) isin = models.TextField(null=True) class Endday(models.Model): company = models.TextField(null=True) isin ...
-1
2016-09-16T08:49:39Z
39,527,788
<p>in your models.py you can relate user like this for example</p> <pre><code>from django.contrib.auth.models import User, Group class Portfolio(models.Model): owner = models.ForeignKey(User,verbose_name = 'User',related_name='portfolios') company = models.TextField(null=True) volume = models.IntegerField(blank=Tr...
0
2016-09-16T09:16:30Z
[ "python", "django" ]
How to let Django fill an html template, then let the user download it without showing it in browser?
39,527,294
<p>I have an HTML template, and I want django to fill it with some data, but rather than redirect the user to a view that uses this template, I want Django to send the filled-template to the user as a download file.<br><br> Any suggestions?</p>
-3
2016-09-16T08:49:58Z
39,527,580
<p>You create a regular view, but before returning the response, you set the HTTP Header <code>Content-Disposition</code>.</p> <pre><code>def download_form(request): form = ... response = render(request, 'form_template.html', {'form': form}) response['Content-Disposition'] = 'attachment; filename="form.htm...
1
2016-09-16T09:06:08Z
[ "python", "django", "python-2.7", "django-templates" ]
How to fix a loop that runs once if value is correct 1st time. But runs for ever if the 1st value is wrong and 2nd value is correct.
39,527,317
<p>I'm doing this controlled assessment. I am just a beginner so I don't know too much about python.</p> <p>I have this code:</p> <pre><code># defining qualification def qualification(): print("\nQualification Level") # informs user what is AP + FQ print('\n"AP" = Apprentice', '\n"FQ" = Fully-Qulaified') ...
0
2016-09-16T08:50:56Z
39,527,437
<p>You tried to use recursion at the wrong place. </p> <p>If the user input is wrong for the first time, you will get into a deeper level recursion that will (maybe) input the right input (or will go deeper).</p> <p>But then, it will end and go back to the previous level of recursion, where the <code>user_qual</code>...
0
2016-09-16T08:56:55Z
[ "python", "python-3.x" ]
How to use Dask to process a file (or files) in multiple stages
39,527,511
<p>I'm processing a large text file in memory in 3 stages (currently not using <code>pandas</code>/<code>dataframes</code>)</p> <p>This takes one raw data text file and processes it in four stages.</p> <ul> <li><p>Stage 1 processes <code>raw.txt</code> and kicks out <code>stage1.txt</code></p></li> <li><p>Stage 2 pro...
0
2016-09-16T09:01:31Z
39,530,058
<p>I suspect you'll run into a few issues.</p> <h3>Function Purity</h3> <p>Dask generally assumes that functions are <a href="http://toolz.readthedocs.io/en/latest/purity.html" rel="nofollow">pure</a> rather than rely on side effects. If you want to use Dask then I recommend that you change your functions so that th...
1
2016-09-16T11:10:13Z
[ "python", "dask" ]
Best way to define Django global variable on apache starup
39,527,565
<p>I have some configuration in a json file and on the database and I want to load those configuration on Django startup (Apache server startup).. I will be using those global variable within all the application. For Example: External server connection api or number of instances. </p> <p>What is the best way to defin...
-2
2016-09-16T09:04:51Z
39,528,006
<p>It sounds like the thing you're probably looking for is <code>environment variables</code> - you can always use a small script to set the environment variables from the JSON that you have at present. </p> <p>Setting these in your .bashrc file or, more preferably a virtualenv will let you:</p> <ol> <li>Take sensiti...
0
2016-09-16T09:27:17Z
[ "python", "django" ]
Regex: Exclude a mix of fixed and unknown length pattern
39,527,616
<p>I have a string like this:</p> <pre><code>'Global Software Version (DID 0xFD15): 4.5.3' </code></pre> <p>And I want to find:</p> <pre><code>4.5.3 </code></pre> <p>The string does always start with <code>Global Software Version</code>, but <code>(DID 0xFD15)</code> is a variable part, it is different each time.</...
0
2016-09-16T09:07:30Z
39,527,774
<p>So you can do multiple things here. The easiest solution would be:</p> <pre><code>&gt;&gt;&gt; x = 'Global Software Version (DID 0xFD15): 4.5.3' &gt;&gt;&gt; version = re.search('\d+[.]\d+[.]\d+', s).group() &gt;&gt;&gt; version '4.5.3' </code></pre> <p>But this would also work:</p> <pre><code>&gt;&gt;&gt; versio...
1
2016-09-16T09:16:00Z
[ "python", "regex" ]
Extract IP addresses from system report
39,527,727
<p>I traverse the address entries, using a Python regex to extract addresses to add to my list. Here is a sample input string and desired output. How do I do this?</p> <pre><code>var = """ sw1:FID256:root&gt; ipaddrshow CHASSIS Ethernet IP Address: 10.17.11.10 Ethernet Subnetmask: 255.255.210.0 CP0 Ethernet IP A...
0
2016-09-16T09:13:55Z
39,529,637
<p>See <a href="https://regex101.com/r/eC0nV7/1" rel="nofollow">this regex</a> that extracts all the data:</p> <pre><code>(?m)^([a-zA-Z0-9]+)(?:\r?\n|\r)Ethernet IP Address: ([\d.]+)(?:\r?\n|\r)Ethernet Subnetmask: ([\d.]+)(?:(?:\r?\n|\r)Host Name: ([a-z\d]+)(?:\r?\n|\r)Gateway IP Address: ([\d.]+))? </code></pre> <p...
1
2016-09-16T10:48:18Z
[ "python", "regex" ]
Extract IP addresses from system report
39,527,727
<p>I traverse the address entries, using a Python regex to extract addresses to add to my list. Here is a sample input string and desired output. How do I do this?</p> <pre><code>var = """ sw1:FID256:root&gt; ipaddrshow CHASSIS Ethernet IP Address: 10.17.11.10 Ethernet Subnetmask: 255.255.210.0 CP0 Ethernet IP A...
0
2016-09-16T09:13:55Z
39,538,095
<p>I had something similar laying around and covers any attributes using a dictionary:</p> <pre><code>(?P&lt;name&gt;^[A-Z0-9]+)\n|(?P&lt;attr&gt;^[\w]+[^:]+):\s(?P&lt;val&gt;[\d\w\.]+)\n </code></pre> <p>In python is not possible to recover intermediate captures from groups that match more than once per regex match ...
0
2016-09-16T18:36:19Z
[ "python", "regex" ]
Replace the delimiter of first line from ',' to ';' in csv file by Python
39,527,811
<p>I got a weird csv file whose header's delimiter are <strong>','</strong> while common rows' delimiter are <strong>';'</strong> which cause troubles for me to read and process it as dictionary by python:</p> <pre><code>players.first_name,players.last_name,players.vis_name,players.player_id Duje;Cop;Cop;8465 Dusan;Sv...
1
2016-09-16T09:17:36Z
39,527,955
<p>You can read the first line with a classical csv reader, just to get field names, then continue reading with the dictionary reader, changing the separator to <code>;</code> at this point.</p> <pre><code>import csv with open("input.csv") as f: cr = csv.reader(f, delimiter=",") fieldnames = next(cr) cr ...
2
2016-09-16T09:25:16Z
[ "python", "csv", "delimiter" ]
How to optimize code that iterates on a big dataframe in Python
39,527,826
<p>I have a big pandas dataframe. It has thousands of columns and over a million rows. I want to calculate the difference between the max value and the min value row-wise. Keep in mind that there are many NaN values and some rows are all NaN values (but I still want to keep them!).</p> <p>I wrote the following code. I...
0
2016-09-16T09:18:22Z
39,528,041
<p>I have the same problem about iterating. 2 points:</p> <ol> <li>Why don't you replace NaN values with 0? You can do it with this <code>df.replace(['inf','nan'],[0,0])</code>. It replaces inf and nan values.</li> <li>Take a look at this <a href="http://stackoverflow.com/questions/7837722/what-is-the-most-efficient-w...
0
2016-09-16T09:28:45Z
[ "python", "pandas", "optimization", "dataframe" ]
How to optimize code that iterates on a big dataframe in Python
39,527,826
<p>I have a big pandas dataframe. It has thousands of columns and over a million rows. I want to calculate the difference between the max value and the min value row-wise. Keep in mind that there are many NaN values and some rows are all NaN values (but I still want to keep them!).</p> <p>I wrote the following code. I...
0
2016-09-16T09:18:22Z
39,528,057
<p>It is usually a bad idea to use a <code>python</code> <code>for</code> loop to iterate over a large <code>pandas.DataFrame</code> or a <code>numpy.ndarray</code>. You should rather use the available build in functions on them as they are optimized and in many cases actually not written in python but in a compiled la...
2
2016-09-16T09:29:41Z
[ "python", "pandas", "optimization", "dataframe" ]
How can I disable Web Driver Exceptions when using the Mozilla Marionette web driver with Selenium
39,527,858
<p>I am remote controlling a Firefox browser using Python and Selenium. I have switched to using Marionette, as directed on the <a href="https://developer.mozilla.org/en-US/docs/Mozilla/QA/Marionette/WebDriver" rel="nofollow">mozilla developer site</a>. That all works fine. </p> <p>There is one page, where when I want...
2
2016-09-16T09:20:14Z
39,532,113
<p>To answer your second question first, <a href="https://marionette-client.readthedocs.io/en/latest/index.html" rel="nofollow">this documentation</a> seems fairly comprehensive; does this meet your needs?</p> <p>As for the question of how to disable <code>WebDriverException</code>, the only thing I know of would be t...
0
2016-09-16T12:57:27Z
[ "python", "selenium", "firefox", "selenium-webdriver", "firefox-marionette" ]
How can I disable Web Driver Exceptions when using the Mozilla Marionette web driver with Selenium
39,527,858
<p>I am remote controlling a Firefox browser using Python and Selenium. I have switched to using Marionette, as directed on the <a href="https://developer.mozilla.org/en-US/docs/Mozilla/QA/Marionette/WebDriver" rel="nofollow">mozilla developer site</a>. That all works fine. </p> <p>There is one page, where when I want...
2
2016-09-16T09:20:14Z
39,537,510
<p>There's a bug in release 3.0.0-beta-3 which prevents the use of <code>get_attribute</code>. So you can either revert to 3.0.0-beta-2 or you can fix the bug by editing the file yourself:</p> <p>In file <code>/Users/dan/anaconda/envs/lt/lib/python3.5/site-packages/selenium/webdriver/remote/webelement.py</code>, repl...
0
2016-09-16T17:56:15Z
[ "python", "selenium", "firefox", "selenium-webdriver", "firefox-marionette" ]
How to access Google Cloud Datastore entity with dash in its name?
39,527,979
<p>I am working on a Google App Engine project and I need to access a Datastore entity with a name that contains dash, e.g. <code>random-entity</code>. I want to do that in Python. Since <code>random-entity</code> is invalid syntax for a class name, I cannot create a model and access it like that.</p> <p>So how can I ...
0
2016-09-16T09:26:18Z
39,528,191
<p>If you are using <a href="https://cloud.google.com/appengine/docs/python/ndb/" rel="nofollow"><strong>NDB</strong> library</a> you need to override <a href="https://github.com/GoogleCloudPlatform/datastore-ndb-python/blob/master/ndb/model.py#L3044" rel="nofollow">class method <code>_get_kind(cls)</code></a> of model...
2
2016-09-16T09:36:19Z
[ "python", "google-app-engine", "google-cloud-platform", "google-cloud-datastore" ]
Comparing two list and getting a new list in python
39,528,202
<p>I have a list - a and a list of columns - b.</p> <pre><code>a = [2, 4, 1, 1, 6, 1, 1, 3, 5, 1] b = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J"] </code></pre> <p>I want to take the columns from list "b" which when compared with list "a" have the value 1.</p> <p>I want the output to be:</p> <pre><code>c = ["...
1
2016-09-16T09:36:34Z
39,528,256
<p>Easy task for comprehension + zip:</p> <pre><code>&gt;&gt;&gt; c = [y for (x, y) in zip(a, b) if x == 1] &gt;&gt;&gt; c ['C', 'D', 'F', 'G', 'J'] </code></pre>
8
2016-09-16T09:39:07Z
[ "python", "list" ]
Comparing two list and getting a new list in python
39,528,202
<p>I have a list - a and a list of columns - b.</p> <pre><code>a = [2, 4, 1, 1, 6, 1, 1, 3, 5, 1] b = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J"] </code></pre> <p>I want to take the columns from list "b" which when compared with list "a" have the value 1.</p> <p>I want the output to be:</p> <pre><code>c = ["...
1
2016-09-16T09:36:34Z
39,528,290
<p>I'd do it with zip and list comprehension.</p> <pre><code>&gt;&gt;&gt; a = [2, 4, 1, 1, 6, 1, 1, 3, 5, 1] &gt;&gt;&gt; b = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J"] &gt;&gt;&gt; c = [x[0] for x in zip(b, a) if x[1] == 1] &gt;&gt;&gt; c ['C', 'D', 'F', 'G', 'J'] &gt;&gt;&gt; </code></pre>
2
2016-09-16T09:40:32Z
[ "python", "list" ]
Comparing two list and getting a new list in python
39,528,202
<p>I have a list - a and a list of columns - b.</p> <pre><code>a = [2, 4, 1, 1, 6, 1, 1, 3, 5, 1] b = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J"] </code></pre> <p>I want to take the columns from list "b" which when compared with list "a" have the value 1.</p> <p>I want the output to be:</p> <pre><code>c = ["...
1
2016-09-16T09:36:34Z
39,528,836
<p>A classic approach:</p> <pre><code>&gt;&gt;&gt; c = [b[i] for i in range(len(b)) if i&lt;len(a) and a[i] == 1] &gt;&gt;&gt; c ['C', 'D', 'F', 'G', 'J'] </code></pre>
3
2016-09-16T10:07:26Z
[ "python", "list" ]
Comparing two list and getting a new list in python
39,528,202
<p>I have a list - a and a list of columns - b.</p> <pre><code>a = [2, 4, 1, 1, 6, 1, 1, 3, 5, 1] b = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J"] </code></pre> <p>I want to take the columns from list "b" which when compared with list "a" have the value 1.</p> <p>I want the output to be:</p> <pre><code>c = ["...
1
2016-09-16T09:36:34Z
39,529,271
<p>Done in many ways:</p> <p><strong>List Comprehension</strong></p> <pre><code>a = [2, 4, 1, 1, 6, 1, 1, 3, 5, 1] b = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J"] print [b[index] for index, item in enumerate(a) if item == 1] </code></pre> <p><strong>Filter with Lambda</strong></p> <pre><code>a = [2, 4, 1, 1,...
0
2016-09-16T10:30:39Z
[ "python", "list" ]
How to call value from excel on python
39,528,448
<p>I'm currently trying to refer to a value from an excel spreadsheet that is full of passenger data for the titanic disaster. Here is the part I'm stuck on.</p> <blockquote> <p>Examining the survival statistics, a large majority of males did not survive the ship sinking. However, a majority of females did survive...
1
2016-09-16T09:48:02Z
39,528,534
<p>Your syntax is not correct with that <code>else</code> missing a <code>:</code>, and you're mixing the <a href="https://docs.python.org/2/library/stdtypes.html#comparisons" rel="nofollow"><em>equality operator</em> <code>==</code></a> with the <a href="https://docs.python.org/2/reference/simple_stmts.html#assignment...
3
2016-09-16T09:52:47Z
[ "python", "excel", "pandas" ]
Redirect to login when session cookie expires in Django
39,528,487
<p>I'm trying to redirect to the login page when the cookie expires but it's not working.</p> <p>It's supposed to be as simple as adding these lines to settings.py:</p> <pre><code>LOGIN_URL = '/login/' LOGIN_REDIRECT_URL='/login/' </code></pre> <p>I'm using the decorator <em>@login_required</em> in my functions and ...
2
2016-09-16T09:50:00Z
39,774,677
<p>Something in your code is trying to import <code>redirect_to</code>, which was removed in Django 1.5. You need to find this code and update it.</p>
0
2016-09-29T15:43:27Z
[ "python", "django", "session", "cookies" ]
Why does SetCellEditor cause error when reapplied after self.m_grid_3.ClearGrid()
39,528,535
<p>The following code populates a grid each time the combobox is used to select a new value. The first time the code runs it works fine and creates a populated grid with a drop down in each cell in col 4. However when I select a second new value and the function executes the self.m_grid_3.ClearGrid() and repopulates I...
0
2016-09-16T09:52:48Z
39,535,216
<p>Try adding this to <code>__init__</code>:</p> <pre><code>self.choice_editor.IncRef() </code></pre> <p>My guess is that the C++ portion of the editor object is being deleted when you call <code>ClearGrid</code>. Giving it that extra reference tells the Grid that you want to hold on to it.</p>
0
2016-09-16T15:31:51Z
[ "python", "wxpython" ]
Why does SetCellEditor cause error when reapplied after self.m_grid_3.ClearGrid()
39,528,535
<p>The following code populates a grid each time the combobox is used to select a new value. The first time the code runs it works fine and creates a populated grid with a drop down in each cell in col 4. However when I select a second new value and the function executes the self.m_grid_3.ClearGrid() and repopulates I...
0
2016-09-16T09:52:48Z
39,700,462
<p>Taking the answer of adding </p> <pre><code>self.choice_editor.IncRef() </code></pre> <p>I moved the choices list definition into the function along with </p> <pre><code>self.choice_editor.IncRef() </code></pre> <p>So now it looks like this</p> <pre><code>def on_engineer_select( self, event ): self.m_grid3....
0
2016-09-26T10:30:11Z
[ "python", "wxpython" ]
Get an ordered dictionary class attributes inside __init__
39,528,653
<p>I have the following class:</p> <pre><code>class NewName: def __init__(self): self.Name = None self.DecomposedAlias = OrderedDict([("Prefix", None), ("Measurement", None), ("Direction", None), ...
2
2016-09-16T09:58:27Z
39,531,388
<p>You can't do that, because the <code>__init__</code> attribute called after the instance has been created (by <code>__new__()</code>) so if you even override the <code>__new__()</code> and use a <code>__prepare__</code> method <a href="https://docs.python.org/3/reference/datamodel.html#creating-the-class-object" rel...
1
2016-09-16T12:20:44Z
[ "python", "class", "object", "dictionary", "order" ]
Creating dictionary from dataframe in python
39,528,707
<p>I want to create a dictionary out of my data frame. Data frame look like this:</p> <pre><code>Vehical | Brand | Model Name car | Suzuki | abc car | Honda | def bike | Suzuki | xyz bike | Honda | asd </code></pre> <p>I want my dictionary like:</p> <pre><code>{car : {Suzuki : abc, Honda : def}, bi...
1
2016-09-16T10:00:57Z
39,528,873
<p>you can do it this way:</p> <pre><code>In [29]: df.pivot(index='Vehical', columns='Brand', values='Model Name').to_dict('i') Out[29]: {'bike': {'Honda': 'asd', 'Suzuki': 'xyz'}, 'car': {'Honda': 'def', 'Suzuki': 'abc'}} </code></pre> <p>result of pivoting:</p> <pre><code>In [28]: df.pivot(index='Vehical', column...
2
2016-09-16T10:09:43Z
[ "python", "pandas", "dictionary", "dataframe" ]
Flask-socketio misses events while copying file in background thread
39,528,730
<p>(Complete test app on github: <a href="https://github.com/olingerc/socketio-copy-large-file" rel="nofollow">https://github.com/olingerc/socketio-copy-large-file</a>)</p> <p>I am using Flask together with the Flask-SocketIO plugin. My clients can ask the server to copy files via websocket but while the files are cop...
1
2016-09-16T10:01:50Z
39,542,933
<p>You are asking two separate questions.</p> <p>First, let's discuss the actual copying of the file.</p> <p>It looks like you are using eventlet for your server. While this framework provides asynchronous replacements for network I/O functions, disk I/O is much more complicated to do in a non-blocking fashion, in pa...
1
2016-09-17T04:44:45Z
[ "python", "multithreading", "multiprocessing", "eventlet", "flask-socketio" ]
How do you organise a python project that contains multiple packages so that each file in a package can still be run individually?
39,528,736
<p><strong>TL;DR</strong></p> <p>Here's an example repository that is set up as described in the first diagram (below): <a href="https://github.com/Poddster/package_problems" rel="nofollow">https://github.com/Poddster/package_problems</a></p> <p>If you could please make it look like the second diagram in terms of pro...
19
2016-09-16T10:02:06Z
39,746,026
<p>Once you move to your desired configuration, the absolute imports you are using to load the modules that are specific to <code>my_tool</code> no longer work.</p> <p>You need three modifications after you create the <code>my_tool</code> subdirectory and move the files into it:</p> <ol> <li><p>Create <code>my_tool/_...
6
2016-09-28T11:22:37Z
[ "python", "python-2.7", "import", "pycharm", "packages" ]
How do you organise a python project that contains multiple packages so that each file in a package can still be run individually?
39,528,736
<p><strong>TL;DR</strong></p> <p>Here's an example repository that is set up as described in the first diagram (below): <a href="https://github.com/Poddster/package_problems" rel="nofollow">https://github.com/Poddster/package_problems</a></p> <p>If you could please make it look like the second diagram in terms of pro...
19
2016-09-16T10:02:06Z
39,758,989
<h1>Point 1</h1> <p>I believe it's working, so I don't comment on it.</p> <h1>Point 2</h1> <p>I always used tests at the same level as my_tool, not below it, but they should work if you do this at the top of each tests files (before importing my_tool or any other py file in the same directory)</p> <pre><code>import...
1
2016-09-28T23:09:09Z
[ "python", "python-2.7", "import", "pycharm", "packages" ]
How do you organise a python project that contains multiple packages so that each file in a package can still be run individually?
39,528,736
<p><strong>TL;DR</strong></p> <p>Here's an example repository that is set up as described in the first diagram (below): <a href="https://github.com/Poddster/package_problems" rel="nofollow">https://github.com/Poddster/package_problems</a></p> <p>If you could please make it look like the second diagram in terms of pro...
19
2016-09-16T10:02:06Z
39,778,464
<p>To run it from both command line and act like library while allowing nosetest to operate in a standard manner, I believe you will have to do a double up approach on Imports. </p> <p>For example, the Python files will require:</p> <pre><code>try: import f except ImportError: import tools.f as f </code></pre...
0
2016-09-29T19:26:38Z
[ "python", "python-2.7", "import", "pycharm", "packages" ]
ImportError: No module named pymongo
39,528,898
<p>I'm trying to install <a href="http://api.mongodb.com/python/current/" rel="nofollow">PyMongo</a> Python package with pip. It is required by <a href="https://docs.ansible.com/ansible/mongodb_user_module.html" rel="nofollow">Ansible mongodb_user module</a>.</p> <p>I'm installing pip and pymongo with following Ansibl...
0
2016-09-16T10:10:48Z
39,529,692
<p>It turned out that I have two versions of python installed (2.6 and 2.7). Even though default is 2.7, my Ansible script installed <code>pymongo</code> under 2.6 folder <code>/usr/local/lib64/python2.6/site-packages</code></p> <p>I found that out by running <code>$ python-pip show pymongo</code> and <code>$ python2....
0
2016-09-16T10:50:48Z
[ "python", "ansible", "pymongo" ]
Pyspark - Get all parameters of models created with ParamGridBuilder
39,529,012
<p>Im using pySpark 2.0 for a kaggle competition. I'd like to know the behavior of a model (randomForest) depending on different parameters. ParamGridBuilder() allows to specify different values for a single parameters, and then perform (i guess) a cartesian product of the entire set of parameters. Assuming my datafram...
0
2016-09-16T10:17:59Z
39,531,097
<p>Long story short you simply cannot get parameters for all models because, <a href="http://stackoverflow.com/a/38874828/1560062">similarly to <code>CrossValidator</code></a>, <code>TrainValidationSplitModel</code> retains only the best model. These classes are designed for semi-automated model selection not explorati...
1
2016-09-16T12:06:26Z
[ "python", "machine-learning", "pyspark", "hyperparameters" ]
Upload multiple files using simple-salesforce python
39,529,028
<p>I started learning SalesForce and developing apps using django.</p> <p>I need assistance with uploading a file to salesforce, For that I read <a href="https://github.com/simple-salesforce/simple-salesforce" rel="nofollow">simple-salesforce</a> and <a href="https://gist.github.com/wadewegner/df609a495df2e4bd7a07" re...
1
2016-09-16T10:18:41Z
39,579,090
<p>Here is the code block I use for uploading files.</p> <pre><code>def load_attachments(sf, new_attachments): ''' Method to attach the Template from the Parent Case to each of the children. @param: new_attachments the dictionary of child cases to the file name of the template ''' url =...
0
2016-09-19T17:42:24Z
[ "python", "django", "salesforce" ]
Selenium and Chrome Driver issues
39,529,341
<p>I am carrying out some automated tasks and am required to run the script as root (for writing dirs to shares etc). The problem Im faced with is that chrome cant be run as root (for obvious reasons) so I have attempted various work arounds. The latest being an attempt to launch chrome using a normal users profile whi...
0
2016-09-16T10:34:00Z
39,530,372
<p>How about using <code>os.setuid</code> to change user id?</p> <p>Also, I haven't looked at it in detail, but the way this works might be of interest : <a href="https://github.com/ionelmc/python-su" rel="nofollow">https://github.com/ionelmc/python-su</a></p>
0
2016-09-16T11:28:12Z
[ "python", "google-chrome", "selenium" ]
Selenium and Chrome Driver issues
39,529,341
<p>I am carrying out some automated tasks and am required to run the script as root (for writing dirs to shares etc). The problem Im faced with is that chrome cant be run as root (for obvious reasons) so I have attempted various work arounds. The latest being an attempt to launch chrome using a normal users profile whi...
0
2016-09-16T10:34:00Z
39,531,557
<p>There are two things you could try. Try running chrome with <code>--no-sandbox.</code> Change ownership OR permission of .pki folder in your home directory. By default its ownership is root. <code>sudo chown -R saurabh:saurabh ~/.pki/</code></p>
0
2016-09-16T12:29:02Z
[ "python", "google-chrome", "selenium" ]
Scrapy settings work using custom_settings but don't work in settings.py
39,529,474
<p>I have been trying to edit some settings in my Spider but they only seem to work when I override the custom_settings dictionary in my custom Spider.</p> <pre><code>custom_settings = { 'DOWNLOAD_DELAY': 1, 'FEED_URI': 'generalspider.json', 'FEED_FORMAT': 'json' } </code></pre> <p>When I put them in sett...
0
2016-09-16T10:40:56Z
39,533,014
<p><code>custom_settings</code> has priority over <code>settings.py</code>. So you'll have to remove the variables in <code>custom_settings</code> for the variables in <code>settings.py</code> to work.</p> <p>Also please check if the class of your spider is derived from other classes (maybe spiders) and those base cla...
2
2016-09-16T13:42:40Z
[ "python", "scrapy", "settings" ]
How to create a Google calendar event with Python and Google calendar API
39,529,481
<p>I started with quickstart (<a href="https://developers.google.com/google-apps/calendar/quickstart/python" rel="nofollow">https://developers.google.com/google-apps/calendar/quickstart/python</a>) and it worked good. Then i tried to insert event with this guide (<a href="https://developers.google.com/google-apps/cale...
0
2016-09-16T10:41:22Z
39,530,400
<p>Problem was in folder ".credentials". I didn't delete it after previous starting of quickstart example with </p> <pre><code>SCOPES = 'https://www.googleapis.com/auth/calendar.readonly' </code></pre> <p>I just deleted this folder and program works. because now </p> <pre><code>SCOPES = 'https://www.googleapis.c...
0
2016-09-16T11:29:32Z
[ "python", "calendar", "google-api", "google-calendar" ]
mod_wsgi: Unable to stat Python home and ImportError: No module named 'encodings'
39,529,574
<p>&nbsp;I am trying to construct a web site on Apache 2.4 using Django and mod_wsgi on Python 3.5.2. But when apache daemon httpd is started, following error message is output on /var/log/httpd/error_log.</p> <blockquote> <p>[Fri Sep 16 17:44:57.145900 2016] [wsgi:warn] [pid 20593] (13)Permission denied: mod_wsgi (...
1
2016-09-16T10:45:40Z
39,530,708
<p>A couple of things to check.</p> <ul> <li><p>The pyenv tool doesn't install Python with a shared library by default. That could result in problems as mod_wsgi wants a shared library. You need to explicitly tell pyenv to build Python with a shared library.</p></li> <li><p>A home directory on many Linux systems is no...
1
2016-09-16T11:44:57Z
[ "python", "django", "apache", "mod-wsgi" ]
Python/Tkinter: Remove titlebar without overrideredirect()
39,529,600
<p>I'm currently working with Tkinter and Python 2.7 on Linux and I was wondering if there was a way to remove the <code>TK()</code> window border frame and title bar without using <code>overrideredirect(1)</code>.</p> <p>I have my own close button and <code>overrideredirect(1)</code> presents me with a few issues tha...
3
2016-09-16T10:46:51Z
39,530,810
<p>The window decoration is all handled by the window manager so what you are trying to do is find a way to tell the window manager to decorate your window differently from a standard application window. Tk provides <code>overrideredirect</code> to have the window manager completely ignore this window but we can also u...
2
2016-09-16T11:51:32Z
[ "python", "python-2.7", "tkinter" ]
How to install matplotlib 2.0 beta on Windows?
39,529,655
<p>I follow the standard installation procedure for matplotlib on Windows. I type the following commands in my terminal:</p> <pre><code> &gt; python -m pip install -U pip setuptools &gt; python -m pip install matplotlib </code></pre> <p>Then I check my matplotlib version:</p> <pre><code> &gt; python &g...
1
2016-09-16T10:49:02Z
39,529,750
<p>for matplotlib 1.5.3</p> <pre><code>conda update matplotlib </code></pre> <p>for matplotlib-2.0.0b4 use wheels provided <a href="http://www.lfd.uci.edu/~gohlke/pythonlibs/#matplotlib" rel="nofollow">here</a> : use the .whl as follows :</p> <pre><code>pip install some-package.whl </code></pre>
1
2016-09-16T10:54:21Z
[ "python", "python-3.x", "matplotlib" ]
Python - Automatically adjust width of an excel file's columns
39,529,662
<p>Newbie - I have a Python script that adjusts the width of different columns of an excel file, according to the values specified:</p> <pre><code>import openpyxl from string import ascii_uppercase newFile = "D:\Excel Files\abc.xlsx" wb = openpyxl.load_workbook(filename = newFile) worksheet = wb.active for ...
0
2016-09-16T10:49:19Z
39,530,261
<p>If possible you should determine the length of the longest entry in the column and use that to set the width.</p> <p>I'm assuming you can make use of for entry in ascii_uppercase.</p> <p>I'm on mobile atm so can't give a concrete code example but what I said before should help you get closer to what you want to ac...
-1
2016-09-16T11:22:06Z
[ "python", "excel", "openpyxl" ]
Python - Automatically adjust width of an excel file's columns
39,529,662
<p>Newbie - I have a Python script that adjusts the width of different columns of an excel file, according to the values specified:</p> <pre><code>import openpyxl from string import ascii_uppercase newFile = "D:\Excel Files\abc.xlsx" wb = openpyxl.load_workbook(filename = newFile) worksheet = wb.active for ...
0
2016-09-16T10:49:19Z
39,530,676
<pre><code>for col in worksheet.columns: max_length = 0 column = col[0].column # Get the column name for cell in col: try: # Necessary to avoid error on empty cells if len(str(cell.value)) &gt; max_length: max_length = len(cell.value) except: p...
4
2016-09-16T11:43:22Z
[ "python", "excel", "openpyxl" ]
Initialization of very big vector in C++
39,529,799
<p>I created very big O(10M) floating point list in python. I would like to use this lookup table in my C++ project. What is the easiest and the most efficient way to transfer this array from python to C++. </p> <p>My first idea was to generate c++ function, which is responsible for initializations of such long vecto...
1
2016-09-16T10:57:33Z
39,530,210
<p>As you have noticed, the compiler crashes on such big data arrays.</p> <p>What you can do besides of reading a binary file (since you don't want to do that) is to link with an assembly file. It still makes the executable self-sufficient and GAS is much more tolerant to big files. Here's an example of some asm file ...
0
2016-09-16T11:19:53Z
[ "python", "c++", "arrays" ]
Initialization of very big vector in C++
39,529,799
<p>I created very big O(10M) floating point list in python. I would like to use this lookup table in my C++ project. What is the easiest and the most efficient way to transfer this array from python to C++. </p> <p>My first idea was to generate c++ function, which is responsible for initializations of such long vecto...
1
2016-09-16T10:57:33Z
39,530,626
<p>Here's a simple example of how to write Python float data to a binary file, and how to read that data in C. To encode the data, we use the <code>struct</code> module.</p> <h2>savefloat.py</h2> <pre class="lang-python prettyprint-override"><code>#!/usr/bin/env python3 from struct import pack # The float data to sa...
2
2016-09-16T11:40:34Z
[ "python", "c++", "arrays" ]
Initialization of very big vector in C++
39,529,799
<p>I created very big O(10M) floating point list in python. I would like to use this lookup table in my C++ project. What is the easiest and the most efficient way to transfer this array from python to C++. </p> <p>My first idea was to generate c++ function, which is responsible for initializations of such long vecto...
1
2016-09-16T10:57:33Z
39,531,749
<p>If you're using GNU tools it is rather easy to directly use <code>objcopy</code> to achieve that which is suggested by Jean-Francois; combining with python script of PM2Ring which writes a binary array, you can execute:</p> <pre><code>objcopy -I binary test.data -B i386:x86-64 -O elf64-x86-64 testdata.o </code></pr...
4
2016-09-16T12:38:02Z
[ "python", "c++", "arrays" ]
Select k random rows from postgres django ORM
39,529,824
<p>We have a requirement, that we want to select k random rows from a database. So, our intial thought was going like this :-</p> <pre><code>table.objects.filter(..).order_by('?')[:k] </code></pre> <p>but then we read over the internet that this is highly inefficient solution so we came up with this (not so innovati...
0
2016-09-16T10:58:48Z
39,530,347
<p>As Daniel Roseman mentioned in a comment, the reason why</p> <pre><code>random.sample(table.objects.filter(..), k) </code></pre> <p>is slow, is because you'd have to fetch <em>all</em> objects, then find <code>k</code> out of that query set.</p> <p>I have encountered exactly the same type of problem and the way w...
0
2016-09-16T11:26:43Z
[ "python", "django", "postgresql", "orm" ]
Select k random rows from postgres django ORM
39,529,824
<p>We have a requirement, that we want to select k random rows from a database. So, our intial thought was going like this :-</p> <pre><code>table.objects.filter(..).order_by('?')[:k] </code></pre> <p>but then we read over the internet that this is highly inefficient solution so we came up with this (not so innovati...
0
2016-09-16T10:58:48Z
39,532,581
<p>Well, if you know roughly the size of your table you can use the new <a href="https://www.postgresql.org/docs/current/static/sql-select.html#SQL-FROM" rel="nofollow">TABLESAMPLE</a> clause to select a percentage of the rows at random. Then, you can always LIMIT it afterwards.</p> <p>A short blog article covering it...
0
2016-09-16T13:21:53Z
[ "python", "django", "postgresql", "orm" ]
Can we check multiple variables against same expression in python
39,529,890
<p>I know we can check a variable against multiple conditions as </p> <pre><code>if all(x &gt;= 2 for x in (A, B, C, D)): print A, B, C, D </code></pre> <p>My question is , can we do the reverse? can we check me or two variables against same conditions(one or two)</p> <pre><code>null_check = (None,'','None') if...
0
2016-09-16T11:02:18Z
39,529,962
<p>You can put the variables in a <code>list</code> or <code>tuple</code>, then use the same idea using <code>all</code> to check that none of them are in your <code>tuple</code>.</p> <pre><code>if all(var not in null_check for var in (variable1, variable2)): print (variable1, variable2) </code></pre>
3
2016-09-16T11:05:44Z
[ "python" ]
Can we check multiple variables against same expression in python
39,529,890
<p>I know we can check a variable against multiple conditions as </p> <pre><code>if all(x &gt;= 2 for x in (A, B, C, D)): print A, B, C, D </code></pre> <p>My question is , can we do the reverse? can we check me or two variables against same conditions(one or two)</p> <pre><code>null_check = (None,'','None') if...
0
2016-09-16T11:02:18Z
39,529,968
<p>You can do this very similarly to your first code block:</p> <pre><code>null_check = (None,'','None') if all(variable not in null_check for variable in (variable1, variable2)): print (variable1, variable2) </code></pre> <p>Or:</p> <pre><code>null_check = (None,'','None') variables = variable1, variable2 # def...
1
2016-09-16T11:05:59Z
[ "python" ]
Can we check multiple variables against same expression in python
39,529,890
<p>I know we can check a variable against multiple conditions as </p> <pre><code>if all(x &gt;= 2 for x in (A, B, C, D)): print A, B, C, D </code></pre> <p>My question is , can we do the reverse? can we check me or two variables against same conditions(one or two)</p> <pre><code>null_check = (None,'','None') if...
0
2016-09-16T11:02:18Z
39,530,014
<p>No you can't do that, but as a pythonic approach you can put your <code>null_check</code> items in a <code>set</code>. And check the intersection:</p> <pre><code>null_check = {None,'','None'} if null_check.intersection({var1, var2}): # instead of `or` or `any()` function # pass if len(null_check.intersection(...
1
2016-09-16T11:08:15Z
[ "python" ]
Plotting histograms in Python using pandas
39,529,941
<p>I'm trying to create a histogram with two data sets overlying each other, however whenever I plot it using pandas.DataFrame.hist(), it creates two graphs:</p> <p><img src="http://i.stack.imgur.com/ldlcs.png" alt=""></p> <p>The code is simply:</p> <pre><code>ratios.hist(bins = 100) plt.show() </code></pre> <p>whe...
0
2016-09-16T11:04:57Z
39,530,135
<p>Try <a href="http://pandas.pydata.org/pandas-docs/stable/visualization.html#histograms" rel="nofollow">plot.hist</a> instead:</p> <pre><code>ratios = pd.DataFrame(np.random.normal((1, 2), size=(100, 2))) ratios.hist(bins=10) </code></pre> <p>This generates:</p> <p><a href="http://i.stack.imgur.com/fyop0.png" rel=...
1
2016-09-16T11:14:49Z
[ "python", "pandas", "histogram" ]