title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
list
Python 3.5: How to read a db of JSON objects
39,755,424
<p>so I'm new to working with JSON and I'm trying to work with the <a href="https://github.com/fictivekin/openrecipes" rel="nofollow">openrecipe database from here.</a> The db dump you get looks like this...</p> <pre><code>{ "_id" : { "$oid" : "5160756d96cc62079cc2db16" }, "name" : "Hot Roast Beef Sandwiches", "ingre...
1
2016-09-28T18:47:45Z
39,755,523
<p>The file is not a <code>json</code> array. <em>Each line of the file</em> is a <code>json</code> document, but the whole file is not in <code>json</code> format.</p> <p>Read the file by lines, and use <code>json.loads</code>:</p> <pre><code>with open('some_file') as f: for line in f: doc = json.loads(line) ...
1
2016-09-28T18:53:11Z
[ "python", "json" ]
Python: Unique items of list in the order that it appears
39,755,464
<p>In Python, we can get the unique items of the list using <code>set(list)</code>. However doing this breaks the order in which the values appear in the original list. Is there an elegant way to get the unique items in the order in which it appears in the list.</p>
1
2016-09-28T18:50:04Z
39,755,540
<pre><code>l = [] for item in list_: if item not in l: l.append(item) </code></pre> <p>This gets slow for really big, diverse <code>list_</code>. In those cases, it would be worth it to also keep track of a set of seen values.</p>
1
2016-09-28T18:54:14Z
[ "python", "list", "order", "set", "unique" ]
Python: Unique items of list in the order that it appears
39,755,464
<p>In Python, we can get the unique items of the list using <code>set(list)</code>. However doing this breaks the order in which the values appear in the original list. Is there an elegant way to get the unique items in the order in which it appears in the list.</p>
1
2016-09-28T18:50:04Z
39,755,585
<p>This is an elegant way:</p> <pre><code>from collections import OrderedDict list(OrderedDict.fromkeys(list)) </code></pre> <p>It works if the list items are all hashable (you will know that all the list items are hashable if converting it to a set did not trigger an exception). </p> <p>If any items are not hashab...
4
2016-09-28T18:57:07Z
[ "python", "list", "order", "set", "unique" ]
JSON printed to console shows wrong encoding
39,755,662
<p>I am trying to read Cyrillic characters from some JSON file and then output it to console using <strong>Python 3.4.3 on Windows</strong>. Normal print('Russian smth буквы') works as intended.</p> <p>But when I print JSON contents it seems to print in Windows-1251 - "СЂСѓСЃСЃРєРёРµ Р±СѓРєРÐ...
1
2016-09-28T19:01:31Z
39,779,780
<p>"<em>But when I print JSON contents …</em>" </p> <p>If you print it using <code>type</code> command, then you get <a href="https://en.wikipedia.org/wiki/Mojibake" rel="nofollow">mojibake</a> <code>СЂСѓСЃСЃРєРёРµ …</code> instead of <code>русские …</code> under <code>CHCP 1251</code> scope...
0
2016-09-29T20:50:43Z
[ "python", "json", "python-3.x", "utf-8", "cyrillic" ]
Overriding update( ) Django rest framework
39,755,669
<p>i have a model wich contains a foreign Key so i create my update function but the problem when i want to update my models all fields are updated except the foreign key .I don't know why .I hope that i get an answer </p> <p>My models:</p> <pre><code>class Produit (models.Model): titre=models.CharField(max_lengt...
0
2016-09-28T19:02:18Z
39,788,667
<p>You shouldn't play with the id directly in that case since the serializer will return an object:</p> <pre><code>class ProduitUpdateSerializer(serializers.ModelSerializer): class Meta: model = Produit fields = ['titre', 'description', 'photo_principal', 'photo_1', 'photo_2', 'photo_3', 'prix', 'n...
0
2016-09-30T09:53:38Z
[ "python", "django", "django-rest-framework" ]
pandas histogram with by: possible to make axes uniform?
39,755,742
<p>I am using the option to generate a separate histogram of a value for each group in a data frame like so (example code from documentation)</p> <pre><code>data = pd.Series(np.random.randn(1000)) data.hist(by=np.random.randint(0, 4, 1000), figsize=(6, 4)) </code></pre> <p>This is great, but what I am not seeing is a...
2
2016-09-28T19:07:08Z
39,756,668
<p>you can pass <code>kwds</code> to hist and it will pass them along to appropriate sub processes. The relevant ones here are <code>sharex</code> and <code>sharey</code></p> <pre><code>data = pd.Series(np.random.randn(1000)) data.hist(by=np.random.randint(0, 4, 1000), figsize=(6, 4), sharex=True, sharey=Tr...
3
2016-09-28T20:02:17Z
[ "python", "pandas" ]
Automatic varable creation when when adding new instance of a class
39,755,813
<p>I am teaching my self Python, and I am getting my head around OOP classes. I keep seeing examples like this.</p> <pre><code>import ClassImade var1 = ClassImade() Var2 = ClassImade() </code></pre> <p>The program I am trying to make will have several thousand instances of the class. My question is: how has this iss...
-1
2016-09-28T19:10:50Z
39,755,912
<pre><code>var = [] for i in range(1000): var.append(ClassImade()) </code></pre> <p>This makes a list of class instances. Is that what you want?</p>
0
2016-09-28T19:17:12Z
[ "python" ]
Simple Hello World, AJAX FOR DJANGO
39,755,826
<p>So I have this function in views.py</p> <pre><code>def home(request): return render_to_response('proj1/index.html', RequestContext(request, {'variable': 'world'})) </code></pre> <p>Which i want to use for AJAX to display "Hello World"; </p> <p>The ajax function is like so :</p> <pre><code>$.ajax({ url: "/pro...
0
2016-09-28T19:11:42Z
39,757,291
<p>Make sure the 'url: "/proj1" ' is pointing to the url that calls that view.</p> <p>This tutorial will solve your doubts:</p> <p><a href="https://godjango.com/18-basic-ajax/" rel="nofollow">https://godjango.com/18-basic-ajax/</a></p>
0
2016-09-28T20:43:06Z
[ "jquery", "python", "ajax", "django" ]
Calling a subset of a dataset
39,755,877
<pre><code>x_train = train['date_x','activity_category','char_1_x','char_2_x','char_3_x','char_4_x','char_5_x','char_6_x', 'char_7_x','char_8_x','char_9_x','char_10_x',.........,'char_27','char_29','char_30','char_31','char_32','char_33', 'char_34','char_35','char_36','char_37','char_38'] y = y_train x_test = test['dat...
1
2016-09-28T19:14:40Z
39,756,774
<p>As suggested by @AndrasDeak<br> Consider the <code>pd.DataFrame</code> <code>train</code></p> <pre><code>train = pd.DataFrame(np.arange(1000).reshape(-1, 20)) </code></pre> <p>Then use the suggestion like this</p> <pre><code>train.iloc[np.r_[0:17, 19:38]] </code></pre>
2
2016-09-28T20:08:51Z
[ "python", "pandas" ]
regex to validate date in DD.MM format
39,755,893
<p>I've googled up a lot of regexes to validate dates in DD.MM.YYYY format. Like this one:</p> <p><code>(0[1-9]|1[0-9]|2[0-8]|(?:29|30)(?!.02)|29(?=.02.\d\d(?:[02468][048]|[13579][26]))|31(?=.0[13578]|.1[02]))(?:\.(?=\d\d\.)|-(?=\d\d-)|\/(?=\d\d\/))(0[1-9]|1[0-2])[.\/\-]([1-9][0-9]{3})</code></p> <p>and it works fine...
0
2016-09-28T19:15:56Z
39,766,116
<h2>Solution</h2> <pre><code> ^(0[1-9]|[12][0-9]|30(?!\.02)|31(?!\.(0[2469]|11)))\.(0[1-9]|1[0-2])$ </code></pre> <h2>Example in python</h2> <pre><code>&gt;&gt;&gt; daymonth_match = r"^(0[1-9]|[12][0-9]|30(?!\.02)|31(?!\.(0[2469]|11)))\.(0[1-9]|1[0-2])$" &gt;&gt;&gt; print re.match(daymonth_match, "12.04") &lt;_sre....
0
2016-09-29T09:11:17Z
[ "python", "regex" ]
regex to validate date in DD.MM format
39,755,893
<p>I've googled up a lot of regexes to validate dates in DD.MM.YYYY format. Like this one:</p> <p><code>(0[1-9]|1[0-9]|2[0-8]|(?:29|30)(?!.02)|29(?=.02.\d\d(?:[02468][048]|[13579][26]))|31(?=.0[13578]|.1[02]))(?:\.(?=\d\d\.)|-(?=\d\d-)|\/(?=\d\d\/))(0[1-9]|1[0-2])[.\/\-]([1-9][0-9]{3})</code></p> <p>and it works fine...
0
2016-09-28T19:15:56Z
39,767,720
<p>Just make the dot and year optional:</p> <pre><code>(?:[.\/\-]([1-9][0-9]{3}))? </code></pre>
0
2016-09-29T10:25:09Z
[ "python", "regex" ]
Dump All XPaths
39,755,923
<p>Does lxml or exml have a function to export all xpaths in an XML?</p> <p>XML Example:</p> <pre><code> &lt;note&gt; &lt;to&gt;Tove&lt;/to&gt; &lt;from&gt;Jani&lt;/from&gt; &lt;heading&gt;Reminder&lt;/heading&gt; &lt;body&gt; &lt;content&gt;Don't forget me this weekend!&lt;/content&gt; &...
0
2016-09-28T19:17:52Z
39,755,979
<p>You have to iterate over the tree and call <a href="http://lxml.de/api/lxml.etree._ElementTree-class.html#getpath" rel="nofollow">getpath</a> on each node:</p> <pre><code>x = """&lt;note&gt; &lt;to&gt;Tove&lt;/to&gt; &lt;from&gt;Jani&lt;/from&gt; &lt;heading&gt;Reminder&lt;/heading&gt; &lt;body&gt; ...
1
2016-09-28T19:21:56Z
[ "python", "xml", "xpath" ]
How do I use `setrlimit` to limit memory usage? RLIMIT_AS kills too soon; RLIMIT_DATA, RLIMIT_RSS, RLIMIT_STACK kill not at all
39,755,928
<p>I'm trying to use <code>setrlimit</code> to limit my memory usage on a Linux system, in order to stop my process from crashing the machine (my code was crashing nodes on a high performance cluster, because a bug led to memory consumption in excess of 100 GiB). I can't seem to find the correct resource to pass to <c...
1
2016-09-28T19:18:05Z
39,765,583
<p>Alas I have no answer for your question. But I hope the following might help:</p> <ul> <li>Your script works as expected on my system. Please share exact spec for yours, might be there is a known problem with Linux distro, kernel or even numpy...</li> <li>You should be OK with <code>RLIMIT_AS</code>. As explained <...
1
2016-09-29T08:46:58Z
[ "python", "numpy", "memory", "setrlimit" ]
regex match proc name without slash
39,755,930
<p>I have a list of proc names on Linux. Some have slash, some don't. For example,</p> <p><strong>kworker</strong>/23:1</p> <strong>migration</strong>/39</p> <strong>qmgr</strong></p> <p>I need to extract just the proc name without the slash and the rest. I tried a few different ways but still won't get it complete...
0
2016-09-28T19:18:13Z
39,755,958
<p>An alternative to regex is to <code>split</code> on <em>slash</em> and take the first item:</p> <pre><code>&gt;&gt;&gt; s ='kworker/23:1' &gt;&gt;&gt; s.split('/')[0] 'kworker' </code></pre> <p>This also works when the string does not contain a slash:</p> <pre><code>&gt;&gt;&gt; s = 'qmgr' &gt;&gt;&gt; s.split('/...
0
2016-09-28T19:20:22Z
[ "python", "regex" ]
regex match proc name without slash
39,755,930
<p>I have a list of proc names on Linux. Some have slash, some don't. For example,</p> <p><strong>kworker</strong>/23:1</p> <strong>migration</strong>/39</p> <strong>qmgr</strong></p> <p>I need to extract just the proc name without the slash and the rest. I tried a few different ways but still won't get it complete...
0
2016-09-28T19:18:13Z
39,756,041
<p>The problem with the regex is, that the greedy <code>.+</code> is going until the end, because everything after it is optional, meaning it is kept as short as possible (essentially empty). To fix this replace the <code>.</code> with anything but a <code>/</code>.</p> <pre><code>([^\/]+)\/?.* </code></pre> <p>works...
0
2016-09-28T19:25:56Z
[ "python", "regex" ]
Using SortedDictionary for .net (imported from C# .dll)
39,755,973
<p>I'm currently working on a python (for .NET) project that interacts with a C# .dll. However, something is wrong with the SortedDictionary I'm importing.</p> <p>This is what I'm doing:</p> <pre><code>import clr from System.Collections.Generic import SortedDictionary sorted_dict = SortedDictionary&lt;int, bool&gt;(1...
1
2016-09-28T19:21:20Z
39,756,514
<p>"In that case it's definitely a syntax issue. You're using C# syntax which the Python interpreter no comprende. I think you want something like SortedDictionary[int, bool] based on some coding examples I just found" @martineau</p>
0
2016-09-28T19:53:31Z
[ "python", ".net" ]
Using SortedDictionary for .net (imported from C# .dll)
39,755,973
<p>I'm currently working on a python (for .NET) project that interacts with a C# .dll. However, something is wrong with the SortedDictionary I'm importing.</p> <p>This is what I'm doing:</p> <pre><code>import clr from System.Collections.Generic import SortedDictionary sorted_dict = SortedDictionary&lt;int, bool&gt;(1...
1
2016-09-28T19:21:20Z
39,756,544
<p>The problem is this:</p> <pre><code>SortedDictionary&lt;int, bool&gt;(1, True) </code></pre> <p>The <code>&lt;</code> and <code>&gt;</code> symbols in this line are being taken as <em>comparison operators.</em> Python sees you asking for two things:</p> <pre><code> SortedDictionary &lt; int bool &gt; (1, True) <...
0
2016-09-28T19:55:11Z
[ "python", ".net" ]
Explain how pandas DataFrame join works
39,755,981
<p>Why does inner join work so strange in pandas?</p> <p><strong>For example:</strong></p> <pre><code>import pandas as pd import io t1 = ('key,col1\n' '1,a\n' '2,b\n' '3,c\n' '4,d') t2 = ('key,col2\n' '1,e\n' '2,f\n' '3,g\n' '4,h') df1 = pd.read_csv(io.StringIO(t1),...
2
2016-09-28T19:22:13Z
39,756,074
<p>First things first:<br> What you wanted was merge</p> <pre><code>df1.merge(df2) </code></pre> <p><a href="http://i.stack.imgur.com/HnoA8.png" rel="nofollow"><img src="http://i.stack.imgur.com/HnoA8.png" alt="enter image description here"></a></p> <hr> <p><code>join</code> defaults to merging on the <code>index</...
2
2016-09-28T19:27:47Z
[ "python", "python-3.x", "pandas", "dataframe" ]
How to map hidden states to their corresponding categories after decoding in hmmlearn (Hidden Markov Model)?
39,756,006
<p>I would like to predict hidden states using Hidden Markov Model (decoding problem). The data is categorical. The hidden states include Hungry, Rest, Exercise and Movie. The observation set include Food, Home, Outdoor &amp; Recreation and Arts &amp; Entertainment. My program is first to train the HMM based on the obs...
0
2016-09-28T19:23:37Z
39,767,561
<p>This is known as label-switching problem. The log-likelihood of the model sums over all of the states and is therefore independent of the particular ordering.</p> <p>As far as I know, there is no general recipe for dealing with it. Among the things you might try are:</p> <ul> <li>Find a partially labelled dataset,...
0
2016-09-29T10:17:23Z
[ "python", "hidden-markov-models", "hmmlearn" ]
MissingSchema: Invalid URL '/': No schema supplied. Perhaps you meant http:///?
39,756,016
<pre><code>for l in l1: r = requests.get(l) html = r.content root = lxml.html.fromstring(html) urls = root.xpath('//div[@class="media-body"]//@href') l2.extend(urls) </code></pre> <p>while running the above code this error coming. any solution??</p> <p>MissingSchemaTraceback (most recent call last)</p> <p>Missing...
-1
2016-09-28T19:24:08Z
39,756,927
<pre><code>urls = root.xpath('//div[1]/header/div[3]/nav/ul/li/a/@href') </code></pre> <p>These HREFs aren't full URLs; they're essentially just pathnames (i.e. <code>/foo/bar/thing.html</code>).</p> <p>When you click on one of these links in a browser, the browser is smart enough to prepend the current page's scheme...
0
2016-09-28T20:19:46Z
[ "python" ]
How to separate a numpy array into separate columns in pandas
39,756,150
<p>I have a dataframe that looks like</p> <pre><code> ID_0 ID_1 ID_2 0 a b 0.05 1 a b 0.10 2 a b 0.19 3 a c 0.25 4 a c 0.40 5 a c 0.65 6 a c 0.71 7 d c 0.95 8 d c 1.00 </code></pre> <p>I want to groupby and make a normalized histogram of the ID_2 column...
1
2016-09-28T19:32:36Z
39,756,435
<p>You can construct a series object from each numpy array and the elements will be broadcasted as columns:</p> <pre><code>import pandas as pd import numpy as np df.groupby(['ID_0', 'ID_1']).apply(lambda x: pd.Series(np.histogram(x['ID_2'], range = (0,1), density=True)[0])).reset_index() </code></pre> <p><a href="htt...
3
2016-09-28T19:48:04Z
[ "python", "pandas", "numpy" ]
What is the cause of the error in this Python WMI script? (Windows 8.1) (Network adapter configuration) (Python 2.7)
39,756,172
<p>I am trying to make a Python script that will set my IP address to a static one instead of a dynamic one. I have searched up methods for this and the WMI implementation for Python seemed to be the best option. The stackoverflow question I got the information about is <a href="http://stackoverflow.com/a/7581831/58994...
0
2016-09-28T19:33:53Z
39,756,598
<p>SetDNSServerSearchOrder is looking for an array of Strings</p> <pre><code>c = nic.SetDNSServerSearchOrder(dns) </code></pre> <p>should be</p> <pre><code>c = nic.SetDNSServerSearchOrder([dns]) </code></pre>
1
2016-09-28T19:57:54Z
[ "python", "windows", "wmi" ]
Cost function erratically varying
39,756,186
<p><strong>Background</strong></p> <p>I am designing a neural network solution for multiclass classification problem using tensorflow.The input data consist of 16 features and 6000 training examples to be read from csv file having 17 columns(16 features+1 label) and 6000 rows(training examples).I have decided to take ...
1
2016-09-28T19:34:39Z
39,779,564
<p>Whenever you see your cost function increase when you use gradient descent, you should try <strong>reducing the learning rate parameter</strong>. Try repeatedly decreasing the learning rate by 1/10 until you see the loss decrease monotonically.</p>
0
2016-09-29T20:37:44Z
[ "python", "machine-learning", "neural-network", "tensorflow" ]
Specfying lease time in DHCP request packet
39,756,217
<p>I am trying to create a Dhcp request packet using scapy. Is there any way in which I can specify DHCP lease time in my request packet?</p>
1
2016-09-28T19:36:15Z
39,756,801
<p>Put option #51, with the desired lease time as its value, in the <code>options</code> section of the <code>DHCPREQUEST</code> or <code>DHCPDISCOVER</code> packet.</p> <p>From <a href="http://www.freesoft.org/CIE/RFC/2131/16.htm" rel="nofollow">RFC 2131 Section 3.5</a>:</p> <blockquote> <p>In addition, the client...
0
2016-09-28T20:11:04Z
[ "python", "networking", "scapy", "dhcp" ]
How to access the project root folder
39,756,254
<p>Below is a screenshot of my project. While I can access my <code>_files_inner</code> folder quite easily with <code>pd.read_csv("./_files_inner/games.csv")</code> I find it tricky to access my 'root' folder <code>_files</code></p> <p>if you see my project explorer, I'm trying to access the <code>_files</code> but w...
1
2016-09-28T19:38:18Z
39,756,504
<p><code>try using ../_files_inner/games.csv</code></p>
1
2016-09-28T19:52:39Z
[ "python", "eclipse" ]
tkinter ttk iterating through treeview
39,756,379
<p>I an using a tkinter ttk GUI to present data on files in a server. The information is stored in a ttk treeview and presented as a table. The goal is for the user to be able to filter these rows so that functions can be performed only on those visible in the treeview after the user is done filtering.</p> <p>Problem ...
1
2016-09-28T19:44:12Z
39,762,166
<p>To iterate through a treeview's individual entries, get a list of treeview item 'id's and use that to iterate in a 'for' loop:</p> <pre><code>#Column integer to match the column which was clicked in the table col=int(treeview.identify_column(event.x).replace('#',''))-1 #Create list of 'id's listOfEntriesInTreeView...
0
2016-09-29T05:35:12Z
[ "python", "tkinter", "treeview", "ttk" ]
How to remove whitespace in a list
39,756,599
<p>I can't remove my whitespace in my list. </p> <pre><code>invoer = "5-9-7-1-7-8-3-2-4-8-7-9" cijferlijst = [] for cijfer in invoer: cijferlijst.append(cijfer.strip('-')) </code></pre> <p>I tried the following but it doesn't work. I already made a list from my string and seperated everything but the <code>"-"</...
0
2016-09-28T19:57:54Z
39,756,657
<p>Try that:</p> <pre><code>&gt;&gt;&gt; ''.join(invoer.split('-')) '597178324879' </code></pre>
4
2016-09-28T20:01:40Z
[ "python", "list" ]
How to remove whitespace in a list
39,756,599
<p>I can't remove my whitespace in my list. </p> <pre><code>invoer = "5-9-7-1-7-8-3-2-4-8-7-9" cijferlijst = [] for cijfer in invoer: cijferlijst.append(cijfer.strip('-')) </code></pre> <p>I tried the following but it doesn't work. I already made a list from my string and seperated everything but the <code>"-"</...
0
2016-09-28T19:57:54Z
39,756,659
<p>This looks a lot like the following question: <a href="http://stackoverflow.com/questions/3232953/python-removing-spaces-from-list-objects">Python: Removing spaces from list objects</a></p> <p>The answer being to use <code>strip</code> instead of <code>replace</code>. Have you tried </p> <pre><code>abc = x.strip('...
1
2016-09-28T20:01:54Z
[ "python", "list" ]
How to remove whitespace in a list
39,756,599
<p>I can't remove my whitespace in my list. </p> <pre><code>invoer = "5-9-7-1-7-8-3-2-4-8-7-9" cijferlijst = [] for cijfer in invoer: cijferlijst.append(cijfer.strip('-')) </code></pre> <p>I tried the following but it doesn't work. I already made a list from my string and seperated everything but the <code>"-"</...
0
2016-09-28T19:57:54Z
39,756,666
<p>If you want the numbers in string without <code>-</code>, use <a href="https://docs.python.org/2/library/string.html#string.replace" rel="nofollow"><code>.replace()</code></a> as:</p> <pre><code>&gt;&gt;&gt; string_list = "5-9-7-1-7-8-3-2-4-8-7-9" &gt;&gt;&gt; string_list.replace('-', '') '597178324879' </code></pr...
2
2016-09-28T20:02:09Z
[ "python", "list" ]
How should I make a class that can be used as my main app window, but also can be used as a secondary window
39,756,617
<p>I know that I can subclass a tk.Frame (or ttk.Frame) and add that to a TopLevel to make secondary windows, but I'm not sure how I should use that as the main window. I know that creating an instance of a Frame class and calling .mainloop() on it seems to work for using it as the main window, but I feel like that's b...
-1
2016-09-28T19:58:59Z
39,757,007
<p>Create a subclass of a Frame, and then put it either in the root window or a toplevel. In either case, you still call <code>mainloop</code> only once on the root window.</p> <p>The only care you have to take is that you have to be careful about letting the user close the root window, because it will cause all of th...
1
2016-09-28T20:24:18Z
[ "python", "tkinter", "tk", "toplevel" ]
How should I make a class that can be used as my main app window, but also can be used as a secondary window
39,756,617
<p>I know that I can subclass a tk.Frame (or ttk.Frame) and add that to a TopLevel to make secondary windows, but I'm not sure how I should use that as the main window. I know that creating an instance of a Frame class and calling .mainloop() on it seems to work for using it as the main window, but I feel like that's b...
-1
2016-09-28T19:58:59Z
39,760,079
<p>Do you mean having a home screen that you can flip back to? If so, you can try looking here: <a href="http://stackoverflow.com/questions/14817210/using-buttons-in-tkinter-to-navigate-to-different-pages-of-the-application">Using buttons in Tkinter to navigate to different pages of the application?</a></p>
1
2016-09-29T01:42:47Z
[ "python", "tkinter", "tk", "toplevel" ]
Make a non-blocking request with requests when running Flask with Gunicorn and Gevent
39,756,807
<p>My Flask application will receive a request, do some processing, and then make a request to a slow external endpoint that takes 5 seconds to respond. It looks like running Gunicorn with Gevent will allow it to handle many of these slow requests at the same time. How can I modify the example below so that the view ...
10
2016-09-28T20:11:22Z
39,903,915
<p>You can use <code>grequests</code>. It allows other greenlets to run while the request is made. It is compatible with the <code>requests</code> library and returns a <code>requests.Response</code> object. The usage is as follows:</p> <pre><code>import grequests @app.route('/do', methods = ['POST']) def do(): r...
0
2016-10-06T19:10:04Z
[ "python", "flask", "python-requests", "gunicorn", "gevent" ]
Make a non-blocking request with requests when running Flask with Gunicorn and Gevent
39,756,807
<p>My Flask application will receive a request, do some processing, and then make a request to a slow external endpoint that takes 5 seconds to respond. It looks like running Gunicorn with Gevent will allow it to handle many of these slow requests at the same time. How can I modify the example below so that the view ...
10
2016-09-28T20:11:22Z
39,911,201
<p>First a bit of background, A blocking socket is the default kind of socket, once you start reading your app or thread does not regain control until data is actually read, or you are disconnected. This is how <code>python-requests</code>, operates by default. There is a spin off called <code>grequests</code> which pr...
1
2016-10-07T06:56:50Z
[ "python", "flask", "python-requests", "gunicorn", "gevent" ]
Make a non-blocking request with requests when running Flask with Gunicorn and Gevent
39,756,807
<p>My Flask application will receive a request, do some processing, and then make a request to a slow external endpoint that takes 5 seconds to respond. It looks like running Gunicorn with Gevent will allow it to handle many of these slow requests at the same time. How can I modify the example below so that the view ...
10
2016-09-28T20:11:22Z
39,941,098
<p>If you're deploying your Flask application with gunicorn, it is already non-blocking. If a client is waiting on a response from one of your views, another client can make a request to the same view without a problem. There will be multiple workers to process multiple requests concurrently. No need to change your cod...
1
2016-10-09T07:27:39Z
[ "python", "flask", "python-requests", "gunicorn", "gevent" ]
Why can't I change the icon on a tkMessagebox.askyesno() on OS X?
39,756,822
<p><code>tkMessageBox.askyesno('Title', 'Message', icon=tkMessageBox.WARNING)</code> on OS X just gives me the rocket icon.</p> <p>I know there is some weirdness with OS X and tkMessageBox icons because <code>tkMessageBox.showerror()</code> just shows the rocket icon, but <code>tkMessageBox.showwarning</code> shows a ...
1
2016-09-28T20:12:49Z
39,757,032
<p>I found a solution:</p> <pre><code>tkMessageBox.askretrycancel(title, message, type=tkMessageBox.YESNO) </code></pre> <p>seems to work, but <strong>both buttons presses return <code>False</code>, so it's not of any use.</strong></p> <pre><code>tkMessageBox.showwarning(title, message, type=tkMessageBox.YESNO) </co...
0
2016-09-28T20:26:25Z
[ "python", "osx", "tkinter", "tkmessagebox" ]
Using parameters in the XPath
39,756,842
<p>I am trying to use parameters in the xpath expression but no luck.</p> <pre><code>field = //*[@id=%s]/optgroup[@label=%s]/*[contains(@title, %s)]"%(FIELDTYPE, label, fieldtype) </code></pre> <p>What am I doing wrong?</p>
0
2016-09-28T20:14:37Z
39,756,871
<p>Don't forget about the quotes around the placeholders:</p> <pre><code>"//*[@id='%s']/optgroup[@label='%s']/[contains(@title, '%s')]" % (FIELDTYPE, label, fieldtype) </code></pre> <p>Also note that I've also added the <code>*</code> after the <code>//</code>.</p>
3
2016-09-28T20:16:13Z
[ "python", "selenium", "xpath" ]
Python Schematics model conversion error rouge field
39,756,878
<p>Please help me on this, I have a model like this which i wanted to import,</p> <pre><code>cricket: players: 1 : Mike 2 : Mark 3 : Miller scores: 12: 222 13: 255 15: 555 </code></pre> <p>When using <code>DictType(ModelType(CricModel), default=None, deserialize_from=('cricket', 'params'))</code> it's t...
1
2016-09-28T20:16:29Z
39,794,666
<p>Need to use ModelType(ModelName) rather thans DictType</p>
0
2016-09-30T15:06:58Z
[ "python", "python-2.7", "python-3.x", "pip", "pycharm" ]
Stuck defining composition function in python
39,756,890
<p>input: two functions f and g, represented as dictionaries, such that g ◦ f exists. output: dictionary that represents the function g ◦ f. example: given f = {0:’a’, 1:’b’} and g = {’a’:’apple’, ’b’:’banana’}, return {0:’apple’, 1:’banana’}.</p> <p>The closest to the correct answ...
1
2016-09-28T20:17:06Z
39,756,948
<p>You need to just iterate over one dict <code>f</code>, and in the comprehension, replace the value of f with the value of <code>g</code> </p> <pre><code>f = {0:'a', 1:'b'} g = {'a':'apple', 'b': 'banana'} new_dict = {k: g[v] for k, v in f.items()} # Value of new_dict = {0: 'apple', 1: 'banana'} </code></pre>
0
2016-09-28T20:21:31Z
[ "python", "composition" ]
Stuck defining composition function in python
39,756,890
<p>input: two functions f and g, represented as dictionaries, such that g ◦ f exists. output: dictionary that represents the function g ◦ f. example: given f = {0:’a’, 1:’b’} and g = {’a’:’apple’, ’b’:’banana’}, return {0:’apple’, 1:’banana’}.</p> <p>The closest to the correct answ...
1
2016-09-28T20:17:06Z
39,756,980
<p>The correct dict comprehension would be:</p> <pre><code>{i:g[f[i]] for i in f} </code></pre> <p>You did:</p> <pre><code>{i:g[j] for i in f for j in g} </code></pre> <p>That mapped every i to every <code>i</code> to every value in <code>g</code>, but then dict removed duplicate keys.</p> <p>To see what is going ...
0
2016-09-28T20:22:54Z
[ "python", "composition" ]
How to check HTTP errors for more than two URLs?
39,756,947
<p><strong><em>Question: I've 3 URLS - testurl1, testurl2 and testurl3. I'd like to try testurl1 first, if I get 404 error then try testurl2, if that gets 404 error then try testurl3. How to achieve this? So far I've tried below but that works only for two url, how to add support for third url?</em></strong></p> <pre>...
2
2016-09-28T20:21:28Z
39,757,025
<p>Another job for plain old for loop:</p> <pre><code>for url in testurl1, testurl2, testurl3 req = Request(url) try: response = urlopen(req) except HttpError as err: if err.code == 404: continue raise else: # do what you want with successful response here (o...
2
2016-09-28T20:25:52Z
[ "python", "http-error" ]
How to check HTTP errors for more than two URLs?
39,756,947
<p><strong><em>Question: I've 3 URLS - testurl1, testurl2 and testurl3. I'd like to try testurl1 first, if I get 404 error then try testurl2, if that gets 404 error then try testurl3. How to achieve this? So far I've tried below but that works only for two url, how to add support for third url?</em></strong></p> <pre>...
2
2016-09-28T20:21:28Z
39,757,114
<p>Hmmm maybe something like this?</p> <pre><code>from urllib2 import Request, urlopen from urllib2 import URLError, HTTPError def checkfiles(): req = Request('http://testurl1') try: response = urlopen(req) url1=('http://testurl1') except HTTPError, URLError: try: url1...
0
2016-09-28T20:31:16Z
[ "python", "http-error" ]
comparing strings in list to strings in list
39,757,126
<p>I see that the code below can check if a word is </p> <pre><code>list1 = 'this' compSet = [ 'this','that','thing' ] if any(list1 in s for s in compSet): print(list1) </code></pre> <p>Now I want to check if a word in a list is in some other list as below:</p> <pre><code>list1 = ['this', 'and', 'that' ] compSet = [...
7
2016-09-28T20:32:09Z
39,757,180
<p>Try that:</p> <pre><code> &gt;&gt;&gt; l = list(set(list1)-set(compSet)) &gt;&gt;&gt; l ['this', 'and'] </code></pre>
1
2016-09-28T20:35:14Z
[ "python", "list" ]
comparing strings in list to strings in list
39,757,126
<p>I see that the code below can check if a word is </p> <pre><code>list1 = 'this' compSet = [ 'this','that','thing' ] if any(list1 in s for s in compSet): print(list1) </code></pre> <p>Now I want to check if a word in a list is in some other list as below:</p> <pre><code>list1 = ['this', 'and', 'that' ] compSet = [...
7
2016-09-28T20:32:09Z
39,757,182
<p>There is a simple way to check for the intersection of two lists: convert them to a set and use <code>intersection</code>:</p> <pre><code>&gt;&gt;&gt; list1 = ['this', 'and', 'that' ] &gt;&gt;&gt; compSet = [ 'check','that','thing' ] &gt;&gt;&gt; set(list1).intersection(compSet) {'that'} </code></pre> <p>You can a...
8
2016-09-28T20:35:20Z
[ "python", "list" ]
Distinct rows from a list of dictionaries based on values
39,757,176
<p>I have this sample input below <strong>sampleInputDbData</strong></p> <pre><code>def sampleInputDbData( self ): return \ [ {'FundCode': 300, 'FundName': 'First Fund', 'ProdStartDate': dt(2016,7,3,4,5,6), 'ProdEndDate': dt(2016,8,3,4,5,6), 'FundFee': 100}, {'FundCode': 300, 'FundName': 'First...
1
2016-09-28T20:35:06Z
39,757,344
<p>This works:</p> <pre><code>from collections import defaultdict from operator import itemgetter code_dict = defaultdict(list) for d in sampleInputDbData: code_dict[d["FundCode"]].append(d) output_data = [max(d, key=itemgetter("ProdEndDate")) for d in code_dict.values()] </code></pre> <p>I first create a defau...
0
2016-09-28T20:45:59Z
[ "python" ]
How can I make a python candlestick chart clickable in matplotlib
39,757,188
<p>I am trying to make a OHLC graph plotted with matplotlib interactive upon the user clicking on a valid point. The data is stored as a pandas dataframe of the form </p> <pre><code>index PX_BID PX_ASK PX_LAST PX_OPEN PX_HIGH PX_LOW 2016-07-01 1.1136 1.1137 1.1136 1.1106 1.1169 1.1072 2016-07-04 ...
2
2016-09-28T20:35:49Z
39,757,585
<p>You need to set <code>set_picker(True)</code> to enable a pick event or give a tolerance in points as a float (see <a href="http://matplotlib.org/api/artist_api.html#matplotlib.artist.Artist.set_picker" rel="nofollow">http://matplotlib.org/api/artist_api.html#matplotlib.artist.Artist.set_picker</a>).</p> <p>So in ...
1
2016-09-28T21:01:11Z
[ "python", "pandas", "matplotlib", "graph", "interactive" ]
using django-registration form instead of own
39,757,258
<p>So I am using <code>django-registration</code> for email activation and the like. I defined my form and am calling to it properly however for some reason it is using the base form out of <code>django-registration</code> instead of my own. I have absolutely no clue as to why this is happening, any thoughts?</p> <p>v...
1
2016-09-28T20:41:20Z
39,757,683
<p>Since <code>urlpatterns</code> has that order:</p> <pre><code>url(r'^accounts/', include('registration.backends.hmac.urls')), url(r'^accounts/register/$', views.register, name='register'), url(r'^accounts/register/complete/$', views.registration_complete, name='registration_complete'), </code></pre> <p>Url from <c...
1
2016-09-28T21:07:55Z
[ "python", "django", "forms", "django-registration" ]
strftime function pandas - Python
39,757,293
<p>I am trying to strip the time out of the date when the dataframe writes to excel but have been unsuccessful. The weird thing is, i am able to manipute the dataframe by using the lambda and striptime function below and can see it the function is working by my 'print df6'. However, for some reason when I open the exce...
1
2016-09-28T20:43:10Z
39,758,866
<p>strftime is creating a textual representation of a datetime value which later is formatted and displayed by Excel according to its formatting templates. We could change this formatting template using <code>date_format</code> parameter in our ExcelWriter constructor e.g.:<code>writer = pandas.ExcelWriter("test.xlsx",...
1
2016-09-28T22:55:36Z
[ "python", "pandas" ]
How to serialize a scandir.DirEntry in Python for sending through a network socket?
39,757,325
<p>I have server and client programs that communicate with each other through a network socket.</p> <p>What I want is to send a directory entry (<code>scandir.DirEntry</code>) obtained from <code>scandir.scandir()</code> through the socket.</p> <p>For now I am using <code>pickle</code> and <code>cPickle</code> module...
0
2016-09-28T20:45:07Z
39,767,389
<p>Well I myself have figured out that for instances of non-standard classes like this <code>scandir.DirEntry</code>, the best way is to <strong>convert the class member data into a (possibly nested) combination of standard objects</strong> like (<code>list</code>, <code>dict</code>, etc.).</p> <p>For example, in the ...
0
2016-09-29T10:09:17Z
[ "python", "sockets", "serialization", "scandir" ]
Numpy: Computing sum(array[i, a[i]:b[i]]) for all rows i
39,757,355
<p>I have a numpy array <code>arr</code> and a list of slice start points <code>start</code> and a list of slice endpoints <code>end</code>. For each row <code>i</code>, I want to determine the sum of the elements from <code>start[i]</code> to <code>end[i]</code>. That is, I want to determine</p> <pre><code>[np.sum(ar...
1
2016-09-28T20:47:02Z
39,757,459
<p>Here's a vectorized approach using <a href="http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html" rel="nofollow"><code>NumPy broadcasting</code></a> and <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.einsum.html" rel="nofollow"><code>np.einsum</code></a> -</p> <pre><code># Create range ...
3
2016-09-28T20:53:33Z
[ "python", "arrays", "numpy", "sum", "slice" ]
How can I resample a DataFrame so that it is properly aligned with another DataFrame?
39,757,437
<p>I've got several Pandas DataFrames at different time intervals. One is at the daily level:</p> <pre><code>DatetimeIndex(['2007-12-01', '2007-12-02', '2007-12-03', '2007-12-04', '2007-12-05', '2007-12-06', '2007-12-07', '2007-12-08', '2007-12-09', '2007-12-10', ... ...
0
2016-09-28T20:51:51Z
39,761,232
<p>Consider using pandas <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.resample.html" rel="nofollow">DataFrame.resample()</a>:</p> <pre><code># EXAMPLE DATA OF SEQUENTIAL DATES AND RANDOM NUMBERS index = pd.date_range('12/01/2007', periods=3197, freq='D', dtype='datetime64[ns]') serie...
2
2016-09-29T04:07:05Z
[ "python", "python-3.x", "pandas" ]
How to send emails with names in headers from Python
39,757,504
<p>I need to send nice-looking emails from Python with address headers that contain names - somehow something that never pops up in tutorials.</p> <p>I'm using email.mime.text.MIMEText() to create the email, but setting <code>msg['To'] = 'á &lt;x@y.cz&gt;'</code> rather than utf8-encoding only the name part, will utf...
1
2016-09-28T20:56:23Z
39,758,812
<p>You have to use the right policy from <code>email.policy</code> to get the correct behaviour.</p> <h2>Wrong Policy</h2> <p><a href="https://docs.python.org/3.5/library/email.message.html#email.message.Message" rel="nofollow"><code>email.message.Message</code></a> will use <code>email.policy.Compat32</code> by defa...
1
2016-09-28T22:50:06Z
[ "python", "python-3.x", "email" ]
Test Requests for Django Rest Framework aren't parsable by its own Request class
39,757,530
<p>I'm writing an endpoint to receive and parse <a href="https://developer.github.com/webhooks/#example-delivery" rel="nofollow">GitHub Webhook payloads</a> using Django Rest Framework 3. In order to match the payload specification, I'm writing a payload request factory and testing that it's generating valid requests.<...
1
2016-09-28T20:58:10Z
39,757,885
<p>"Yo dawg, I heard you like Request, cos' you put a Request inside a Request" XD</p> <p>I'd do it like this:</p> <pre><code>from rest_framework.test import APIClient client = APIClient() response = client.post('/', {'github': 'payload'}, format='json') self.assertEqual(response.data, {'github': 'payload'}) # ...or...
1
2016-09-28T21:22:02Z
[ "python", "unit-testing", "django-rest-framework" ]
Test Requests for Django Rest Framework aren't parsable by its own Request class
39,757,530
<p>I'm writing an endpoint to receive and parse <a href="https://developer.github.com/webhooks/#example-delivery" rel="nofollow">GitHub Webhook payloads</a> using Django Rest Framework 3. In order to match the payload specification, I'm writing a payload request factory and testing that it's generating valid requests.<...
1
2016-09-28T20:58:10Z
39,770,829
<p>Looking at the <a href="https://github.com/tomchristie/django-rest-framework/blob/master/tests/test_testing.py" rel="nofollow">tests for <code>APIRequestFactory</code> in DRF</a>, <a href="https://github.com/tomchristie/django-rest-framework/blob/master/tests/test_testing.py#L18-L23" rel="nofollow">stub views</a> ar...
0
2016-09-29T12:50:30Z
[ "python", "unit-testing", "django-rest-framework" ]
Working with floating point NumPy arrays for comparison and related operations
39,757,559
<p>I have an array of random floats and I need to compare it to another one that has the same values in a different order. For that matter I use the sum, product (and other combinations depending on the dimension of the table hence the number of equations needed).</p> <p>Nevertheless, I encountered a precision issue w...
1
2016-09-28T20:59:39Z
39,758,154
<p>For the listed code, you can use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.isclose.html" rel="nofollow"><code>np.isclose</code></a> and with it tolerance values could be specified too.</p> <p>Using the provided sample, let's see how it could be used -</p> <pre><code>In [201]: n = 10 ....
2
2016-09-28T21:43:27Z
[ "python", "arrays", "numpy", "random", "precision" ]
Use regex to match 5 num, dot, 1 num, dot, 5 num
39,757,573
<p>I'm trying to create regex to match the following pattern:</p> <pre><code>00000.1.17372 </code></pre> <p>i.e: <code>5 Numbers DOT 1 Number DOT 5 Numbers</code></p> <p>I have tried the following re.match:</p> <pre><code>find = re.match('d{5}.d{1}.d{5}', string) </code></pre> <p>In context:</p> <pre><code>import...
0
2016-09-28T21:00:18Z
39,757,619
<p>Use the following with <code>re.findall</code>:</p> <pre><code>r'\b\d{5}\.\d\.\d{5}\b' </code></pre> <p>See the <a href="https://regex101.com/r/ExVBOp/1" rel="nofollow">regex demo</a></p> <p>The point is:</p> <ul> <li>to match a digit, you need to use <code>\d</code></li> <li>a dot must be escaped to match a lit...
2
2016-09-28T21:03:21Z
[ "python", "regex", "python-2.7" ]
Use regex to match 5 num, dot, 1 num, dot, 5 num
39,757,573
<p>I'm trying to create regex to match the following pattern:</p> <pre><code>00000.1.17372 </code></pre> <p>i.e: <code>5 Numbers DOT 1 Number DOT 5 Numbers</code></p> <p>I have tried the following re.match:</p> <pre><code>find = re.match('d{5}.d{1}.d{5}', string) </code></pre> <p>In context:</p> <pre><code>import...
0
2016-09-28T21:00:18Z
39,757,626
<p>The pattern you want is:</p> <pre><code>\d{5}\.\d\.\d{5} </code></pre> <p>You need to escape the dots and use the proper token for a number, which is <code>\d</code>.</p>
0
2016-09-28T21:03:42Z
[ "python", "regex", "python-2.7" ]
What is causing 'unicode' object has no attribute 'toordinal' in pyspark?
39,757,591
<p>I got this error but I don't what causes it. My python code ran in pyspark. The stacktrace is long and i just show some of them. All the stacktrace doesn't show my code in it so I don't know where to look for. What is possible the cause for this error? </p> <pre><code>/usr/hdp/2.4.2.0-258/spark/python/lib/py4j-0.9-...
0
2016-09-28T21:01:39Z
39,757,681
<p>The specific exception is caused by trying to store a <code>unicode</code> value in a <em>date</em> datatype that is part of a struct. The conversion of the Python type to Spark internal representation expected to be able to call <a href="https://docs.python.org/3/library/datetime.html#datetime.date.toordinal" rel="...
1
2016-09-28T21:07:37Z
[ "python", "pyspark" ]
Write multiple rows from dict using csv
39,757,609
<p><strong>Update</strong>: I do not want to use <code>pandas</code> because I have a list of dict's and want to write each one to disk as they come in (part of webscraping workflow).</p> <p>I have a dict that I'd like to write to a csv file. I've come up with a solution, but I'd like to know if there's a more <code>p...
0
2016-09-28T21:02:44Z
39,757,688
<p>If you don't mind using a 3rd-party package, you could do it with <a href="http://pandas.pydata.org/" rel="nofollow"><code>pandas</code></a>.</p> <pre><code>import pandas as pd pd.DataFrame(test_dict).to_csv('test.csv', index=False) </code></pre> <p><strong>update</strong></p> <p>So, you have several dictionaries...
0
2016-09-28T21:08:30Z
[ "python", "csv" ]
Write multiple rows from dict using csv
39,757,609
<p><strong>Update</strong>: I do not want to use <code>pandas</code> because I have a list of dict's and want to write each one to disk as they come in (part of webscraping workflow).</p> <p>I have a dict that I'd like to write to a csv file. I've come up with a solution, but I'd like to know if there's a more <code>p...
0
2016-09-28T21:02:44Z
39,757,714
<p>Try using pandas of python..</p> <p>Here is a simple example</p> <pre><code>import pandas as pd test_dict = {"review_id": [1, 2, 3, 4], "text": [5, 6, 7, 8]} d1 = pd.DataFrame(test_dict) d1.to_csv("output.csv") </code></pre> <p>Cheers</p>
0
2016-09-28T21:10:24Z
[ "python", "csv" ]
Write multiple rows from dict using csv
39,757,609
<p><strong>Update</strong>: I do not want to use <code>pandas</code> because I have a list of dict's and want to write each one to disk as they come in (part of webscraping workflow).</p> <p>I have a dict that I'd like to write to a csv file. I've come up with a solution, but I'd like to know if there's a more <code>p...
0
2016-09-28T21:02:44Z
39,757,893
<p>Your first example will work with minor edits. <code>DictWriter</code> expects a <code>list</code> of <code>dict</code>s rather than a <code>dict</code> of <code>list</code>s. Assuming you can't change the format of the <code>test_dict</code>:</p> <pre><code>import csv test_dict = {"review_id": [1, 2, 3, 4], ...
0
2016-09-28T21:22:52Z
[ "python", "csv" ]
Write multiple rows from dict using csv
39,757,609
<p><strong>Update</strong>: I do not want to use <code>pandas</code> because I have a list of dict's and want to write each one to disk as they come in (part of webscraping workflow).</p> <p>I have a dict that I'd like to write to a csv file. I've come up with a solution, but I'd like to know if there's a more <code>p...
0
2016-09-28T21:02:44Z
39,757,896
<p>The built-in <a href="https://docs.python.org/2/library/functions.html#zip" rel="nofollow"><code>zip</code> function</a> can join together different iterables into tuples which can be passed to <code>writerows</code>. Try this as the last line:</p> <pre><code>writer.writerows(zip(test_dict["review_id"], test_dict["...
0
2016-09-28T21:22:57Z
[ "python", "csv" ]
Write multiple rows from dict using csv
39,757,609
<p><strong>Update</strong>: I do not want to use <code>pandas</code> because I have a list of dict's and want to write each one to disk as they come in (part of webscraping workflow).</p> <p>I have a dict that I'd like to write to a csv file. I've come up with a solution, but I'd like to know if there's a more <code>p...
0
2016-09-28T21:02:44Z
39,758,030
<p>The problem is that with <code>DictWriter.writerows()</code> you are forced to have a dict for each row. Instead you can simply add the values changing your csv creation:</p> <pre><code>with open('test.csv', 'w') as csvfile: fieldnames = test_dict.keys() fieldvalues = zip(*test_dict.values()) writer...
0
2016-09-28T21:33:24Z
[ "python", "csv" ]
Write multiple rows from dict using csv
39,757,609
<p><strong>Update</strong>: I do not want to use <code>pandas</code> because I have a list of dict's and want to write each one to disk as they come in (part of webscraping workflow).</p> <p>I have a dict that I'd like to write to a csv file. I've come up with a solution, but I'd like to know if there's a more <code>p...
0
2016-09-28T21:02:44Z
39,758,347
<p>You have two different problems in your question:</p> <ol> <li>Create a csv file from a dictionary where the values are containers and not primitives.</li> </ol> <p>For the first problem, the solution is generally to transform the container type into a primitive type. The most common method is creating a json-str...
0
2016-09-28T21:59:36Z
[ "python", "csv" ]
tf.contrib.learn Quickstart: Fix float64 Warning
39,757,639
<p>I'm getting myself started with TensorFlow by working through the posted tutorials.</p> <p>I have the Linux CPU python2.7 version 0.10.0 running on Fedora 23 (twenty three).</p> <p>I am trying the tf.contrib.learn Quickstart tutorial as per the following code.</p> <blockquote> <p><a href="https://www.tensorflow...
0
2016-09-28T21:04:41Z
39,859,570
<p>I received this answer from the development team via Git-hub.</p> <blockquote> <p>Hi @qweelar, the float64 warning is due to a bug with the load_csv_with_header function that was fixed in commit b6813bd. This fix isn't in TensorFlow release 0.10, but should be in the next release.</p> <p>In the meantime, for...
0
2016-10-04T18:44:14Z
[ "python", "python-2.7", "tensorflow" ]
Python video system not intilated
39,757,662
<p>Here it is, I dont know what is wrong, I looked at other answers but I still dont know what is wrong?</p> <pre><code>import pygame pygame.init() gameWindow = pygame.display.set_mode((1000,600)); pygame.display.set_caption("Practice") #game starts gameActive = True while gameActive: for event in pygame.event.g...
1
2016-09-28T21:06:20Z
39,759,942
<p>You have <code>pygame.quit()</code> in your main loop, so after one iteration through the loop you are calling <code>pygame.quit()</code>, which causes pygame to no longer be initialized which creates the error of not having a display surface. </p> <p>Moving <code>pygame.quit()</code> out of the main while loop fix...
0
2016-09-29T01:23:54Z
[ "python", "pygame" ]
Selenium click trouble (Python)
39,757,696
<p>I am using Selenium (<code>ChromeDriver</code>) to automate a <a href="https://www.chess.com/play/computer" rel="nofollow">chess site</a> but I am having trouble clicking on a piece and moving it. I have tried <code>click()</code> and <code>ActionChains</code> but nothing is working. Here is my code:</p> <pre><code...
0
2016-09-28T21:08:59Z
39,761,172
<p>This is somewhat complicated. The chess pieces are <code>IMG</code>s that can be clicked but empty chess squares are not represented by an element. You will have to determine a coordinate system and use <a href="http://selenium-python.readthedocs.io/api.html#selenium.webdriver.common.action_chains.ActionChains.move_...
0
2016-09-29T04:00:04Z
[ "python", "selenium", "selenium-webdriver" ]
Selenium click trouble (Python)
39,757,696
<p>I am using Selenium (<code>ChromeDriver</code>) to automate a <a href="https://www.chess.com/play/computer" rel="nofollow">chess site</a> but I am having trouble clicking on a piece and moving it. I have tried <code>click()</code> and <code>ActionChains</code> but nothing is working. Here is my code:</p> <pre><code...
0
2016-09-28T21:08:59Z
39,764,746
<p>Selenium Webdriver is not the right tool for it.</p> <p>You could try <a href="https://sourceforge.net/adobe/genie/wiki/Home/" rel="nofollow">Genie automation tool</a> if you are looking for a free tool. I've tried my hands on Genie, it's a bit complex but at the end it solves your problem.</p>
0
2016-09-29T08:07:46Z
[ "python", "selenium", "selenium-webdriver" ]
Trying to find smallest number
39,757,754
<p>In my program I'm trying to find the smallest number that python can give me. When I kept dividing a number by 2, I got 5 x 10^-324 (5e-324). I thought I could divide this by the biggest number I can use in python. I tried to get the biggest number in python by doing this:</p> <pre><code>z = 1 while True: ...
1
2016-09-28T21:13:13Z
39,757,815
<p>You may use <code>sys.float_info</code> to get the maximum/minimum representable finite float as:</p> <pre><code>&gt;&gt;&gt; import sys &gt;&gt;&gt; sys.float_info.min 2.2250738585072014e-308 &gt;&gt;&gt; sys.float_info.max 1.7976931348623157e+308 </code></pre> <p>Python uses double-precision floats, which can ho...
3
2016-09-28T21:17:06Z
[ "python", "numbers" ]
Trying to find smallest number
39,757,754
<p>In my program I'm trying to find the smallest number that python can give me. When I kept dividing a number by 2, I got 5 x 10^-324 (5e-324). I thought I could divide this by the biggest number I can use in python. I tried to get the biggest number in python by doing this:</p> <pre><code>z = 1 while True: ...
1
2016-09-28T21:13:13Z
39,758,010
<p>The key word that you're apparently missing is "<a href="https://en.wikipedia.org/wiki/Epsilon" rel="nofollow">epsilon</a>." If you search on <strong>Python epsilon value</strong> then it returns a links to <a href="http://stackoverflow.com/a/9528486/149076">StackOverflow: Value for epsilon in Python</a> near the t...
0
2016-09-28T21:32:14Z
[ "python", "numbers" ]
Trying to find smallest number
39,757,754
<p>In my program I'm trying to find the smallest number that python can give me. When I kept dividing a number by 2, I got 5 x 10^-324 (5e-324). I thought I could divide this by the biggest number I can use in python. I tried to get the biggest number in python by doing this:</p> <pre><code>z = 1 while True: ...
1
2016-09-28T21:13:13Z
39,758,456
<p>The smallest floating point number representable in Python is <code>5e-324</code>, or <code>2.0**-1075</code>.</p> <p>The other two answers have each given you half of what you need to find this number. It can be found by multiplying <code>sys.float_info.min</code> (<code>2.2250738585072014e-308</code>, the smalles...
1
2016-09-28T22:08:34Z
[ "python", "numbers" ]
Using python requests and beautiful soup to pull text
39,757,805
<p>thanks for taking a look at my problem. i would like to know if there is any way to pull the data-sitekey from this text... here is the url to the page <a href="https://e-com.secure.force.com/adidasUSContact/" rel="nofollow">https://e-com.secure.force.com/adidasUSContact/</a></p> <pre><code>&lt;div class="g-recaptc...
2
2016-09-28T21:16:27Z
39,757,879
<p>Ok now we have code, it is as simple as:</p> <pre><code>import requests from bs4 import BeautifulSoup soup = BeautifulSoup(requests.get("https://e-com.secure.force.com/adidasUSContact/").content, "html.parser") key = soup.select_one("#ncaptchaRecaptchaId")["data-sitekey"] </code></pre> <p><em>data-sitekey</em> ...
3
2016-09-28T21:21:41Z
[ "python", "beautifulsoup", "python-requests", "bs4" ]
Celery redis backend not always returning result
39,757,813
<p>I'm running a celery worker such that:</p> <pre><code> -------------- celery@ v3.1.23 (Cipater) ---- **** ----- --- * *** * -- Linux-4.4.0-31-generic-x86_64-with-debian-stretch-sid -- * - **** --- - ** ---------- [config] - ** ---------- .&gt; app: __main__:0x7fe76cd42400 - ** ---------- .&gt; transport:...
1
2016-09-28T21:16:55Z
39,768,592
<p><strong>You have a race condition.</strong> This is what happens:</p> <ol> <li><p>The loop arrives at <code>_, resp = r.blpop('/task_finished')</code> and blocks there.</p></li> <li><p>The task executes <code>r.rpush('/task_finished', task.request.id)</code></p></li> <li><p>The loop unblocks, executes <code>task = ...
0
2016-09-29T11:07:20Z
[ "python", "rabbitmq", "celery" ]
how to initialize multiple columns to existing pandas DataFrame
39,757,901
<p>how can I initialize multiple columns in a single instance in an existing pandas DataFrame object? I can initialize single column at an instance, this way:</p> <pre><code>df = pd.DataFrame({'a':[1,2,3],'b':[4,5,6]}, dtype='int') df['c'] = 0 </code></pre> <p>but i cannot do something like:</p> <pre><code>df[['c','...
3
2016-09-28T21:23:07Z
39,757,962
<p>i got a solution <a href="http://stackoverflow.com/questions/30926670/pandas-add-multiple-empty-columns-to-dataframe">here</a>. </p> <pre><code>df.reindex(columns = list['cd']) </code></pre> <p>will do the trick.</p> <p>actually it will be:</p> <pre><code>df.reindex(columns = list['abcd']) </code></pre>
1
2016-09-28T21:28:16Z
[ "python", "pandas", "dataframe" ]
how to initialize multiple columns to existing pandas DataFrame
39,757,901
<p>how can I initialize multiple columns in a single instance in an existing pandas DataFrame object? I can initialize single column at an instance, this way:</p> <pre><code>df = pd.DataFrame({'a':[1,2,3],'b':[4,5,6]}, dtype='int') df['c'] = 0 </code></pre> <p>but i cannot do something like:</p> <pre><code>df[['c','...
3
2016-09-28T21:23:07Z
39,758,675
<p><strong><em><code>pd.concat</code></em></strong></p> <pre><code>pd.concat([df, pd.DataFrame(0, df.index, list('cd'))], axis=1) </code></pre> <p><a href="http://i.stack.imgur.com/4L9rZ.png" rel="nofollow"><img src="http://i.stack.imgur.com/4L9rZ.png" alt="enter image description here"></a></p> <hr> <p><strong><em...
1
2016-09-28T22:33:32Z
[ "python", "pandas", "dataframe" ]
argparse: how to parse a single string argument OR a file listing many arguments?
39,757,910
<p>I have a use case where I'd like the user to be able to provide, as an argument to argparse, EITHER a single string OR a filename where each line has a string.</p> <p>Assume the user launches <code>./myscript.py -i foobar</code></p> <p>The logical flow I'm looking for is something like this:</p> <p>The script det...
0
2016-09-28T21:23:45Z
39,758,144
<p>A way would be:</p> <p>Let's say that you have created a parser like this:</p> <pre><code>parser.add_argument('-i', help='...', type=function) </code></pre> <p>Where <code>type</code> points to the <code>function</code> which will be an outer function that evaluates the ...
0
2016-09-28T21:42:41Z
[ "python", "argparse" ]
argparse: how to parse a single string argument OR a file listing many arguments?
39,757,910
<p>I have a use case where I'd like the user to be able to provide, as an argument to argparse, EITHER a single string OR a filename where each line has a string.</p> <p>Assume the user launches <code>./myscript.py -i foobar</code></p> <p>The logical flow I'm looking for is something like this:</p> <p>The script det...
0
2016-09-28T21:23:45Z
39,758,720
<p>This doesn't look like an <code>argparse</code> problem, since all you want from it is a string. That string can be a filename or a function argument. To a <code>parser</code> these will look the same. Also <code>argparse</code> isn't normally used to run functions. It is used to parse the commandline. Your cod...
0
2016-09-28T22:38:11Z
[ "python", "argparse" ]
How to go through a ManyToMany field in chunks in Django
39,757,922
<p>I am trying to display sets of three objects in a HTML template in a tiled interface. So, for example, an Album model has a ManyToMany field with specific photos. I want to iterate through the photos and show them in sets of three in the view. Currently, I can get all the photos using <code>{{ for photo in album.ima...
0
2016-09-28T21:24:55Z
39,758,064
<pre><code>{% for photo in album.images.all %} {{ photo }} {% if forloop.counter|divisibleby:4 %} &lt;hr&gt; {# or some other markup #} {% endif {% endfor %} </code></pre> <p>You might also do the grouping in your view. This might result in cleaner markup. See: <a href="http://stackoverflow.com/que...
1
2016-09-28T21:36:36Z
[ "python", "django" ]
How to add more functionality with arguments in this code?
39,757,924
<p>I have found nice little program for making quick notes in terminal. There is a little lack of functionality- I can't read notes I have made with it and also I cannot clear notes from file where they are stored. I would like to modify this program, so i can run it with arguments to read what I have written there and...
0
2016-09-28T21:24:59Z
39,758,222
<p>First, <code>sys.argv</code> is an array with the arguments of the command line in it. So you need to test the length of it :</p> <pre><code>if len(sys.argv) &gt;= 2 : #sys.argv[0] is the name of your program if sys.argv[1] == '-c' : </code></pre> <p>Then you can see that the file is written the latest lines...
0
2016-09-28T21:48:21Z
[ "python" ]
Trying to create a csv using python, and getting "list indices" error
39,758,022
<p>In my last question, I asked how to get python to assign a set of values to phrases in a csv files. I was told to create a list of tuples, and this worked great. </p> <p>Currently my list, called clean_titles looks like this:</p> <pre><code>[('a', 1), ('a', 1), ('a', 1), ('a', 1), ('a', 1), ('a', 1), ('a...
0
2016-09-28T21:32:59Z
39,758,138
<p>(My answer is for Python3)</p> <p>You are opening the file in "bytes" mode. It worked for me when I removed the "b" argument:</p> <pre><code>with open("testabc.csv" , "w") as f: writer = csv.writer(f) for val in clean_titles: writer.writerow(val) </code></pre> <p>Also, you can just use a built-in <code...
2
2016-09-28T21:42:15Z
[ "python", "csv" ]
Cannot connect to remote MongoDB server using flask-mongoengine
39,758,077
<p>Trying to connect to a MongoDB cluster hosted on a remote server using flask-mongoengine but the following error is thrown:</p> <pre><code>File "test.py", line 9, in &lt;module&gt; inserted = Something(some='whatever').save() File "/home/lokesh/Desktop/Work/Survaider_Apps/new_survaider/survaider-env/lib/pytho...
0
2016-09-28T21:37:09Z
39,764,540
<p>I figured out that it's a bug in <a href="https://github.com/MongoEngine/flask-mongoengine" rel="nofollow">flask-mongoengine</a> version <code>0.8</code> and has beed reported <a href="https://github.com/MongoEngine/flask-mongoengine/issues/247" rel="nofollow">here</a>.</p>
0
2016-09-29T07:57:30Z
[ "python", "mongodb", "pymongo", "mongoengine", "flask-mongoengine" ]
Clearing Tensorflow GPU memory after model execution
39,758,094
<p>I've trained 3 models and am now running code that loads each of the 3 checkpoints in sequence and runs predictions using them. I'm using the GPU.</p> <p>When the first model is loaded it pre-allocates the entire GPU memory (which I want for working through the first batch of data). But it doesn't unload memory whe...
0
2016-09-28T21:38:34Z
39,781,178
<p>GPU memory allocated by tensors is released as soon as the tensor is not needed anymore (before the .run call terminates). GPU memory allocated for variables is released when variable containers are destroyed. In case of DirectSession (ie, sess=tf.Session("")) it is when session is closed or explicitly reset (added ...
0
2016-09-29T22:47:09Z
[ "python", "tensorflow", "gpu" ]
python django app settings log level
39,758,177
<p>I am new to python and Django. My changes in app/settings.py are not picking up. I have changed the log level FROM:</p> <pre><code>LOGGING = { 'version': 1, ... 'handlers': { 'mail_admins': { 'level': 'ERROR', 'filters': ['require_debug_false'], 'class': 'django.utils.log.AdminEmailHand...
0
2016-09-28T21:44:21Z
39,758,216
<p>You need to restart the web server for it to pick up changes in your app.</p>
0
2016-09-28T21:48:05Z
[ "python", "django" ]
Using xlwings with excel, which of these two approaches is the quickest/ preferred?
39,758,226
<p>I have just started to learn Python and am using xlwings to write to an excel spreadsheet. I am really new to coding (and this is my first question) so this may be a bit of a simple question but any comments would be really appreciated.</p> <p>I am reading the page source of a website (using selenium and beautiful...
1
2016-09-28T21:48:26Z
39,758,533
<p>The overhead of the Excel call reigns supreme. When using XLWings, write to your spreadsheet as infrequently as possible.</p> <p>I've found rewriting the whole sheet (or area of the sheet to be changed) using the Range object to be leaps and bounds faster than writing individual cells, rows, or columns. If I'm not ...
1
2016-09-28T22:17:03Z
[ "python", "xlwings" ]
Merging mutliple pandas dfs time series on DATE index and which are contained in a python dictionary
39,758,268
<p>I have a python dictionary that contains CLOSE prices for several stocks, stock indices, fixed income instruments and currencies (AAPL, AORD, etc.), using a DATE index. The different DFs in the dictionary have different lengths, i.e. some time series are longer than others. All the DFs have the same field, ie. 'CLOS...
0
2016-09-28T21:52:01Z
39,781,422
<p>After not getting any answers, I found a solution that works, although there might be better ones. This is what I did:</p> <pre><code>asset_dict = {} for name, file in zip(asset_name, files_to_test): asset_dict[name] = pd.read_csv(file, index_col='DATE', parse_dates=True) asset_dict[name].sort_index(ascendi...
0
2016-09-29T23:15:21Z
[ "python", "pandas", "dictionary" ]
Pandas Dataframe Data Type Conversion or Isomap Transformation
39,758,315
<p>I load images with scipy's misc.imread, which returns in my case 2304x3 ndarray. Later, I append this array to the list and convert it to a DataFrame. The purpose of doing so is to later apply Isomap transform on the DataFrame. My data frame is 84 rows/samples (images in the folder) and 2304 features each feature is...
0
2016-09-28T21:56:28Z
40,058,421
<p>Do you want to reshape your image to a new shape instead of the original one?</p> <p>If that is not the case then you should change the following line in your code </p> <pre><code>x = (img/255.0).reshape(-1,3) </code></pre> <p>with</p> <pre><code>x = (img/255.0).reshape(-1) </code></pre> <p>Hope this will resol...
0
2016-10-15T11:25:33Z
[ "python", "pandas", "dataframe" ]
Initial value in form's __init__ for the model with generic relation
39,758,386
<p>I have a model with generic relation like this:</p> <pre><code> content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE, blank=True, null=True) object_id = models.PositiveIntegerField(blank=True, null=True) content_object = GenericForeignKey('content_type', 'object_id') </code></pre> <p>To ma...
0
2016-09-28T22:03:06Z
39,758,762
<p>I have found a nice answer to my question <a href="http://stackoverflow.com/a/11400559/709897">here</a>: </p> <blockquote> <p>If you have already called super().<strong>init</strong> in your Form class, you should update the form.initial dictionary, not the field.initial property. If you study form.initial (e...
0
2016-09-28T22:43:06Z
[ "python", "django" ]
Python/Psychopy: checking if a point is within a circle
39,758,412
<p>I want to know the most efficient way to check if a given point (an eye coordinate) is within a specific region (in this case a circle).</p> <p>Code:</p> <pre><code>win = visual.Window([600,600], allowGUI=False) coordinate = [50,70] #example x and y coordinates shape = visual.Circle(win, radius=120, units='pix'...
1
2016-09-28T22:05:42Z
39,758,535
<p>I don't think it needs to be that complicated:</p> <pre><code>center=(600,600) rad=120 coordinate=(50,70) if (coordinate[0]-circle[0])**2 + (coordinate[1]-circle[1])**2 &lt; radius**2: print "inside" else: print "outside" </code></pre>
0
2016-09-28T22:17:13Z
[ "python", "psychopy" ]
Python/Psychopy: checking if a point is within a circle
39,758,412
<p>I want to know the most efficient way to check if a given point (an eye coordinate) is within a specific region (in this case a circle).</p> <p>Code:</p> <pre><code>win = visual.Window([600,600], allowGUI=False) coordinate = [50,70] #example x and y coordinates shape = visual.Circle(win, radius=120, units='pix'...
1
2016-09-28T22:05:42Z
39,758,660
<p>PsychoPy's <code>ShapeStim</code> classes have a <code>.contains()</code> method, as per the API: <a href="http://psychopy.org/api/visual/shapestim.html#psychopy.visual.ShapeStim.contains">http://psychopy.org/api/visual/shapestim.html#psychopy.visual.ShapeStim.contains</a></p> <p>So your code could simply be:</p> ...
6
2016-09-28T22:31:25Z
[ "python", "psychopy" ]
Socket issue when connecting to IRC
39,758,442
<p>I am trying create a very simple python bot that joins a specific channel, and says a random phrase every time someone says anything. I am doing this primarily to learn how sockets and IRC works. I am getting the following error message: </p> <pre><code> Traceback (most recent call last): File "D:/Users/Admini...
0
2016-09-28T22:07:46Z
39,758,589
<p>You are determining the proxy port with</p> <pre><code>port = proxy.split(":")[1] </code></pre> <p>You are then passing it to socks:</p> <pre><code>irc.setproxy(socks.PROXY_TYPE_HTTP, hostname, port) </code></pre> <p>But it's still a string. I bet it will work if you change the latter to</p> <pre><code>irc.setp...
1
2016-09-28T22:23:24Z
[ "python", "python-2.7", "sockets", "irc" ]
Socket issue when connecting to IRC
39,758,442
<p>I am trying create a very simple python bot that joins a specific channel, and says a random phrase every time someone says anything. I am doing this primarily to learn how sockets and IRC works. I am getting the following error message: </p> <pre><code> Traceback (most recent call last): File "D:/Users/Admini...
0
2016-09-28T22:07:46Z
39,758,593
<p>These lines:</p> <pre><code>port = proxy.split(":")[1] irc.setproxy(socks.PROXY_TYPE_HTTP, hostname, port) </code></pre> <p>will result in port being a <em>string</em> containing the required port number. An <code>integer</code> is required for the port. Change your code to :</p> <pre><code>port = int(proxy.split...
1
2016-09-28T22:24:03Z
[ "python", "python-2.7", "sockets", "irc" ]
Normalise between 0 and 1 ignoring NaN
39,758,449
<p>For a list of numbers ranging from <code>x</code> to <code>y</code> that may contain <code>NaN</code>, how can I normalise between 0 and 1, ignoring the <code>NaN</code> values (they stay as <code>NaN</code>).</p> <p>Typically I would use <code>MinMaxScaler</code> (<a href="http://scikit-learn.org/stable/modules/ge...
5
2016-09-28T22:08:13Z
39,758,551
<p>consider <code>pd.Series</code> <code>s</code></p> <pre><code>s = pd.Series(np.random.choice([3, 4, 5, 6, np.nan], 100)) s.hist() </code></pre> <p><a href="http://i.stack.imgur.com/hzlrF.png" rel="nofollow"><img src="http://i.stack.imgur.com/hzlrF.png" alt="enter image description here"></a></p> <hr> <p><strong>...
3
2016-09-28T22:19:29Z
[ "python", "pandas", "numpy", "scikit-learn" ]
How do I import a module from within a Pycharm project?
39,758,606
<p>In my project, the file structure is as follows:</p> <p>root/folder1/folder2/script1.py</p> <p>root/folder1/folder2/script2.py</p> <p>I have a statement in script2.py that says "import script1", and Pycharm says no module is found. How do I fix this?</p>
0
2016-09-28T22:25:11Z
39,758,651
<p>To import as object : </p> <p><code>from root.folder1.folder2 import script1</code></p> <p>To import a function of your script:</p> <p><code>from root.folder1.folder2.script1 import NameOfTheFunction</code></p>
2
2016-09-28T22:30:33Z
[ "python", "pycharm" ]
401 error using the Streaming features of Twitter API (through Tweepy)
39,758,666
<p>I've got an application which takes advantage of a number of features of the Twitter API. I've tested the application on one Windows 7 system, and all features worked well. </p> <p>Testing the application on a second Windows 7 system, it seems that everything but the Public Stream and User Stream features is workin...
0
2016-09-28T22:31:49Z
39,759,792
<p>Your system clock is probably more than 5 minutes off. </p>
0
2016-09-29T01:03:31Z
[ "python", "twitter", "tweepy" ]
401 error using the Streaming features of Twitter API (through Tweepy)
39,758,666
<p>I've got an application which takes advantage of a number of features of the Twitter API. I've tested the application on one Windows 7 system, and all features worked well. </p> <p>Testing the application on a second Windows 7 system, it seems that everything but the Public Stream and User Stream features is workin...
0
2016-09-28T22:31:49Z
39,760,653
<p>401 is a Authorization Error. Did you log out of Twitter accidentally? Try logging in again. Here are some links for reference:</p> <p><a href="https://dev.twitter.com/overview/api/response-codes" rel="nofollow">Twitter Error Code (401)</a></p> <p><a href="http://pcsupport.about.com/od/findbyerrormessage/a/401erro...
-1
2016-09-29T02:55:05Z
[ "python", "twitter", "tweepy" ]
Python - Filter a dict JSON response to send back only two values or convert to a string?
39,758,835
<p>I am manipulating a URL in Python that calls an API and gets a valid result in JSON.</p> <p>I only need the 'latitude' and 'longitude' provided by [result]</p> <p>But, I cannot seem to find any good way to handle sending dict values back.</p> <p>I've tried to convert the JSON to a string, but as my end goal is to...
2
2016-09-28T22:51:52Z
39,758,883
<p>You got a nested dictionary back, so access it's values using the right keys:</p> <pre><code>d = json.loads(json_str) lat, long = d['result']['latitude'], d['result']['longitude'] newurl = url + '?' + 'lat=' + lat + '&amp;lon=' + lon </code></pre>
0
2016-09-28T22:57:13Z
[ "python", "json", "string", "dictionary", "filter" ]
Python - Filter a dict JSON response to send back only two values or convert to a string?
39,758,835
<p>I am manipulating a URL in Python that calls an API and gets a valid result in JSON.</p> <p>I only need the 'latitude' and 'longitude' provided by [result]</p> <p>But, I cannot seem to find any good way to handle sending dict values back.</p> <p>I've tried to convert the JSON to a string, but as my end goal is to...
2
2016-09-28T22:51:52Z
39,758,899
<p>You can access your JSON object exactly like a dictionary. So to get the latitude and longitude from your result, you can use:</p> <p><code>lat, long = d[result][latitude], d[result][longitude]</code></p> <p>Load these into strings, do your error checking, and then append them into your new URL.</p>
-1
2016-09-28T22:59:02Z
[ "python", "json", "string", "dictionary", "filter" ]
Django Template Loader not reaching app template
39,758,854
<p>According to Django documentation</p> <p>"Your project’s TEMPLATES setting describes how Django will load and render templates. The default settings file configures a DjangoTemplates backend whose APP_DIRS option is set to True. By convention DjangoTemplates looks for a “templates” subdirectory in each of the...
1
2016-09-28T22:54:31Z
39,759,201
<p>Then you could reach your template with 'app_name/index.html'</p>
0
2016-09-28T23:37:09Z
[ "python", "django", "django-templates", "mezzanine" ]
Django Template Loader not reaching app template
39,758,854
<p>According to Django documentation</p> <p>"Your project’s TEMPLATES setting describes how Django will load and render templates. The default settings file configures a DjangoTemplates backend whose APP_DIRS option is set to True. By convention DjangoTemplates looks for a “templates” subdirectory in each of the...
1
2016-09-28T22:54:31Z
39,760,450
<p>Did you try to change your template dirs on <code>setting.py</code> like this</p> <pre><code>'DIRS': ["templates"], </code></pre> <p>and did your <code>views.py</code> provide specific location of template E.g.</p> <pre><code>return render(request, 'foldername/templatename.html', {}) </code></pre>
0
2016-09-29T02:31:57Z
[ "python", "django", "django-templates", "mezzanine" ]
Why is my protected loop erroring?
39,758,857
<p>I have this script</p> <pre><code>for line in file: while line[i] == " ": if i == len(line): break i += 1 if i == len(line): pass while not line[i] == " ": if i == len(line): break obj += line[i] i += 1 print obj </code></pre> ...
2
2016-09-28T22:54:48Z
39,758,890
<p>Your loop is not "safe", "break" only breaks <strong>inner</strong> loop, thus once i==len(line) it goes out of first while, stays in the main for and you try to read out line[i] in "while not line[i] == """ line, which causes you to index outside "line" (since the condition is checked before entering the loop).</p>...
1
2016-09-28T22:57:54Z
[ "python", "while-loop" ]
Why is my protected loop erroring?
39,758,857
<p>I have this script</p> <pre><code>for line in file: while line[i] == " ": if i == len(line): break i += 1 if i == len(line): pass while not line[i] == " ": if i == len(line): break obj += line[i] i += 1 print obj </code></pre> ...
2
2016-09-28T22:54:48Z
39,758,893
<blockquote> <p>my loop is protected</p> </blockquote> <p>No it isn't. The condition on the <code>while</code> has to be evaluated first before reaching the body of the loop where the <em>protection</em> <code>if</code> condition is.</p> <p>To be sure <code>i</code> does not exceed the length of the list, move the ...
1
2016-09-28T22:57:57Z
[ "python", "while-loop" ]