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
print elements in list as concatenated string
38,528,453
<p>I have a simple dictionary: </p> <pre><code>convert = {'a' : 1, 'b' : 2, 'c' : 3, 'd' : 4} </code></pre> <p>and list</p> <pre><code>letters = ('a', 'b', 'c', 'd') </code></pre> <p>I want to iterate over each element in the list, and use it as a lookup in my dictionary, and print the value <strong>as a concatenat...
2
2016-07-22T14:03:58Z
38,529,777
<p>To get rid of the extra spaces introduced by <code>print</code> you could write data to standard output using <code>sys.stdout.write()</code>: </p> <pre><code>In [55]: letters = ('a', 'b', 'c', 'd') In [56]: convert = {'a' : 1, 'b' : 2, 'c' : 3, 'd' : 4} In [57]: import sys In [58]: for letter in letters: sys.st...
0
2016-07-22T15:06:34Z
[ "python", "python-2.7", "printing" ]
print elements in list as concatenated string
38,528,453
<p>I have a simple dictionary: </p> <pre><code>convert = {'a' : 1, 'b' : 2, 'c' : 3, 'd' : 4} </code></pre> <p>and list</p> <pre><code>letters = ('a', 'b', 'c', 'd') </code></pre> <p>I want to iterate over each element in the list, and use it as a lookup in my dictionary, and print the value <strong>as a concatenat...
2
2016-07-22T14:03:58Z
38,529,909
<p>Just wanted to add an alternative that uses <code>reduce</code>, although it's not necessarily more readable, it may be more flexible later on. If you need to change the code to do something else, you can just adjust the <code>lambda</code> function:</p> <pre><code>&gt;&gt;&gt; print reduce(lambda x,y: str(x)+str(y...
0
2016-07-22T15:12:05Z
[ "python", "python-2.7", "printing" ]
print elements in list as concatenated string
38,528,453
<p>I have a simple dictionary: </p> <pre><code>convert = {'a' : 1, 'b' : 2, 'c' : 3, 'd' : 4} </code></pre> <p>and list</p> <pre><code>letters = ('a', 'b', 'c', 'd') </code></pre> <p>I want to iterate over each element in the list, and use it as a lookup in my dictionary, and print the value <strong>as a concatenat...
2
2016-07-22T14:03:58Z
38,530,000
<p>Try this out :-</p> <pre><code>&gt;&gt;&gt; convert = {'a' : 1, 'b' : 2, 'c' : 3, 'd' : 4} &gt;&gt;&gt; letters = ('a', 'b', 'c', 'd') &gt;&gt;&gt; result = '' &gt;&gt;&gt; for i in letters: result += str(convert[i]) # Since you want concatenated string &gt;&gt;&gt; print result '1234' </code></pre> <p>Or...
1
2016-07-22T15:16:05Z
[ "python", "python-2.7", "printing" ]
Use string method format() to extract values from string
38,528,461
<p>In python I can do the following:</p> <pre class="lang-py prettyprint-override"><code>who = "tim" what = "cake" print "{0} likes {1}".format(who, what) </code></pre> <p>to yield "tim likes cake". </p> <p>However the inverse operation is not as straightforward since I need to use regular expressions. I mean, to pa...
1
2016-07-22T14:04:10Z
38,528,591
<pre><code>who = "tim" what = "cake" print "{0} likes {1}".format(who, what) </code></pre> <p>This works because you know exactly where who and what are in the string. If that's the case, you don't need regex. Strings are lists of characters :)</p> <pre><code>def extract_who_what_from_string(string): words = stri...
1
2016-07-22T14:09:55Z
[ "python", "string" ]
Use string method format() to extract values from string
38,528,461
<p>In python I can do the following:</p> <pre class="lang-py prettyprint-override"><code>who = "tim" what = "cake" print "{0} likes {1}".format(who, what) </code></pre> <p>to yield "tim likes cake". </p> <p>However the inverse operation is not as straightforward since I need to use regular expressions. I mean, to pa...
1
2016-07-22T14:04:10Z
38,528,752
<p>Here's an idea. </p> <pre><code>import re template ="{0} likes {1}" str_re = r"\w+" re.search(template.format(str_re, str_re), ...) </code></pre> <p>Though, seems messy </p>
0
2016-07-22T14:17:40Z
[ "python", "string" ]
Use string method format() to extract values from string
38,528,461
<p>In python I can do the following:</p> <pre class="lang-py prettyprint-override"><code>who = "tim" what = "cake" print "{0} likes {1}".format(who, what) </code></pre> <p>to yield "tim likes cake". </p> <p>However the inverse operation is not as straightforward since I need to use regular expressions. I mean, to pa...
1
2016-07-22T14:04:10Z
40,114,397
<p>There doesn't seem to be a built-in solution beyond splitting the string and casting the components or using <code>re</code>.</p> <p>Which is a little weird, because format can be used to specify types on input: <code>"{0:03d}_{1:f}".format(12, 1)</code> gives <code>'012_3.000000'</code>, so I'm not sure why there'...
0
2016-10-18T17:21:59Z
[ "python", "string" ]
Datetime from year and week number
38,528,515
<p>I have a year and a week number which I want to convert into a <code>datetime.datetiem</code> object. My (naive?) reading of the documentation hinted that <code>strptime('2016 00', '%Y %W')</code> should do just that. However:</p> <pre><code>In [2]: from datetime import datetime In [3]: datetime.strptime('2016 00'...
3
2016-07-22T14:06:23Z
38,528,685
<p>From the <a href="https://docs.python.org/3.5/library/datetime.html#strftime-strptime-behavior" rel="nofollow">docs</a> (see note 7 at the bottom):</p> <blockquote> <p>When used with the <code>strptime()</code> method, <code>%U</code> and <code>%W</code> are only used in calculations when the day of the week an...
1
2016-07-22T14:14:37Z
[ "python", "datetime", "datetime-format" ]
Datetime from year and week number
38,528,515
<p>I have a year and a week number which I want to convert into a <code>datetime.datetiem</code> object. My (naive?) reading of the documentation hinted that <code>strptime('2016 00', '%Y %W')</code> should do just that. However:</p> <pre><code>In [2]: from datetime import datetime In [3]: datetime.strptime('2016 00'...
3
2016-07-22T14:06:23Z
38,528,688
<p>So it turns out that the week number isn't enough for <code>strptime</code> to get the date. Add a default day of the week to your string so it will work. </p> <pre><code>&gt; from datetime import datetime &gt; myDate = "2016 51" &gt; datetime.strptime(myDate + ' 0', "%Y %W %w") &gt; datetime.datetime(2016, 12, 25,...
2
2016-07-22T14:14:39Z
[ "python", "datetime", "datetime-format" ]
Add all timezones from pytz to a tuple
38,528,517
<p>I'm trying to add all the timezones to a tuple in Python. I have done it this way:</p> <pre><code>ALL_TIMEZONES = ( for idx, tz in enumerate(pytz.all_timezones): (idx, (tz)), ) </code></pre> <p>But I get a syntax error when <code>for</code> starts.</p> <p>Why can't I do it that way? Must I do the iter...
0
2016-07-22T14:06:24Z
38,528,592
<p>You can't do it that way because your expression is not producing a value.</p> <p>You can use a generator expression to achieve that:</p> <pre><code>ALL_TIMEZONES = tuple((idx, tz) for idx, tz in enumerate(pytz.all_timezones)) </code></pre>
1
2016-07-22T14:09:55Z
[ "python", "python-3.x" ]
Add all timezones from pytz to a tuple
38,528,517
<p>I'm trying to add all the timezones to a tuple in Python. I have done it this way:</p> <pre><code>ALL_TIMEZONES = ( for idx, tz in enumerate(pytz.all_timezones): (idx, (tz)), ) </code></pre> <p>But I get a syntax error when <code>for</code> starts.</p> <p>Why can't I do it that way? Must I do the iter...
0
2016-07-22T14:06:24Z
38,529,050
<p><a href="https://docs.python.org/3/library/functions.html#enumerate" rel="nofollow"><code>enumerate</code></a> returns an iterator which produces tuples when you iterate over it. <a href="https://docs.python.org/3/library/stdtypes.html#typesseq-tuple" rel="nofollow"><code>tuple()</code></a> will consume an iterator...
1
2016-07-22T14:31:50Z
[ "python", "python-3.x" ]
Difference between dict[item].append(word) and dict[item] + [word]
38,528,587
<p>The structure of my dictionary is:</p> <pre><code> key val item a list of values </code></pre> <p>How I initiated my <code>dict</code>:</p> <pre><code>dict[item] = [word] type(dict[item]) ---&gt; gives me list </code></pre> <p>When going down the loop and try to add more values to the list w...
0
2016-07-22T14:09:45Z
38,528,668
<ul> <li>The code <code>dict[item].append(word)</code> mutates the list at <code>dict[item]</code>, and the return value of the function <code>append</code> is <code>None</code>.</li> <li>The code <code>dict[item] + [word]</code> does not mutate the list at <code>dict[item]</code>, and just computes a concatenation of ...
2
2016-07-22T14:13:56Z
[ "python", "dictionary", "syntax" ]
Difference between dict[item].append(word) and dict[item] + [word]
38,528,587
<p>The structure of my dictionary is:</p> <pre><code> key val item a list of values </code></pre> <p>How I initiated my <code>dict</code>:</p> <pre><code>dict[item] = [word] type(dict[item]) ---&gt; gives me list </code></pre> <p>When going down the loop and try to add more values to the list w...
0
2016-07-22T14:09:45Z
38,528,778
<p><strong>Using .append()</strong></p> <pre><code>d = {'example': ['string']} d['example'].append('test') # mutates the list print d &gt;&gt; {'example': ['string','test']} </code></pre> <p><strong>Using <em>list</em> + <em>list</em></strong></p> <pre><code>d = {'example': ['string']} d['example'] + ['test'] # retu...
0
2016-07-22T14:18:39Z
[ "python", "dictionary", "syntax" ]
How to fix libpapi.so.* cannot open shared object file when running (py)COMPSs with tracing?
38,528,638
<p>When I try to run some COMPSs application with the tracing system activated I get the following error:</p> <pre><code>libpapi.so.5.3.0.0 cannot open shared object file </code></pre> <p>I am using ubuntu and I have installed COMPSs from the packages with apt-get. To launch the application I use:</p> <pre><code>ru...
2
2016-07-22T14:12:45Z
38,529,271
<p>The tracing system can not find your PAPI installation because the packages are pre-compiled. </p> <p>To solve this you have two options: build and install from source the tracing package or build and install from source the whole COMPSs framework. The recommended way would be to build the whole framework in order ...
3
2016-07-22T14:42:30Z
[ "python", "distributed-computing", "papi", "compss", "pycompss" ]
python - SOAP suds library Type Not Found Error
38,528,653
<p>I'm trying to create Python client for Textbroker API, but having troubles accessing their SOAP interface. I can access Login Service ( <a href="https://api.textbroker.com/Budget/loginService.php?wsdl" rel="nofollow">https://api.textbroker.com/Budget/loginService.php?wsdl</a> ) just fine, but when I try to access Bu...
2
2016-07-22T14:13:19Z
38,622,905
<p>As per this answer: <a href="http://stackoverflow.com/questions/4719854/soap-suds-and-the-dreaded-schema-type-not-found-error">SOAP suds and the dreaded schema Type Not Found error</a> you probably need to add a specific location to Import() </p> <pre><code>imp = Import('http://www.w3.org/2001/XMLSchema', ...
2
2016-07-27T20:46:49Z
[ "python", "xml", "soap", "wsdl", "suds" ]
Parsing a complex xml in python lxml parser
38,528,678
<p>I have the follwoing xml,</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8" standalone="yes"?&gt; &lt;Suite&gt; &lt;TestCase&gt; &lt;TestCaseID&gt;001&lt;/TestCaseID&gt; &lt;TestCaseDescription&gt;Hello&lt;/TestCaseDescription&gt; &lt;TestSetup&gt; &lt;Action&gt; &lt;ActionCommand&gt;gfdg&lt;/A...
0
2016-07-22T14:14:19Z
38,529,026
<p>You are not using <code>lxml</code>, you are currently using <code>xml.etree.ElementTree</code> from the Python standard library.</p> <p>If you were to actually use <code>lxml</code>, assuming you have it installed, change your import to:</p> <pre><code>import lxml.etree as ET </code></pre> <p>Then, you can check...
1
2016-07-22T14:30:46Z
[ "python", "xml" ]
Parsing a complex xml in python lxml parser
38,528,678
<p>I have the follwoing xml,</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8" standalone="yes"?&gt; &lt;Suite&gt; &lt;TestCase&gt; &lt;TestCaseID&gt;001&lt;/TestCaseID&gt; &lt;TestCaseDescription&gt;Hello&lt;/TestCaseDescription&gt; &lt;TestSetup&gt; &lt;Action&gt; &lt;ActionCommand&gt;gfdg&lt;/A...
0
2016-07-22T14:14:19Z
38,529,052
<p>If I understand you correctly, you need something like this:</p> <pre><code>for testSetup4 in root.findall(".TestCase/TestSetup/Action"): if testSetup4.find('ActionCommand').text == "gfdg": for c1 in testSetup4: if c1.tag != "ValidationStep": t2.append(c1.tag) ...
0
2016-07-22T14:31:53Z
[ "python", "xml" ]
Parsing a complex xml in python lxml parser
38,528,678
<p>I have the follwoing xml,</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8" standalone="yes"?&gt; &lt;Suite&gt; &lt;TestCase&gt; &lt;TestCaseID&gt;001&lt;/TestCaseID&gt; &lt;TestCaseDescription&gt;Hello&lt;/TestCaseDescription&gt; &lt;TestSetup&gt; &lt;Action&gt; &lt;ActionCommand&gt;gfdg&lt;/A...
0
2016-07-22T14:14:19Z
38,529,243
<p>This is done . Here is my code :</p> <pre><code>for testSetup4 in root.findall(".TestCase/TestSetup/Action"): if testSetup4.find('ActionCommand').text == "gfdg": for c1 in testSetup4: t1.append(c1.tag) v1.append(c1.text) for k,v in zip(t1, v1): test_case[k...
0
2016-07-22T14:41:25Z
[ "python", "xml" ]
CSV Module Always Needs FilePath? Automation?
38,528,724
<p>Why does this open the file, read it, close it without error. The error being 'filename' does not exist. How are you supposed to eliminate the need to enter a filepath every time you use the csv module? Is there no way to have a script loop through a directory for csv files without requiring a filepath?</p> <pre><c...
-1
2016-07-22T14:16:01Z
38,529,235
<p>Because of the nature of file objects in Python, one must always specify the path. However, the path is just a string, so you could always write a script to find all files in the current directory (using the <code>os</code> module), filter the ones with a <code>.csv</code> extension and put them in a list. Here's an...
0
2016-07-22T14:41:06Z
[ "python", "csv" ]
displaying maximum difference between arrays as a list
38,528,761
<p>I have 2 two-dimensional arrays, where each row represents a time and each column represents an item. I want to find the maximum difference between the two arrays for each item. (I don't particularly care about finding where in time that greatest difference is at this point.) </p> <p>I want to create a list of thes...
0
2016-07-22T14:18:06Z
38,528,941
<p>How about using <code>np.subtract</code> you're missing the point of using numpy while you create loop iterators.</p> <p>Not 100% sure if this works since I don't have numpy installed but here's code:</p> <pre><code>import numpy as np array1 = [[1, 2, 3, 4, 5], [2, 4, 6, 8, 10], [3, 6, 9, 12, 15]] array2 = [[6, 7...
1
2016-07-22T14:26:24Z
[ "python", "arrays", "multidimensional-array" ]
displaying maximum difference between arrays as a list
38,528,761
<p>I have 2 two-dimensional arrays, where each row represents a time and each column represents an item. I want to find the maximum difference between the two arrays for each item. (I don't particularly care about finding where in time that greatest difference is at this point.) </p> <p>I want to create a list of thes...
0
2016-07-22T14:18:06Z
38,529,109
<p>With list comprehention you can do :</p> <pre><code>a=[abs(b-c) for x,y in zip(array1,array2) for b,c in zip(x,y)] </code></pre> <blockquote> <p>output : [5, 5, 5, 5, 5, 9, 18, 27, 36, 45, 2, 2, 0, 4, 10]</p> </blockquote> <p>Edit: you just want the last one so :</p> <pre><code>a=[abs(x-y) for x,y in zip(array...
1
2016-07-22T14:34:46Z
[ "python", "arrays", "multidimensional-array" ]
displaying maximum difference between arrays as a list
38,528,761
<p>I have 2 two-dimensional arrays, where each row represents a time and each column represents an item. I want to find the maximum difference between the two arrays for each item. (I don't particularly care about finding where in time that greatest difference is at this point.) </p> <p>I want to create a list of thes...
0
2016-07-22T14:18:06Z
38,529,191
<p>You need to move <code>max_diff = []</code> outside of the for loop in order to get your required output. This would lead to the following code:</p> <pre><code>import numpy as np array1 = [[1, 2, 3, 4, 5], [2, 4, 6, 8, 10], [3, 6, 9, 12, 15]] array2 = [[6, 7, 8, 9, 10], [11, 22, 33, 44, 55], [1, 4, 9, 16, 25]] nu...
1
2016-07-22T14:38:25Z
[ "python", "arrays", "multidimensional-array" ]
Connecting to AWS Elasticsearch instance using Python
38,528,839
<p>I have an Elasticsearch instance, hosted on AWS. I can connect from my terminal with Curl. I am now trying to use the python elasticsearch wrapper. I have:</p> <pre><code>from elasticsearch import Elasticsearch client = Elasticsearch(host='https://ec2-xx-xx-xxx-xxx.us-west-2.compute.amazonaws.com', port=9200) </co...
2
2016-07-22T14:21:34Z
38,556,028
<p>This is the correct way to connect to elasticsearch server using python:</p> <pre><code>es = Elasticsearch(['IP:PORT',]) </code></pre> <p>Elasticsearch's constructor <strong>doesn't have</strong> the <code>host</code> nor the <code>port</code> parameters. The first parameter should be a list, where each item in th...
2
2016-07-24T19:41:27Z
[ "python", "amazon-web-services", "heroku", "elasticsearch", "amazon-ec2" ]
Grouped data in python with pandas and
38,528,852
<p>I use python, pandas, numpy. </p> <pre><code>df = pd.read_csv('data.csv') print df.head(7) </code></pre> <p>I have DataFrame:</p> <pre><code>name day sum A D1 6 B D1 7 B D3 8 A D10 3 A D2 4 C D2 6 A D1 9 </code></pre> <p>I need:</p> <pre><code>name ...
0
2016-07-22T14:22:01Z
38,529,148
<p><code>pivot</code>ing with <code>sum</code>, followed by <code>fillna</code>, actually <em>does</em> exactly what you specified in the question:</p> <pre><code>In [18]: df Out[18]: name day sum 0 A D1 6 1 B D1 7 2 B D3 8 3 A D10 3 4 A D2 4 5 C D2 6 6 A D1 ...
1
2016-07-22T14:36:08Z
[ "python", "numpy", "pandas", "pivot-table", "data-analysis" ]
Grouped data in python with pandas and
38,528,852
<p>I use python, pandas, numpy. </p> <pre><code>df = pd.read_csv('data.csv') print df.head(7) </code></pre> <p>I have DataFrame:</p> <pre><code>name day sum A D1 6 B D1 7 B D3 8 A D10 3 A D2 4 C D2 6 A D1 9 </code></pre> <p>I need:</p> <pre><code>name ...
0
2016-07-22T14:22:01Z
38,529,899
<p>Use df.cumsum(axis=1)</p> <pre><code>pivotedDf = pd.pivot_table(df, values='sum', index=['name'], columns=['day'], aggfunc=np.sum) pivotedDf = pivotedDf[['D1', 'D2', 'D3', 'D10']] # manually sort columns pivotedDf.cumsum(axis=1) </code></pre>
1
2016-07-22T15:11:21Z
[ "python", "numpy", "pandas", "pivot-table", "data-analysis" ]
Using endswith to read list of files doesn't find extension in list
38,529,036
<p>I am trying to get my python script to read a text file with a list of file names with extensions and print out when it finds a particular extension (.txt files to be exact). It reads the file and goes through each line (I've tested by putting a simple "print line" after the for statement), but doesn't do anything w...
3
2016-07-22T14:31:11Z
38,529,088
<p>Each line ends with a new line character <code>'\n'</code> so the test will rightly fail. So you should <code>strip</code> the line first then test:</p> <pre><code>line.rstrip().endswith('.txt') # ^ </code></pre>
4
2016-07-22T14:33:24Z
[ "python", "readfile" ]
Using endswith to read list of files doesn't find extension in list
38,529,036
<p>I am trying to get my python script to read a text file with a list of file names with extensions and print out when it finds a particular extension (.txt files to be exact). It reads the file and goes through each line (I've tested by putting a simple "print line" after the for statement), but doesn't do anything w...
3
2016-07-22T14:31:11Z
38,529,105
<p>Use <a href="https://docs.python.org/3/library/stdtypes.html?highlight=rstrip#str.rstrip" rel="nofollow"><code>str.rstrip</code></a> to remove trailing whitespaces, such as <code>\n</code> or <code>\r\n</code>.</p> <pre><code>with open ("file_list.txt", "r") as L: for line in L: if line.rstrip().endswit...
1
2016-07-22T14:34:23Z
[ "python", "readfile" ]
Using endswith to read list of files doesn't find extension in list
38,529,036
<p>I am trying to get my python script to read a text file with a list of file names with extensions and print out when it finds a particular extension (.txt files to be exact). It reads the file and goes through each line (I've tested by putting a simple "print line" after the for statement), but doesn't do anything w...
3
2016-07-22T14:31:11Z
38,529,124
<p>I guess you should add the endline sign <code>\n</code> at the end of the extension:</p> <pre><code>with open ("file_list.txt", "r") as L: for line in L: if line.endswith(".txt\n"): print ("This has a .txt: " + line) </code></pre>
3
2016-07-22T14:35:14Z
[ "python", "readfile" ]
Trying to stream tweets in database using twitter API Python
38,529,182
<p>I'm trying to retrieve tweets from twitter using a python script but every time I run the script I get the following error:</p> <p><img src="http://i.stack.imgur.com/VBRmJ.jpg" alt="image"></p> <pre><code>from tweepy import Stream from tweepy import OAuthHandler from tweepy.streaming import StreamListener import M...
0
2016-07-22T14:38:00Z
38,531,884
<p>What is the error you are receiving? My understanding is if you are scraping you should put it into a nosql, like Mongo. I have <a href="https://github.com/miahunsicker/twitterbot/blob/master/twitter_to_mongo.py" rel="nofollow">code on Github</a> that does so. </p>
0
2016-07-22T17:04:30Z
[ "python", "tweepy" ]
Adding widgets to third page causes Frames to adjust size
38,529,224
<p>I've created 3 frames (pages) for my GUI and added a couple of widgets to show a basic framework of my GUI.</p> <p>I have used the <code>.grid_propagate(0)</code> method to stop my frames from adjusting size based on the widgets within them.</p> <p>See below for code:</p> <pre><code>from Tkinter import * # from t...
2
2016-07-22T14:40:38Z
38,530,945
<p>Inside your three windows, you are packing the widgets, not griding them. So all what you need to do is to change this line:</p> <pre><code>window.grid_propagate(0) </code></pre> <p>to:</p> <pre><code>window.pack_propagate(0) </code></pre> <p>After doing so, you will get what you expect:</p> <p><a href="http://...
0
2016-07-22T16:04:55Z
[ "python", "python-2.7", "class", "user-interface", "tkinter" ]
Adding widgets to third page causes Frames to adjust size
38,529,224
<p>I've created 3 frames (pages) for my GUI and added a couple of widgets to show a basic framework of my GUI.</p> <p>I have used the <code>.grid_propagate(0)</code> method to stop my frames from adjusting size based on the widgets within them.</p> <p>See below for code:</p> <pre><code>from Tkinter import * # from t...
2
2016-07-22T14:40:38Z
38,530,970
<p>My recommendation is to never turn off geometry propagation. It's almost always the wrong choice. Tkinter does a fantastic job of efficiently laying out widgets. Let the frame shrink (or grow) to fit the contents, and use the geometry manager to cause the frame to fit the space allotted to it.</p> <p>The problem in...
1
2016-07-22T16:06:05Z
[ "python", "python-2.7", "class", "user-interface", "tkinter" ]
How do I set permissions for POST requests in Django REST Framework?
38,529,453
<p>I've got two Django models that are linked like this:</p> <pre><code>class ParentModel(models.Model): creator = models.ForeignKey(User, related_name='objects') name = models.CharField(max_length=40) class ChildModel(models.Model): parent = models.ForeignKey(ParentModel, related_name='child_objects') ...
1
2016-07-22T14:51:28Z
38,530,189
<p>It's hard to know for sure without seeing your urls and views, but please look at the default methods implemented in <code>BasePermission</code> which you inherit:</p> <pre><code>def has_permission(self, request, view): """ Return `True` if permission is granted, `False` otherwise. """ return True ...
0
2016-07-22T15:25:38Z
[ "python", "django", "django-rest-framework" ]
How do I set permissions for POST requests in Django REST Framework?
38,529,453
<p>I've got two Django models that are linked like this:</p> <pre><code>class ParentModel(models.Model): creator = models.ForeignKey(User, related_name='objects') name = models.CharField(max_length=40) class ChildModel(models.Model): parent = models.ForeignKey(ParentModel, related_name='child_objects') ...
1
2016-07-22T14:51:28Z
38,531,437
<p>Thanks to <a href="https://stackoverflow.com/users/674039/wim">wim</a> for providing me with a hint to an answer!</p> <p>The reason why my permission didn't work with <code>POST</code> requests is, indeed, that the object has not yet been created and so I should use <code>has_permission</code> in my permission clas...
0
2016-07-22T16:34:29Z
[ "python", "django", "django-rest-framework" ]
CGI: Execute python script as root
38,529,591
<p>I'm attempting to execute <em>foo.py</em> from <strong>mysite.com/foo.py</strong>, however the script requires access to directories that would normally require <code>sudo -i</code> root access first. <code>chmod u+s foo.py</code> still doesn't give the script enough permission. What can I do so the script has root ...
0
2016-07-22T14:57:22Z
38,529,657
<p>Have you tried <code>chmod 777 foo.py</code> or <code>chmod +x foo.py</code>? Those are generally the commands used to give file permission to run.</p>
0
2016-07-22T15:00:36Z
[ "python", "apache", "cgi" ]
Fixing COMPSs tracing error: PAPI_read failed for thread X evtset X (papi_hwc.c:*)
38,529,625
<p>I am trying to run COMPSs with the tracing system (extrae) activated. I first had an installation issue but I solved it thanks this question:</p> <p><a href="http://stackoverflow.com/questions/38528638/how-to-fix-libpapi-so-cannot-open-shared-object-file-when-running-pycompss-w/">How to fix libpapi.so.* cannot open...
3
2016-07-22T14:59:07Z
38,564,263
<p><strong>Check and disable unavailable PAPI counters</strong></p> <p>It appears that you don't have that counters available in your machine. Use:</p> <pre><code>papi_avail -a </code></pre> <p>to see the available papi counters. Edit the config files under: <code>/opt/COMPSs/Runtime/configuration/xml/tracing/*.xml<...
5
2016-07-25T09:36:04Z
[ "python", "distributed-computing", "papi", "compss", "pycompss" ]
Trouble writing pivot table to excel file
38,529,632
<p>I am using pandas/openpyxl to process an excel file and then create a pivot table to add to a new worksheet in the current workbook. When I execute my code, the new sheet gets created but the pivot table does not get added to the sheet.</p> <p>Here is my code:</p> <pre><code>worksheet2 = workbook.create_sheet() wo...
-1
2016-07-22T14:59:24Z
38,533,869
<p>You can't do this because openpyxl does not currently support pivot tables. See <a href="https://bitbucket.org/openpyxl/openpyxl/issues/295" rel="nofollow">https://bitbucket.org/openpyxl/openpyxl/issues/295</a> for further information.</p>
1
2016-07-22T19:17:33Z
[ "python", "pandas", "openpyxl" ]
ryu controller not forwarding packets
38,529,656
<p>i'm trying to make a simple sdn network with ryu and openVswitch, but my ryu controller seems to not work properly.<br> I'm just trying to ping two hosts, but when i execute the command<br> <code>ryu-manager simple_switch_13.py</code><br> (which is a prebuilt script) the controller does nothing and the packets are n...
0
2016-07-22T15:00:33Z
39,308,136
<p>At last i solved the problem, i think it was soomething i missed in the datapath configuration, since i didn't change the code. I'll post it here if somebody will need it:</p> <pre><code>ifconfig eth0 add FC00:1::2/64 up ifconfig eth1 10.0.0.2/24 up ifconfig eth2 add FC02:1::2/64 up /etc/init.d/openvswitch-switch ...
0
2016-09-03T14:42:01Z
[ "python", "python-2.7", "sdn", "ryu" ]
How can I perform simple calculations with a variable number of inputs?
38,529,742
<p>I'm writing an example program to demonstrate a concept. The program is intended to be a command-line simple calculator. I've defined four functions in IDLE to be run in the Python script shell. Theoretically, it will accept a variable number of inputs, but it will not perform calculations. How can I finish this out...
-7
2016-07-22T15:04:44Z
38,529,837
<p>You can use a 'for' loop like that :</p> <pre><code>def add(*numbers): print(sum(numbers)) </code></pre> <p>For the division, you can use :</p> <pre><code>def divide(*numbers): if len(numbers) &gt;= 2: quotient = numbers[0] for number in numbers[1:]: quotient /= number ...
0
2016-07-22T15:08:52Z
[ "python", "variables", "math", "parameters", "calculator" ]
How can I perform simple calculations with a variable number of inputs?
38,529,742
<p>I'm writing an example program to demonstrate a concept. The program is intended to be a command-line simple calculator. I've defined four functions in IDLE to be run in the Python script shell. Theoretically, it will accept a variable number of inputs, but it will not perform calculations. How can I finish this out...
-7
2016-07-22T15:04:44Z
38,530,305
<p>I think this is what you are after.</p> <p>You can loop over your arguments to perform the operations on them. This is probably not the best way, as the only builtin method that does what you want is for <code>sum</code> the rest are as you see and uses if statements to determine if they have any values</p> <p>You...
-1
2016-07-22T15:30:15Z
[ "python", "variables", "math", "parameters", "calculator" ]
How can I perform simple calculations with a variable number of inputs?
38,529,742
<p>I'm writing an example program to demonstrate a concept. The program is intended to be a command-line simple calculator. I've defined four functions in IDLE to be run in the Python script shell. Theoretically, it will accept a variable number of inputs, but it will not perform calculations. How can I finish this out...
-7
2016-07-22T15:04:44Z
38,530,424
<p>Is this the sort of syntactic example you're looking for :</p> <pre><code>def generic_math_function(variables): result = variables[0] if result == 0: # handle special case. e.g throw an error or return 0 or None return 0 if len(variables) &gt; 1: for variable in variables[1:]: ...
0
2016-07-22T15:36:38Z
[ "python", "variables", "math", "parameters", "calculator" ]
How do I unit test a method that sets internal data, but doesn't return?
38,529,807
<p>From what I’ve read, unit test should test only one function/method at a time. But I’m not clear on how to test methods that only set internal object data with no return value to test off of, like the setvalue() method in the following Python class (and this is a simple representation of something more complicat...
7
2016-07-22T15:07:36Z
38,530,151
<p>I would consider accessing your internal data structure in your test less of a "disgusting hack" since it tests one function at a time and you know what's wrong almost immediately.</p> <p>I admit it's not a great idea to access private members from the test, but still I see this adding more value:</p> <pre><code>c...
3
2016-07-22T15:23:01Z
[ "python", "unit-testing" ]
How do I unit test a method that sets internal data, but doesn't return?
38,529,807
<p>From what I’ve read, unit test should test only one function/method at a time. But I’m not clear on how to test methods that only set internal object data with no return value to test off of, like the setvalue() method in the following Python class (and this is a simple representation of something more complicat...
7
2016-07-22T15:07:36Z
38,531,286
<h2>The misconception</h2> <p>The real problem you have here is that you are working on a false premise:</p> <blockquote> <p>If unit test law dictates that we should test every function, one at a time...</p> </blockquote> <p>This is not at all what good unit testing is about.</p> <p>Good unit testing is about dec...
7
2016-07-22T16:26:00Z
[ "python", "unit-testing" ]
GAE Task queue is keeping negative tasks running in the "Tasks Running" section in the admin console
38,529,993
<p>I am currently working on a Python project with GAE, and as strange as it may seem, my default queue is keeping a negative count of tasks running even though i manually deleted all tasks. Why is it doing this odd thing? and how to stop it? attached you can find a picture of what i mean...</p> <p><a href="http://i.s...
0
2016-07-22T15:15:51Z
39,279,899
<p>This was an AppEngine issue, it was fixed later that day.</p>
0
2016-09-01T19:55:34Z
[ "python", "google-app-engine", "task-queue" ]
Weird error—sometimes it shows and sometimes not
38,530,010
<p>I'm making a script, but there are some troblems with a part of it, so I'll paste just that part instead of all script.. anyway this only part works also alone. Here it is:</p> <pre><code>import re, random, os.path, urllib.request from bs4 import BeautifulSoup def proxyget(): if os.path.isfile("proxy.txt"): ...
1
2016-07-22T15:16:44Z
38,530,392
<pre><code>proxylist = y.split('\n') </code></pre> <p>creates an empty string <code>''</code> at the end of the list such that <code>proxylist = [..., '']</code>. </p> <p>So when <code>random.choice</code> selects one of the items in the list, at some point it selects <code>''</code> for which a <code>split</code> o...
4
2016-07-22T15:35:06Z
[ "python", "python-3.x" ]
Weird error—sometimes it shows and sometimes not
38,530,010
<p>I'm making a script, but there are some troblems with a part of it, so I'll paste just that part instead of all script.. anyway this only part works also alone. Here it is:</p> <pre><code>import re, random, os.path, urllib.request from bs4 import BeautifulSoup def proxyget(): if os.path.isfile("proxy.txt"): ...
1
2016-07-22T15:16:44Z
38,530,498
<p>The error itself is straight forward; while <code>proxy</code> at the end of <code>withproxy</code> supports subscripts, it doesn't have the index 1. It might be a list of one entry, or a single character, something along those lines. </p> <p>A quick glance through the body above that point shows that <code>proxy</...
2
2016-07-22T15:40:49Z
[ "python", "python-3.x" ]
Weird error—sometimes it shows and sometimes not
38,530,010
<p>I'm making a script, but there are some troblems with a part of it, so I'll paste just that part instead of all script.. anyway this only part works also alone. Here it is:</p> <pre><code>import re, random, os.path, urllib.request from bs4 import BeautifulSoup def proxyget(): if os.path.isfile("proxy.txt"): ...
1
2016-07-22T15:16:44Z
38,530,605
<p>I doubt this will fully answer the question, but, "list index out of range" generally means you asked for an element that does not exist, remember, list element numbers start at 0, so in line 41: "port = int(proxy[1])", "proxy[1]" probably didn't exist, meaning the list "proxy" is either empty or contians one elemen...
1
2016-07-22T15:46:52Z
[ "python", "python-3.x" ]
regex to verify url?
38,530,087
<p>Could anyone help with regex? I have an URL like</p> <pre><code>"http://example.com/ru/path/?id=1234&amp;var=abcd" </code></pre> <p>I'd like an assertion that checks that the URL has a stucture:</p> <pre><code>"http://example.com/ru/path/?id={id value}&amp;var={var value}" </code></pre>
-3
2016-07-22T15:20:19Z
38,530,261
<pre><code>import re s="http://example.com/ru/path/?id=1234&amp;var=abcd" pattern = r'http:\/\/example.com\/ru\/path\/\?id=\d+&amp;var=\w+' res = re.findall(patten,s) if res: print "yes: </code></pre>
1
2016-07-22T15:28:45Z
[ "python", "regex" ]
regex to verify url?
38,530,087
<p>Could anyone help with regex? I have an URL like</p> <pre><code>"http://example.com/ru/path/?id=1234&amp;var=abcd" </code></pre> <p>I'd like an assertion that checks that the URL has a stucture:</p> <pre><code>"http://example.com/ru/path/?id={id value}&amp;var={var value}" </code></pre>
-3
2016-07-22T15:20:19Z
38,530,366
<p>Regex isn't needed but using regex just check that there is a digit (<code>\d+</code>) and a var (<code>[A-z]+</code>)</p> <pre><code>import re p = re.compile('http://example.com/ru/path/\?id=\d+&amp;var=[A-z]+') check=p.match("http://example.com/ru/path/?id=1234&amp;var=abcd") if check: print 'match' else: ...
1
2016-07-22T15:33:27Z
[ "python", "regex" ]
regex to verify url?
38,530,087
<p>Could anyone help with regex? I have an URL like</p> <pre><code>"http://example.com/ru/path/?id=1234&amp;var=abcd" </code></pre> <p>I'd like an assertion that checks that the URL has a stucture:</p> <pre><code>"http://example.com/ru/path/?id={id value}&amp;var={var value}" </code></pre>
-3
2016-07-22T15:20:19Z
38,530,376
<p>Surely regex is overkill. if it's repeatable like that you could use:</p> <pre><code>url="http://example.com/ru/path/?id=1234&amp;var=abcd" if url.split('?')[1].startswith('id=') and url.split('&amp;')[1].startswith('var='): print "yay!" </code></pre>
2
2016-07-22T15:34:00Z
[ "python", "regex" ]
Group by, count and calculate proportions in pandas?
38,530,130
<p>I have a dataframe as follows:</p> <pre><code>d = { 'id': [1, 2, 3, 4, 5], 'is_overdue': [True, False, True, True, False], 'org': ['A81001', 'A81002', 'A81001', 'A81002', 'A81003'] } df = pd.DataFrame(data=d) </code></pre> <p>Now I want to work out for each organisation, what percentage of rows are overdue,...
3
2016-07-22T15:22:02Z
38,530,386
<p>You could use <code>pd.crosstab</code> to create a frequency table -- i.e. to count the number of <code>is_overdue</code>s for each <code>org</code>. </p> <pre><code>import pandas as pd d = { 'id': [1, 2, 3, 4, 5], 'is_overdue': [True, False, True, True, False], 'org': ['A81001', 'A81002', 'A81001', 'A81002'...
4
2016-07-22T15:34:41Z
[ "python", "pandas" ]
Group by, count and calculate proportions in pandas?
38,530,130
<p>I have a dataframe as follows:</p> <pre><code>d = { 'id': [1, 2, 3, 4, 5], 'is_overdue': [True, False, True, True, False], 'org': ['A81001', 'A81002', 'A81001', 'A81002', 'A81003'] } df = pd.DataFrame(data=d) </code></pre> <p>Now I want to work out for each organisation, what percentage of rows are overdue,...
3
2016-07-22T15:22:02Z
38,530,403
<p>You could use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.apply.html" rel="nofollow"><code>DataFrame.apply</code></a>.</p> <p>First group by the organizations and count the number of overdue/non-overdue. Then calculate the percentage.</p> <pre><code>df_overdue = df.groupby(['org...
4
2016-07-22T15:35:47Z
[ "python", "pandas" ]
Group by, count and calculate proportions in pandas?
38,530,130
<p>I have a dataframe as follows:</p> <pre><code>d = { 'id': [1, 2, 3, 4, 5], 'is_overdue': [True, False, True, True, False], 'org': ['A81001', 'A81002', 'A81001', 'A81002', 'A81003'] } df = pd.DataFrame(data=d) </code></pre> <p>Now I want to work out for each organisation, what percentage of rows are overdue,...
3
2016-07-22T15:22:02Z
38,530,861
<p>There are more efficient ways to do this but since you were trying to use aggregate functions initially, this is the way to solve your problem using aggregate functions:</p> <pre><code>df.is_overdue = df.is_overdue.map({True: 1, False: 0}) df.groupby(['org'])['is_overdue'].agg({'total_count':'count', 'is_overdue': ...
2
2016-07-22T16:00:08Z
[ "python", "pandas" ]
Cleaning up a messy data file to a more readable format in Python?
38,530,316
<p>I have a text file (heavily modified for this example) which has some data that I want to extract and do some calculations with it. However the text file is extremely messy, so I'm trying to clean it up and write it out to new files first.</p> <p>Here is the .txt file I'm working with: <a href="http://textuploader....
0
2016-07-22T15:30:47Z
38,530,716
<p>I don't know exactly how you want to store your data but assuming you want a dictionary you could use regex to check if the incoming line matched the pattern, then because <code>fileTitle</code> isn't global you could use that as the key and add the values. I also added <code>rstrip('\r\n')</code> to remove the newl...
0
2016-07-22T15:53:06Z
[ "python", "file-io" ]
Cleaning up a messy data file to a more readable format in Python?
38,530,316
<p>I have a text file (heavily modified for this example) which has some data that I want to extract and do some calculations with it. However the text file is extremely messy, so I'm trying to clean it up and write it out to new files first.</p> <p>Here is the .txt file I'm working with: <a href="http://textuploader....
0
2016-07-22T15:30:47Z
38,531,289
<p>You could use regex.</p> <pre><code>import re pattern = r"(\s+X\s+Y\s*)|(\s*\d+\s+\d+\s*)" prog = re.compile(pattern) with open("example.txt") as file: cur_filename = '' content = "" for line in file: if line.startswith('DATASET:'): fileTitle = line[9:] elif line.startswith("DATE:"): fileD...
1
2016-07-22T16:26:08Z
[ "python", "file-io" ]
Cleaning up a messy data file to a more readable format in Python?
38,530,316
<p>I have a text file (heavily modified for this example) which has some data that I want to extract and do some calculations with it. However the text file is extremely messy, so I'm trying to clean it up and write it out to new files first.</p> <p>Here is the .txt file I'm working with: <a href="http://textuploader....
0
2016-07-22T15:30:47Z
38,538,139
<p>Yet another regex solution:</p> <pre><code>sep = '*************************\n' pattern = r'DATASET[^%]*' good_stuff = re.compile(pattern) pattern = r'^DATASET: (.*?)$' title = re.compile(pattern, flags = re.MULTILINE) pattern = r'^DATE: (.*?)$' date = re.compile(pattern, flags = re.MULTILINE) with open(r'foo.txt'...
0
2016-07-23T04:23:36Z
[ "python", "file-io" ]
Pandas: use str.contains with a lot of values
38,530,407
<p>I have <code>df</code> and I need to use <code>str.contains</code>, but I have a lot of condition and there are in <code>df1</code>. I try</p> <p><code>df2[df2['url'].str.contains[df3['buys']]]</code> but it returns </p> <p><code>TypeError: 'instancemethod' object has no attribute '__getitem__'</code> What's wrong...
0
2016-07-22T15:36:04Z
38,530,441
<p>You need parenthesis:</p> <pre><code>df2[df2['url'].str.contains(df3['buys'])] </code></pre> <p>the error</p> <pre><code>TypeError: 'instancemethod' object has no attribute '__getitem__' </code></pre> <p>is saying that you are using square brackets after an object that doesn't know what to do with the square bra...
1
2016-07-22T15:37:22Z
[ "python", "pandas" ]
Pandas: use str.contains with a lot of values
38,530,407
<p>I have <code>df</code> and I need to use <code>str.contains</code>, but I have a lot of condition and there are in <code>df1</code>. I try</p> <p><code>df2[df2['url'].str.contains[df3['buys']]]</code> but it returns </p> <p><code>TypeError: 'instancemethod' object has no attribute '__getitem__'</code> What's wrong...
0
2016-07-22T15:36:04Z
38,530,442
<p>IIUC you can pass a regex that joins the contents:</p> <pre><code>In [180]: df = pd.DataFrame({'a':['hello','world','python']}) df1 = pd.DataFrame({'a':['hello','johnny']}) df[df['a'].str.contains('|'.join(df1['a']))] Out[180]: a 0 hello </code></pre> <p>So in your case:</p> <pre><code>df2[df2['url'].str...
0
2016-07-22T15:37:28Z
[ "python", "pandas" ]
Reindex method of Pandas does not respect the set frequency
38,530,423
<p>I have a Pandas DataFrame with a daily DatetimeIndex. I am trying to apply the Resample method to sum the values into a monthly series like this:</p> <pre><code>&gt;&gt;&gt; aggVols.resample('M',axis=1).sum() </code></pre> <p>But when I try this I get the error </p> <pre><code>TypeError: Only valid with DatetimeI...
1
2016-07-22T15:36:38Z
38,530,674
<p>Change</p> <pre><code>aggVols.resample('M',axis=1).sum() </code></pre> <p>to</p> <pre><code>aggVols.resample('M',axis=0).sum() </code></pre> <p>Your <code>DatetimeIndex</code> is on the rows (not the columns).</p> <p>In general axis 0 is the rows, axis 1 is the columns, axis 2 is the height, and axes 3-N ... we...
0
2016-07-22T15:51:13Z
[ "python", "pandas", "dataframe", "frequency", "datetimeindex" ]
Reindex method of Pandas does not respect the set frequency
38,530,423
<p>I have a Pandas DataFrame with a daily DatetimeIndex. I am trying to apply the Resample method to sum the values into a monthly series like this:</p> <pre><code>&gt;&gt;&gt; aggVols.resample('M',axis=1).sum() </code></pre> <p>But when I try this I get the error </p> <pre><code>TypeError: Only valid with DatetimeI...
1
2016-07-22T15:36:38Z
38,530,890
<p>Got it in the end. Was using the method the wrong way with the operation at the end, as if it was a series. The right code is:</p> <pre><code>aggVols.resample('M',axis=0,how=sum) </code></pre>
0
2016-07-22T16:01:53Z
[ "python", "pandas", "dataframe", "frequency", "datetimeindex" ]
Where to check if something was changed on Django Admin
38,530,690
<p>I have a Model on Django-rest-framework, and I need to check every time a field on that Model was updated in the Django-Admin in order to do a update in another model.</p> <p>How and where can I check it?</p> <p>Thanks</p>
1
2016-07-22T15:52:08Z
38,548,922
<p>@ssice is right you can utilise <a href="https://docs.djangoproject.com/en/1.9/ref/signals/#django.db.models.signals.post_save" rel="nofollow">Django Signals</a>, along with something like <a href="https://github.com/romgar/django-dirtyfields" rel="nofollow">django-dirtyfields</a>. </p> <p>Or</p> <p>If it's a one ...
0
2016-07-24T05:04:20Z
[ "python", "django-admin", "django-rest-framework" ]
Where to check if something was changed on Django Admin
38,530,690
<p>I have a Model on Django-rest-framework, and I need to check every time a field on that Model was updated in the Django-Admin in order to do a update in another model.</p> <p>How and where can I check it?</p> <p>Thanks</p>
1
2016-07-22T15:52:08Z
38,552,774
<p>If you only need to watch changes in Django Admin change form, you can hook the <code>save_model()</code> method of your ModelAdmin.</p> <pre><code>class YourAdmin(ModelAdmin): def save_model(self, request, obj, form, change): super().save_model(request, obj, form, change) # do what you have to...
0
2016-07-24T13:54:17Z
[ "python", "django-admin", "django-rest-framework" ]
How do I take a string and make festival say it
38,530,707
<p>How do I take a string such as: <code>K = "Hello User"</code> and use it in the code that says it using festival tts: <code>os.system('echo "Hello user." | festival --tts')</code>? Is there a way to do it some other way (1st way would be better) I tried searching to do this on Google, Youtube and StackOverflow but I...
0
2016-07-22T15:52:41Z
38,530,791
<p>Use <a href="https://docs.python.org/3/library/stdtypes.html#str.format" rel="nofollow">str.format</a>.</p> <pre><code>import os K = "Hello user." os.system('echo "{0}" | festival --tts'.format(K)) </code></pre>
0
2016-07-22T15:56:27Z
[ "python", "python-2.7", "gnome-terminal", "festival" ]
How do I take a string and make festival say it
38,530,707
<p>How do I take a string such as: <code>K = "Hello User"</code> and use it in the code that says it using festival tts: <code>os.system('echo "Hello user." | festival --tts')</code>? Is there a way to do it some other way (1st way would be better) I tried searching to do this on Google, Youtube and StackOverflow but I...
0
2016-07-22T15:52:41Z
38,530,807
<p>You should just be able to do something like this:</p> <pre><code>os.system('echo %s | festival --tts' % K) </code></pre> <p>That should replace the %s with the string K</p>
1
2016-07-22T15:57:19Z
[ "python", "python-2.7", "gnome-terminal", "festival" ]
How to link yaml key values to json key values in python
38,530,720
<p>Hi I would like to essentially use yaml data inside json for eg.</p> <p>json file:</p> <pre><code>{ "Name": "foo", "Birthdate": "1/1/1991", "Address": "FOO_ADDRESS", "Note": "Please deliver package to foo at FOO_ADDRESS using COURIER service" } </code></pre> <p>yaml file:</p> <pre> --- FOO_ADDRES...
0
2016-07-22T15:53:16Z
38,532,127
<p>To be safe, first load the JSON and then do the replacements in the loaded strings. If you do the replacements in the JSON source, you might end up with invalid JSON output (when the replacement strings contain <code>"</code> or other characters that have to be escaped in JSON).</p> <pre><code>import yaml, json de...
0
2016-07-22T17:22:25Z
[ "python", "json", "yaml" ]
How to access field names of a ModelForm in Django?
38,530,756
<p>Just to be clear, I'm asking about accessing the fields in views.py</p> <p>I want to add extra data into the form before it is validated (because it's a required field), and <a href="http://stackoverflow.com/a/30849799/6562245">another answer</a> on stackexchange seems to imply I have to create a new form to do so....
0
2016-07-22T15:54:50Z
38,530,806
<p>This is the wrong thing to do. There is no reason to add in a required field programmatically; if you know the value of the field already, there is no reason to include it on the form at all.</p> <p>I don't know what you mean about having to create another form; instead you should explicitly exclude that field, in ...
0
2016-07-22T15:57:18Z
[ "python", "django", "python-2.7", "django-forms" ]
How to access field names of a ModelForm in Django?
38,530,756
<p>Just to be clear, I'm asking about accessing the fields in views.py</p> <p>I want to add extra data into the form before it is validated (because it's a required field), and <a href="http://stackoverflow.com/a/30849799/6562245">another answer</a> on stackexchange seems to imply I have to create a new form to do so....
0
2016-07-22T15:54:50Z
38,532,260
<p>I figured out what I was doing wrong. In my TestForm modelform I didn't include the 'component' field because I didn't want it to show up on the form. As a result, the 'component' data was being cleaned out during form validation even if I inserted it into the form correctly. So to solve this I just added 'component...
0
2016-07-22T17:30:55Z
[ "python", "django", "python-2.7", "django-forms" ]
Concatenate an HTML attribute value with Flask data
38,530,773
<p>How do I concatenate a value in a Jinja template? I tried the following but the value is rendered separately from the attribute. </p> <pre><code>&lt;input type="button" id="button" + {{ entry.id }}&gt; </code></pre>
1
2016-07-22T15:55:44Z
38,531,430
<p>Look at the output of your current template: <code>id="button" + 3</code>. Anything outside of <code>{{ }}</code> isn't interpreted by Jinja, it's just treated as text.</p> <p>Either put the expression right next to the text, or put the string inside the expression.</p> <pre class="lang-none prettyprint-override"...
4
2016-07-22T16:34:04Z
[ "python", "flask", "jinja2" ]
Count diff with datetimes and today and group it in one month frequency using Pandas
38,530,787
<p>I have the following format of data in a csv:</p> <pre><code>1,2015-02-01 </code></pre> <p>The format is</p> <pre><code>&lt;internal_id&gt;,&lt;datetime&gt; </code></pre> <p>I want to ignore the internal id, and use the datetime (if posible even not read it from the csv to save memory).</p> <p>And what I want ...
-1
2016-07-22T15:56:14Z
38,530,881
<pre><code>from StringIO import StringIO import pandas as pd text = """1,2015-01-18 1,2015-02-10 1,2015-02-15 1,2015-02-20 1,2015-03-01 1,2015-03-02 1,2015-03-03""" df = pd.read_csv(StringIO(text), header=None, parse_dates=[1], names=['count', 'Date'], index_col=1) df.groupby(pd.TimeGrouper('M')).count().hist() </co...
0
2016-07-22T16:01:15Z
[ "python", "pandas" ]
How to delete a row if one of the cells is empty
38,530,808
<p>Here is the spreadsheet :</p> <pre><code>Color Name Size red Apple large green Apple small orange Orange small pea Green super small </code></pre> <p>Here I replace all instances of Apple with Apple_Object and delete any name that isn't apple:</p> <pre><code>for x in name: if 'Appl...
-2
2016-07-22T15:57:19Z
38,530,911
<p>Try this out. It filters out rows that does contains an empty string leaving the rest</p> <p><code>result = filter(lambda x: '' not in x, list)</code></p>
0
2016-07-22T16:02:44Z
[ "python", "replace" ]
How to delete a row if one of the cells is empty
38,530,808
<p>Here is the spreadsheet :</p> <pre><code>Color Name Size red Apple large green Apple small orange Orange small pea Green super small </code></pre> <p>Here I replace all instances of Apple with Apple_Object and delete any name that isn't apple:</p> <pre><code>for x in name: if 'Appl...
-2
2016-07-22T15:57:19Z
38,530,924
<p>You are replacing the value of apple for nothing</p> <pre><code>for x in list: if 'Apple' not in list: list = list.replace(x, '') </code></pre> <p>but you should be eliminating the current row</p> <pre><code>for x in list: if 'Apple' not in list: del list[index] </code></pre>
1
2016-07-22T16:03:43Z
[ "python", "replace" ]
Why do long HTTP round trip-times stall my Tornado AsyncHttpClient?
38,530,886
<p>I'm using Tornado to send requests in rapid, periodic succession (every 0.1s or even 0.01s) to a server. For this, I'm using <code>AsyncHttpClient.fetch</code> with a callback to handle the response. Here's a very simple code to show what I mean:</p> <pre><code>from functools import partial from tornado import gen,...
1
2016-07-22T16:01:36Z
38,932,744
<p>After some tinkering and tcpdumping, I've concluded that two things were really slowing down my coroutine. With these two corrected stalling has gone down enormously drastically and the <code>timeout</code> in <code>yield wakeup_condition.wait(timeout=timedelta(seconds=interval))</code> is much better respected:</p...
1
2016-08-13T12:30:15Z
[ "python", "http", "asynchronous", "tornado" ]
Python Fit ellipse to an image
38,530,899
<p>I have a webcam feed using OpenCV, and I am trying to fit an ellipse in real time. </p> <p>The code I am using at the moment works, but it fails to fit an ellipse to the image a lot of the time. What other methods of ellipse fitting to an image can I pursue?</p> <p>Current code:</p> <pre><code>def find_ellipses(i...
10
2016-07-22T16:02:04Z
38,531,424
<p>I would define my contours outside of the function, as you don't need to keep re-defining them in this image.</p> <pre><code>def create_ellipse(thresh,cnt): ellipse = cv2.fitEllipse(cnt) thresh = cv2.ellipse(thresh,ellipse,(0,255,0),2) return thresh </code></pre> <p>What this code is doing is im taking...
0
2016-07-22T16:33:46Z
[ "python", "opencv", "ellipse" ]
Python Fit ellipse to an image
38,530,899
<p>I have a webcam feed using OpenCV, and I am trying to fit an ellipse in real time. </p> <p>The code I am using at the moment works, but it fails to fit an ellipse to the image a lot of the time. What other methods of ellipse fitting to an image can I pursue?</p> <p>Current code:</p> <pre><code>def find_ellipses(i...
10
2016-07-22T16:02:04Z
38,572,372
<p>Turns out I was wrong is just getting the first ellipse from the function. While I thought the first calculated ellipse was the most correct one, what I actually had to do was go through all the ellipses - and choose the most suitable one that bounded the object in the image.</p>
3
2016-07-25T15:54:49Z
[ "python", "opencv", "ellipse" ]
Outlier detection with pandas for data with many missing values
38,531,009
<p>I have several long-term data series with gaps and want to use a low pass filter to detect outliers. In theory, (data-median) > 3 sigma seems like an appropriate test, but there are two issues with this:</p> <ol> <li><p>the data series are too long and variable, so that using only one median and standard deviation ...
1
2016-07-22T16:08:18Z
38,531,083
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.ffill.html" rel="nofollow"><code>ffill</code></a> and <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.bfill.html" rel="nofollow"><code>bfill</code></a>.</p> <p><code>ffill</code> will propagate the ...
1
2016-07-22T16:13:19Z
[ "python", "pandas", "outliers" ]
Django trying to split a user's email to display in a template
38,531,015
<p>I'm trying to split a user's email to just the domain and display it on the front end. I'm using Django's user model.</p> <p>models.py</p> <pre><code>class UserDomain(models.Model): user = models.ForeignKey(User) def splitEmailToDomain(self): return self.user.email.split('@')[1].lower() </code></p...
0
2016-07-22T16:08:27Z
38,531,041
<p>You may need to define it as a property, and apply <code>join</code> to an empty string:</p> <pre><code>class UserDomain(models.Model): @property def splitEmailToDomain(self): return ''.join(self.user.email.split('@')[1]).lower() </code></pre>
0
2016-07-22T16:10:29Z
[ "python", "django" ]
Django trying to split a user's email to display in a template
38,531,015
<p>I'm trying to split a user's email to just the domain and display it on the front end. I'm using Django's user model.</p> <p>models.py</p> <pre><code>class UserDomain(models.Model): user = models.ForeignKey(User) def splitEmailToDomain(self): return self.user.email.split('@')[1].lower() </code></p...
0
2016-07-22T16:08:27Z
38,531,183
<p>Assuming your class actually looks something like</p> <pre><code>class UserDomain(models.Model): user = models.ForeignKey(User,...) </code></pre> <p>And your <code>User</code> class has an <code>email</code> field.</p> <p>Then your method needs to be more like this:</p> <pre><code> ... def email_domain...
0
2016-07-22T16:19:15Z
[ "python", "django" ]
How is the function argument defined in matplotlib animation?
38,531,076
<p>Hi guys Im quite a newbie in python/matplotlib.</p> <p>I am struggling to understand the following animation code on the matplotlib website. How is the <strong><em>data</em></strong> argument in the <strong><em>def update</em></strong> defined if this function is called in <strong><em>animation.FuncAnimation</em></...
0
2016-07-22T16:12:53Z
38,531,151
<p><code>data_gen</code> is a generator which, for each animation frame, will yield an array of 10 random values. The array returned from <code>data_gen</code> is what is passed to your <code>update</code> function as the first input argument. </p> <p>If you called <a href="http://matplotlib.org/api/animation_api.html...
1
2016-07-22T16:17:29Z
[ "python", "animation", "matplotlib" ]
A weird string literal identity issue in Django
38,531,078
<p>I have an API in the Django project I am working on that sends commands to devices. The API expects a POST request with data containing something like <code>{"command": "activate"}</code>. A few minutes ago I found this bit of code in the view function for the API</p> <pre> ... ommitting the DRF viewset class def f...
3
2016-07-22T16:13:02Z
38,531,120
<p>Do not rely on string comparison by identity, in any cases. The fact that it <em>appears to work sometimes</em> is due to an implementation detail of CPython called string interning. The rules governing whether a given string will be interned or not are very complicated, and subject to change without notice. </p>...
4
2016-07-22T16:15:35Z
[ "python", "django" ]
A weird string literal identity issue in Django
38,531,078
<p>I have an API in the Django project I am working on that sends commands to devices. The API expects a POST request with data containing something like <code>{"command": "activate"}</code>. A few minutes ago I found this bit of code in the view function for the API</p> <pre> ... ommitting the DRF viewset class def f...
3
2016-07-22T16:13:02Z
38,531,165
<blockquote> <p>But, again, as far as I know, literals should have the same identity no matter where they come from.</p> </blockquote> <p>First, that's not actually true. Unlike, say, Java, Python makes no guarantees about whether literals are interned:</p> <pre><code>In [1]: x = 'a b' In [2]: x is 'a b' Out[2]: F...
0
2016-07-22T16:18:14Z
[ "python", "django" ]
Getting the source code of a running Python script externally
38,531,085
<h2>Original question</h2> <p>I recently wrote a small Python script which acted like a server, it was +/- 200 lines long and wasn't separated into multiple files. The original file has since been removed and has no backup, however the process itself is still running.</p> <p>I know the following code will read out th...
3
2016-07-22T16:13:25Z
38,531,209
<p>Do you have access to the server where the process is running? </p> <p>Then maybe you could try <a href="http://pyrasite.readthedocs.io/en/latest/CLI.html" rel="nofollow">http://pyrasite.readthedocs.io/en/latest/CLI.html</a></p> <p>(Disclaimer: I've never used it myself)</p> <p>HTH,</p>
2
2016-07-22T16:21:13Z
[ "python" ]
Getting the source code of a running Python script externally
38,531,085
<h2>Original question</h2> <p>I recently wrote a small Python script which acted like a server, it was +/- 200 lines long and wasn't separated into multiple files. The original file has since been removed and has no backup, however the process itself is still running.</p> <p>I know the following code will read out th...
3
2016-07-22T16:13:25Z
38,531,867
<p>Pyrasite is probably your best bet but here's a total shot in the dark: Try checking for files in the directory <code>/proc/&lt;pid&gt;/fd/</code>, where pid is the process id of your running script. If you're very lucky you could recover a <code>pyc</code> which you could then decompile.</p>
0
2016-07-22T17:03:17Z
[ "python" ]
Using Python, is there a way to create a new tab and navigate to a site in an active Chrome browser?
38,531,169
<p>I know I can use Selenium, but that opens a new browser window which isn't what I want. I would like to access the browser window I am already using and open a new tab with the domain/url I'm trying to load.</p>
0
2016-07-22T16:18:31Z
38,531,340
<p>Maybe you are looking for this: <a href="https://docs.python.org/2/library/webbrowser.html" rel="nofollow">https://docs.python.org/2/library/webbrowser.html</a></p> <p>This will open a new tab in default browser.</p> <p>My Apologies, i dont have enough reputation to comment yet.</p>
0
2016-07-22T16:29:10Z
[ "python", "google-chrome" ]
Using Python, is there a way to create a new tab and navigate to a site in an active Chrome browser?
38,531,169
<p>I know I can use Selenium, but that opens a new browser window which isn't what I want. I would like to access the browser window I am already using and open a new tab with the domain/url I'm trying to load.</p>
0
2016-07-22T16:18:31Z
38,531,451
<p>I just tested the following code in my computer and opened a new tab in my default browser (Chrome in my case):</p> <pre><code>import webbrowser webbrowser.open_new('http://www.google.com') </code></pre> <p>If you want to open a new tab in a non-default browser you will have to do the following:</p> <pre><code>im...
0
2016-07-22T16:35:55Z
[ "python", "google-chrome" ]
Writing Panda Dataframes to csv file in chunks
38,531,195
<p>I have a set of large data files (1M rows x 20 cols). However, only 5 or so columns of that data is of interest to me. </p> <p>I figure I can make things easier for me by creating copies of these files with only the columns of interest so I have smaller files to work with for post processing.</p> <p>My plan was to...
1
2016-07-22T16:20:15Z
38,531,304
<p>Try:</p> <pre><code>chunk.to_csv(os.path.join(folder, new_folder, "new_file_" + filename), cols = [['TIME','STUFF']], mode='a') </code></pre> <p>The <code>mode='a'</code> tells pandas to append.</p>
1
2016-07-22T16:27:02Z
[ "python", "pandas", "dataframe", "export-to-csv", "large-data" ]
Writing Panda Dataframes to csv file in chunks
38,531,195
<p>I have a set of large data files (1M rows x 20 cols). However, only 5 or so columns of that data is of interest to me. </p> <p>I figure I can make things easier for me by creating copies of these files with only the columns of interest so I have smaller files to work with for post processing.</p> <p>My plan was to...
1
2016-07-22T16:20:15Z
38,531,305
<p>Check out the <code>chunksize</code> argument in the <code>to_csv</code> method. <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_csv.html" rel="nofollow">Here</a> are the docs.</p> <p>Writing to file would look like:</p> <pre><code>df.to_csv("path/to/save/file.csv", chunksize=100...
2
2016-07-22T16:27:07Z
[ "python", "pandas", "dataframe", "export-to-csv", "large-data" ]
Writing Panda Dataframes to csv file in chunks
38,531,195
<p>I have a set of large data files (1M rows x 20 cols). However, only 5 or so columns of that data is of interest to me. </p> <p>I figure I can make things easier for me by creating copies of these files with only the columns of interest so I have smaller files to work with for post processing.</p> <p>My plan was to...
1
2016-07-22T16:20:15Z
38,531,978
<p>Why don't you only read the columns of interest and then save it?</p> <pre><code>file_in = os.path.join(folder, filename) file_out = os.path.join(folder, new_folder, 'new_file' + filename) df = pd.read_csv(file_in, sep='\t', skiprows=(0, 1, 2), header=0, names=['TIME', 'STUFF']) df.to_csv(file_out) </code></pre>
0
2016-07-22T17:11:18Z
[ "python", "pandas", "dataframe", "export-to-csv", "large-data" ]
Using Python to download an Excel file from OneDrive results in corrupt file
38,531,278
<p>I am trying to download an excel file from a OneDrive location. My code works okay to get the file, but the file is corrupt (I get an error message):</p> <pre><code>import urllib2 data = urllib2.urlopen("enter url here") with open('C:\\Video.xlsx', 'wb') as output: output.write(data.read()) output.close() pri...
0
2016-07-22T16:25:43Z
38,544,638
<p>You can't just download the Excel file directly from OneDrive using a URL. Even when you would share the file without any authorization, you'll probably still get a link to an intermediate HTML page, rather than the Excel binary itself.</p> <p>To download items from your OneDrive, you'll first need to authenticate ...
1
2016-07-23T17:29:45Z
[ "python", "excel", "sharepoint", "onedrive" ]
How to read timezone aware datetimes as a timezone naive local DatetimeIndex with read_csv in pandas?
38,531,317
<p>When I use pandas read_csv to read a column with a timezone aware datetime (and specify this column to be the index), pandas converts it to a <strong>timezone naive utc</strong> DatetimeIndex.</p> <p>Data in Test.csv:</p> <p><code>DateTime,Temperature 2016-07-01T11:05:07+02:00,21.125 2016-07-01T11:05:09+02:00,21.1...
2
2016-07-22T16:27:49Z
38,532,026
<p>According to <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html" rel="nofollow">the docs</a> the default <code>date_parser</code> uses <code>dateutil.parser.parser</code>. According to <a href="http://dateutil.readthedocs.io/en/stable/parser.html#dateutil.parser.parse" rel="nofollow"...
1
2016-07-22T17:14:08Z
[ "python", "datetime", "pandas" ]
How to read timezone aware datetimes as a timezone naive local DatetimeIndex with read_csv in pandas?
38,531,317
<p>When I use pandas read_csv to read a column with a timezone aware datetime (and specify this column to be the index), pandas converts it to a <strong>timezone naive utc</strong> DatetimeIndex.</p> <p>Data in Test.csv:</p> <p><code>DateTime,Temperature 2016-07-01T11:05:07+02:00,21.125 2016-07-01T11:05:09+02:00,21.1...
2
2016-07-22T16:27:49Z
38,565,018
<p>The <a href="http://stackoverflow.com/a/38532026/1504026">answer</a> of Alex leads to a timezone aware DatetimeIndex. To get a <strong>timezone naive local</strong> DatetimeIndex, as asked by the OP, inform <code>dateutil.parser.parser</code> to ignore the timezone information by setting <code>ignoretz=True</code>:<...
1
2016-07-25T10:13:40Z
[ "python", "datetime", "pandas" ]
How to read timezone aware datetimes as a timezone naive local DatetimeIndex with read_csv in pandas?
38,531,317
<p>When I use pandas read_csv to read a column with a timezone aware datetime (and specify this column to be the index), pandas converts it to a <strong>timezone naive utc</strong> DatetimeIndex.</p> <p>Data in Test.csv:</p> <p><code>DateTime,Temperature 2016-07-01T11:05:07+02:00,21.125 2016-07-01T11:05:09+02:00,21.1...
2
2016-07-22T16:27:49Z
39,156,778
<p>I adopted the <code>dateutil</code> technique earlier today but have since switched to a faster alternative: </p> <pre><code>date_parser = lambda ts: pd.to_datetime([s[:-5] for s in ts])) </code></pre> <blockquote> <p>Edit: <code>s[:-5]</code> is correct (screenshot has error)</p> </blockquote> <p>In the screen...
0
2016-08-26T00:44:17Z
[ "python", "datetime", "pandas" ]
Agreggate Array into a Dataframe with a group by
38,531,320
<p>I need to aggregate an array inside my dataframe. </p> <p>The dataframe was created in this way</p> <pre> splitted.map(lambda x: Row(store= int(x[0]), date= parser.parse(x[1]), values= (x[2:(len(x))]) ) ) </pre> <p><strong>Values</strong> is an Array</p> <p>I want to do think like this</p> <pre> mean_by_week ...
0
2016-07-22T16:28:16Z
38,535,013
<p>Matching dimensions or not sum for <code>array&lt;&gt;</code> is not meaningful hence not implemented. You can try to restructure and aggregate:</p> <pre><code>from pyspark.sql.functions import col, array, size, sum as sum_ n = df.select(size("values")).first()[0] df = sc.parallelize([(1, [1, 2, 3]), (1, [4, 5, 6]...
0
2016-07-22T20:48:30Z
[ "python", "apache-spark" ]
Write Python List to Excel rows using xlwt
38,531,372
<p>I would like to write each value in a Python list to a new row in an Excel cell. The object I am generating the list from does not support indexing which is giving me an issue. If my list only generates one value, then there is no problem, however when I generate multiple values, I get multiple errors. I am a Python...
1
2016-07-22T16:30:54Z
38,531,489
<p>You can use <code>enumerate()</code> to get the index of the list. Then you can write to successive rows like so:</p> <pre><code>for i,game in enumerate(games): ws.write(i,0,str(game)) </code></pre>
1
2016-07-22T16:38:22Z
[ "python", "excel", "python-2.7", "xlwt" ]
NoReverseMatch using {% url %}
38,531,445
<p>I'm trying to follow the examples given here: <a href="http://stackoverflow.com/questions/3583534/refresh-div-element-generated-by-a-django-template">Refresh &lt;div&gt; element generated by a django template</a></p> <p>But I end up with: </p> <pre><code>NoReverseMatch at /search/: Reverse for '' with arguments '...
0
2016-07-22T16:35:40Z
38,531,467
<p>You're missing the url's name:</p> <pre><code>url(r'^search/(?P&lt;flights&gt;[^/]*)/search_results/$', "fsApp.views.search_results", name='search_results'), </code></pre> <p>In your template:</p> <pre><code>{% url 'search_results' flights as url_search %} &lt;script&gt; ... url: '{{ url_search }}', ... &l...
1
2016-07-22T16:37:00Z
[ "javascript", "python", "django" ]
Can't run scripts through console in QPython
38,531,593
<p>I'm using the app QPython, and while it's easy to run scripts from a file, I'm struggling to see how to load a script into the Console so that I can use it there (e.g. to use functions defined in a script).</p> <p>I'm not very familiar with Python, so I don't know whether I'm having difficulty with Python or with t...
0
2016-07-22T16:45:08Z
38,531,710
<p>To import some functions :</p> <pre><code>from script import functiona, functionb() </code></pre> <p>To import all functions from a script use :</p> <pre><code>from script import * </code></pre> <p>You could just do :</p> <pre><code>import script </code></pre> <p>But then you'll have to call your functions li...
0
2016-07-22T16:52:38Z
[ "python", "qpython" ]
How can I make a read-only property mutable?
38,531,608
<p>I have two classes, one with an "in-place operator" override (say <code>+=</code>) and another that exposes an instance of the first through a <code>@property</code>. (Note: this is <em>greatly</em> simplified from my actual code to the minimum that reproduces the problem.)</p> <pre><code>class MyValue(object): ...
4
2016-07-22T16:46:11Z
38,531,732
<p>This is a quirk of the language; the <code>object += value</code> operation translates to:</p> <pre><code>object = object.__iadd__(value) </code></pre> <p>This is necessary because not all objects are mutable. Yours is, and correctly returns <code>self</code> resulting in a virtual no-op for the assignment part of...
5
2016-07-22T16:54:19Z
[ "python", "python-2.7", "properties", "new-style-class", "augmented-assignment" ]
Upstart - stop: Unknown instance:
38,531,611
<p>I'm trying to do a simple upstart script, I't seems to start, I don't see an error. Says it started running on 5975. But when I <code>ps ax | grep test</code> I see 11 instances. When I try to <code>sudo stop test</code> I get <code>stop: Unknown instance:</code></p> <p>My example is bare bones, not sure what I'm d...
0
2016-07-22T16:46:23Z
38,531,661
<p>the name instance is test.py, not test only</p> <p>the command is sudo stop test.py</p>
-2
2016-07-22T16:49:42Z
[ "python", "upstart" ]
Create pandas pivot table on new sheet in workbook
38,531,670
<p>I am trying to send my pivot table that I have created onto a new sheet in the workbook, however, for some reason when I execute my code a new sheet is created with the pivot table (sheet is called 'Sheet1') and the data sheet gets deleted.</p> <p>Here is my code:</p> <pre><code>worksheet2 = workbook.create_sheet(...
1
2016-07-22T16:50:28Z
38,531,700
<p>Just use <code>margins=True</code> and <code>margins_name='Grand Total'</code> parameters when calling <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.pivot_table.html" rel="nofollow">pivot_table()</a></p> <p>Demo:</p> <pre><code>In [15]: df = pd.DataFrame(np.random.randint(0, 5, size=(10, 3)...
3
2016-07-22T16:51:50Z
[ "python", "pandas", "dataframe", "openpyxl" ]
Open a Jupyter notebook within running server from command line
38,531,685
<p>My Jupyter/IPython notebooks reside in various directories all over my file system. I don't enjoy navigating hierarchies of directories in the Jupyter notebook browser every time I have to open a notebook. In absence of the (still) missing feature allowing to bookmark directories within Jupyter, I want to explore if...
0
2016-07-22T16:51:11Z
38,531,985
<p><strong>Option 1</strong>: Run multiple jupyter notebook servers from your project directory root(s). This avoids navigating deeply nested structures using the browser ui. I often run many notebook servers simultaneously without issue.</p> <p><code>$ cd path/to/project/; jupyter notebook;</code></p> <p><strong>O...
1
2016-07-22T17:11:37Z
[ "python", "ipython-notebook", "jupyter-notebook" ]
How to download files from Scraped Links[python] without logging in to a specified directory
38,531,762
<p><a href="http://stackoverflow.com/questions/29641671/how-to-download-pdfs-from-scraped-links-python">How to Download PDFs from Scraped Links [Python]?</a></p> <p>After working on this I was stuck with the following issues Is it possible to download if my college portal has a login page and if yes what should be ad...
0
2016-07-22T16:55:54Z
38,531,862
<p>It is possible, but you should use something like Selenium. This library will allow you to run a browser and navigate through coding, just like you would. You will be able <a href="http://stackoverflow.com/questions/21186327/fill-username-and-password-using-selenium-in-python">to fill out the username and password f...
0
2016-07-22T17:02:59Z
[ "python", "web", "download", "text-mining", "url-encoding" ]
captureWarnings set to True doesn't capture warnings
38,531,786
<p>I would like to log all warnings assuming that setting captureWarnings to True should do the trick. But it doesn't. Code:</p> <pre><code>import logging import warnings from logging.handlers import RotatingFileHandler logger_file_handler = RotatingFileHandler(u'./test.log') logger_file_handler.setLevel(logging.DEB...
1
2016-07-22T16:57:27Z
38,531,892
<p><code>logging.captureWarnings</code> is not using your logger. It uses a logger named <code>'py.warnings'</code>. You will need to configure that logger to do what you want.</p>
1
2016-07-22T17:05:13Z
[ "python", "python-2.7", "logging" ]
captureWarnings set to True doesn't capture warnings
38,531,786
<p>I would like to log all warnings assuming that setting captureWarnings to True should do the trick. But it doesn't. Code:</p> <pre><code>import logging import warnings from logging.handlers import RotatingFileHandler logger_file_handler = RotatingFileHandler(u'./test.log') logger_file_handler.setLevel(logging.DEB...
1
2016-07-22T16:57:27Z
38,531,930
<p>From the <a href="https://docs.python.org/2.7/library/logging.html#logging.captureWarnings" rel="nofollow"><code>logging.captureWarnings</code></a> documentation:</p> <blockquote> <p>Warnings issued by the warnings module will be redirected to the logging system. Specifically, a warning will be formatted using ...
3
2016-07-22T17:07:26Z
[ "python", "python-2.7", "logging" ]