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
Call C code with cython and cython-code from c
38,477,635
<p>this is my first question here. Up to now I got a lot of answers by other questions, but now there is no more answer.</p> <p>The aim of my work is to work with a developed stack of a communication-module (get as .so), which is written in C. I want to combine it with python (cython), because all other software is al...
1
2016-07-20T09:39:05Z
38,481,246
<p>In <code>caller.pyx</code> there is </p> <pre><code>def run(): cdef extern from "main.c": int main() main() </code></pre> <p>that causes trouble by including <code>main.c</code>, that in turn includes <code>caller.h</code> which is something unexpected by the code generated by cython. Furthermore, ...
0
2016-07-20T12:24:33Z
[ "python", "cython" ]
RandomForest Regressor: Predict and check performance
38,477,643
<p>I am trying predict price for 5 days in future. I followed <a href="http://www.analyticsvidhya.com/blog/2015/09/build-predictive-model-10-minutes-python/" rel="nofollow">this</a> tutorial. This tutorial is about predicting categorical variable and is hence using RandomForest Classifier. I am using the same approach ...
0
2016-07-20T09:39:28Z
38,478,464
<p>Your x_validate is 'pandas.core.series.Series' in nature. So you could execute this: x_validate[0:5]</p> <p>This will solve your 2nd question by calculating the R square value. rf.score(x_train,y_train)</p>
1
2016-07-20T10:15:25Z
[ "python", "regression", "random-forest" ]
Query string in Bokeh Python
38,477,679
<p>I have developed a Bokeh App. hosted on Windows Server. I need query string passed in browser to manipulate my plots.</p> <pre><code>192.168.190.126/bokehApp?csv=xyz.csv&amp;tsv=abc.tsv </code></pre> <p>I want to know the values after ?.</p>
0
2016-07-20T09:41:22Z
38,479,593
<p>As of <code>0.12</code> this is an <a href="https://github.com/bokeh/bokeh/issues/4828" rel="nofollow">open feature request</a>, which will hopefully be implemented soon. The issue does have a prototype implementation, if you are able to run from your own forked or patched version. </p>
0
2016-07-20T11:08:33Z
[ "python", "bokeh" ]
Python - nested for loops and index out of range
38,477,807
<p>I'm rather new to Python, and am running into the following error when using a nested for loop</p> <pre><code>IndexError: list index out of range </code></pre> <p>Here is my code</p> <pre><code>count = 0 count2 = 1 rlength = range(len(records)) for i in rlength: ex = records[count].id for bla in rlength: ...
0
2016-07-20T09:47:19Z
38,478,010
<p>The loop should fail for <code>i=1</code>. Why ?<br> When <code>i=1, count2 = 2 (= count + 1, and count = 0+1 = 1)</code><br> In the inner loop, <code>count2 goes from 2 to 2+len(records)-1-1</code> (since we increment after looking at the values) = <code>len(records)</code><br> But there is no <code>records[len(rec...
0
2016-07-20T09:55:31Z
[ "python", "list", "loops", "for-loop", "nested" ]
Python - nested for loops and index out of range
38,477,807
<p>I'm rather new to Python, and am running into the following error when using a nested for loop</p> <pre><code>IndexError: list index out of range </code></pre> <p>Here is my code</p> <pre><code>count = 0 count2 = 1 rlength = range(len(records)) for i in rlength: ex = records[count].id for bla in rlength: ...
0
2016-07-20T09:47:19Z
38,478,233
<p>If I understand what you are trying to do, I'm not sure you need the <code>count</code> and <code>count2</code> at all. I think you can just use the numbers generated by your loop. I suggest using <code>enumerate()</code> instead of <code>range(len())</code>.</p> <pre><code>for i1,rlength1 in enumerate(records): ...
1
2016-07-20T10:05:05Z
[ "python", "list", "loops", "for-loop", "nested" ]
Insecure rfcomm connection in Python
38,477,848
<p>I would like to establish a bluetooth connection from an android device to a Raspberry Pi without pairing. The language used in RPi is Python. I am connecting using <code>createInsecureRfcommSocketToServiceRecord</code> from android. </p> <p>However the connection is established only when the two devices are paired...
0
2016-07-20T09:49:04Z
38,592,672
<p>I was able to connect to the Raspberry Pi without pairing. For this I had to make the RPi discoverable. Then I used <code>socket.connect()</code> from my Nexus running on Marshmallow. By doing this I was able to get the MAC address of my Nexus in the RPi. Only problem is that I get a pairing request every time I con...
0
2016-07-26T14:29:29Z
[ "python", "bluetooth", "raspberry-pi", "rfcomm" ]
Python argparse appears in gc.garbage
38,477,881
<p>I'm trying to debug a memory leak in a python application and I can see a lot of non collected object belonging to the module <code>argparse</code> </p> <p>Here a minimal script reproducing the error</p> <pre><code>import gc gc.set_debug(gc.DEBUG_LEAK) def get_cli_arguments(): import argparse parser = arg...
0
2016-07-20T09:50:26Z
38,478,224
<p>This line</p> <pre><code>gc.set_debug(gc.DEBUG_LEAK) </code></pre> <p>Is <a href="https://docs.python.org/3/library/gc.html#gc.DEBUG_LEAK" rel="nofollow">equivalent to saying</a></p> <pre><code>gc.set_debug(gc.DEBUG_COLLECTABLE | gc.DEBUG_UNCOLLECTABLE | gc.DEBUG_SAVEALL) </code></pre> <p>And <a href="https://do...
2
2016-07-20T10:04:40Z
[ "python", "memory-leaks", "garbage-collection" ]
Smallest positive float64 number
38,477,908
<p>I need to find a <code>numpy.float64</code> value that is as close to zero as possible. </p> <p>Numpy offers several constants that allow to do something similar:</p> <ul> <li><code>np.finfo(np.float64).eps = 2.2204460492503131e-16</code></li> <li><code>np.finfo(np.float64).tiny = 2.2250738585072014e-308</code></l...
6
2016-07-20T09:51:30Z
38,481,260
<p>Use <code>np.nextafter</code>. </p> <pre><code>&gt;&gt;&gt; import numpy as np &gt;&gt;&gt; np.nextafter(0, 1) 4.9406564584124654e-324 &gt;&gt;&gt; np.nextafter(np.float32(0), np.float32(1)) 1.4012985e-45 </code></pre>
3
2016-07-20T12:25:15Z
[ "python", "numpy" ]
python django exporing excel server down
38,477,929
<p>My website has a feature of exporting daily report in excel which may vary according to users. Due to some reason i can't consider redis or memcache. For each user the no of rows in db are around 2-5 lacks. when user call the export-to-excel feature it takes 5-10 minutes to export and till that website all resources...
2
2016-07-20T09:52:09Z
38,495,932
<ul> <li>Instead of a <code>HttpResponse</code> use <a href="https://docs.djangoproject.com/en/1.9/howto/outputting-csv/#streaming-large-csv-files" rel="nofollow">StreamingHttpResponse</a></li> </ul> <blockquote> <p>Streaming a file that takes a long time to generate you can avoid a load balancer dropping a connecti...
1
2016-07-21T05:56:03Z
[ "python", "django", "optimization" ]
Pandas: Union strings in dataframe
38,477,990
<p>I have a dataframe <code>df</code></p> <pre><code>ID active_seconds domain subdomain search_engine search_term 0120bc30e78ba5582617a9f3d6dfd8ca 35 vk.com vk.com None None 0120bc30e78ba5582617a9f3d6dfd8ca 54 vk.com vk.com None None 0120bc30e78ba5582617a9f3d6dfd8ca 34 vk.com vk.com None...
3
2016-07-20T09:54:40Z
38,478,799
<p>This get's real close. Not sure if getting that order correct is important to you.</p> <p>Also, I made an assumption that I should <code>groupby</code> <code>ID</code>. This means that if the same <code>ID</code> spans across another <code>ID</code> and still in the same subdomain, I'll aggregate the <code>active...
3
2016-07-20T10:29:40Z
[ "python", "pandas" ]
char array to unsigned char python
38,478,009
<p>I'm trying to translate this c code into python, but Im having problems with the <code>char*</code> to <code>ushort*</code> conversion:</p> <pre><code>void sendAsciiCommand(string command) { unsigned int nchars = command.length() + 1; // Char count of command string unsigned int nshorts = ceil(nchars / 2); ...
-3
2016-07-20T09:55:24Z
38,481,711
<p>The exception text:</p> <pre><code>ValueError: string length not a multiple of item size </code></pre> <p>means what is says, i.e., the length of the string from which you are trying to create an array must be a multiple of the item size. In this case the item size is that of an <code>unsigned short</code>, which ...
0
2016-07-20T12:44:47Z
[ "python", "c++" ]
DecisionTreeClassifier's fit() returns different trees with same data
38,478,015
<p>I have been playing around with sklearn a bit and following some simple examples online using the iris data. </p> <p>I've now begun to play with some other datas. I'm not sure if this behaviour is correct and I'm misunderstanding but everytime I call fit(x,y) I get completely different tree data. So when I then run...
0
2016-07-20T09:55:51Z
38,480,260
<p>There is a random component to the algorithm, which you can read about in the <a href="http://scikit-learn.org/stable/modules/tree.html#tree" rel="nofollow">user guide</a>. The relevant part:</p> <blockquote> <p>The problem of learning an optimal decision tree is known to be NP-complete under several aspects of o...
1
2016-07-20T11:37:52Z
[ "python", "machine-learning", "scikit-learn" ]
Kivy button and game score
38,478,189
<p>I am new to programming and decided to create a game in Kivy. I am stuck with quite simple problem. If there is a button and a label which shows the score, how can I use the <code>on_press</code> event to increment the score? </p> <p>e.g. when the button is pressed, then the score changes to 1 and so on.</p> <p>Al...
0
2016-07-20T10:02:36Z
38,480,682
<p>You can use python only, or kv language. That is entirely up to you. In this case we make the buttons call function, increment the label text. I will make two examples. One with python only, and one in conjunction with kivy language.</p> <p>This is an example in python only:</p> <pre><code>from kivy.app import App...
0
2016-07-20T11:58:30Z
[ "python", "button", "label", "kivy" ]
finding out complementary/opposite color of a given color
38,478,409
<p>I am trying to find out the complementary color of a given color using Python. here is my code. the code returns error message telling "AttributeError: 'list' object has no attribute 'join'" I need a hint. In addition, there might be a more robust code which calculates the opposite/complementary color, which I am b...
0
2016-07-20T10:13:00Z
38,478,744
<p>Your <code>join</code> and <em>formatting</em> needed a fix. Lists do not have a <code>join</code> method, strings do:</p> <pre><code>def complementaryColor(my_hex): """Returns complementary RGB color Example: &gt;&gt;&gt;complementaryColor('FFFFFF') '000000' """ if my_hex[0] == '#': ...
1
2016-07-20T10:26:49Z
[ "python" ]
Gae/cloudsql error: Access denied for user 'root'@'cloudsqlproxy
38,478,451
<p>I am running GAE/python application (App Engine Standard Edition) in same project as (2nd Gen) CloudSQL, in same Region as well.</p> <p>However I continue to get following error</p> <pre><code>OperationalError: (1045, "Access denied for user 'root'@'cloudsqlproxy~xx.xxx.xx.xx' (using password: NO)") </code></pre> ...
1
2016-07-20T10:14:39Z
38,487,688
<p>If you set a root password for your instance, you will need to specify that password when connecting.</p> <p>First Generation instances come out of the box with a root user with an empty password, but Second Generation instances do not. For a Second Generation instance, you should set the root password and use that...
2
2016-07-20T18:01:46Z
[ "python", "google-app-engine", "google-cloud-sql" ]
Date Conversion Difference Between Python Datetime and Excel
38,478,748
<p>I’m trying to parse data that I’ve received from an excel file in Python. For this I am using the <code>xlrd</code> library. I have a cell in Excel whose value is 5/16/2016 12:15 and I receive it in Python as 42506.6493. I understand that Excel saves the date as the number of days since 1/1/1900. So in Python Iâ...
0
2016-07-20T10:27:04Z
38,492,379
<p>Please consult the xlrd <a href="http://xlrd.readthedocs.io/en/latest/index.html" rel="nofollow">documentation</a>, particularly the section on <a href="http://xlrd.readthedocs.io/en/latest/dates.html" rel="nofollow">dates in Excel</a>.</p> <p>Dates don't really start at 1900-01-01. You have a two-day difference be...
1
2016-07-20T23:16:33Z
[ "python", "excel", "datetime", "xlrd" ]
Cost function for word2vec
38,478,776
<p>I am currently doing text classification with pretrain by <code>word2vec</code>. But before feeding to <code>Convolution neural network</code>, I have to write cost function. </p> <p>Here is my code:</p> <pre><code>W = tf.Variable(tf.constant(0.0, shape=[vocabulary_size, embedding_size]), trainable=Fal...
0
2016-07-20T10:28:20Z
39,760,007
<p>The error you got is because the input vector to <code>tf.nn.conv2d</code> expects a tensor of shape:</p> <pre><code>[batch, in_height, in_width, in_channels] </code></pre> <p>and what you have here is with shape (50000, 128). You might want to use <code>embedded_chars_expanded</code> as the input.</p>
1
2016-09-29T01:32:27Z
[ "python", "tensorflow", "word2vec" ]
Unable to import boto3 library after installation
38,478,850
<p>I installed boto3 library from AWS SDK but when I try to import in python interpreter, I get error. Here is the traceback:</p> <blockquote> <blockquote> <blockquote> <p>import boto3 Traceback (most recent call last): File "", line 1, in File "/home/rahul/rahul/boto3/boto3/<strong>...
0
2016-07-20T10:32:24Z
38,479,249
<p>Apparently you have installed boto3 but not botocore</p> <p>botocore is the basis of boto3 but is lower level</p> <p>See <a href="https://pypi.python.org/pypi/botocore" rel="nofollow">https://pypi.python.org/pypi/botocore</a></p>
0
2016-07-20T10:52:34Z
[ "python", "django", "amazon-web-services", "amazon-sqs", "boto3" ]
PyParsing Different String Lengths
38,478,877
<p>I'm writing a parser for firewall configuration file. I am new to PyParsing and Python in general.</p> <p>The question is how do i parse if more then 3 arguments occur, (xxxx,xxxx,xxxx) != (xxxx,xxxx,xxxx,xxxx), All rules are working fine and parse everything correctly if each line contain no more that 3 strings, b...
1
2016-07-20T10:34:01Z
38,479,950
<p>If you want to match any number of expressions with a certain delimiter, use <a href="http://infohost.nmt.edu/~shipman/soft/pyparsing/web/delimitedList.html" rel="nofollow">PyParsing's delimitedList</a>. By default it allows whitespace around the delimiters; add <code>combine=True</code> to require no whitespace.</p...
1
2016-07-20T11:24:25Z
[ "python", "parsing", "firewall", "rules", "pyparsing" ]
Delay when receiving UDP packets in Python in real-time
38,478,913
<p>I am using <a href="https://github.com/opentrack/opentrack" rel="nofollow">Opentrack</a> to track head movements and the coordinates are sent through UDP to my Python program. The program works in the sense that it receives the coordinates correctly, but however I have noticed that there is a large delay before info...
0
2016-07-20T10:35:43Z
38,503,864
<p>So I solved it by adding the line</p> <pre><code>self.s.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 1) </code></pre> <p>in my code. This sets the buffer to size 1 which solved my problem. </p>
0
2016-07-21T12:07:20Z
[ "python", "udp" ]
Getting Value Error while adding days to a particular date
38,478,932
<p>I'm using Python to add 2 days to a particular date in Python. Using <code>datetime.now()</code>, I'm able to add 2 days. But not using a particular date. Here's the code:</p> <pre><code>import datetime start_date = datetime.datetime.strptime('7/18/2016','%m/%d/%y') date_to_start_predicting = start_date + datetime...
-2
2016-07-20T10:36:25Z
38,478,990
<p>Use this:</p> <pre><code>start_date = datetime.datetime.strptime('7/18/2016','%m/%d/%Y') </code></pre> <p>(I've changed the lowercase <code>y</code> to an uppercase <code>Y</code>.)</p>
0
2016-07-20T10:39:49Z
[ "python", "datetime" ]
Getting Value Error while adding days to a particular date
38,478,932
<p>I'm using Python to add 2 days to a particular date in Python. Using <code>datetime.now()</code>, I'm able to add 2 days. But not using a particular date. Here's the code:</p> <pre><code>import datetime start_date = datetime.datetime.strptime('7/18/2016','%m/%d/%y') date_to_start_predicting = start_date + datetime...
-2
2016-07-20T10:36:25Z
38,479,000
<p>There is nothing wrong with the "adding" part. You just use the wrong formating. </p> <p>You should change it to:</p> <pre><code>start_date = datetime.datetime.strptime('7/18/2016','%m/%d/%Y') </code></pre> <p>as you can see <a href="https://docs.python.org/2/library/datetime.html" rel="nofollow">here</a>.</p> <...
0
2016-07-20T10:40:12Z
[ "python", "datetime" ]
Getting Value Error while adding days to a particular date
38,478,932
<p>I'm using Python to add 2 days to a particular date in Python. Using <code>datetime.now()</code>, I'm able to add 2 days. But not using a particular date. Here's the code:</p> <pre><code>import datetime start_date = datetime.datetime.strptime('7/18/2016','%m/%d/%y') date_to_start_predicting = start_date + datetime...
-2
2016-07-20T10:36:25Z
38,479,002
<p>You are parsing the string <code>'7/18/2016'</code> with the format <code>'%m/%d/%y'</code>. </p> <p><code>%y</code> tries to parse the year part in 2 digits format (so the year of your date object is 1920). So <code>2016</code> becomes <code>20</code> and <code>16</code> is left over which is what the error says.<...
2
2016-07-20T10:40:19Z
[ "python", "datetime" ]
Get first word after substring in string
38,478,952
<p>Hi I'm trying to get the word after a specified sub string, like...</p> <pre><code>str = Quote from: Bob1 ... </code></pre> <p>I'm trying to search for everytime Quote from: appears and get the word after, in this case Bob1.</p> <p>I've tried:</p> <pre><code>print((re.findall(r'Quote from:\a\X\\9', str))) </code...
-3
2016-07-20T10:37:28Z
38,479,023
<p>This should work for you, using <code>split</code>.</p> <pre><code>&gt;&gt;&gt; str = "Quote from: Bob1 ..." &gt;&gt;&gt; str.split("Quote from:")[1].split()[0] 'Bob1' </code></pre>
4
2016-07-20T10:41:26Z
[ "python" ]
Get first word after substring in string
38,478,952
<p>Hi I'm trying to get the word after a specified sub string, like...</p> <pre><code>str = Quote from: Bob1 ... </code></pre> <p>I'm trying to search for everytime Quote from: appears and get the word after, in this case Bob1.</p> <p>I've tried:</p> <pre><code>print((re.findall(r'Quote from:\a\X\\9', str))) </code...
-3
2016-07-20T10:37:28Z
38,479,061
<pre><code>import re s = 'Quote from: Bob1 ...' re.sub(r'Quote from: (\S+).*', r'\1', s) 'Bob1' </code></pre>
1
2016-07-20T10:43:43Z
[ "python" ]
django-debug-toolbar breaking on admin while getting sql stats
38,479,063
<p>Environment:django debug toolbar breaking while using to get sql stats else it's working fine on the other pages, breaking only on the pages which have sql queries.</p> <pre><code>Request Method: GET Request URL: http://www.blog.local/admin/ Django Version: 1.9.7 Python Version: 2.7.6 Installed Applications: [ .....
19
2016-07-20T10:43:45Z
38,479,670
<p>sqlparse latest version was released today and it's not compatible with django-debug-toolbar version 1.4, Django version 1.9</p> <p>workaround is force pip to install <code>sqlparse==0.1.19</code></p>
34
2016-07-20T11:12:25Z
[ "python", "django", "django-admin", "django-debug-toolbar" ]
django-debug-toolbar breaking on admin while getting sql stats
38,479,063
<p>Environment:django debug toolbar breaking while using to get sql stats else it's working fine on the other pages, breaking only on the pages which have sql queries.</p> <pre><code>Request Method: GET Request URL: http://www.blog.local/admin/ Django Version: 1.9.7 Python Version: 2.7.6 Installed Applications: [ .....
19
2016-07-20T10:43:45Z
38,623,348
<p>the latest version of <code>sqlparse</code> is not compatible with <code>django-debug-toolbar==1.4</code>. </p> <p>Your choices are:</p> <ul> <li>upgrade <code>django-debug-toolbar</code> to <code>1.5</code></li> <li>force install <code>sqlparse==0.1.19</code></li> </ul>
6
2016-07-27T21:17:56Z
[ "python", "django", "django-admin", "django-debug-toolbar" ]
django-debug-toolbar breaking on admin while getting sql stats
38,479,063
<p>Environment:django debug toolbar breaking while using to get sql stats else it's working fine on the other pages, breaking only on the pages which have sql queries.</p> <pre><code>Request Method: GET Request URL: http://www.blog.local/admin/ Django Version: 1.9.7 Python Version: 2.7.6 Installed Applications: [ .....
19
2016-07-20T10:43:45Z
38,930,362
<p>@Rex Salisbury That's not correct.</p> <p>You have to install</p> <pre><code>django-debug-toolbar==1.5 sqlparse==0.2.0 </code></pre> <p>or</p> <pre><code>django-debug-toolbar==1.4 sqlparse==0.1.19 </code></pre> <p>Tested on Cloud9, with django 1.9.2</p>
3
2016-08-13T07:30:05Z
[ "python", "django", "django-admin", "django-debug-toolbar" ]
django-debug-toolbar breaking on admin while getting sql stats
38,479,063
<p>Environment:django debug toolbar breaking while using to get sql stats else it's working fine on the other pages, breaking only on the pages which have sql queries.</p> <pre><code>Request Method: GET Request URL: http://www.blog.local/admin/ Django Version: 1.9.7 Python Version: 2.7.6 Installed Applications: [ .....
19
2016-07-20T10:43:45Z
39,799,361
<p>Sorry,but for me, with Django 1.8.11, it only worked with this:</p> <pre><code>django-debug-toolbar==1.5 sqlparse==0.2.1 </code></pre>
0
2016-09-30T20:09:01Z
[ "python", "django", "django-admin", "django-debug-toolbar" ]
DropWhile to extract between two specific lines
38,479,076
<p>practising using DropWhile in Python, and have hit a bump.</p> <p>For example if this is line in a file:</p> <pre><code>Test1 Test2 Test3 Test4 Test5 Test6 Test7 Test8 Test9 Test10 </code></pre> <p>And I want to pull out the lines between Test5 and Test8.</p> <p>I know how to do this another way (for line in fil...
0
2016-07-20T10:44:14Z
38,479,141
<p><code>DropWhile</code> is not what you need, from a functional aproach you have to use filter:</p> <pre><code>filter(lambda line: 5 &lt; int(line.strip()[-1]) &lt; 8, dataset) </code></pre> <p>DropWhile will stop once the condition is reached one time, so the list will continue to have the rest of the values once ...
2
2016-07-20T10:46:45Z
[ "python", "itertools" ]
DropWhile to extract between two specific lines
38,479,076
<p>practising using DropWhile in Python, and have hit a bump.</p> <p>For example if this is line in a file:</p> <pre><code>Test1 Test2 Test3 Test4 Test5 Test6 Test7 Test8 Test9 Test10 </code></pre> <p>And I want to pull out the lines between Test5 and Test8.</p> <p>I know how to do this another way (for line in fil...
0
2016-07-20T10:44:14Z
38,480,547
<p>If you plan to use <code>dropwhile()</code> on your dataset, then you need to also make use of <code>takewhile()</code> to grab the required lines as follows:</p> <pre><code>from itertools import takewhile, dropwhile for line in takewhile(lambda x: int(x.strip()[-1]) &lt; 8, dropwhile(lambda x: int(x.strip()[-1...
0
2016-07-20T11:52:08Z
[ "python", "itertools" ]
How to extract values from json which has multiple hierarchies inside using Python
38,479,152
<p>Below is the json content, how to extract values for "GBL_ACTIVE_CPU" using python.</p> <pre><code>{ "test": "00.00.004", "Metric Payload": [ { "ClassName": "test", "SystemId": "test", "uri": "http://test/testmet", "MetaData...
0
2016-07-20T10:47:20Z
38,479,190
<p>In <strong>JSON</strong> "<strong>Instances</strong>" is a list. You are accessing it like a dict. So it have 2 ways on is static other is dynamic.</p> <p>If you like to use static way:-</p> <pre><code>result = json.loads(jsonoutput) print(result) node = result["Metric Payload"][0]["Instances"][0]["GBL_ACTIVE_CPU"...
4
2016-07-20T10:49:43Z
[ "python", "json", "extract" ]
How to run python-daemon with twisted
38,479,280
<p>I am trying to run a daemon process using python-daemon library. I am also using twisted for networking.</p> <p>The server is pretty simple:</p> <pre><code>class Echoer(pb.Root): def remote_echo(self, st): print 'echoing:', st return st if __name__ == '__main__': serverfactory = pb.PBServe...
0
2016-07-20T10:53:58Z
38,483,349
<p>Twisted has daemonizing capabilities built-in already, so you don't need to add <code>python-daemon</code>. There may be some funny behavior overlaps between the two that may be biting you. As you've seen, once you've gotten your application it's pretty easy to run in the foreground as you've done above. It's also p...
0
2016-07-20T13:56:51Z
[ "python", "twisted", "daemon" ]
Python optimize fmin gives A value in x_new is above the interpolation range error
38,479,760
<p>I am trying to interpolate the minimum of a quadratic function of which I have three samples. The first test in the code snippet below works. It gives: <a href="http://i.stack.imgur.com/tzTYq.png" rel="nofollow"><img src="http://i.stack.imgur.com/tzTYq.png" alt="test 1"></a></p> <p>In the second test there are two ...
0
2016-07-20T11:16:11Z
38,498,109
<p>Analytically works like a charm</p> <pre><code>def getMinFit(x, y): p = np.polyfit(x, y, 2) xmin = -p[1]/(2*p[0]) ymin = np.polyval(p, xmin) return xmin, ymin </code></pre> <p><a href="http://i.stack.imgur.com/PfyQq.png" rel="nofollow"><img src="http://i.stack.imgur.com/PfyQq.png" alt="enter image ...
0
2016-07-21T07:48:10Z
[ "python", "optimization", "scipy", "interpolation" ]
Pandas: replace values in dataframe
38,479,841
<p>I have a dataframe df</p> <pre><code>ID active_seconds domain subdomain search_engine search_term 0120bc30e78ba5582617a9f3d6dfd8ca 35 city-link.com msk.city-link.com None None 0120bc30e78ba5582617a9f3d6dfd8ca 54 vk.com vk.com None None 0120bc30e78ba5582617a9f3d6dfd8ca 34 mts.ru shop.mt...
0
2016-07-20T11:19:56Z
38,480,685
<p>First, you need to get records where domain field in urls list:</p> <pre><code>domains_in_urls = df[df.domain.isin(urls)] </code></pre> <p>Next, you have to take these records and find out records where subdomain field are not in urls:</p> <pre><code>subdomains_not_in_urls = domains_in_urls[~domains_in_urls.subdo...
2
2016-07-20T11:58:38Z
[ "python", "pandas" ]
How to add axes to subplots?
38,479,863
<p>I have a series of related functions that I plot with <code>matplotlib.pyplot.subplots</code>, and I need to include in each subplot a zoomed part of the corresponding function.</p> <p>I started doing it like explained <a href="http://stackoverflow.com/questions/13583153/">here</a> and it works perfectly when there...
0
2016-07-20T11:21:21Z
38,480,761
<p>If I understood well, You can use <code>inset_axes</code></p> <pre><code>import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.axes_grid.inset_locator import inset_axes x = np.arange(-10, 10, 0.01) sinx = np.sin(x) tanx = np.tan(x) fig, ax = plt.subplots( 1, 2, sharey='row', figsize=(9, 3) ) for ...
1
2016-07-20T12:01:56Z
[ "python", "matplotlib", "subplot" ]
Decoding ampersand hash strings (&#124&#120&#97)etc
38,479,865
<p>The solutions in other answers do not work when I try them, the same string outputs when I try those methods.</p> <p>I am trying to do web scraping using Python 2.7. I have the webpage downloaded and it has some characters which are in the form <code>&amp;#120</code> where 120 seems to represent the ascii code. I t...
4
2016-07-20T11:21:25Z
38,481,378
<p>The correct format for character reference is <code>&amp;#nnnn;</code> so the <code>;</code> is missing in your example. You can add the <code>;</code> and then use HTMLParser.unescape() :</p> <pre><code>from HTMLParser import HTMLParser import re x ='&amp;#66&amp;#108&amp;#97&amp;#115&amp;#116&amp;#101&amp;#114&am...
1
2016-07-20T12:30:54Z
[ "python", "html", "decode" ]
Decoding ampersand hash strings (&#124&#120&#97)etc
38,479,865
<p>The solutions in other answers do not work when I try them, the same string outputs when I try those methods.</p> <p>I am trying to do web scraping using Python 2.7. I have the webpage downloaded and it has some characters which are in the form <code>&amp;#120</code> where 120 seems to represent the ascii code. I t...
4
2016-07-20T11:21:25Z
38,482,291
<p>Depending on what you're doing, you may wish to convert that data to valid HTML <a href="https://en.wikipedia.org/wiki/List_of_XML_and_HTML_character_entity_references#Character_reference_overview" rel="nofollow">character references</a> so you can parse it in context with a proper HTML parser.</p> <p>However, it's...
3
2016-07-20T13:11:32Z
[ "python", "html", "decode" ]
Plot bar graph using the first column as x axe
38,479,972
<p>I have a DataFrame like this</p> <pre><code>action | Mark | Linda | Paul | Sarah goals | 10 | 11 | 5 | 8 assist | 6 | 5 | 2 | 4 corners | 1 | 6 | 5 | 2 </code></pre> <p>I would like to create a bar plot to compare columns Mark Linda Paul Sarah by the action column. </p> <p>I...
0
2016-07-20T11:25:27Z
38,480,065
<p>I'd do it this way:</p> <pre><code>In [51]: import matplotlib In [52]: matplotlib.style.use('ggplot') In [53]: df.set_index('action').plot.bar(title ="Championship", rot=0) Out[53]: &lt;matplotlib.axes._subplots.AxesSubplot at 0x93cb080&gt; </code></pre> <p><a href="http://i.stack.imgur.com/j8jUZ.png" rel="nofol...
0
2016-07-20T11:29:22Z
[ "python", "pandas", "matplotlib" ]
How to set static path in Tornado?
38,479,973
<p>I want to set my http server's static directory, and put some pictures in it, so that users can get my pictures use the url. But I failed, code below does not work:</p> <pre><code># 静态路径 STATIC_DIRNAME = "resources" # 设置static path settings = { "static_path": os.path.join(os.path.dirname(__file__), ...
0
2016-07-20T11:25:29Z
38,480,693
<p>Use <a href="http://www.tornadoweb.org/en/stable/web.html#tornado.web.Application.settings" rel="nofollow">static_url_prefix</a></p> <pre><code>settings = { "static_path": os.path.join(os.path.dirname(__file__), STATIC_DIRNAME), "static_url_prefix": "/resources/", } </code></pre>
1
2016-07-20T11:58:59Z
[ "python", "python-3.x", "tornado" ]
Design practice for certain data sets?
38,480,007
<p>I am trying to dig into database design of grofers.com to understand how grofers manages to list store of merchant and make available to the buyers. What i found is </p> <p>For Merchant to list their store</p> <p><strong>Basic Details</strong></p> <pre><code>Name, Email,Phone,Store Category </code></pre> <p><str...
0
2016-07-20T11:26:57Z
38,481,517
<p>Is this what you are trying to achieve? </p> <pre><code>class Store(models.Model): name_of_user = models.CharField() email = models.EmailField() phone_number_of_user = models.PositiveIntegerField() name_of_legal_entity = models.CharField() pan_number = models.PositiveIntegerField() regist...
1
2016-07-20T12:37:10Z
[ "python", "django", "database", "database-design", "django-models" ]
Pygame - Pause menu not working?
38,480,018
<p><strong>Over View</strong></p> <p>I am at a stage where I want to add a couple of 'Extra' menus to my game. I am starting this off by creating the pause menu and plan to use the same concept to create a 'Shop' and 'Player creation' as well as a 'Mini Game'. </p> <p><strong>Problem</strong></p> <p>So far I have th...
0
2016-07-20T11:27:13Z
38,481,806
<p>The pause should occur from an event.</p> <p>You want it by a keypress 'P', right? </p> <pre><code>paused = False while game_loop: for event in pygame.event.get(): if event.type==KEYDOWN: if event.key=='P': paused = not paused //other events if paused: //...
0
2016-07-20T12:49:17Z
[ "python", "python-2.7", "menu", "pygame", "pause" ]
df.to_csv structuring the output
38,480,043
<p>I am trying to write an output to a <code>csv</code> but I am getting different format. </p> <p>What do I change for getting a clean output. </p> <p>Code:</p> <pre><code>import pandas as pd from datetime import datetime import csv df = pd.read_csv('one_hour.csv') df.columns = ['date', 'startTime', 'endTime', 'd...
3
2016-07-20T11:28:37Z
38,480,441
<p>You need:</p> <pre><code>import pandas as pd import io temp=u"""2004-01-05,21:00:00,22:00:00,Mon,16553,783 2004-01-05,22:00:00,23:00:00,Mon,18944,790 2004-01-05,23:00:00,00:00:00,Mon,17534,750 2004-01-06,00:00:00,01:00:00,Tue,17262,747 2004-01-06,01:00:00,02:00:00,Tue,19072,777 2004-01-06,02:00:00,03:00:00,Tue,182...
2
2016-07-20T11:46:56Z
[ "python", "date", "csv", "pandas", "dataframe" ]
df.to_csv structuring the output
38,480,043
<p>I am trying to write an output to a <code>csv</code> but I am getting different format. </p> <p>What do I change for getting a clean output. </p> <p>Code:</p> <pre><code>import pandas as pd from datetime import datetime import csv df = pd.read_csv('one_hour.csv') df.columns = ['date', 'startTime', 'endTime', 'd...
3
2016-07-20T11:28:37Z
38,480,587
<p>try this:</p> <pre><code>cols = ['date', 'startTime', 'endTime', 'day', 'count', 'unique'] df = pd.read_csv(fn, header=None, names=cols) df.groupby(['date'])[['count','unique']].agg({'count':'median','unique':'median'}).round().to_csv('d:/temp/out.csv', header=None) </code></pre> <p>out.csv:</p> <pre><code>2004...
4
2016-07-20T11:54:06Z
[ "python", "date", "csv", "pandas", "dataframe" ]
Find max value of RDD with reduceByKey and then find associate value of a different variable
38,480,109
<p>I have an RDD with 3 values</p> <pre><code>rdd = rdd.map(lambda x: (x['Id'],[float(x['value1']),int(x['value2'])])) </code></pre> <p>I want to find and return the entire RDD where value1 is maximised I know i could do </p> <pre><code>rddMax = rdd.map(lambda x: (x['Id'], int(x['value1']))).reduceByKey(max) </code>...
0
2016-07-20T11:31:24Z
38,480,451
<p>Try this:</p> <pre><code>&gt;&gt;&gt; rdd = rdd.map(lambda x: ... (x['key'], (float(x['value1']), int(x['value2'])))) &gt;&gt;&gt; rdd.reduceByKey( ... lambda (v11, v21), (v12,v22): (v11, v21) if v11 &gt; v12 else (v12, v22)) </code></pre>
1
2016-07-20T11:47:29Z
[ "python", "apache-spark", "mapreduce", "pyspark", "rdd" ]
How to update django model objects if no update has happened over time(say 10 seconds)
38,480,133
<p>In my use case, I'll keep getting data from different devices for every 10 seconds when they are <strong>Active</strong> (active=True)</p> <p>When ever I receive data I'll update particular django object(database). But I'll never come to know if any device is inactive.</p> <p>It's clear that, if I'm not getting d...
0
2016-07-20T11:32:37Z
38,480,354
<p>Do you actually need them <em>marked</em> as active?</p> <p>How about simply recording the time of the latest update and make <code>active</code> a computed property?</p> <pre><code>from django.utils import timezone # in your model, remove the "active" field # and store the last update's datetime in a "last_upda...
2
2016-07-20T11:42:18Z
[ "python", "django", "time" ]
Python list of dictionaries containing lists comprehension
38,480,526
<p>I have a list of dictionary containing lists: </p> <pre><code>a = [{'alpha': 'a', 'val': 10, 'num': ['one', 'two']}, {'alpha': 'b', 'val': 22, 'num': ['two']}, {'alpha': 'c', 'val': 1, 'num': ['seven']}, {'alpha': 'a', 'val': 10, 'num': ['three','nine']}, {'alpha': 'b', 'val': 9, 'num': ['two',...
0
2016-07-20T11:50:50Z
38,481,166
<p>Try this code:</p> <pre><code>a = [{'alpha':'a','val':10,'num':['one','two']},{'alpha':'b','val':22,'num':['two']},{'alpha':'c','val':1,'num':['seven']},{'alpha':'a','val':10,'num':['three','nine']},{'alpha':'b','val':9,'num':['two','four']}] def merge_dicts(x, y): x.update(y) return x def r(acc, x): ...
1
2016-07-20T12:21:32Z
[ "python" ]
Python list of dictionaries containing lists comprehension
38,480,526
<p>I have a list of dictionary containing lists: </p> <pre><code>a = [{'alpha': 'a', 'val': 10, 'num': ['one', 'two']}, {'alpha': 'b', 'val': 22, 'num': ['two']}, {'alpha': 'c', 'val': 1, 'num': ['seven']}, {'alpha': 'a', 'val': 10, 'num': ['three','nine']}, {'alpha': 'b', 'val': 9, 'num': ['two',...
0
2016-07-20T11:50:50Z
38,481,188
<p>The problem is in this line:</p> <pre><code>numList[info['alpha']].append(info['num']) </code></pre> <p>appending a list onto a list, puts the list that you are appending inside the list you are appending to.</p> <p>I think what you want is extend.</p> <p><a href="http://stackoverflow.com/questions/252703/append...
1
2016-07-20T12:22:29Z
[ "python" ]
Python list of dictionaries containing lists comprehension
38,480,526
<p>I have a list of dictionary containing lists: </p> <pre><code>a = [{'alpha': 'a', 'val': 10, 'num': ['one', 'two']}, {'alpha': 'b', 'val': 22, 'num': ['two']}, {'alpha': 'c', 'val': 1, 'num': ['seven']}, {'alpha': 'a', 'val': 10, 'num': ['three','nine']}, {'alpha': 'b', 'val': 9, 'num': ['two',...
0
2016-07-20T11:50:50Z
38,481,298
<pre><code>#!/usr/bin/env python a = [{'alpha':'a','val':10,'num':['one','two', 'one', 'two']},{'alpha':'b','val':22,'num':['two']},{'alpha':'c','val':1,'num':['seven']},{'alpha':'a','val':10,'num':['three','nine']},{'alpha':'b','val':9,'num':['two','four']}] def merge_lists(src, key): merged = {} for i in s...
1
2016-07-20T12:27:18Z
[ "python" ]
Python list of dictionaries containing lists comprehension
38,480,526
<p>I have a list of dictionary containing lists: </p> <pre><code>a = [{'alpha': 'a', 'val': 10, 'num': ['one', 'two']}, {'alpha': 'b', 'val': 22, 'num': ['two']}, {'alpha': 'c', 'val': 1, 'num': ['seven']}, {'alpha': 'a', 'val': 10, 'num': ['three','nine']}, {'alpha': 'b', 'val': 9, 'num': ['two',...
0
2016-07-20T11:50:50Z
38,481,476
<p>Not as short as other answers but simple in its implementation</p> <pre><code>a = [{'alpha':'a','val':10,'num':['one','two']}, {'alpha':'b','val':22,'num':['two']}, {'alpha':'c','val':1,'num':['seven']}, {'alpha':'a','val':10,'num':['three','nine']}, {'alpha':'b','val':9,'num':['two','four']}] new...
1
2016-07-20T12:35:10Z
[ "python" ]
Python list of dictionaries containing lists comprehension
38,480,526
<p>I have a list of dictionary containing lists: </p> <pre><code>a = [{'alpha': 'a', 'val': 10, 'num': ['one', 'two']}, {'alpha': 'b', 'val': 22, 'num': ['two']}, {'alpha': 'c', 'val': 1, 'num': ['seven']}, {'alpha': 'a', 'val': 10, 'num': ['three','nine']}, {'alpha': 'b', 'val': 9, 'num': ['two',...
0
2016-07-20T11:50:50Z
38,482,046
<p>Here's the simplest solution I came up with:</p> <pre><code>a = [{'alpha':'a','val':10,'num':['one','two']}, {'alpha':'b','val':22,'num':['two']}, {'alpha':'c','val':1,'num':['seven']}, {'alpha':'a','val':10,'num':['three','nine']}, {'alpha':'b','val':9,'num':['two','four']}] a2 = [] alphas = ...
1
2016-07-20T13:01:00Z
[ "python" ]
Wait and complete processes when Python script is stopped from PyCharm console?
38,480,595
<p>Basically I am writing a script that can be stopped and resumed at any time. So if the user uses, say <code>PyCharm console</code> to execute the program, he can just click on the stop button whenever he wants. </p> <p>Now, I need to save some variables and let an ongoing function finish before terminating. What fu...
0
2016-07-20T11:54:24Z
38,480,841
<p>It looks like you might want to catch a signal. </p> <p>When a program is told to stop a signal is sent to the process from the OS, you can then catch them and do cleanup before exit. There are many diffferent signals , for xample when you press CTRL+C a SIGINT signal is sent by the OS to stop your process, but the...
0
2016-07-20T12:06:22Z
[ "python", "pycharm", "exit" ]
Wait and complete processes when Python script is stopped from PyCharm console?
38,480,595
<p>Basically I am writing a script that can be stopped and resumed at any time. So if the user uses, say <code>PyCharm console</code> to execute the program, he can just click on the stop button whenever he wants. </p> <p>Now, I need to save some variables and let an ongoing function finish before terminating. What fu...
0
2016-07-20T11:54:24Z
38,529,814
<p>Solved it using a really bad workaround. I used all functions that are related to exit in Python, including SIG* functions, but uniquely, I did not find a way to catch the exit signal when Python program is being stopped by pressing the "Stop" button in PyCharm application. Finally got a workaround by using tkinter ...
1
2016-07-22T15:07:48Z
[ "python", "pycharm", "exit" ]
How to reshape layer in caffe with python?
38,480,599
<p>It is possible to use <a href="http://caffe.berkeleyvision.org/tutorial/layers.html#reshape" rel="nofollow"><code>"Reshape"</code></a> layer within a prototxt file.<br> However, trying to use it in python (using <code>NetSpec()</code>):</p> <pre><code>n.resh = L.Reshape(n.fc3, reshape_param={'shape':'{dim:1 dim:1 d...
1
2016-07-20T11:54:56Z
38,480,663
<p>Try:</p> <pre><code>n.resh = L.Reshape(n.fc3, reshape_param={'shape':{'dim': [1, 1, 64, 64]}}) </code></pre> <p>Note that the shape vector <code>[1, 1, 64, 64]</code> is passed as a list and not as a string like in the prototxt syntax.</p> <p>In fact, any entry defined as <code>repeated</code> in <code>caffe.prot...
1
2016-07-20T11:57:46Z
[ "python", "neural-network", "deep-learning", "caffe", "pycaffe" ]
Logging and inheritance of loggers' configurations
38,480,665
<p>I come from SLF4J and Log4J, so that might be the reason why I don't get how logging works in Python.</p> <p>I have the following</p> <p>---- logging.yaml</p> <pre><code>version: 1 handlers: console: class: logging.StreamHandler level: DEBUG stream: ext://sys.stderr formatter: simpleFormatter ...
1
2016-07-20T11:57:50Z
38,481,365
<p>You have a fairly simple error: note that, per <a href="https://docs.python.org/2/library/logging.config.html#logging-config-dictschema" rel="nofollow">the docs</a>, configuration for loggers <em>other than <code>root</code></em> should be under the <code>loggers</code> key as:</p> <blockquote> <p>a dict in which...
1
2016-07-20T12:30:35Z
[ "python", "logging" ]
Python on OSx - set the new limit of open files
38,480,705
<p>I want to set a new limit of possible open files with the command:</p> <pre><code>import resource resource.setrlimit(RLIMIT_NOFILE, (resource.RLIM_INFINITY, resource.RLIM_INFINITY)) </code></pre> <p>However, I'm getting an error: <code>ValueError: current limit exceeds maximum limit</code> Is there any way to...
0
2016-07-20T11:59:39Z
38,481,635
<p>You can only do it like this in Mac os.</p> <pre><code>import resource target_procs = 10240 your_procs = ??? real_procs = min(target_procs, your_procs) resource.setrlimit(RLIMIT_NOFILE, real_procs, resource.RLIM_INFINITY)) </code></pre> <p>The reference is <a href="https://github.com/chapmanb/bcbio-nextgen/commit/...
1
2016-07-20T12:42:02Z
[ "python", "osx", "resources", "setrlimit" ]
Aligning a text box edge with an image corner
38,480,739
<p>I'm looking for a way of exactly aligning (overlaying) the corner edge of my image with corner and edge of a text box edge (bbox or other)</p> <p>The code in question is:</p> <pre><code>import numpy as np import matplotlib.pyplot as plt fig, ax = plt.subplots(1) ax.imshow(np.random.random((256,256)), cmap=plt.get_...
4
2016-07-20T12:00:42Z
38,482,595
<p>The issue is caused from the padding of the bounding box. You can change the padding by passing the <code>pad</code> argument to the bounding box dictionary (for instance <code>pad = 0</code> will keep the box inside the axes). I'm assuming you want some padding so it's probably best to set a padding argument and ...
2
2016-07-20T13:24:42Z
[ "python", "matplotlib" ]
Aligning a text box edge with an image corner
38,480,739
<p>I'm looking for a way of exactly aligning (overlaying) the corner edge of my image with corner and edge of a text box edge (bbox or other)</p> <p>The code in question is:</p> <pre><code>import numpy as np import matplotlib.pyplot as plt fig, ax = plt.subplots(1) ax.imshow(np.random.random((256,256)), cmap=plt.get_...
4
2016-07-20T12:00:42Z
38,487,750
<p>Thanks to P-robot for the solution. The key part of the solution is that the annotation <em>text edge</em> is offset x and y by one pixel from the <code>xy</code> coordinate. Any extra padding used increases the necessary amount to compensate for this offset. The second grouping of arguments given to <code>ax.annota...
1
2016-07-20T18:05:35Z
[ "python", "matplotlib" ]
Writing into certain csv columns using python
38,480,909
<p>I have a list of addresses and using GeoPy I'm getting the longitude and latitude. Everything works great but now I want to insert the longitude and latitude into the same csv file, so latitude in the 8th column and longitude in the 9th column.</p> <pre><code>AREA, ADDRESS1, ADDRESS2, ADDRESS3, ADDRESS4, ADDRESS7, ...
-1
2016-07-20T12:09:13Z
38,482,995
<p>You should not be changing files in place when you are adding stuff. <a href="http://stackoverflow.com/questions/16020858/inline-csv-file-editing-with-python">Check this question for that dicussion.</a> However, you can create a new file with the desired output.</p> <p>Assuming that your code works, try doing this ...
0
2016-07-20T13:41:50Z
[ "python", "csv", "geocoding" ]
Pandas deleting row with df.drop doesn't work
38,481,409
<p>I have a DataFrame like this (first column is <code>index</code> (786...) and second <code>day</code> (25...) and <code>Rainfall amount</code> is empty): </p> <pre><code>Day Rainfall amount (millimetres) 786 25 787 26 788 27 ...
1
2016-07-20T12:31:42Z
38,481,492
<p>While dropping new DataFrame returns. If you want to apply changes to the current DataFrame you have to specify <code>inplace</code> parameter.</p> <pre><code># getting new dataframe instance df = df.drop(790) # or with inplace argument df.drop(790, inplace=True) </code></pre>
2
2016-07-20T12:36:11Z
[ "python", "python-3.x", "pandas", "dataframe" ]
How to delete a specific terms in a long array (python)?
38,481,413
<p>I have a long array/list of numbers (from a netcdf file), and I want to a specific term which appears multiple times in the array. This is what I have:</p> <pre><code>lon = np.array(ncfile.variables['LONGITUDE'][:]) lon[lon&gt;1000]=float('nan'); lat = np.array(ncfile.variables['LATITUDE'][:]) lat[lat&gt;1000]=floa...
1
2016-07-20T12:32:01Z
38,481,733
<p>If you're using numpy for your arrays, you can do x = x[~numpy.isnan(x)]</p>
0
2016-07-20T12:45:34Z
[ "python", "arrays" ]
How to delete a specific terms in a long array (python)?
38,481,413
<p>I have a long array/list of numbers (from a netcdf file), and I want to a specific term which appears multiple times in the array. This is what I have:</p> <pre><code>lon = np.array(ncfile.variables['LONGITUDE'][:]) lon[lon&gt;1000]=float('nan'); lat = np.array(ncfile.variables['LATITUDE'][:]) lat[lat&gt;1000]=floa...
1
2016-07-20T12:32:01Z
38,485,114
<p>Note: NetCDF variables are cast to numpy arrays, so there is no need to include the <code>np.array</code> call during the read in. </p> <pre><code>&gt;&gt;&gt; lat = ncfile.variables['LATITUDE'][:] &gt;&gt;&gt; type(lat) &lt;class 'numpy.ndarray'&gt; </code></pre> <p>If you want to simply retain the portion of the...
0
2016-07-20T15:46:46Z
[ "python", "arrays" ]
python, shapely: How to determine if two polygons cross each other, while allowing their edges to overlap
38,481,437
<p>I'm trying to find out whether two polygons cross each other. By 'cross' I mean their exteriors are allowed to touch each other, but their interior cannot:</p> <p>Only the two <strong>rightmost</strong> solutions below are allowed:</p> <p><a href="http://i.stack.imgur.com/leEre.png" rel="nofollow"><img src="http:/...
2
2016-07-20T12:32:55Z
38,481,605
<p>Did you look at the <code>touches</code> method? It seems to do what you want. </p> <p>If not, you could "roll your own". For example, some variation of this:</p> <pre><code>def myTouches(poly1, poly2): return poly1.intersects(poly2) and not poly1.crosses(poly2) and not poly1.contains(poly2) </code></pre> ...
1
2016-07-20T12:40:47Z
[ "python", "shapely" ]
python, shapely: How to determine if two polygons cross each other, while allowing their edges to overlap
38,481,437
<p>I'm trying to find out whether two polygons cross each other. By 'cross' I mean their exteriors are allowed to touch each other, but their interior cannot:</p> <p>Only the two <strong>rightmost</strong> solutions below are allowed:</p> <p><a href="http://i.stack.imgur.com/leEre.png" rel="nofollow"><img src="http:/...
2
2016-07-20T12:32:55Z
38,745,732
<p>This is the solution that worked for the OP (taken from question):</p> <pre><code>if ((pol1.intersects(pol2) == False) and (pol1.disjoint(pol2) == True)) or ((pol1.intersects(pol2) == True) and (pol1.touches(pol2) == True)): allowed = True elif (pol1.intersects(polMe) == True) and (pol1.disjoint(polMe) == False...
2
2016-08-03T13:57:42Z
[ "python", "shapely" ]
how to make this function count backwards
38,481,486
<p>There is this <code>getNextPlayer()</code> function that counts forwards, but I want to adapt it for a card game that occasionally requires counting backwards.</p> <pre><code>def GetNextPlayer(self, p): """ Return the player to the left of the specified player, skipping players who have been knocked out """...
0
2016-07-20T12:35:53Z
38,481,871
<p>Just changing the <code>+1</code> to <code>-1</code> produces invalid values because the <code>modulo</code> operator ignores the sign in the case where you would do <code>0 - 1 % self.numberOfPlayers</code>. E.g. <code>-1 % 4 == 3</code> </p> <p><strong>Update, thanks to @pwnsauce</strong>, this should produce wha...
1
2016-07-20T12:52:36Z
[ "python", "artificial-intelligence" ]
how to make this function count backwards
38,481,486
<p>There is this <code>getNextPlayer()</code> function that counts forwards, but I want to adapt it for a card game that occasionally requires counting backwards.</p> <pre><code>def GetNextPlayer(self, p): """ Return the player to the left of the specified player, skipping players who have been knocked out """...
0
2016-07-20T12:35:53Z
38,482,089
<p>You could use something like this:</p> <pre><code>def GetNextPlayer(self, p, forward=True): """ Return the player to the left of the specified player, skipping players who have been knocked out """ def get_next(): ref = p if forward else p + self.numberOfPlayers - 1 return p + 1 nex...
0
2016-07-20T13:03:00Z
[ "python", "artificial-intelligence" ]
how to show current directory in ipython promp
38,481,506
<p>Is there is way to show the current directory in IPython prompt?</p> <pre><code>Instead of this: In [1]: Something like this: In&lt;~/user/src/proj1&gt;[1]: </code></pre>
1
2016-07-20T12:36:41Z
38,481,800
<p>You can use <code>os.getcwd</code>(current working directory) or in the native os command <code>pwd</code>.</p> <pre><code>In [8]: import os In [9]: os.getcwd() Out[9]: '/home/rockwool' In [10]: pwd Out[10]: '/home/rockwool' </code></pre>
1
2016-07-20T12:48:54Z
[ "python", "ipython", "prompt" ]
how to show current directory in ipython promp
38,481,506
<p>Is there is way to show the current directory in IPython prompt?</p> <pre><code>Instead of this: In [1]: Something like this: In&lt;~/user/src/proj1&gt;[1]: </code></pre>
1
2016-07-20T12:36:41Z
38,481,861
<p><a href="https://ipython.org/ipython-doc/3/config/details.html#specific-config-details" rel="nofollow">https://ipython.org/ipython-doc/3/config/details.html#specific-config-details</a></p> <blockquote> <p>In the terminal, the format of the input and output prompts can be customised. This does not currently affect...
2
2016-07-20T12:52:05Z
[ "python", "ipython", "prompt" ]
'in' operator: text containing words versus list of words
38,481,568
<p>Why does example 3 below, which uses <code>text.split()</code>, produce the correct result, while example 4 is incorrect - i.e. it produces no result, just like example 1.</p> <p>And why does example 2 still produce a result (even though it not the desired result), despite the fact that it does NOT use <code>text.s...
0
2016-07-20T12:39:06Z
38,481,672
<p>Iterating on a string (<code>text</code>) will iterate on its characters, hence 4th loop could be rewritten more explicitly:</p> <pre><code>firstAdjective = next((character for character in text if character in adjectives), None) </code></pre>
2
2016-07-20T12:43:22Z
[ "python", "list", "python-2.7", "split" ]
'in' operator: text containing words versus list of words
38,481,568
<p>Why does example 3 below, which uses <code>text.split()</code>, produce the correct result, while example 4 is incorrect - i.e. it produces no result, just like example 1.</p> <p>And why does example 2 still produce a result (even though it not the desired result), despite the fact that it does NOT use <code>text.s...
0
2016-07-20T12:39:06Z
38,481,809
<p>A string is a container, so <code>in</code> will still work on it. However, it does not naturally separate into words, it iterates over characters. In Example 4, <code>word</code> will take the value of each character in succession. Giving it the variable name <code>word</code> doesn't make it a word.</p> <p>In ...
0
2016-07-20T12:49:22Z
[ "python", "list", "python-2.7", "split" ]
Pause the code at some point
38,481,624
<p>I want to pause the code at exact position and wait for the different input plus the start button clicked. However, if it is not achievable, how can I add another button into the start button to make it work?</p> <pre><code>import wx import time import RPi.GPIO as GPIO global Total_Length Total_Length = 500 glo...
0
2016-07-20T12:41:36Z
38,485,286
<p>"Pause and wait" and "event-driven GUI programming" do not go together. As long as the main GUI thread is blocked waiting for something, then other events can't be processed and the program will appear to be frozen. Your options are to change how you "wait" (by not actually waiting) or to use another thread. </p> ...
0
2016-07-20T15:54:59Z
[ "python", "timer", "wxpython" ]
Paralelization python list comprehension not enhancing performance
38,481,696
<p>Recently I have been trying to paralelize some list comprehensions to speed up my code but I found out that the paralelization lead to a worse time execution... can someone help me understand why?</p> <p>my computer is an i7 4 cores 8 threads around 3GHz core speed and I am using pytthon 2.7</p> <p>Here you have a...
1
2016-07-20T12:44:14Z
38,631,035
<p>Because your function is small the overhead of the function call (and other multiprocessing machinery) is dominant )</p> <pre><code>import numpy as np import timeit d1 = 0.1; d2 = 0.2; def parAddRandom(array): return (array[0] + np.random.uniform(array[1],array[2])) array = 45436, d1, d2 with_function_call...
1
2016-07-28T08:31:46Z
[ "python", "multithreading", "multiprocessing", "python-multithreading", "python-multiprocessing" ]
Reshape from flattened indices in Python
38,481,877
<p>I have an image of size M*N whose pixels coordinates has been flattened to a 1D array according to a space-filling curve (i.e. not a classical rasterization where I could have used reshape).</p> <p>I thus process my 1D array (flattened image) and I then would like to reshape it to a M*N array (initial size).</p> <...
0
2016-07-20T12:52:53Z
38,482,019
<p>In fact, it was easy:</p> <pre><code>vec = np.arange(0, seg.size, dtype=np.uint) img_res[x[vec], y[vec]] = seg[vec] </code></pre>
0
2016-07-20T12:59:23Z
[ "python", "space-filling-curve" ]
Reshape from flattened indices in Python
38,481,877
<p>I have an image of size M*N whose pixels coordinates has been flattened to a 1D array according to a space-filling curve (i.e. not a classical rasterization where I could have used reshape).</p> <p>I thus process my 1D array (flattened image) and I then would like to reshape it to a M*N array (initial size).</p> <...
0
2016-07-20T12:52:53Z
38,482,057
<p>If <code>x</code> and <code>y</code> are numpy arrays of dimension 1 and lengths <code>n</code>, and <code>img_flat</code> also has length <code>n</code> <code>img_res</code> is a numpy array of dimension 2 <code>(h, w)</code> such that `h*w = n, then:</p> <pre><code>img_res[x, y] = img_flat </code></pre> <p>Shoul...
1
2016-07-20T13:01:27Z
[ "python", "space-filling-curve" ]
Python Excel and Selenium Copy Cell value and paste into searchbox NEED HELP FAST
38,481,889
<p>I'm trying to design an automation process that reads the value of a cell in an excel document, copies the value into a variable, and that variable is is pasted into a search box on a site. When the process is called again it goes to the next line, gets the new cell value, and searches again. However I can't seem to...
-1
2016-07-20T12:53:16Z
38,488,022
<p>I figured it out finally. I have to update the actions variable or else the strings are stored in it each time. will post solution soon once its written</p>
0
2016-07-20T18:19:54Z
[ "python", "excel", "oop", "selenium", "automation" ]
Find NumPy array rows which contain any of list
38,481,926
<p>I have a 2D NumPy array <code>a</code> and a list/set/1D NumPy array <code>b</code>. I would like to find those rows of <code>a</code> which contain any of <code>b</code>, i.e.,</p> <pre><code>import numpy as np a = np.array([ [1, 2, 3], [4, 5, 3], [0, 1, 0] ]) b = np.array([1, 2]) # result: [T...
4
2016-07-20T12:54:57Z
38,481,969
<p>You can use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.in1d.html"><code>np.in1d</code></a> to find matches for any element from <code>b</code> in every element in <code>a</code>. Now, <code>np.in1d</code> would flatten arrays, so we need to reshape afterwards. Finally, since we want to find <...
5
2016-07-20T12:56:47Z
[ "python", "arrays", "numpy" ]
Adding an integer to all values in a tuple
38,481,947
<p>What is the recommended/most pythonic way of editing a tuple in code like that shown below?</p> <pre><code>tup_list = [(1, 2), (5, 0), (3, 3), (5, 4)] max_tup = max(tup_list) my_tup1 = (max_tup[0] + 1, max_tup[1] + 1) my_tup2 = tuple(map(lambda x: x + 1, max_tup)) my_tup3 = max([(x+1, y+1) for (x, y) in tup_list]) ...
1
2016-07-20T12:55:48Z
38,482,191
<p>Just use a generator expression with <code>tuple</code>:</p> <pre><code>my_tup = tuple(x+1 for x in max_tup) # or my_tup = tuple(x+1 for x in max(tup_list)) </code></pre>
5
2016-07-20T13:07:01Z
[ "python", "python-2.7", "tuples" ]
Adding an integer to all values in a tuple
38,481,947
<p>What is the recommended/most pythonic way of editing a tuple in code like that shown below?</p> <pre><code>tup_list = [(1, 2), (5, 0), (3, 3), (5, 4)] max_tup = max(tup_list) my_tup1 = (max_tup[0] + 1, max_tup[1] + 1) my_tup2 = tuple(map(lambda x: x + 1, max_tup)) my_tup3 = max([(x+1, y+1) for (x, y) in tup_list]) ...
1
2016-07-20T12:55:48Z
38,482,226
<pre><code>my_tup1 = (max_tup[0] + 1, max_tup[1] + 1) </code></pre> <p>Straight-forward and easy to read. The parentheses explicitly indicate that a tuple will be created and + indicates that numbers will be modified. Therefore it also seems pythonic.</p> <pre><code>my_tup2 = tuple(map(lambda x: x + 1, max_tup)) </co...
1
2016-07-20T13:08:31Z
[ "python", "python-2.7", "tuples" ]
Iterating through a list passed as a parameter in python function
38,482,012
<p>I'm having trouble creating the correct algo, the correct code should meet the specs in the unit test, as follows:</p> <p>Create a function get_algorithm_result to implement the algorithm below<br> 1. Get a list of numbers L1, L2, L3....LN as argument<br> 2. Assume L1 is the largest, Largest = L1<br> 3. Take next n...
0
2016-07-20T12:58:56Z
38,482,376
<p>The keyword argument <code>list1</code> is retained in every function call, and is modified. You could make a copy of that list inside the function and work on the copy:</p> <pre><code>def get_algorithm_result(list_1=[1, 78, 34, 12, 10, 3]): working_list = working_list.copy() if working_list else [] max_ind...
0
2016-07-20T13:15:04Z
[ "python" ]
Iterating through a list passed as a parameter in python function
38,482,012
<p>I'm having trouble creating the correct algo, the correct code should meet the specs in the unit test, as follows:</p> <p>Create a function get_algorithm_result to implement the algorithm below<br> 1. Get a list of numbers L1, L2, L3....LN as argument<br> 2. Assume L1 is the largest, Largest = L1<br> 3. Take next n...
0
2016-07-20T12:58:56Z
38,482,549
<p>for will take all your list elements one by one : <br> simply do this for the first one :<br></p> <pre><code>def get_algorithm_result(list1=[1, 78, 34, 12, 10, 3]): max_index = 0 index = 0 max_num = list1[0] for i in list1: if i &gt; max_num: max_num = i max_index = index index += 1 re...
0
2016-07-20T13:22:45Z
[ "python" ]
Iterating through a list passed as a parameter in python function
38,482,012
<p>I'm having trouble creating the correct algo, the correct code should meet the specs in the unit test, as follows:</p> <p>Create a function get_algorithm_result to implement the algorithm below<br> 1. Get a list of numbers L1, L2, L3....LN as argument<br> 2. Assume L1 is the largest, Largest = L1<br> 3. Take next n...
0
2016-07-20T12:58:56Z
38,482,894
<p>I'm not sure why you're updateing the original list of numbers as that is not what the description you give calls for. Is this what you're after :</p> <pre><code># 1. Get a list of numbers L1, L2, L3....LN as argument def get_algorithm_result(list1=[1, 78, 34, 12, 10, 3]): # 2. Assume L1 is the largest, Largest...
0
2016-07-20T13:37:04Z
[ "python" ]
Iterating through a list passed as a parameter in python function
38,482,012
<p>I'm having trouble creating the correct algo, the correct code should meet the specs in the unit test, as follows:</p> <p>Create a function get_algorithm_result to implement the algorithm below<br> 1. Get a list of numbers L1, L2, L3....LN as argument<br> 2. Assume L1 is the largest, Largest = L1<br> 3. Take next n...
0
2016-07-20T12:58:56Z
38,506,124
<p>I have modified the code to this, but same error message is returned. Is there explicit way to check if the item currently in the loop is the last list item? </p> <pre><code>list1 = [1, 2, 34, 12, 10, 78] def get_algorithm_result(*list1): max_num = list1[0] for i in range(1, len(list1)): if list1[i] &gt; m...
0
2016-07-21T13:50:26Z
[ "python" ]
How to easily allow location input with back slashes in Python
38,482,025
<p>I am trying to manipulate folders and files in Windows using python. Unfortunately, my company's standard includes using back slashes instead of forward slashes in folder locations. </p> <p>If I, or someone else copies over a location with back slashes in it, the code gets confused because it thinks it is an escape...
0
2016-07-20T12:59:48Z
38,482,108
<p>You can do this:</p> <pre><code>print raw_input().replace('\\','/') </code></pre> <p>Here you need to escape the backslash so Python could treat it as a single backslash. </p> <blockquote> <p>Input: <code>C:\\Windows\Users\ForceBru</code> Output: <code>C://Windows/Users/ForceBru</code></p> </blockquote>
0
2016-07-20T13:04:01Z
[ "python", "python-2.7" ]
Taking a range out of an array
38,482,091
<p>I have an array with different numbers called wave_data. It has 101 numbers from 0.30000001 to 0.60000002. </p> <p>This is the code I have:</p> <pre><code>center_wave = 450e-9 width = 50e-9 wavelengths = wave_data*1e-6 range = width/2 min = center_wave - range max = center_wave + range wavelengths = wavelengths[...
1
2016-07-20T13:03:07Z
38,482,158
<p><a href="http://docs.scipy.org/doc/numpy/user/basics.indexing.html#boolean-or-mask-index-arrays" rel="nofollow">Select by boolean mask</a>, not by slicing:</p> <pre><code>waverange = width/2 wavemin = center_wave - waverange wavemax = center_wave + waverange mask = (wavelengths &gt; wavemin) &amp; (wavelengths &lt;...
4
2016-07-20T13:05:47Z
[ "python", "arrays", "numpy", "range" ]
Taking a range out of an array
38,482,091
<p>I have an array with different numbers called wave_data. It has 101 numbers from 0.30000001 to 0.60000002. </p> <p>This is the code I have:</p> <pre><code>center_wave = 450e-9 width = 50e-9 wavelengths = wave_data*1e-6 range = width/2 min = center_wave - range max = center_wave + range wavelengths = wavelengths[...
1
2016-07-20T13:03:07Z
38,482,355
<p>It could be done with a simple list comprehension.</p> <pre><code>center_wave = 450e-9 width = 50e-9 wavelengths = wave_data*1e-6 wave_range = width/2 wave_min = center_wave - wave_range wave_max = center_wave + wave_range wavelengths = [x for x in wavelengths if x &gt;= wave_min and x &lt;= wave_max] </code></pr...
1
2016-07-20T13:14:18Z
[ "python", "arrays", "numpy", "range" ]
CPython memory management
38,482,327
<p>I am writing a CPython module <code>mrloader</code> on top of a C library, I compiled source code and started making some tests.</p> <p>Python takes 4 Gb of RAM to run 100 iteration loop to get some data from network. This is a big problem, so I used <code>resource</code> to limit the amount of RAM and test if the ...
0
2016-07-20T13:13:10Z
38,498,606
<p>I found the solution, I was using <code>PyArrayObject</code> that I did not keep a pointer for in the declared struct. The memory was not being released because of this huge numpy array.</p> <p>So my struct look like this now:</p> <pre><code>typedef struct { PyObject_HEAD AL_KEY ienaKey; char* dataPath...
0
2016-07-21T08:12:55Z
[ "python", "c", "memory-management", "cpython" ]
Django raise Exception on blank CharFields
38,482,336
<p>I am using Django and the REST Framework to build an API that serves data to an AngularJS website. I need to make sure that all validation gets done on the back-end.</p> <p>I have a model named Candidate:</p> <pre><code>class Candidate(CreatedModel): first_name = CharField(max_length=30) last_name = CharF...
1
2016-07-20T13:13:37Z
38,482,707
<p>Why it happens is explained here: <a href="https://docs.djangoproject.com/en/1.9/ref/models/fields/#django.db.models.Field.null" rel="nofollow">https://docs.djangoproject.com/en/1.9/ref/models/fields/#django.db.models.Field.null</a></p> <blockquote> <p>Avoid using null on string-based fields such as CharField and...
1
2016-07-20T13:29:19Z
[ "python", "django", "django-rest-framework" ]
Django raise Exception on blank CharFields
38,482,336
<p>I am using Django and the REST Framework to build an API that serves data to an AngularJS website. I need to make sure that all validation gets done on the back-end.</p> <p>I have a model named Candidate:</p> <pre><code>class Candidate(CreatedModel): first_name = CharField(max_length=30) last_name = CharF...
1
2016-07-20T13:13:37Z
38,483,320
<p>After some researching, I found a way to avoid the empty strings being saved on my database. I created a custom Django <code>Field</code> named <code>NonBlankCharField</code> that inherits <code>CharField</code> and overrides <code>empty_strings_allowed</code>.</p> <pre><code>class NonBlankCharField(CharField): ...
1
2016-07-20T13:55:27Z
[ "python", "django", "django-rest-framework" ]
how to read list which contains comma from csv file as a column?
38,482,479
<p>I want to read csv file which contains following data : </p> <p><strong>Input.csv-</strong></p> <pre><code> 10,[40000,1][50000,5][60000,14] 20,[40000,5][50000,2][60000,1][70000,1][80000,1][90000,1] 30,[60000,4] 40,[40000,5][50000,14] </code></pre> <p>I want to parse this csv file and parse it row by row. But t...
1
2016-07-20T13:19:27Z
38,482,769
<p>you can join those items together, since you know it split by comma </p> <pre><code>if __name__ == "__main__": with open(inputfile, "r") as f: reader = csv.reader(f,skipinitialspace=True) next(reader,None) for read in reader: no = read[0] splitted_record = ','.j...
1
2016-07-20T13:32:03Z
[ "python", "list", "csv", "comma" ]
how to read list which contains comma from csv file as a column?
38,482,479
<p>I want to read csv file which contains following data : </p> <p><strong>Input.csv-</strong></p> <pre><code> 10,[40000,1][50000,5][60000,14] 20,[40000,5][50000,2][60000,1][70000,1][80000,1][90000,1] 30,[60000,4] 40,[40000,5][50000,14] </code></pre> <p>I want to parse this csv file and parse it row by row. But t...
1
2016-07-20T13:19:27Z
38,482,850
<p>You can use your own dialect and register it to read as you need. <a href="http://dialect" rel="nofollow">https://docs.python.org/2/library/csv.html</a></p>
0
2016-07-20T13:35:19Z
[ "python", "list", "csv", "comma" ]
'WSGIRequest' object has no attribute 'get' error while overriding AUTHENTICATIONFORM
38,482,568
<p>I am new to Django and Python. I have some problems with the default <code>AuthenticationForm</code>, so I followed this question: <a href="http://stackoverflow.com/questions/4643884/how-do-i-extend-the-django-login-form">How do I extend the Django &quot;login&quot; form?</a>. Now, I am getting some error which says...
0
2016-07-20T13:23:45Z
38,537,940
<p>i solved it, i changed my form name to LoginFormi and the error is gone. maybe django's bug</p>
0
2016-07-23T03:46:12Z
[ "python", "django", "django-forms" ]
Recursive list functions
38,482,682
<p>I am trying to create a recursive Python function that accepts a list of periods and consolidates them into a clean timeline. It should scan through a list and apply these rules:</p> <ul> <li><p>If value of <strong>None</strong> is found within period: <strong>replace None with datetime.date.today()</strong></p></l...
3
2016-07-20T13:28:11Z
38,484,925
<pre><code>from datetime import datetime # Here is an example list of time periods periods = [('01/2011', '02/2015'), ('04/2012', '08/2014'), ('09/2014', '03/2015'), ('05/2015', '06/2016')] # this lambda function converts a string of the format you have specified to a # datetime object. If the string is None or empt...
1
2016-07-20T15:38:36Z
[ "python", "list", "datetime", "recursion", "zip" ]
How to detect if an axis belongs to a colorbar in matplotlib
38,482,848
<p>How can I detect if an axis belongs to a colorbar in a matplotlib figure?</p> <p>To be specific, the code looks more or less like this:</p> <pre><code>for ax in fig.axes: if is_colorbar(ax): continue apply_some_changes(ax) </code></pre> <p>What's the best way to implement is_colorbar() function?</...
1
2016-07-20T13:35:18Z
38,484,632
<p>Most axes have ticks along the x-axis (at least when they contain a plot of some kind) and colorbar axes don't, so you could check whether <code>ax.get_xticks()</code> is empty or not.</p> <p>I don't think this is the best way to implement <code>is_colorbar</code>, but I don't have any other idea.</p>
-1
2016-07-20T15:25:32Z
[ "python", "matplotlib" ]
How can I unittest whether PDF files have been generated correctly?
38,482,918
<p>I write a small python library that uses matplotlib and seaborn to draw charts, and I wonder how I can test whether the charts look like what I actually want.</p> <p>Thus, given a reference pdf file which I declared as correct, how would I automatically check whether it equals a dynamically generated file with dumm...
-1
2016-07-20T13:38:06Z
38,500,419
<p>Some ideas:</p> <ul> <li>Use <a href="https://vslavik.github.io/diff-pdf/" rel="nofollow">diff-pdf</a></li> <li>Convert it to an image (e.g. using ImageMagick) and use <a href="http://pdiff.sourceforge.net/" rel="nofollow">PerceptualDiff</a></li> <li>Get the data out of the PDF somehow (<a href="http://mstamy2.gith...
0
2016-07-21T09:34:38Z
[ "python", "unit-testing", "pdf", "py.test" ]
How can I unittest whether PDF files have been generated correctly?
38,482,918
<p>I write a small python library that uses matplotlib and seaborn to draw charts, and I wonder how I can test whether the charts look like what I actually want.</p> <p>Thus, given a reference pdf file which I declared as correct, how would I automatically check whether it equals a dynamically generated file with dumm...
-1
2016-07-20T13:38:06Z
38,552,066
<p>For use with regression testing, I have written <a href="https://github.com/brechtm/rinohtype/blob/69d6d5329d674d77c2749bf547230e497a83ea29/tests_regression/helpers/diffpdf.sh" rel="nofollow"><code>diffpdf.sh</code></a> to perform a page-by-page visual diff for PDFs. It makes use of ImageMagick and the Poppler PDF u...
1
2016-07-24T12:33:07Z
[ "python", "unit-testing", "pdf", "py.test" ]
AWS: Run server-side script via load balancer
38,482,923
<p>I have an app server with 3 availability regions, using a load balancer. When I want to access my app's phpmyadmin, I navigate to <strong><em>loadbalancer.com/phpmyadmin</em></strong>.</p> <p>I have a python script <strong><em>myscript.py</em></strong> which I want to run without having to SSH into the servers or a...
1
2016-07-20T13:38:15Z
38,483,011
<p>Yes.To make this URL viable follow this <a href="http://wiki.python.org/moin/CgiScripts" rel="nofollow">http://wiki.python.org/moin/CgiScripts</a>. You'll have to either put your scripts in a cgi-bin folder or adjust the configuration for your web server.</p>
1
2016-07-20T13:42:25Z
[ "python", "amazon-web-services" ]
Django - Display an image with static files
38,482,988
<p>I have some issues with "static files" in my project I'd like to simply load an image. Here is my code : </p> <p>views.py</p> <pre><code>from django.shortcuts import render from django.http import HttpResponse from django.template import loader # Create your views here. def D3(request):      template = lo...
0
2016-07-20T13:41:27Z
38,484,351
<p>There are following issue with your code:</p> <p>1) Check quotes in </p> <pre><code>&lt;img src="{% static "appli1/testimg.png" %}" alt="My image"/&gt; </code></pre> <p>Technically,in the above "{% static " will be read as one value, then " %}" as other, and finally "My image" as another.</p> <p>Following is th...
1
2016-07-20T14:40:31Z
[ "python", "html", "django", "image" ]
pyplot colormap with extend option (in contourf)
38,483,041
<p>I have a set of data ranging from -0.5 to 2 (for example). I only want to color the data that are within [-0.5,1]. I did something like:</p> <pre><code>from matplotlib import colors as mpl_colors color_map = plt.cm.jet color_map.set_bad('gray', 1.0) norm_color = mpl_colors.Normalize(vmin=-0.5, vmax=1, clip=Fals...
0
2016-07-20T13:43:51Z
38,494,569
<p>Here is my solution. </p> <p>I don't have your data, so I choose my data as an example. </p> <p>The temperature at 2 m from model simulation show like this: </p> <p><a href="http://i.stack.imgur.com/4nkYw.png" rel="nofollow"><img src="http://i.stack.imgur.com/4nkYw.png" alt="enter image description here"></a><...
0
2016-07-21T03:51:10Z
[ "python", "matplotlib", "matplotlib-basemap" ]
MATLAB "any" conditional deletion translation to Python
38,483,062
<p>I'm having trouble understanding what <code>B = A(~any(A &lt; threshold, 2), :);</code> (in MATLAB) does given array <code>A</code> with dimensions N x 3. </p> <p>Ultimately, I am trying to implement a function do perform the same operation in Python (so far, I have something like <code>B = A[not any(A[:,1] &lt; th...
2
2016-07-20T13:44:38Z
38,483,255
<p>Not much of difference really. In MATLAB, you are performing <code>ANY</code> along the rows with <code>any(...,2)</code>. In NumPy, you have <code>axis</code> to denote those dimensions and for a <code>2D</code> array, it would be <code>np.any(...,axis=1)</code>.</p> <p>Thus, the NumPy equivalent implementation wo...
4
2016-07-20T13:52:52Z
[ "python", "matlab", "numpy" ]
How do I turn a repeated list element with delimiters into a list?
38,483,118
<p>I imported a CSV file that's basically a table with 5 headers and data sets with 5 elements. </p> <p>With this code I turned that data into a list of individuals with 5 bits of information (list within a list):</p> <pre><code>import csv readFile = open('Category.csv','r') categoryList = [] for row in csv.reader(re...
1
2016-07-20T13:46:50Z
38,483,220
<p>You can use a <em>list comprehension</em> on each row and split items containing <code>':'</code> into a new <em>sublist</em>:</p> <pre><code>for row in csv.reader(readFile): new_row = [i.split(':') if ':' in i else i for i in row] categoryList.append(new_row) </code></pre> <p>This works if you also have o...
0
2016-07-20T13:51:26Z
[ "python", "list", "csv" ]