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
listlengths
1
5
Iteration number processing large files line by line
38,556,192
<p>I have the need to process a large file in Python (about 1GB) line by line. I use this approach to do it:</p> <pre><code>with open('file.txt', 'r') as f: i = 0 for fline in f: process(fline) i = i + 1 print i </code></pre> <p>the value of <code>i</code> (the number of iteration = the number of lines of the file) is 19,991,889.</p> <p>but the file (opened with EmEditor) reports that the file have 63,941,070 lines.</p> <p>Why don't the number of lines match? What I'm doing wrong?</p> <p>Thanks.</p>
0
2016-07-24T20:00:12Z
38,557,432
<p>I can think of two possibilities.</p> <ol> <li>You are running 2.x on Windows, the file contains about 3x as many '\r' characters as recognized '\r\n' or '\n' line endings, and EmEditor recognizes '\r' as a line ending, as does Python 3.x. Or something similar is happening with 2.7 on another OS.</li> </ol> <p>Explanation: you open the file in text mode. 3.x uses OS-independent universal newlines are used and '\r' and '\r\n' are converted to '\n'. 2.x uses OS-dependent reading and on Windows, only '\r\n' is used.</p> <p>Example:</p> <pre><code>with open('tem.dat', 'wb') as f: f.write(b'a\rb\r\nc\n\rd\n') with open('tem.dat', 'r') as f: for i, t in enumerate(f): print(i, t, repr(t[-1])) </code></pre> <p>3.x prints</p> <pre><code>0 a '\n' 1 b '\n' 2 c '\n' 3 '\n' 4 d '\n' </code></pre> <p>2.x prints</p> <pre><code>(0, 'a\rb\n', "'\\n'") (1, 'c\n', "'\\n'") (2, '\rd\n', "'\\n'") </code></pre> <p>Diagnosis: add to your code "if '\r' in fline: print(fline)" before processing.</p> <ol start="2"> <li>There is something in the file that Python sees as End-of-File and EmEditor does not. Diagnosis. Add 'length = 0' before the loop and 'length += len(fline)' in the loop and see if it is at least approximately right after.</li> </ol>
0
2016-07-24T22:25:54Z
[ "python", "file" ]
Iteration number processing large files line by line
38,556,192
<p>I have the need to process a large file in Python (about 1GB) line by line. I use this approach to do it:</p> <pre><code>with open('file.txt', 'r') as f: i = 0 for fline in f: process(fline) i = i + 1 print i </code></pre> <p>the value of <code>i</code> (the number of iteration = the number of lines of the file) is 19,991,889.</p> <p>but the file (opened with EmEditor) reports that the file have 63,941,070 lines.</p> <p>Why don't the number of lines match? What I'm doing wrong?</p> <p>Thanks.</p>
0
2016-07-24T20:00:12Z
38,558,717
<p>The numbers don't match because the encoding that the <code>open</code> function uses isn't correct for this file, try to use the "ISO-8859-1" encoding.</p>
0
2016-07-25T01:57:34Z
[ "python", "file" ]
How do I mock a class's function's return value?
38,556,197
<p>I have a method in Python that looks like this (in <code>comicfile.py</code>):</p> <pre><code>from zipfile import ZipFile ... class ComicFile(): ... def page_count(self): """Return the number of pages in the file.""" if self.file == None: raise ComicFile.FileNoneError() if not os.path.isfile(self.file): raise ComicFile.FileNotFoundError() with ZipFile(self.file) as zip: members = zip.namelist() pruned = self.prune_dirs(members) length = len(pruned) return length </code></pre> <p>I'm trying to write a unit test for this (I've already tested <code>prune_dirs</code>), and so for this is what I have (<code>test_comicfile.py</code>):</p> <pre><code>import unittest import unittest.mock import comicfile ... class TestPageCount(unittest.TestCase): def setUp(self): self.comic_file = comicfile.ComicFile() @unittest.mock.patch('comicfile.ZipFile') def test_page_count(self, mock_zip_file): # Store as tuples to use as dictionary keys. members_dict = {('dir/', 'dir/file1', 'dir/file2'):2, ('file1.jpg', 'file2.jpg', 'file3.jpg'):3 } # Make the file point to something to prevent FileNoneError. self.comic_file.file = __file__ for file_tuple, count in members_dict.items(): mock_zip_file.return_value.namelist = list(file_tuple) self.assertEqual(count, self.comic_file.page_count()) </code></pre> <p>When I run this test, I get the following:</p> <pre><code>F..ss.... ====================================================================== FAIL: test_page_count (test_comicfile.TestPageCount) ---------------------------------------------------------------------- Traceback (most recent call last): File "/usr/local/Cellar/python3/3.5.1/Frameworks/Python.framework/Versions/3.5/lib/python3.5/unittest/mock.py", line 1157, in patched return func(*args, **keywargs) File "/Users/chuck/Dropbox/Projects/chiv/chiv.cbstar/test_comicfile.py", line 86, in test_page_count self.assertEqual(count, self.comic_file.page_count()) AssertionError: 2 != 0 ---------------------------------------------------------------------- Ran 9 tests in 0.010s FAILED (failures=1, skipped=2) </code></pre> <p>OK, so <code>self.comic_file.page_count()</code> is returning <code>0</code>. I tried placing the following line after <code>members = zip.namelist()</code> in <code>page_count</code>.</p> <pre><code>print('\nmembers -&gt; ' + str(members)) </code></pre> <p>During the test, I get this:</p> <pre><code>members -&gt; &lt;MagicMock name='ZipFile().__enter__().namelist()' id='4483358280'&gt; </code></pre> <p>I'm quite new to unit testing and am quite nebulous on using <code>unittest.mock</code>, but my understanding is that <code>mock_zip-file.return_value.namelist = list(file_tuple)</code> should have made it so that the <code>namelist</code> method of the <code>ZipFile</code> class would return each of the <code>file_tuple</code> contents in turn. What it <em>is</em> doing I have no idea.</p> <p>I think what I'm trying to do here is clear, but I can't seem to figure out how to override the <code>namelist</code> method so that my unit test is only testing this one function instead of having to deal with <code>ZipFile</code> as well.</p>
1
2016-07-24T20:00:57Z
38,557,262
<p><code>ZipFile</code> is instantiated as a <a href="https://jeffknupp.com/blog/2016/03/07/python-with-context-managers/" rel="nofollow">context manager</a>. to <a href="https://docs.python.org/3/library/unittest.mock.html#calling" rel="nofollow">mock</a> it you have to refer to its <code>__enter__</code> method.</p> <p><code>mock_zip_file.return_value.__enter__.return_value.namelist.return_value = list(file_tuple)</code></p> <p>What you're trying to do is very clear, but the context manager adds complexity to the mocking. </p> <hr> <p>One trick is that when a mock registers all calls made to it, in this example it is saying it has a call at:</p> <p><code>members -&gt; &lt;MagicMock name='ZipFile().__enter__().namelist()' id='4483358280'&gt;</code></p> <p>This can guide you in registering your mocked object, replace all <code>()</code> with <code>return_value</code></p>
2
2016-07-24T22:01:18Z
[ "python", "unit-testing" ]
Different data structures result in huge different size in python
38,556,213
<p>I'm trying using Facebook Graph API to get something by python, and there's no problem in my programs.</p> <p>However, When outputting data to files, I found something strange. I change a structure in output, then my file would be several times bigger.</p> <p>The original data look like this:</p> <pre><code>{ "data": [ { "id": "20531316728_10154835146021729", "created_time": "2016-07-21T16:00:00+0000" }, { "id": "20531316728_10154833920726729", "created_time": "2016-07-21T03:02:11+0000" }, { "id": "20531316728_10154729016861729", "created_time": "2016-06-14T00:04:45+0000" } ] } </code></pre> <p>I used this before: (I parsed the data above to a JSON format, and I call it <code>jsonData</code>)</p> <pre><code>for tuples in jsonData['data']: print(tuples, file=open('test.txt','a')) </code></pre> <p>It will output some strings in files and the output looks like:</p> <pre><code>{'keyA': 'something1', 'keyB': 'something2'} {'keyA': 'something3', 'keyB': 'something4'} {'keyA': 'something5', 'keyB': 'something6'} </code></pre> <p>Cause there's no structures, so I changed the <code>tuples</code> to <code>jsonData['data']</code>, in order to make the return becoming an array:</p> <pre><code>for tuples in jsonData['data']: print(jsonData['data'], file=open('test.txt','a')) </code></pre> <p>The output would be:</p> <pre><code> [ {'keyA': 'something1', 'keyB': 'something2'}, {'keyA': 'something3', 'keyB': 'something4'}, {'keyA': 'something5', 'keyB': 'something6'} ] </code></pre> <p>But the file size is totally different! For instance, I got a <strong>196KB</strong> file by using the <code>tuples</code>, and got a <strong>18.9MB</strong> by using the <code>jsonData['data']</code></p> <p>I used python3, and I tested several times by only changing the statement. Are the differences in files common and normal?</p>
-1
2016-07-24T20:02:09Z
38,556,586
<p>The difference between these two <code>for</code> loops is that in the second one, you're printing out the entire structure each time the <code>for</code> loop body runs.</p> <p>In the first loop, you are only printing out the current item (well appending it to the output file, but you know that bit already!).</p> <p>Here's a tiny example that might illuminate it for you.</p> <pre><code>&gt;&gt;&gt; x = [1, 2, 3, 4, 5] &gt;&gt;&gt; for i in x: ... print(i) ... 1 2 3 4 5 &gt;&gt;&gt; for i in x: ... print(x) ... [1, 2, 3, 4, 5] [1, 2, 3, 4, 5] [1, 2, 3, 4, 5] [1, 2, 3, 4, 5] [1, 2, 3, 4, 5] </code></pre>
0
2016-07-24T20:42:24Z
[ "python", "python-3.x", "data-structures" ]
Automatic 'created by user' field using django-rest-framework?
38,556,217
<h3>models.py</h3> <pre><code>class Nugget(TimeStampedModel): added_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, related_name='added_by', blank=True, null=True) </code></pre> <h3>serializers.py</h3> <pre><code>class NuggetSerializer(TaggitSerializer, serializers.ModelSerializer): added_by = serializers.CreateOnlyDefault(default=serializers.CurrentUserDefault()) </code></pre> <h3>views.py</h3> <pre><code>class NuggetList(generics.ListCreateAPIView): queryset = Nugget.objects.all() serializer_class = NuggetSerializer def perform_create(self, serializer): serializer.save(added_by=self.request.user) </code></pre> <h3>What I'm trying to achieve:</h3> <p><code>added_by</code> should:</p> <ol> <li>Be set on <code>create</code> of a <code>Nugget</code></li> <li>Default to the <code>user</code> who created the <code>Nugget</code>, with no way to override this default</li> <li>Be included and shown when a <code>Nugget</code> is retrieved</li> <li>Not be shown as an option for <code>create/POST</code> in the browsable API</li> <li>Not be editable after <code>create</code></li> </ol>
0
2016-07-24T20:02:36Z
38,564,949
<p>Changed <code>added_by</code> in <code>serializers.py</code> (wasn't using a field, and set to read_only) and <code>.save()</code> in <code>views.py</code> to stop overriding the default.</p> <p><code>CurrentUserDefault()</code> requires <code>request</code> within the <code>context</code> dict. In this case <code>generics.ListCreateAPIView</code> already does that. </p> <h3>models.py</h3> <pre><code>class Nugget(TimeStampedModel): added_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, related_name='added_by', blank=True, null=True) </code></pre> <h3>serializers.py</h3> <pre><code>class NuggetSerializer(TaggitSerializer, serializers.ModelSerializer): added_by = serializers.StringRelatedField(default=serializers.CurrentUserDefault(), read_only=True) </code></pre> <h3>views.py</h3> <pre><code>class NuggetList(generics.ListCreateAPIView): queryset = Nugget.objects.all() serializer_class = NuggetSerializer def perform_create(self, serializer): serializer.save() </code></pre>
1
2016-07-25T10:10:33Z
[ "python", "django", "django-models", "django-rest-framework" ]
Returning arguments in SWIG/Python
38,556,223
<p>According to Swig docs and the marvelous explanation at <a href="http://stackoverflow.com/questions/21373259/swig-in-typemap-works-but-argout-does-not">SWIG in typemap works, but argout does not</a> by @Flexo, the <code>argout</code> typemap turns reference arguments into return values in Python. </p> <p>I have a scenario, in which I pass a <code>dict</code>, which then is converted to an <code>unordered_map</code> in <code>typemap(in)</code>, which then gets populated in the C++ lib. Stepping through the code, I can see the mapping changed after it returned from C++, so I wonder why there is not a possibility to just convert the <code>unordered_map</code> back in place in to the <code>dict</code> that was passed. Or is it possible by now and I'm just overlooking something? </p> <p>Thanks!</p>
0
2016-07-24T20:03:15Z
38,557,397
<p>I am a little confused as to what exactly you are asking, but my understanding is:</p> <ul> <li>You have an "in" typemap to convert a Python <code>dict</code> to a C++ <code>unordered_map</code> for some function argument.</li> <li>The function then modifies the <code>unordered_map</code>.</li> <li>After completion of the function, you want the Python <code>dict</code> updated to the current <code>unordered_map</code>, and are somehow having trouble with this step.</li> <li>Since you know how to convert a <code>dict</code> to an <code>unordered_map</code>, I assume you basically do know how to convert the <code>unordered_map</code> back to the <code>dict</code> using the Python C-API, but are somehow unsure into which SWIG typemap to put the code.</li> </ul> <p>So, under these assumptions, I'll try to help:</p> <ul> <li><p>"the argout typemap turns reference arguments into return values in Python". Not really, although it is mostly used for this purpose. An <a href="http://www.swig.org/Doc3.0/SWIGDocumentation.html#Typemaps_nn32" rel="nofollow">"argout" typemap</a> simply supplies code to deal with some function argument (internally referred to as <code>$1</code>) that is inserted into the wrapper code <em>after</em> the C++ function is called. Compare this with an "in" typemap that supplies code to convert the supplied Python argument <code>$input</code> to a C++ argument <code>$1</code>, which is obviously inserted into the wrapper code <em>before</em> the C++ function is called.</p></li> <li><p>The original passed Python <code>dict</code> can be referred to in the "argout" typemap as <code>$input</code>, and the modified <code>unordered_map</code> as <code>$1</code> (see the SWIG docs linked above).</p></li> <li><p>Therefore, all you need to do is write an "argout" typemap for the same argument signature as the "in" typemap that you already have, and insert the code (using the Python C-API) to update the contents of the Python <code>dict</code> (<code>$input</code>) to reflect the contents of the <code>unordered_map</code> (<code>$1</code>).</p></li> <li><p>Note that this is different from the classical use of "argout" typemaps, which would typically convert the <code>$1</code> back to a new Python <code>dict</code> and append this to the Python return object, which you can refer to by <code>$result</code>.</p></li> </ul> <p>I hope this helps. If you are still stuck at some point, please edit your question to make clear at which point you are having trouble.</p>
2
2016-07-24T22:20:28Z
[ "python", "swig", "typemaps" ]
Returning arguments in SWIG/Python
38,556,223
<p>According to Swig docs and the marvelous explanation at <a href="http://stackoverflow.com/questions/21373259/swig-in-typemap-works-but-argout-does-not">SWIG in typemap works, but argout does not</a> by @Flexo, the <code>argout</code> typemap turns reference arguments into return values in Python. </p> <p>I have a scenario, in which I pass a <code>dict</code>, which then is converted to an <code>unordered_map</code> in <code>typemap(in)</code>, which then gets populated in the C++ lib. Stepping through the code, I can see the mapping changed after it returned from C++, so I wonder why there is not a possibility to just convert the <code>unordered_map</code> back in place in to the <code>dict</code> that was passed. Or is it possible by now and I'm just overlooking something? </p> <p>Thanks!</p>
0
2016-07-24T20:03:15Z
38,578,993
<p>I am well aware of that the user has already solved his issue, but here goes a solution. Some validation of inputs may be introduced to avoid non-string values of the input dictionary.</p> <p>Header file</p> <pre><code>// File: test.h #pragma once #include &lt;iostream&gt; #include &lt;string&gt; #include &lt;unordered_map&gt; void method(std::unordered_map&lt;std::string, std::string&gt;* inout) { for( const auto&amp; n : (*inout) ) { std::cout &lt;&lt; "Key:[" &lt;&lt; n.first &lt;&lt; "] Value:[" &lt;&lt; n.second &lt;&lt; "]\n"; } (*inout)["BLACK"] = "#000000"; }; </code></pre> <p>Interface file</p> <pre><code>// File : dictmap.i %module dictmap %{ #include "test.h" %} %include "typemaps.i" %typemap(in) std::unordered_map&lt;std::string, std::string&gt;* (std::unordered_map&lt;std::string, std::string&gt; temp) { PyObject *key, *value; Py_ssize_t pos = 0; $1 = &amp;temp; temp = std::unordered_map&lt;std::string, std::string&gt;(); while (PyDict_Next($input, &amp;pos, &amp;key, &amp;value)) { (*$1)[PyString_AsString(key)] = std::string(PyString_AsString(value)); } } %typemap(argout) std::unordered_map&lt;std::string, std::string&gt;* { $result = PyDict_New(); for( const auto&amp; n : *$1) { PyDict_SetItemString($result, n.first.c_str(), PyString_FromString(n.second.c_str())); } } %include "test.h" </code></pre> <p>Test</p> <pre><code>import dictmap out = dictmap.method({'WHITE' : '#FFFFFF'}) </code></pre> <p>Output is an updated dictionary</p> <pre><code>In[2]: out Out[3] : {'BLACK': '#000000', 'WHITE': '#FFFFFF'} </code></pre>
0
2016-07-25T23:42:22Z
[ "python", "swig", "typemaps" ]
Standard deviation from center of mass along Numpy array axis
38,556,297
<p>I am trying to find a well-performing way to calculate the standard deviation from the center of mass/gravity along an axis of a Numpy array.</p> <p>In formula this is (sorry for the misalignment):</p> <p><img src="http://latex.codecogs.com/gif.latex?%5Cmu_j&space;=&space;%5Cfrac%7B%5Csum_i%7Bi&space;A_%7Bij%7D%7D%7D%7B%5Csum_i%7B&space;A_%7Bij%7D%7D%7D&space;%5Cnewline&space;%5Cnewline&space;%5Ctext%7Bvar%7D_j&space;=&space;%5Cfrac%7B%5Csum_i%7Bi%5E2&space;A_%7Bij%7D%7D%7D%7B%5Csum_i%7BA_%7Bij%7D%7D%7D&space;-&space;%5Cmu%5E2&space;%5Cnewline&space;%5Cnewline&space;%5Ctext%7Bstd%7D_j&space;=&space;%5Csqrt%7B%5Ctext%7Bvar%7D_j%7D" title="\mu_j = \frac{\sum_i{i A_{ij}}}{\sum_i{ A_{ij}}} \newline \newline \text{var}_j = \frac{\sum_i{i^2 A_{ij}}}{\sum_i{A_{ij}}} - \mu^2 \newline \newline \text{std}_j = \sqrt{\text{var}_j}" /></p> <p>The best I could come up with is this:</p> <pre><code>def weighted_com(A, axis, weights): average = np.average(A, axis=axis, weights=weights) return average * weights.sum() / A.sum(axis=axis).astype(float) def weighted_std(A, axis): weights = np.arange(A.shape[axis]) w1com2 = weighted_com(A, axis, weights)**2 w2com1 = weighted_com(A, axis, weights**2) return np.sqrt(w2com1 - w1com2) </code></pre> <p>In <code>weighted_com</code>, I need to correct the normalization from sum of weights to sum of values (which is an ugly workaround, I guess). <code>weighted_std</code> is probably fine.</p> <p>To avoid the XY problem, I still ask for what I actually want, (a better <code>weighted_std</code>) instead of a better version of my <code>weighted_com</code>.</p> <p>The <code>.astype(float)</code> is a safety measure as I'll apply this to histograms containing ints, which caused problems due to integer division when not in Python 3 or when <code>from __future__ import division</code> is not active.</p>
1
2016-07-24T20:09:56Z
38,557,752
<p>You want to take the mean, variance and standard deviation of the vector <code>[1, 2, 3, ..., n]</code> &mdash; where <code>n</code> is the dimension of the input matrix <code>A</code> along the axis of interest &mdash;, with weights given by the matrix <code>A</code> itself.</p> <p>For concreteness, say you want to consider these center-of-mass statistics along the vertical axis (<code>axis=0</code>) &mdash; this is what corresponds to the formulas you wrote. For a fixed column <code>j</code>, you would do</p> <pre><code>n = A.shape[0] r = np.arange(1, n+1) mu = np.average(r, weights=A[:,j]) var = np.average(r**2, weights=A[:,j]) - mu**2 std = np.sqrt(var) </code></pre> <p>In order to put all of the computations for the different columns together, you have to stack together a bunch of copies of <code>r</code> (one per column) to form a matrix (that I have called <code>R</code> in the code below). With a bit of care, you can make things work for both <code>axis=0</code> and <code>axis=1</code>.</p> <pre><code>import numpy as np def com_stats(A, axis=0): A = A.astype(float) # if you are worried about int vs. float n = A.shape[axis] m = A.shape[(axis-1)%2] r = np.arange(1, n+1) R = np.vstack([r] * m) if axis == 0: R = R.T mu = np.average(R, axis=axis, weights=A) var = np.average(R**2, axis=axis, weights=A) - mu**2 std = np.sqrt(var) return mu, var, std </code></pre> <p>For example,</p> <pre><code>A = np.array([[1, 1, 0], [1, 2, 1], [1, 1, 1]]) print(A) # [[1 1 0] # [1 2 1] # [1 1 1]] print(com_stats(A)) # (array([ 2. , 2. , 2.5]), # centre-of-mass mean by column # array([ 0.66666667, 0.5 , 0.25 ]), # centre-of-mass variance by column # array([ 0.81649658, 0.70710678, 0.5 ])) # centre-of-mass std by column </code></pre> <p>EDIT:</p> <p>One can avoid creating in-memory copies of <code>r</code> to build <code>R</code> by using <code>numpy.lib.stride_tricks</code>: swap the line</p> <pre><code>R = np.vstack([r] * m) </code></pre> <p>above with</p> <pre><code>from numpy.lib.stride_tricks import as_strided R = as_strided(r, strides=(0, r.itemsize), shape=(m, n)) </code></pre> <p>The resulting <code>R</code> is a (strided) <code>ndarray</code> whose underlying array is the same as <code>r</code>'s &mdash; absolutely no copying of any values occurs.</p> <pre><code>from numpy.lib.stride_tricks import as_strided FMT = '''\ Shape: {} Strides: {} Position in memory: {} Size in memory (bytes): {} ''' def find_base_nbytes(obj): if obj.base is not None: return find_base_nbytes(obj.base) return obj.nbytes def stats(obj): return FMT.format(obj.shape, obj.strides, obj.__array_interface__['data'][0], find_base_nbytes(obj)) n=10 m=1000 r = np.arange(1, n+1) R = np.vstack([r] * m) S = as_strided(r, strides=(0, r.itemsize), shape=(m, n)) print(stats(r)) print(stats(R)) print(stats(S)) </code></pre> <p>Output:</p> <pre class="lang-none prettyprint-override"><code>Shape: (10,) Strides: (8,) Position in memory: 4299744576 Size in memory (bytes): 80 Shape: (1000, 10) Strides: (80, 8) Position in memory: 4304464384 Size in memory (bytes): 80000 Shape: (1000, 10) Strides: (0, 8) Position in memory: 4299744576 Size in memory (bytes): 80 </code></pre> <p>Credit to <a href="http://stackoverflow.com/questions/34637875/size-of-numpy-strided-array-broadcast-array-in-memory/34638891#34638891">this SO answer</a> and <a href="http://stackoverflow.com/questions/11264838/how-to-get-the-memory-address-of-a-numpy-array-for-c/11266170#11266170">this one</a> for explanations on how to get the memory address and size of the underlying array of a strided <code>ndarray</code>.</p>
0
2016-07-24T23:10:07Z
[ "python", "python-2.7", "numpy", "standard-deviation", "weighted-average" ]
Pass multiple variable value into URL in python
38,556,304
<p>I have below code to get data using url. I pass ticker value from text file and its successful and its;works (part-1) but as code per part-2, when I pass multiple value using multiple variable by raw_input(), its give <strong>error "TypeError: not enough arguments for format string"</strong></p> <p>Part-1</p> <pre><code>ticker = line.strip(); url = "http://ichart.finance.yahoo.com/table.csv?s=%s.ns&amp;a=08&amp;b=08&amp;c=2015&amp;d=08&amp;e=08&amp;f=2016&amp;g=d&amp;ignore=.csv" % ticker r = requests.get(url) </code></pre> <p>Part-2</p> <pre><code>ticker = line.strip(); url = "http://ichart.finance.yahoo.com/table.csv?s=%s.ns&amp;a=%s&amp;b=%s&amp;c=%s&amp;d=%s&amp;e=%s&amp;f=%s&amp;g=d&amp;ignore=.csv" %ticker %a %b %c %d %e %f r = requests.get(url) </code></pre>
-2
2016-07-24T20:10:45Z
38,556,322
<p>You're not passing those <em>format</em> parameters correctly:</p> <pre><code>url = "...?s=%s.ns&amp;a=%s&amp;b=%s&amp;c=%s&amp;d=%s&amp;e=%s&amp;f=%s&amp;g=d&amp;ignore=.csv"%(ticker, a, b, c, d, e, f) # ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ </code></pre> <p>When passing the parameters for formatting, you should pass them all in a tuple, and not independently.</p> <p>Considering the number of your parameters, you can instead use the new style formatting to have a more readable code. </p> <p>An example usage is shown below:</p> <pre><code>c = 'a={a}&amp;b={b}'.format(a=1, b=2) # 'a=1&amp;b=2' </code></pre> <p>So in your case, you would pass your paramters as named arguments viz. <code>ticker, a, b, c, d, e, f</code></p> <p>You can learn more about string formatting at <a href="https://pyformat.info/" rel="nofollow">pyformat</a></p>
2
2016-07-24T20:12:48Z
[ "python" ]
Daphne, twisted pip error when installing django channels
38,556,363
<p>I have a small problem with <code>pip</code> installing <code>django channels</code>, I noticed this from the <em>github</em> repository </p> <blockquote> <p>Note: Recent versions of Channels also need recent versions of Daphne, asgi_redis and asgiref, so make sure you update all at once</p> </blockquote> <p>I have neglected this and just started with <code>pip install channels</code>, but error occurred</p> <p><code>Could not find a version that satisfies the requirement twisted&lt;16.3,&gt;=15.5 (from daphne) (from versions: ) No matching distribution found for twisted&lt;16.3,&gt;=15.5 (from daphne)</code></p> <p>and when I try <code>pip install twisted</code>, it's just get confusing </p> <pre><code>Could not find a version that satisfies the requirement twisted (from versions: ) No matching distribution found for twisted </code></pre> <p>So I have tried to find some solutions for this, and the solution suggest that I recompile my python, so I'm asking you is there any other solutions for resolving this issue.</p> <p>I'm using <code>django==1.8.7</code> and <code>python3.5</code> for my existing project.</p>
1
2016-07-24T20:16:15Z
38,597,359
<p>Channels is entirely new concept and in beta, In this time recommended way to install channels is <code>pip install -U Channels</code> </p> <p>Of cource, you can install twisted by visiting in this page <a href="http://twistedmatrix.com/trac/" rel="nofollow">http://twistedmatrix.com/trac/</a> and download the source file and install it.</p>
1
2016-07-26T18:28:12Z
[ "python", "django", "python-3.5", "django-channels" ]
Hide or removing a menubar of tkinter in python
38,556,387
<p>I can set my menu with the following instruction:</p> <pre><code>my_tk.config(menu=my_menu_bar) </code></pre> <p>But, How do I remove it or hide it completely?</p> <pre><code>my_tk.config(menu=None) </code></pre> <p>doesn't work :-( </p>
0
2016-07-24T20:18:33Z
38,557,221
<p>Is this what you're looking for:</p> <pre><code>from tkinter import * root = Tk() menubar = Menu(root) root.config(menu=menubar) submenu = Menu(menubar) menubar.add_cascade(label="Submenu", menu=submenu) submenu.add_command(label="Option 1") submenu.add_command(label="Option 2") submenu.add_command(label="Option 3") def remove_func(): menubar.delete(0, END) remove_button = Button(root, text="Remove", command=remove_func) remove_button.pack() </code></pre> <p>?</p>
1
2016-07-24T21:56:23Z
[ "python", "python-3.x", "tkinter", "menu" ]
Hide or removing a menubar of tkinter in python
38,556,387
<p>I can set my menu with the following instruction:</p> <pre><code>my_tk.config(menu=my_menu_bar) </code></pre> <p>But, How do I remove it or hide it completely?</p> <pre><code>my_tk.config(menu=None) </code></pre> <p>doesn't work :-( </p>
0
2016-07-24T20:18:33Z
38,557,588
<p>Another way is:</p> <pre><code>from tkinter import * root = Tk() menubar = Menu(root) root.config(menu=menubar) submenu = Menu(menubar) menubar.add_cascade(label="Submenu", menu=submenu) submenu.add_command(label="Option 1") submenu.add_command(label="Option 2") submenu.add_command(label="Option 3") def remove_func(): emptyMenu = Menu(root) root.config(menu=emptyMenu) remove_button = Button(root, text="Remove", command=remove_func) remove_button.pack() </code></pre> <p>What's different:<br> in</p> <pre><code>def remove_func(): </code></pre> <p>created an empty menu</p> <pre><code>emptyMenu = Menu(root) </code></pre> <p>and replaced it with the current menu (<code>menubar</code>)</p> <pre><code>root.config(menu=emptyMenu) </code></pre>
0
2016-07-24T22:45:52Z
[ "python", "python-3.x", "tkinter", "menu" ]
Is there a way to block django views from serving multiple requests concurrently?
38,556,461
<p>I have a django app, where I am using one of the views to fetch data from local filesystem and parse it and add it to my database. Now the thing is, I want to restrict this view from serving multiple requests concurrently, I want them to be served sequentially instead. Or just block the new request when one request is already being served. Is there a way to achieve it?</p>
1
2016-07-24T20:26:59Z
38,556,568
<p>You need some kind of mutex. Since your operations involve the filesystem already, perhaps you could use a file as a mutex. For instance, at the start of the operation, check if a specific file exists in a specific place; if it does, return an error, but if not, create it and proceed, deleting it at the end of the operation (making sure to also delete it in the case of any error).</p>
2
2016-07-24T20:39:21Z
[ "python", "django" ]
Is there a way to block django views from serving multiple requests concurrently?
38,556,461
<p>I have a django app, where I am using one of the views to fetch data from local filesystem and parse it and add it to my database. Now the thing is, I want to restrict this view from serving multiple requests concurrently, I want them to be served sequentially instead. Or just block the new request when one request is already being served. Is there a way to achieve it?</p>
1
2016-07-24T20:26:59Z
38,557,365
<p>here is a link to python functions and module that support inter-thread locking:</p> <p><a href="https://docs.python.org/3/library/asyncio-sync.html" rel="nofollow">https://docs.python.org/3/library/asyncio-sync.html</a></p> <p>There are some simple examples on the page.</p>
1
2016-07-24T22:15:15Z
[ "python", "django" ]
Combine result of two functions in python
38,556,474
<p>The objective I'm trying to reach is to take a string, extract time as hours and minutes and return them as degrees on an analogue clock dial, the only way i could think to do this is to create 2 functions, one to return the hours and another to return the minutes. I've probably gone about this the completely the wrong way (i'm a beginner). I now need to combine the result of two functions as a string. my code looks like this:</p> <pre><code>def clock_degree(s): hr, min = s.split(':') if int(hr) &gt; 12: return str((int(hr)-12)*30) elif int(hr) == 0: return str((int(hr)+12)*30) elif int(hr) &gt; 24: return "Check your time !" elif int(hr) &lt; 0: return "Check your time !" else: return int(hr) * 30 def clock_degree_min(x): hour, mn = x.split(':') if int(mn) == 60: return 360 elif int(mn) == 0: return 360 elif int(mn) &gt; 60: return "Check your time !" elif int(mn) &lt; 0: return "Check your time !" else: return int(mn) * 6 </code></pre> <p>any other solution to how i could achieve this is welcome. Thank you in advance.</p>
0
2016-07-24T20:29:11Z
38,556,541
<p>Once you have the times in a list, then you can do the following:</p> <pre><code>currentTimes = [] # Here's a list of times before the functions manipulate each element. analogDialTimes = [(clock_degree(time), clock_degree_min(time)) for time in currentTimes] </code></pre> <p>This returns a list of tuples, similar to what Moses suggested.</p>
1
2016-07-24T20:35:46Z
[ "python" ]
Combine result of two functions in python
38,556,474
<p>The objective I'm trying to reach is to take a string, extract time as hours and minutes and return them as degrees on an analogue clock dial, the only way i could think to do this is to create 2 functions, one to return the hours and another to return the minutes. I've probably gone about this the completely the wrong way (i'm a beginner). I now need to combine the result of two functions as a string. my code looks like this:</p> <pre><code>def clock_degree(s): hr, min = s.split(':') if int(hr) &gt; 12: return str((int(hr)-12)*30) elif int(hr) == 0: return str((int(hr)+12)*30) elif int(hr) &gt; 24: return "Check your time !" elif int(hr) &lt; 0: return "Check your time !" else: return int(hr) * 30 def clock_degree_min(x): hour, mn = x.split(':') if int(mn) == 60: return 360 elif int(mn) == 0: return 360 elif int(mn) &gt; 60: return "Check your time !" elif int(mn) &lt; 0: return "Check your time !" else: return int(mn) * 6 </code></pre> <p>any other solution to how i could achieve this is welcome. Thank you in advance.</p>
0
2016-07-24T20:29:11Z
38,556,561
<p>I'd rather avoid mixing return types (that's what exceptions are for), and use standard library functions for common operations like parsing time (<a href="https://docs.python.org/2/library/time.html#time.strptime" rel="nofollow" title="time.strptime">time.strptime</a>):</p> <pre><code>import time s="15:43" t=time.strptime(s,"%H:%M") pair = t.tm_hour*360/12, t.tm_min*360/60 </code></pre> <p>Use modulo <code>t.tm_hour%12</code> if you want to restrict the hour hand to one turn, and combine hour and minute for a smoothly moving hour hand <code>(t.tm_hour+t.tm_min/60.0)</code>.</p> <p>Finally, as to how to handle that pair, you said "combine the result of two functions as a string" but that doesn't tell me what sort of format you want it in. Could you provide an example?</p>
0
2016-07-24T20:38:56Z
[ "python" ]
Combine result of two functions in python
38,556,474
<p>The objective I'm trying to reach is to take a string, extract time as hours and minutes and return them as degrees on an analogue clock dial, the only way i could think to do this is to create 2 functions, one to return the hours and another to return the minutes. I've probably gone about this the completely the wrong way (i'm a beginner). I now need to combine the result of two functions as a string. my code looks like this:</p> <pre><code>def clock_degree(s): hr, min = s.split(':') if int(hr) &gt; 12: return str((int(hr)-12)*30) elif int(hr) == 0: return str((int(hr)+12)*30) elif int(hr) &gt; 24: return "Check your time !" elif int(hr) &lt; 0: return "Check your time !" else: return int(hr) * 30 def clock_degree_min(x): hour, mn = x.split(':') if int(mn) == 60: return 360 elif int(mn) == 0: return 360 elif int(mn) &gt; 60: return "Check your time !" elif int(mn) &lt; 0: return "Check your time !" else: return int(mn) * 6 </code></pre> <p>any other solution to how i could achieve this is welcome. Thank you in advance.</p>
0
2016-07-24T20:29:11Z
38,556,596
<pre><code>def clock_degree(s): hr, min = s.split(':') hr = float(hr) + float(min)/60 # convert minutes to hours (ex : 30 min = 0.5h) hr = hr % 12 # have a time between 0:00 and 12:00 angle = (360 / 12) * hr # calculate the angle (6h =&gt; 180°) print(hr, angle) return (hr, angle) clock_degree('24:00') clock_degree('12:00') clock_degree('6:00') clock_degree('24:30') </code></pre> <p>outputs :</p> <pre><code>0.0 0.0 0.0 0.0 6.0 180.0 0.5 15.0 </code></pre>
0
2016-07-24T20:43:10Z
[ "python" ]
Combine result of two functions in python
38,556,474
<p>The objective I'm trying to reach is to take a string, extract time as hours and minutes and return them as degrees on an analogue clock dial, the only way i could think to do this is to create 2 functions, one to return the hours and another to return the minutes. I've probably gone about this the completely the wrong way (i'm a beginner). I now need to combine the result of two functions as a string. my code looks like this:</p> <pre><code>def clock_degree(s): hr, min = s.split(':') if int(hr) &gt; 12: return str((int(hr)-12)*30) elif int(hr) == 0: return str((int(hr)+12)*30) elif int(hr) &gt; 24: return "Check your time !" elif int(hr) &lt; 0: return "Check your time !" else: return int(hr) * 30 def clock_degree_min(x): hour, mn = x.split(':') if int(mn) == 60: return 360 elif int(mn) == 0: return 360 elif int(mn) &gt; 60: return "Check your time !" elif int(mn) &lt; 0: return "Check your time !" else: return int(mn) * 6 </code></pre> <p>any other solution to how i could achieve this is welcome. Thank you in advance.</p>
0
2016-07-24T20:29:11Z
38,556,601
<p>I would prefer something like this that is a bit more terse:</p> <pre><code>def getDegrees(t): h, m = [float(n) for n in t.split(":")] result = [] for n, denominator in (h, 12), (m, 60): result.append(str((n % denominator) / denominator * 360)) return ",".join(result) </code></pre> <p>For both minutes and seconds, start with the maximum value and use it to get the modulus (e.g., 22->10) and then divide by it (6->0.5), then multiply by 360.</p>
0
2016-07-24T20:43:46Z
[ "python" ]
Matrix using only one column for header and row
38,556,574
<p>Let's say I have a list of names like this one in a csv:</p> <pre><code>Nom;Link;NonLink Deb;John; John;Deb; Martha;Travis; Travis;Martha; Allan;; Lois;; Jayne;; Brad;;Abby Abby;;Brad </code></pre> <p>I imported it using numpy:</p> <pre><code>import numpy as np file = np.genfromtxt('liste.csv', dtype=None, delimiter =';',skip_header=1) </code></pre> <p>Now, I'm isolating my first column:</p> <pre><code>Nom = np.array(file[:,0]) </code></pre> <p>I would like to create a matrix using only this first column to get a result like this one:</p> <pre><code> Deb John Martha etc... Deb 0 0 0 ... John 0 0 0 ... Martha 0 0 0 ... etc... </code></pre> <p>Is there a numpy function for that? </p> <p>Edit: My end goal is to make a little program to assign seats at tables where people in Link must be seated at the same table and NonLink must not be at the same table.</p> <p>Thank you,</p>
0
2016-07-24T20:40:27Z
38,556,665
<p>You can use pandas and create a dataframe using <code>Nom</code> variable. Something like this:</p> <pre><code>import pandas as pd df = pd.DataFrame([[0] * len(Nom)] * len(Nom), Nom, Nom) print(df) </code></pre>
1
2016-07-24T20:52:47Z
[ "python", "numpy", "pandas" ]
it is possible to type-hint a compiled regex in python?
38,556,579
<p>I would like to use autocompletion for a pre-compiled and stored list of regular expressions, but it doesn't appear that I can import the _sre.SRE_Pattern class, and I can't programmatically feed the obtained type from type() to a comment of the format # type: classname or use it for a return -> classname style hint</p> <p>is there a way to explicitly import a class from the _sre.c thing?</p>
0
2016-07-24T20:41:47Z
38,935,153
<p>You should use <a href="https://docs.python.org/3/library/typing.html#typing.re" rel="nofollow"><code>typing.Pattern</code> and <code>typing.Match</code></a> which were specifically added to the typing module to accommodate this use case.</p> <p>Example:</p> <pre><code>from typing import Pattern, Match import re my_pattern = re.compile("[abc]*") # type: Pattern[str] my_match = re.match(my_pattern, "abbcab") # type: Match[str] print(my_match) </code></pre>
0
2016-08-13T17:12:27Z
[ "python", "regex", "type-hinting" ]
Is there a more efficient way to write this Python code?
38,556,646
<p>I am dealing with a preprocessing stage of a data table. My current code works but I am wondering if there is a more efficient way.</p> <p>My data table looks like this</p> <pre><code>object A object B features of A features of B aaa w 1 0 aaa q 1 1 bbb x 0 0 ccc w 1 0 </code></pre> <p>for the X it would be</p> <pre><code>[ (aaa, aaa, bbb, ccc), (w, q, x, w), (1, 1, 0, 1), (0, 1, 0, 0)] </code></pre> <p>Now I am writing a code to make a table that includes all the combination of every possible match of object A &amp; object B (iterate the combination of object A &amp; object B without repetition), while A &amp; B keeps their features respectively. The table would look like the follows:(rows with a star are the added rows) </p> <pre><code>object A object B features of A features of B aaa w 1 0 aaa q 1 1 * aaa x 1 0 --------------------------------------------------------- bbb x 0 0 * bbb w 0 0 * bbb q 0 1 --------------------------------------------------------- ccc w 1 0 * ccc x 1 0 * ccc q 1 1 </code></pre> <p>The whole data is named X To get the table: My code is as follows, but it runs very slow:</p> <pre><code>----------------------------------------- #This part is still fast #to make the combination of object A and object B with no repetition def uprod(*seqs): def inner(i): if i == n: yield tuple(result) return for elt in sets[i] - seen: seen.add(elt) result[i] = elt for t in inner(i+1): yield t seen.remove(elt) sets = [set(seq) for seq in seqs] n = len(sets) seen = set() result = [None] * n for t in inner(0): yield t #add all possibility into a new list named "new_data" new_data = list(uprod(X[0],X[1])) X_8v = X[:] y_8v = y[:] ----------------------------------------- #if the current X_8v( content equals to X) does not have the match of object A and object B #in the list "new_data" #append a new row to the current X_8v #Now this part is super slow, I think because I iterate a lot for i, j in list(enumerate(X_8v[0])): for k, w in list(enumerate(X_8v[1])): if (X_8v[0][i], X_8v[1][k]) not in new_data: X_8v[0] + (X_8v[0][i],) X_8v[1] + (X_8v[1][k],) X_8v[2] + (X_8v[2][i],) X_8v[3] + (X_8v[3][k],) X_8v[4] + (X_8v[4][i],) X_8v[5] + (0,) X_8v[6] + (0,) y_8v.append(0) </code></pre> <p>is there any possible improvement for the code above?</p> <p>Many thanks!</p>
0
2016-07-24T20:50:21Z
38,557,260
<p>In relational algebra terms, it sounds like you want </p> <p><code>π[features of A, features of B] ((object A) X (object B))</code></p> <p>i.e. project fields 'features of A', 'features of B' from the cross-product of "object A" and "object B". </p> <p>This is very natural to express in SQL. </p> <p>For Python, you probably want to load your data into a couple of dictionaries i.e. <code>object_a_to_features = {"aaa": 1, "bbb": 0} object_b_to_features = {"w": 0, "q": 1}</code></p> <p>You'll then want to generate the cross-product of <code>object_a_to_features.keys()</code> and <code>object_b_to_features.keys()</code> and then for each row, look up the features in the appropriate dictionary.</p> <p>Have a look at <a href="https://docs.python.org/2/library/itertools.html#itertools.product" rel="nofollow">product() from itertools</a>.</p> <p>Something like:</p> <p><code>import itertools for pair in itertools.product(object_a_to_features.keys(), object_b_to_features.keys()): yield (pair[0], pair[1], object_a_to_features[pair[0]], object_b_to_features[pair[1]]) </code></p> <p>Sample output:</p> <p><code>('aaa', 'q', 1, 1) ('aaa', 'w', 1, 0) ('bbb', 'q', 0, 1) ('bbb', 'w', 0, 0) </code></p>
2
2016-07-24T22:01:10Z
[ "python", "iteration" ]
Is there a more efficient way to write this Python code?
38,556,646
<p>I am dealing with a preprocessing stage of a data table. My current code works but I am wondering if there is a more efficient way.</p> <p>My data table looks like this</p> <pre><code>object A object B features of A features of B aaa w 1 0 aaa q 1 1 bbb x 0 0 ccc w 1 0 </code></pre> <p>for the X it would be</p> <pre><code>[ (aaa, aaa, bbb, ccc), (w, q, x, w), (1, 1, 0, 1), (0, 1, 0, 0)] </code></pre> <p>Now I am writing a code to make a table that includes all the combination of every possible match of object A &amp; object B (iterate the combination of object A &amp; object B without repetition), while A &amp; B keeps their features respectively. The table would look like the follows:(rows with a star are the added rows) </p> <pre><code>object A object B features of A features of B aaa w 1 0 aaa q 1 1 * aaa x 1 0 --------------------------------------------------------- bbb x 0 0 * bbb w 0 0 * bbb q 0 1 --------------------------------------------------------- ccc w 1 0 * ccc x 1 0 * ccc q 1 1 </code></pre> <p>The whole data is named X To get the table: My code is as follows, but it runs very slow:</p> <pre><code>----------------------------------------- #This part is still fast #to make the combination of object A and object B with no repetition def uprod(*seqs): def inner(i): if i == n: yield tuple(result) return for elt in sets[i] - seen: seen.add(elt) result[i] = elt for t in inner(i+1): yield t seen.remove(elt) sets = [set(seq) for seq in seqs] n = len(sets) seen = set() result = [None] * n for t in inner(0): yield t #add all possibility into a new list named "new_data" new_data = list(uprod(X[0],X[1])) X_8v = X[:] y_8v = y[:] ----------------------------------------- #if the current X_8v( content equals to X) does not have the match of object A and object B #in the list "new_data" #append a new row to the current X_8v #Now this part is super slow, I think because I iterate a lot for i, j in list(enumerate(X_8v[0])): for k, w in list(enumerate(X_8v[1])): if (X_8v[0][i], X_8v[1][k]) not in new_data: X_8v[0] + (X_8v[0][i],) X_8v[1] + (X_8v[1][k],) X_8v[2] + (X_8v[2][i],) X_8v[3] + (X_8v[3][k],) X_8v[4] + (X_8v[4][i],) X_8v[5] + (0,) X_8v[6] + (0,) y_8v.append(0) </code></pre> <p>is there any possible improvement for the code above?</p> <p>Many thanks!</p>
0
2016-07-24T20:50:21Z
38,557,349
<p>Assuming the data actually looks like I think it does, this should do what you want quite efficiently:</p> <pre><code>import itertools x = [('aaa', 'aaa', 'bbb', 'ccc'), ('w', 'q', 'x', 'w'), (1, 1, 0, 1), (0, 1, 0, 0)] a_list = set((x[0][i], x[2][i]) for i in range(len(x[0]))) b_list = set((x[1][i], x[3][i]) for i in range(len(x[1]))) for combination in itertools.product(a_list, b_list): print(combination) # Output: # (('ccc', 1), ('w', 0)) # (('ccc', 1), ('x', 0)) # (('ccc', 1), ('q', 1)) # (('aaa', 1), ('w', 0)) # (('aaa', 1), ('x', 0)) # (('aaa', 1), ('q', 1)) # (('bbb', 0), ('w', 0)) # (('bbb', 0), ('x', 0)) # (('bbb', 0), ('q', 1)) </code></pre> <p>Of course you can easily convert the data back into the order you originally had:</p> <pre><code>reordered = [[a[0], b[0], a[1], b[1]] for a, b in itertools.product(a_list, b_list)] for row in reordered: print(row) # ['ccc', 'w', 1, 0] # ['ccc', 'x', 1, 0] # ['ccc', 'q', 1, 1] # ['aaa', 'w', 1, 0] # ['aaa', 'x', 1, 0] # ['aaa', 'q', 1, 1] # ['bbb', 'w', 0, 0] # ['bbb', 'x', 0, 0] # ['bbb', 'q', 0, 1] </code></pre> <p><strong>EDIT</strong></p> <p>Based on the comment below, if you want to add a column with 1 indicating "This row was in the original dataset" and 0 indicating "This row was not in the original dataset," give this a try:</p> <pre><code>existing_combinations = set(zip(x[0], x[1])) reordered = [ [a[0], b[0], a[1], b[1], 1 if (a[0], b[0]) in existing_combinations else 0 ] for a, b in itertools.product(a_list, b_list) ] # Output: # ['ccc', 'x', 1, 0, 0] # ['ccc', 'q', 1, 1, 0] # ['ccc', 'w', 1, 0, 1] # ['bbb', 'x', 0, 0, 1] # ['bbb', 'q', 0, 1, 0] # ['bbb', 'w', 0, 0, 0] # ['aaa', 'x', 1, 0, 0] # ['aaa', 'q', 1, 1, 1] # ['aaa', 'w', 1, 0, 1] </code></pre>
1
2016-07-24T22:12:44Z
[ "python", "iteration" ]
Why do numpy array arr2d[:, :1] and arr2d[:, 0] produce different results?
38,556,674
<p>Say:</p> <pre><code>arr2d = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) </code></pre> <p><code>arr2d[:, :1]</code> gives me</p> <pre><code>array([[1], [4], [7]]) </code></pre> <p><code>arr2d[:,0]</code> gives me </p> <pre><code>array([1, 4, 7]) </code></pre> <p>I thought they would produce exactly same thing.</p>
0
2016-07-24T20:53:47Z
38,556,780
<p>With a list, you have the same behavior you described:</p> <pre><code>&gt;&gt;&gt; a = [1, 2, 3, 4] &gt;&gt;&gt; a[0] 1 &gt;&gt;&gt; a[:1] [1] </code></pre> <p>The addition with <code>numpy</code> is the introduction of <code>axis</code> which makes it a little less intuitive.</p> <p>In the first case, you're <em>returning</em> an item at a specific index, in the second case, you're <em>returning</em> a slice of the list.</p> <hr> <p>With <code>numpy</code>, for the former, you're selecting all the items in the first column which returns a one axis array (is one less than the number of axis of the parent as expected with indexing), but in the second case, you're slicing the original array, for which the result still retains the original dimensions of the parent array.</p>
2
2016-07-24T21:05:15Z
[ "python", "numpy", "indexing", "python-2.x" ]
Why do numpy array arr2d[:, :1] and arr2d[:, 0] produce different results?
38,556,674
<p>Say:</p> <pre><code>arr2d = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) </code></pre> <p><code>arr2d[:, :1]</code> gives me</p> <pre><code>array([[1], [4], [7]]) </code></pre> <p><code>arr2d[:,0]</code> gives me </p> <pre><code>array([1, 4, 7]) </code></pre> <p>I thought they would produce exactly same thing.</p>
0
2016-07-24T20:53:47Z
38,557,108
<p>Index <code>':1'</code> implies:</p> <p>'The <strong>list</strong> of items from <code>index 0</code> to <code>index 0</code>' which is obviously a list of 1 item.</p> <p>Index <code>'0'</code> implies:</p> <p>'The item at <code>index 0</code>'.</p> <p>Extending that to your question should make the results you obtained pretty clear.</p> <p><code>arr2d[:, :1]</code> means 'data corresponding to all rows and the list of columns 0 to 0'. </p> <p>So the result is a list of lists.</p> <p><code>arr2d[:, 0]</code> means 'data corresponding to all rows and just the first column'. </p> <p>So it is just a list.</p>
1
2016-07-24T21:41:52Z
[ "python", "numpy", "indexing", "python-2.x" ]
Why do numpy array arr2d[:, :1] and arr2d[:, 0] produce different results?
38,556,674
<p>Say:</p> <pre><code>arr2d = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) </code></pre> <p><code>arr2d[:, :1]</code> gives me</p> <pre><code>array([[1], [4], [7]]) </code></pre> <p><code>arr2d[:,0]</code> gives me </p> <pre><code>array([1, 4, 7]) </code></pre> <p>I thought they would produce exactly same thing.</p>
0
2016-07-24T20:53:47Z
38,557,414
<p>1) When you say <code>arr2d[:, 0]</code>, you're saying give me the 0th index of all the rows in arr2d (this is another way of saying give me the 0th column). </p> <p>2) When you say <code>arr2d[:, :1]</code>, you're saying give me all the <code>:1</code> index of all the rows in arr2d. Numpy interprets <code>:1</code> the same as it would interpret <code>0:1</code>. Thus, you're saying "for each row, give me the 0th through first index (exclusive) of each row". This turns out to be just the 0th index, but you've explicitly asked for the second dimension to have length one (since <code>0:1</code> is only "length" one).</p> <p>So:</p> <p>1)</p> <pre><code>print arr2d[:, 0].shape </code></pre> <p>Output:</p> <pre><code>(3L,) </code></pre> <p>2)</p> <pre><code>print arr2d[:, 0:1].shape </code></pre> <p>Output:</p> <pre><code>(3L, 1L) </code></pre> <p><strong>I still don't get it, why don't they return the same thing?</strong></p> <p>Consider:</p> <pre><code>print arr2d[:, 0:3] print arr2d[:, 0:3].shape print arr2d[:, 0:2] print arr2d[:, 0:2].shape print arr2d[:, 0:1] print arr2d[:, 0:1].shape </code></pre> <p>This outputs:</p> <pre><code>[[1 2 3] [4 5 6] [7 8 9]] (3L, 3L) [[1 2] [4 5] [7 8]] (3L, 2L) [[1] [4] [7]] (3L, 1L) </code></pre> <p>It would be a bit unexpected and inconsistent for that last shape to be <code>(3L,)</code>.</p>
3
2016-07-24T22:23:02Z
[ "python", "numpy", "indexing", "python-2.x" ]
Django: Linking two tables
38,556,735
<p>first of all, I'm aware that this question might've been answered already, but there are two reasons why I'm opening another question: One, obviously, is I'm struggling with the Django syntax. Secondly, and perhaps more importantly, I'm not quite sure whether my database setup makes even sense at this point. So, please bear with me. </p> <p>I work in a hospital and one of my daily stuggles is that, oftentimes, one single drug can have a lot of different names. So, I thought that'd be a good task to practice some Django with.</p> <p>Basically I want two databases: One that simply links the drugs "nick name" to it's actual name. And another one which links the actual name to some additional information, something along the lines of a wiki page. </p> <p>What I've come up with so far:</p> <pre><code>(django)django@ip:~/medwiki$ cat medsearch/models.py from django.db import models # Create your models here. class medsearch(models.Model): proprietary_name = models.CharField(max_length = 100, unique = True) non_proprietary_name = models.CharField(max_length = 100, unique = True) def __str__(self): return self.non_proprietary_name class medwiki(models.Model): proprietary_name = models.ForeignKey('medisearch', on_delete=models.CASCADE) cetegory = models.CharField(max_length = 255) #wiki = models.TextField() etc. def __str__(self): return self.proprietary_name (django)django@ip-:~/medwiki$ </code></pre> <p>So, I can add a new "medsearch object" just fine. However, when adding the "Category" at medwiki I get <code>__str__ returned non-string (type medsearch)</code>. Presumably, because there's more than one key in medsearch? I thus suspect that "FroeignKey" is not suited for this application and I know that there are other ways to link databases in Django. However, I don't know which one to choose and how to implement it correctly.</p> <p>Hopefully, some of you have some ideas? </p> <p>EDIT: Here's what I've come up with so far:</p> <pre><code>class Proprietary_name(models.Model): proprietary_name = models.CharField(max_length = 100, unique = True) def __str__(self): return self.proprietary_name class Category(models.Model): category = models.CharField(max_length = 100, unique = True) def __str__(self): return self.category class Mediwiki(models.Model): proprietary_name = models.ManyToManyField(Proprietary_name) non_proprietary_name = models.CharField(max_length = 100, unique = True) category = models.ManyToManyField(Category) wiki_page = models.TextField() def __str__(self): return self.non_proprietary_name </code></pre> <p>Now I can attribute different categorys and different proprietary_names to one drug. Which works great so far. </p> <p>So does looking up the non-proprietary_name when I know the proprietary "nick name". </p> <pre><code>&gt;&gt;&gt; Mediwiki.objects.get(proprietary_name__proprietary_name="Aspirin") &lt;Mediwiki: acetylsalicylic acid&gt; &gt;&gt;&gt; </code></pre> <p>However, I'd also like to display all the proprietary_names, when I know the non_proprietary_name. Do I have to further change the database design, or am I just missing some other thing here? </p>
0
2016-07-24T21:00:02Z
38,556,844
<p>As you note, the <code>proprietary_name</code> field on medwiki is a ForeignKey. You can't return that value directly from the <code>__str__</code> method because that needs to return a string. You need to convert that value into a string before returning it: either use the default string representation of the medsearch instance:</p> <pre><code>return str(self.proprietary_name) </code></pre> <p>or choose a specific string field to return:</p> <pre><code>return self.proprietary_name.proprietary_name </code></pre>
1
2016-07-24T21:13:18Z
[ "python", "sql", "django", "database" ]
Django: Linking two tables
38,556,735
<p>first of all, I'm aware that this question might've been answered already, but there are two reasons why I'm opening another question: One, obviously, is I'm struggling with the Django syntax. Secondly, and perhaps more importantly, I'm not quite sure whether my database setup makes even sense at this point. So, please bear with me. </p> <p>I work in a hospital and one of my daily stuggles is that, oftentimes, one single drug can have a lot of different names. So, I thought that'd be a good task to practice some Django with.</p> <p>Basically I want two databases: One that simply links the drugs "nick name" to it's actual name. And another one which links the actual name to some additional information, something along the lines of a wiki page. </p> <p>What I've come up with so far:</p> <pre><code>(django)django@ip:~/medwiki$ cat medsearch/models.py from django.db import models # Create your models here. class medsearch(models.Model): proprietary_name = models.CharField(max_length = 100, unique = True) non_proprietary_name = models.CharField(max_length = 100, unique = True) def __str__(self): return self.non_proprietary_name class medwiki(models.Model): proprietary_name = models.ForeignKey('medisearch', on_delete=models.CASCADE) cetegory = models.CharField(max_length = 255) #wiki = models.TextField() etc. def __str__(self): return self.proprietary_name (django)django@ip-:~/medwiki$ </code></pre> <p>So, I can add a new "medsearch object" just fine. However, when adding the "Category" at medwiki I get <code>__str__ returned non-string (type medsearch)</code>. Presumably, because there's more than one key in medsearch? I thus suspect that "FroeignKey" is not suited for this application and I know that there are other ways to link databases in Django. However, I don't know which one to choose and how to implement it correctly.</p> <p>Hopefully, some of you have some ideas? </p> <p>EDIT: Here's what I've come up with so far:</p> <pre><code>class Proprietary_name(models.Model): proprietary_name = models.CharField(max_length = 100, unique = True) def __str__(self): return self.proprietary_name class Category(models.Model): category = models.CharField(max_length = 100, unique = True) def __str__(self): return self.category class Mediwiki(models.Model): proprietary_name = models.ManyToManyField(Proprietary_name) non_proprietary_name = models.CharField(max_length = 100, unique = True) category = models.ManyToManyField(Category) wiki_page = models.TextField() def __str__(self): return self.non_proprietary_name </code></pre> <p>Now I can attribute different categorys and different proprietary_names to one drug. Which works great so far. </p> <p>So does looking up the non-proprietary_name when I know the proprietary "nick name". </p> <pre><code>&gt;&gt;&gt; Mediwiki.objects.get(proprietary_name__proprietary_name="Aspirin") &lt;Mediwiki: acetylsalicylic acid&gt; &gt;&gt;&gt; </code></pre> <p>However, I'd also like to display all the proprietary_names, when I know the non_proprietary_name. Do I have to further change the database design, or am I just missing some other thing here? </p>
0
2016-07-24T21:00:02Z
38,556,852
<p>This would work:</p> <pre><code>return self.proprietary_name.proprietary_name </code></pre> <p>But that doesn't really make sense !</p> <hr> <p>The main issue is that you've called the foreign key to <code>medsearch</code>, <code>proprietary_name</code>.</p> <p>The second issue is just a convention one. In Python (and many programming languages), classes must start with an uppercase letter. </p> <p>The following would be better:</p> <pre><code>class MedSearch(models.Model): proprietary_name = models.CharField(max_length=100, unique=True) non_proprietary_name = models.CharField(max_length=100, unique=True) def __str__(self): return self.non_proprietary_name class MedWiki(models.Model): med_search = models.ForeignKey('MedSearch', on_delete=models.CASCADE, related_name='wikis') cetegory = models.CharField(max_length = 255) #wiki = models.TextField() etc. def __str__(self): return self.med_serach.proprietary_name </code></pre>
2
2016-07-24T21:14:06Z
[ "python", "sql", "django", "database" ]
Iterate over variables in spss and get a conditional sum
38,556,808
<p>I have the following variables: <code>attribute1 , value1, attribute2, value2</code>, ...</p> <p>Each attribute can have a numeric value between 0 and 6.</p> <p>How can I iterate over the variables and get the sum for each attribute?</p> <p>Like: get sum of all values where <code>attribute == 0</code>?</p>
-1
2016-07-24T21:08:17Z
38,556,858
<p>I don't know the structure of your variable storage, so I'll assume a list of tuples.</p> <p>Use a list comprehension:</p> <pre><code>listOfTuples = [(2, 5), (4, 3), (2, 4), (2, 3)] # etc... someValue = 2 # Your desired value # Store the VALUE - not the key sumOfAttrsForAValue = sum([y for x, y in listOfTuples if x == someValue]) print (sumOfAttrsForAValue) # 12 </code></pre>
0
2016-07-24T21:14:41Z
[ "python", "ibm" ]
Iterating over columns and reassigning values - Pandas/Python
38,556,822
<p>Trying to use a for loop to iterate over columns and change Yes and No's to 1 and 0.</p> <p>For some reason, I am getting an invalid type comparison error when attempting this:</p> <p>Panda DataFrame has multiple columns, one of them being "Combined"</p> <pre><code>for col,row in d.iteritems(): d.loc[d[col] == 'No', col] = 0 d.loc[d[col] == 'Yes', col] = 1 </code></pre> <p>TypeError: invalid type comparison</p> <p>For comparison, I can successfully perform this on a single column without issues:</p> <pre><code>d.loc[d['Combined'] == 'No', 'Combined'] = 0 d.loc[d['Combined'] == 'Yes', 'Combined'] = 1 </code></pre> <p>Any reason why plugging the value of col into the loc function in place of the actual column name throws an error? Does it need to be converted to a string or something before?</p>
0
2016-07-24T21:10:24Z
38,556,916
<p>There must be columns which are taking integer values and for those rows its an "invalid comparison". So just check if its an instance of str and you are good to go.</p> <pre><code>for col,row in d.iteritems(): if isinstance(row[0], str): d.loc[d[col] == 'No', col] = 0 d.loc[d[col] == 'Yes', col] = 1 </code></pre> <p>And for the same reason</p> <pre><code>d.loc[d['Combined'] == 'No', 'Combined'] = 0 </code></pre> <p>this is working perfectly, as its already a column with string values.</p>
0
2016-07-24T21:20:24Z
[ "python", "pandas", "dataframe" ]
Acceptable use of os.open/read/write/close?
38,556,833
<p>I intend to frequently read/write small pieces of information from many different files. The following somewhat contrived example shows substantially less time taken when using <code>os</code> operations for acting directly on file descriptors. Am I missing any downside other than the convenience of file objects?</p> <pre><code>import os import time N = 10000 PATH = "/tmp/foo.test" def testOpen(): for i in range(N): with open(PATH, "wb") as fh: fh.write("A") for i in range(N): with open(PATH, "rb") as fh: s = fh.read() def testOsOpen(): for i in range(N): fd = os.open(PATH, os.O_CREAT | os.O_WRONLY) try: os.write(fd, "A") finally: os.close(fd) for i in range(N): fd = os.open(PATH, os.O_RDONLY) try: s = os.read(fd, 1) finally: os.close(fd) if __name__ == "__main__": for fn in testOpen, testOsOpen: start = time.time() fn() print fn.func_name, "took", time.time() - start </code></pre> <p>Sample run:</p> <pre><code>$ python bench.py testOpen took 1.82302999496 testOsOpen took 0.436559915543 </code></pre>
4
2016-07-24T21:11:44Z
38,558,165
<p>I'll answer just so this doesn't stay open forever ;-)</p> <p>There's really little to say: as you already noted, a <code>file</code> object is more convenient. In <em>some</em> cases it's also more functional; for example, it does its own layer of buffering to speed line-oriented text operations (like <code>file_object.readline()</code>) (BTW, that's one reason it's slower too.) And a <code>file</code> object strives to work the same way across all platforms.</p> <p>But if you don't need/want that, there's nothing at all wrong with using the lower-level &amp; zippier <code>os</code> file descriptor functions instead. There are many of the latter, and not all are supported on all platforms, and not all options are supported on all platforms. Of course you're responsible for restricting yourself to a subset of operations &amp; options in the intersection of the platforms you care about (which is generally true of all functions in <code>os</code>, not just its file descriptor functions - the name <code>os</code> is a strong hint that the stuff it contains may be OS-dependent).</p> <p>With respect to Pythons 2 and 3, the differences are due to the strong distinction Python 3 makes between "text" and "binary" modes on <em>all</em> platforms. It's a Unicode world, and "text mode" for <code>file</code> objects make no sense without specifying the intended encoding. In Python 3, a <code>file</code> object read method returns a <code>str</code> object (a Unicode string) if the file was opened in "text mode", but a <code>bytes</code> object if in "binary mode". Similarly for write methods.</p> <p>Because the <code>os</code> file descriptor methods have no notion of encoding, they can only work with bytes-like objects in Python 3 (regardless of whether, e.g., on Windows, the file descriptor was opened with the low-level <code>os.open()</code> <code>O_BINARY</code> or <code>O_TEXT</code> flags).</p> <p>In practice, in the example you gave, this just means you would have to change instances of</p> <pre><code>"A" </code></pre> <p>to</p> <pre><code>b"A" </code></pre> <p>Note that you can also use the <code>b"..."</code> literal syntax in a recent-enough version of Python 2, although it's still just a string literal in Python 2. In Python 3 it denotes a different kind of object (<code>bytes</code>), and file descriptor functions are restricted to writing and returning bytes-like objects.</p> <p>But if you're working with "binary data", that's no restriction at all. If you're working with "text data", it <em>may</em> be (not enough info about your specifics to guess).</p>
1
2016-07-25T00:22:24Z
[ "python", "file" ]
No twitter Module error [Mac]
38,556,890
<p>I have a python script that follows/unfollows and favorites tweets. I keep getting an error:</p> <pre><code>from twitter import Twitter, OAuth, TwitterHTTPError ImportError: No module named twitter </code></pre> <p>I put in all the oauth info in my script and i continue to get this error. I think im being blocked from the api. Can someone help me out?</p>
-3
2016-07-24T21:17:09Z
38,556,998
<p>First of all: which library do you use? I expect you use tweepy so from a terminal type:</p> <pre><code>pip install Tweepy </code></pre>
0
2016-07-24T21:29:48Z
[ "python", "osx", "twitter", "importerror" ]
UnicodeEncodeError at /admin/... - Django admin
38,556,904
<p>I'm facing an encoding problem in <code>Django-admin</code>. I have a model, which represents a language quiz which consists of questions and answers (both are models) inlined to <code>Quiz</code> model.</p> <p>I've created a simple <code>csv</code> import. In <code>Quiz</code> model, there is a file field. When admin is creating a new <code>Quiz</code>, they upload a csv file which calls a signal which parse csv and creates questions and answers for this quiz. </p> <p>There is no problem with english, but I tried to import French quiz and it raises error.</p> <pre><code>Exception Value: 'ascii' codec can't encode character u'\ufeff' in position 0: ordinal not in range(128) </code></pre> <p>Import signal is very simple:</p> <pre><code>def parse_csv(csv): questions = [] for line in csv: line = line.strip('\r\n').strip('\n') d = {} items = line.split(';;') def parse_csv(csv): questions = [] i=0 for line in csv: i+=1 print i line = line.strip('\r\n').strip('\n') d = {} items = line.split(';;') question = items[0] d['question'] = question for item in (x.strip() for x in items[1:]): if '|' in item: d['answer'] = item else: if 'choices' in d.keys(): d['choices'].append(item) else: d['choices'] = [item] if 'answer' not in d.keys(): continue questions.append(d) return questions @receiver(post_save,sender=LanguageQuiz) def quiz_import_csv(sender,instance,created,**kwargs): if created: if instance.import_csv: questions = parse_csv(instance.import_csv.readlines()) for q in questions: question = Question(text=q['question']) question.save() for ch in q['choices']: choice = Choice(text=ch,correct=False) choice.save() question.choices.add(choice) answer = Choice(text=q['answer'].strip('|'),correct=True) answer.save() question.choices.add(answer) question.save() instance.questions.add(question) instance.save() </code></pre> <p>Do you know what should I do?</p> <p>EDIT:</p> <p><strong>TRACEBACK:</strong></p> <pre><code>Environment: Request Method: GET Request URL: http://127.0.0.1:8000/admin/language_tests/languagequiz/7/ Django Version: 1.8.12 Python Version: 2.7.10 Installed Applications: ('django.contrib.auth', 'SolutionsForLanguagesApp', 'django.contrib.admin', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'crispy_forms', 'super_inlines', 'django_tables2', 'language_tests', 'smart_selects', 'django_extensions', 'constance', 'constance.backends.database', 'nested_inline') Installed Middleware: ('django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.middleware.locale.LocaleMiddleware') Template error: In template C:\Users\Milano\PycharmProjects\FutileStudio\SolutionsForLanguages_2\venv\lib\site-packages\nested_inline\templates\admin\edit_inline\stacked-nested.html, error at line 9 ascii 1 : {% load i18n admin_static %} 2 : &lt;div class="inline-group{% if recursive_formset %} {{ recursive_formset.formset.prefix|default:"Root" }}-nested-inline {% if prev_prefix %} {{ prev_prefix }}-{{ loopCounter }}-nested-inline{% endif %} nested-inline{% endif %}" id="{{ inline_admin_formset.formset.prefix }}-group"&gt; 3 : {% with recursive_formset=inline_admin_formset stacked_template='admin/edit_inline/stacked-nested.html' tabular_template='admin/edit_inline/tabular-nested.html'%} 4 : &lt;h2&gt;{{ recursive_formset.opts.verbose_name_plural|title }}&lt;/h2&gt; 5 : {{ recursive_formset.formset.management_form }} 6 : {{ recursive_formset.formset.non_form_errors }} 7 : 8 : {% for inline_admin_form in recursive_formset %}&lt;div class="inline-related{% if forloop.last %} empty-form last-related{% endif %}" id="{{ recursive_formset.formset.prefix }}-{% if not forloop.last %}{{ forloop.counter0 }}{% else %}empty{% endif %}"&gt; 9 : &lt;h3&gt;&lt;b&gt;{{ recursive_formset.opts.verbose_name|title }}:&lt;/b&gt;&amp;nbsp;&lt;span class="inline_label"&gt;{% if inline_admin_form.original %} {{ inline_admin_form.original }} {% else %}#{{ forloop.counter }}{% endif %}&lt;/span&gt; 10 : {% if inline_admin_form.show_url %}&lt;a href="../../../r/{{ inline_admin_form.original_content_type_id }}/{{ inline_admin_form.original.id }}/"&gt;{% trans "View on site" %}&lt;/a&gt;{% endif %} 11 : {% if recursive_formset.formset.can_delete and inline_admin_form.original %}&lt;span class="delete"&gt;{{ inline_admin_form.deletion_field.field }} {{ inline_admin_form.deletion_field.label_tag }}&lt;/span&gt;{% endif %} 12 : &lt;/h3&gt; 13 : {% if inline_admin_form.form.non_field_errors %}{{ inline_admin_form.form.non_field_errors }}{% endif %} 14 : {% for fieldset in inline_admin_form %} 15 : {% include "admin/includes/fieldset.html" %} 16 : {% endfor %} 17 : {% if inline_admin_form.pk_field %}{{ inline_admin_form.pk_field.field }}{% endif %} 18 : {{ inline_admin_form.fk_field.field }} 19 : {% if inline_admin_form.form.nested_formsets %} Traceback: File "C:\Users\Milano\PycharmProjects\FutileStudio\SolutionsForLanguages_2\venv\lib\site-packages\django\core\handlers\base.py" in get_response 164. response = response.render() File "C:\Users\Milano\PycharmProjects\FutileStudio\SolutionsForLanguages_2\venv\lib\site-packages\django\template\response.py" in render 158. self.content = self.rendered_content File "C:\Users\Milano\PycharmProjects\FutileStudio\SolutionsForLanguages_2\venv\lib\site-packages\django\template\response.py" in rendered_content 135. content = template.render(context, self._request) File "C:\Users\Milano\PycharmProjects\FutileStudio\SolutionsForLanguages_2\venv\lib\site-packages\django\template\backends\django.py" in render 74. return self.template.render(context) File "C:\Users\Milano\PycharmProjects\FutileStudio\SolutionsForLanguages_2\venv\lib\site-packages\django\template\base.py" in render 210. return self._render(context) File "C:\Users\Milano\PycharmProjects\FutileStudio\SolutionsForLanguages_2\venv\lib\site-packages\django\template\base.py" in _render 202. return self.nodelist.render(context) File "C:\Users\Milano\PycharmProjects\FutileStudio\SolutionsForLanguages_2\venv\lib\site-packages\django\template\base.py" in render 905. bit = self.render_node(node, context) File "C:\Users\Milano\PycharmProjects\FutileStudio\SolutionsForLanguages_2\venv\lib\site-packages\django\template\debug.py" in render_node 79. return node.render(context) File "C:\Users\Milano\PycharmProjects\FutileStudio\SolutionsForLanguages_2\venv\lib\site-packages\django\template\loader_tags.py" in render 135. return compiled_parent._render(context) File "C:\Users\Milano\PycharmProjects\FutileStudio\SolutionsForLanguages_2\venv\lib\site-packages\django\template\base.py" in _render 202. return self.nodelist.render(context) File "C:\Users\Milano\PycharmProjects\FutileStudio\SolutionsForLanguages_2\venv\lib\site-packages\django\template\base.py" in render 905. bit = self.render_node(node, context) File "C:\Users\Milano\PycharmProjects\FutileStudio\SolutionsForLanguages_2\venv\lib\site-packages\django\template\debug.py" in render_node 79. return node.render(context) File "C:\Users\Milano\PycharmProjects\FutileStudio\SolutionsForLanguages_2\venv\lib\site-packages\django\template\loader_tags.py" in render 135. return compiled_parent._render(context) File "C:\Users\Milano\PycharmProjects\FutileStudio\SolutionsForLanguages_2\venv\lib\site-packages\django\template\base.py" in _render 202. return self.nodelist.render(context) File "C:\Users\Milano\PycharmProjects\FutileStudio\SolutionsForLanguages_2\venv\lib\site-packages\django\template\base.py" in render 905. bit = self.render_node(node, context) File "C:\Users\Milano\PycharmProjects\FutileStudio\SolutionsForLanguages_2\venv\lib\site-packages\django\template\debug.py" in render_node 79. return node.render(context) File "C:\Users\Milano\PycharmProjects\FutileStudio\SolutionsForLanguages_2\venv\lib\site-packages\django\template\loader_tags.py" in render 65. result = block.nodelist.render(context) File "C:\Users\Milano\PycharmProjects\FutileStudio\SolutionsForLanguages_2\venv\lib\site-packages\django\template\base.py" in render 905. bit = self.render_node(node, context) File "C:\Users\Milano\PycharmProjects\FutileStudio\SolutionsForLanguages_2\venv\lib\site-packages\django\template\debug.py" in render_node 79. return node.render(context) File "C:\Users\Milano\PycharmProjects\FutileStudio\SolutionsForLanguages_2\venv\lib\site-packages\django\template\loader_tags.py" in render 65. result = block.nodelist.render(context) File "C:\Users\Milano\PycharmProjects\FutileStudio\SolutionsForLanguages_2\venv\lib\site-packages\django\template\base.py" in render 905. bit = self.render_node(node, context) File "C:\Users\Milano\PycharmProjects\FutileStudio\SolutionsForLanguages_2\venv\lib\site-packages\django\template\debug.py" in render_node 79. return node.render(context) File "C:\Users\Milano\PycharmProjects\FutileStudio\SolutionsForLanguages_2\venv\lib\site-packages\django\template\defaulttags.py" in render 217. nodelist.append(node.render(context)) File "C:\Users\Milano\PycharmProjects\FutileStudio\SolutionsForLanguages_2\venv\lib\site-packages\django\template\loader_tags.py" in render 159. return template.render(context) File "C:\Users\Milano\PycharmProjects\FutileStudio\SolutionsForLanguages_2\venv\lib\site-packages\django\template\base.py" in render 212. return self._render(context) File "C:\Users\Milano\PycharmProjects\FutileStudio\SolutionsForLanguages_2\venv\lib\site-packages\django\template\base.py" in _render 202. return self.nodelist.render(context) File "C:\Users\Milano\PycharmProjects\FutileStudio\SolutionsForLanguages_2\venv\lib\site-packages\django\template\base.py" in render 905. bit = self.render_node(node, context) File "C:\Users\Milano\PycharmProjects\FutileStudio\SolutionsForLanguages_2\venv\lib\site-packages\django\template\debug.py" in render_node 79. return node.render(context) File "C:\Users\Milano\PycharmProjects\FutileStudio\SolutionsForLanguages_2\venv\lib\site-packages\django\template\defaulttags.py" in render 576. return self.nodelist.render(context) File "C:\Users\Milano\PycharmProjects\FutileStudio\SolutionsForLanguages_2\venv\lib\site-packages\django\template\base.py" in render 905. bit = self.render_node(node, context) File "C:\Users\Milano\PycharmProjects\FutileStudio\SolutionsForLanguages_2\venv\lib\site-packages\django\template\debug.py" in render_node 79. return node.render(context) File "C:\Users\Milano\PycharmProjects\FutileStudio\SolutionsForLanguages_2\venv\lib\site-packages\django\template\defaulttags.py" in render 217. nodelist.append(node.render(context)) File "C:\Users\Milano\PycharmProjects\FutileStudio\SolutionsForLanguages_2\venv\lib\site-packages\django\template\defaulttags.py" in render 329. return nodelist.render(context) File "C:\Users\Milano\PycharmProjects\FutileStudio\SolutionsForLanguages_2\venv\lib\site-packages\django\template\base.py" in render 905. bit = self.render_node(node, context) File "C:\Users\Milano\PycharmProjects\FutileStudio\SolutionsForLanguages_2\venv\lib\site-packages\django\template\debug.py" in render_node 79. return node.render(context) File "C:\Users\Milano\PycharmProjects\FutileStudio\SolutionsForLanguages_2\venv\lib\site-packages\django\template\defaulttags.py" in render 217. nodelist.append(node.render(context)) File "C:\Users\Milano\PycharmProjects\FutileStudio\SolutionsForLanguages_2\venv\lib\site-packages\django\template\defaulttags.py" in render 329. return nodelist.render(context) File "C:\Users\Milano\PycharmProjects\FutileStudio\SolutionsForLanguages_2\venv\lib\site-packages\django\template\base.py" in render 905. bit = self.render_node(node, context) File "C:\Users\Milano\PycharmProjects\FutileStudio\SolutionsForLanguages_2\venv\lib\site-packages\django\template\debug.py" in render_node 79. return node.render(context) File "C:\Users\Milano\PycharmProjects\FutileStudio\SolutionsForLanguages_2\venv\lib\site-packages\django\template\loader_tags.py" in render 159. return template.render(context) File "C:\Users\Milano\PycharmProjects\FutileStudio\SolutionsForLanguages_2\venv\lib\site-packages\django\template\base.py" in render 212. return self._render(context) File "C:\Users\Milano\PycharmProjects\FutileStudio\SolutionsForLanguages_2\venv\lib\site-packages\django\template\base.py" in _render 202. return self.nodelist.render(context) File "C:\Users\Milano\PycharmProjects\FutileStudio\SolutionsForLanguages_2\venv\lib\site-packages\django\template\base.py" in render 905. bit = self.render_node(node, context) File "C:\Users\Milano\PycharmProjects\FutileStudio\SolutionsForLanguages_2\venv\lib\site-packages\django\template\debug.py" in render_node 79. return node.render(context) File "C:\Users\Milano\PycharmProjects\FutileStudio\SolutionsForLanguages_2\venv\lib\site-packages\django\template\defaulttags.py" in render 576. return self.nodelist.render(context) File "C:\Users\Milano\PycharmProjects\FutileStudio\SolutionsForLanguages_2\venv\lib\site-packages\django\template\base.py" in render 905. bit = self.render_node(node, context) File "C:\Users\Milano\PycharmProjects\FutileStudio\SolutionsForLanguages_2\venv\lib\site-packages\django\template\debug.py" in render_node 79. return node.render(context) File "C:\Users\Milano\PycharmProjects\FutileStudio\SolutionsForLanguages_2\venv\lib\site-packages\django\template\defaulttags.py" in render 217. nodelist.append(node.render(context)) File "C:\Users\Milano\PycharmProjects\FutileStudio\SolutionsForLanguages_2\venv\lib\site-packages\django\template\defaulttags.py" in render 329. return nodelist.render(context) File "C:\Users\Milano\PycharmProjects\FutileStudio\SolutionsForLanguages_2\venv\lib\site-packages\django\template\base.py" in render 905. bit = self.render_node(node, context) File "C:\Users\Milano\PycharmProjects\FutileStudio\SolutionsForLanguages_2\venv\lib\site-packages\django\template\debug.py" in render_node 79. return node.render(context) File "C:\Users\Milano\PycharmProjects\FutileStudio\SolutionsForLanguages_2\venv\lib\site-packages\django\template\debug.py" in render 92. output = force_text(output) File "C:\Users\Milano\PycharmProjects\FutileStudio\SolutionsForLanguages_2\venv\lib\site-packages\django\utils\encoding.py" in force_text 94. s = six.text_type(bytes(s), encoding, errors) Exception Type: UnicodeEncodeError at /admin/language_tests/languagequiz/7/ Exception Value: 'ascii' codec can't encode character u'\ufeff' in position 8: ordinal not in range(128) </code></pre>
-1
2016-07-24T21:19:03Z
38,556,973
<p>The following letters are really common in French: 'é', 'è', 'ç', 'à' and would probably break your code. </p> <blockquote> <p>Do you know what should I do?</p> </blockquote> <p>Write a test for it reproducing the issue. Once you've written it, you can make experiments a lot faster (use inmemory files); add problematic characters in all cells in your test CSV; make sure the problem won't occur again, etc.</p> <p>And fix it, probably by using <code>unicode(...)</code>. For example:</p> <pre><code>text=unicode(q['question']) </code></pre>
-3
2016-07-24T21:26:45Z
[ "python", "django", "encoding", "django-admin" ]
UnicodeEncodeError at /admin/... - Django admin
38,556,904
<p>I'm facing an encoding problem in <code>Django-admin</code>. I have a model, which represents a language quiz which consists of questions and answers (both are models) inlined to <code>Quiz</code> model.</p> <p>I've created a simple <code>csv</code> import. In <code>Quiz</code> model, there is a file field. When admin is creating a new <code>Quiz</code>, they upload a csv file which calls a signal which parse csv and creates questions and answers for this quiz. </p> <p>There is no problem with english, but I tried to import French quiz and it raises error.</p> <pre><code>Exception Value: 'ascii' codec can't encode character u'\ufeff' in position 0: ordinal not in range(128) </code></pre> <p>Import signal is very simple:</p> <pre><code>def parse_csv(csv): questions = [] for line in csv: line = line.strip('\r\n').strip('\n') d = {} items = line.split(';;') def parse_csv(csv): questions = [] i=0 for line in csv: i+=1 print i line = line.strip('\r\n').strip('\n') d = {} items = line.split(';;') question = items[0] d['question'] = question for item in (x.strip() for x in items[1:]): if '|' in item: d['answer'] = item else: if 'choices' in d.keys(): d['choices'].append(item) else: d['choices'] = [item] if 'answer' not in d.keys(): continue questions.append(d) return questions @receiver(post_save,sender=LanguageQuiz) def quiz_import_csv(sender,instance,created,**kwargs): if created: if instance.import_csv: questions = parse_csv(instance.import_csv.readlines()) for q in questions: question = Question(text=q['question']) question.save() for ch in q['choices']: choice = Choice(text=ch,correct=False) choice.save() question.choices.add(choice) answer = Choice(text=q['answer'].strip('|'),correct=True) answer.save() question.choices.add(answer) question.save() instance.questions.add(question) instance.save() </code></pre> <p>Do you know what should I do?</p> <p>EDIT:</p> <p><strong>TRACEBACK:</strong></p> <pre><code>Environment: Request Method: GET Request URL: http://127.0.0.1:8000/admin/language_tests/languagequiz/7/ Django Version: 1.8.12 Python Version: 2.7.10 Installed Applications: ('django.contrib.auth', 'SolutionsForLanguagesApp', 'django.contrib.admin', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'crispy_forms', 'super_inlines', 'django_tables2', 'language_tests', 'smart_selects', 'django_extensions', 'constance', 'constance.backends.database', 'nested_inline') Installed Middleware: ('django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.middleware.locale.LocaleMiddleware') Template error: In template C:\Users\Milano\PycharmProjects\FutileStudio\SolutionsForLanguages_2\venv\lib\site-packages\nested_inline\templates\admin\edit_inline\stacked-nested.html, error at line 9 ascii 1 : {% load i18n admin_static %} 2 : &lt;div class="inline-group{% if recursive_formset %} {{ recursive_formset.formset.prefix|default:"Root" }}-nested-inline {% if prev_prefix %} {{ prev_prefix }}-{{ loopCounter }}-nested-inline{% endif %} nested-inline{% endif %}" id="{{ inline_admin_formset.formset.prefix }}-group"&gt; 3 : {% with recursive_formset=inline_admin_formset stacked_template='admin/edit_inline/stacked-nested.html' tabular_template='admin/edit_inline/tabular-nested.html'%} 4 : &lt;h2&gt;{{ recursive_formset.opts.verbose_name_plural|title }}&lt;/h2&gt; 5 : {{ recursive_formset.formset.management_form }} 6 : {{ recursive_formset.formset.non_form_errors }} 7 : 8 : {% for inline_admin_form in recursive_formset %}&lt;div class="inline-related{% if forloop.last %} empty-form last-related{% endif %}" id="{{ recursive_formset.formset.prefix }}-{% if not forloop.last %}{{ forloop.counter0 }}{% else %}empty{% endif %}"&gt; 9 : &lt;h3&gt;&lt;b&gt;{{ recursive_formset.opts.verbose_name|title }}:&lt;/b&gt;&amp;nbsp;&lt;span class="inline_label"&gt;{% if inline_admin_form.original %} {{ inline_admin_form.original }} {% else %}#{{ forloop.counter }}{% endif %}&lt;/span&gt; 10 : {% if inline_admin_form.show_url %}&lt;a href="../../../r/{{ inline_admin_form.original_content_type_id }}/{{ inline_admin_form.original.id }}/"&gt;{% trans "View on site" %}&lt;/a&gt;{% endif %} 11 : {% if recursive_formset.formset.can_delete and inline_admin_form.original %}&lt;span class="delete"&gt;{{ inline_admin_form.deletion_field.field }} {{ inline_admin_form.deletion_field.label_tag }}&lt;/span&gt;{% endif %} 12 : &lt;/h3&gt; 13 : {% if inline_admin_form.form.non_field_errors %}{{ inline_admin_form.form.non_field_errors }}{% endif %} 14 : {% for fieldset in inline_admin_form %} 15 : {% include "admin/includes/fieldset.html" %} 16 : {% endfor %} 17 : {% if inline_admin_form.pk_field %}{{ inline_admin_form.pk_field.field }}{% endif %} 18 : {{ inline_admin_form.fk_field.field }} 19 : {% if inline_admin_form.form.nested_formsets %} Traceback: File "C:\Users\Milano\PycharmProjects\FutileStudio\SolutionsForLanguages_2\venv\lib\site-packages\django\core\handlers\base.py" in get_response 164. response = response.render() File "C:\Users\Milano\PycharmProjects\FutileStudio\SolutionsForLanguages_2\venv\lib\site-packages\django\template\response.py" in render 158. self.content = self.rendered_content File "C:\Users\Milano\PycharmProjects\FutileStudio\SolutionsForLanguages_2\venv\lib\site-packages\django\template\response.py" in rendered_content 135. content = template.render(context, self._request) File "C:\Users\Milano\PycharmProjects\FutileStudio\SolutionsForLanguages_2\venv\lib\site-packages\django\template\backends\django.py" in render 74. return self.template.render(context) File "C:\Users\Milano\PycharmProjects\FutileStudio\SolutionsForLanguages_2\venv\lib\site-packages\django\template\base.py" in render 210. return self._render(context) File "C:\Users\Milano\PycharmProjects\FutileStudio\SolutionsForLanguages_2\venv\lib\site-packages\django\template\base.py" in _render 202. return self.nodelist.render(context) File "C:\Users\Milano\PycharmProjects\FutileStudio\SolutionsForLanguages_2\venv\lib\site-packages\django\template\base.py" in render 905. bit = self.render_node(node, context) File "C:\Users\Milano\PycharmProjects\FutileStudio\SolutionsForLanguages_2\venv\lib\site-packages\django\template\debug.py" in render_node 79. return node.render(context) File "C:\Users\Milano\PycharmProjects\FutileStudio\SolutionsForLanguages_2\venv\lib\site-packages\django\template\loader_tags.py" in render 135. return compiled_parent._render(context) File "C:\Users\Milano\PycharmProjects\FutileStudio\SolutionsForLanguages_2\venv\lib\site-packages\django\template\base.py" in _render 202. return self.nodelist.render(context) File "C:\Users\Milano\PycharmProjects\FutileStudio\SolutionsForLanguages_2\venv\lib\site-packages\django\template\base.py" in render 905. bit = self.render_node(node, context) File "C:\Users\Milano\PycharmProjects\FutileStudio\SolutionsForLanguages_2\venv\lib\site-packages\django\template\debug.py" in render_node 79. return node.render(context) File "C:\Users\Milano\PycharmProjects\FutileStudio\SolutionsForLanguages_2\venv\lib\site-packages\django\template\loader_tags.py" in render 135. return compiled_parent._render(context) File "C:\Users\Milano\PycharmProjects\FutileStudio\SolutionsForLanguages_2\venv\lib\site-packages\django\template\base.py" in _render 202. return self.nodelist.render(context) File "C:\Users\Milano\PycharmProjects\FutileStudio\SolutionsForLanguages_2\venv\lib\site-packages\django\template\base.py" in render 905. bit = self.render_node(node, context) File "C:\Users\Milano\PycharmProjects\FutileStudio\SolutionsForLanguages_2\venv\lib\site-packages\django\template\debug.py" in render_node 79. return node.render(context) File "C:\Users\Milano\PycharmProjects\FutileStudio\SolutionsForLanguages_2\venv\lib\site-packages\django\template\loader_tags.py" in render 65. result = block.nodelist.render(context) File "C:\Users\Milano\PycharmProjects\FutileStudio\SolutionsForLanguages_2\venv\lib\site-packages\django\template\base.py" in render 905. bit = self.render_node(node, context) File "C:\Users\Milano\PycharmProjects\FutileStudio\SolutionsForLanguages_2\venv\lib\site-packages\django\template\debug.py" in render_node 79. return node.render(context) File "C:\Users\Milano\PycharmProjects\FutileStudio\SolutionsForLanguages_2\venv\lib\site-packages\django\template\loader_tags.py" in render 65. result = block.nodelist.render(context) File "C:\Users\Milano\PycharmProjects\FutileStudio\SolutionsForLanguages_2\venv\lib\site-packages\django\template\base.py" in render 905. bit = self.render_node(node, context) File "C:\Users\Milano\PycharmProjects\FutileStudio\SolutionsForLanguages_2\venv\lib\site-packages\django\template\debug.py" in render_node 79. return node.render(context) File "C:\Users\Milano\PycharmProjects\FutileStudio\SolutionsForLanguages_2\venv\lib\site-packages\django\template\defaulttags.py" in render 217. nodelist.append(node.render(context)) File "C:\Users\Milano\PycharmProjects\FutileStudio\SolutionsForLanguages_2\venv\lib\site-packages\django\template\loader_tags.py" in render 159. return template.render(context) File "C:\Users\Milano\PycharmProjects\FutileStudio\SolutionsForLanguages_2\venv\lib\site-packages\django\template\base.py" in render 212. return self._render(context) File "C:\Users\Milano\PycharmProjects\FutileStudio\SolutionsForLanguages_2\venv\lib\site-packages\django\template\base.py" in _render 202. return self.nodelist.render(context) File "C:\Users\Milano\PycharmProjects\FutileStudio\SolutionsForLanguages_2\venv\lib\site-packages\django\template\base.py" in render 905. bit = self.render_node(node, context) File "C:\Users\Milano\PycharmProjects\FutileStudio\SolutionsForLanguages_2\venv\lib\site-packages\django\template\debug.py" in render_node 79. return node.render(context) File "C:\Users\Milano\PycharmProjects\FutileStudio\SolutionsForLanguages_2\venv\lib\site-packages\django\template\defaulttags.py" in render 576. return self.nodelist.render(context) File "C:\Users\Milano\PycharmProjects\FutileStudio\SolutionsForLanguages_2\venv\lib\site-packages\django\template\base.py" in render 905. bit = self.render_node(node, context) File "C:\Users\Milano\PycharmProjects\FutileStudio\SolutionsForLanguages_2\venv\lib\site-packages\django\template\debug.py" in render_node 79. return node.render(context) File "C:\Users\Milano\PycharmProjects\FutileStudio\SolutionsForLanguages_2\venv\lib\site-packages\django\template\defaulttags.py" in render 217. nodelist.append(node.render(context)) File "C:\Users\Milano\PycharmProjects\FutileStudio\SolutionsForLanguages_2\venv\lib\site-packages\django\template\defaulttags.py" in render 329. return nodelist.render(context) File "C:\Users\Milano\PycharmProjects\FutileStudio\SolutionsForLanguages_2\venv\lib\site-packages\django\template\base.py" in render 905. bit = self.render_node(node, context) File "C:\Users\Milano\PycharmProjects\FutileStudio\SolutionsForLanguages_2\venv\lib\site-packages\django\template\debug.py" in render_node 79. return node.render(context) File "C:\Users\Milano\PycharmProjects\FutileStudio\SolutionsForLanguages_2\venv\lib\site-packages\django\template\defaulttags.py" in render 217. nodelist.append(node.render(context)) File "C:\Users\Milano\PycharmProjects\FutileStudio\SolutionsForLanguages_2\venv\lib\site-packages\django\template\defaulttags.py" in render 329. return nodelist.render(context) File "C:\Users\Milano\PycharmProjects\FutileStudio\SolutionsForLanguages_2\venv\lib\site-packages\django\template\base.py" in render 905. bit = self.render_node(node, context) File "C:\Users\Milano\PycharmProjects\FutileStudio\SolutionsForLanguages_2\venv\lib\site-packages\django\template\debug.py" in render_node 79. return node.render(context) File "C:\Users\Milano\PycharmProjects\FutileStudio\SolutionsForLanguages_2\venv\lib\site-packages\django\template\loader_tags.py" in render 159. return template.render(context) File "C:\Users\Milano\PycharmProjects\FutileStudio\SolutionsForLanguages_2\venv\lib\site-packages\django\template\base.py" in render 212. return self._render(context) File "C:\Users\Milano\PycharmProjects\FutileStudio\SolutionsForLanguages_2\venv\lib\site-packages\django\template\base.py" in _render 202. return self.nodelist.render(context) File "C:\Users\Milano\PycharmProjects\FutileStudio\SolutionsForLanguages_2\venv\lib\site-packages\django\template\base.py" in render 905. bit = self.render_node(node, context) File "C:\Users\Milano\PycharmProjects\FutileStudio\SolutionsForLanguages_2\venv\lib\site-packages\django\template\debug.py" in render_node 79. return node.render(context) File "C:\Users\Milano\PycharmProjects\FutileStudio\SolutionsForLanguages_2\venv\lib\site-packages\django\template\defaulttags.py" in render 576. return self.nodelist.render(context) File "C:\Users\Milano\PycharmProjects\FutileStudio\SolutionsForLanguages_2\venv\lib\site-packages\django\template\base.py" in render 905. bit = self.render_node(node, context) File "C:\Users\Milano\PycharmProjects\FutileStudio\SolutionsForLanguages_2\venv\lib\site-packages\django\template\debug.py" in render_node 79. return node.render(context) File "C:\Users\Milano\PycharmProjects\FutileStudio\SolutionsForLanguages_2\venv\lib\site-packages\django\template\defaulttags.py" in render 217. nodelist.append(node.render(context)) File "C:\Users\Milano\PycharmProjects\FutileStudio\SolutionsForLanguages_2\venv\lib\site-packages\django\template\defaulttags.py" in render 329. return nodelist.render(context) File "C:\Users\Milano\PycharmProjects\FutileStudio\SolutionsForLanguages_2\venv\lib\site-packages\django\template\base.py" in render 905. bit = self.render_node(node, context) File "C:\Users\Milano\PycharmProjects\FutileStudio\SolutionsForLanguages_2\venv\lib\site-packages\django\template\debug.py" in render_node 79. return node.render(context) File "C:\Users\Milano\PycharmProjects\FutileStudio\SolutionsForLanguages_2\venv\lib\site-packages\django\template\debug.py" in render 92. output = force_text(output) File "C:\Users\Milano\PycharmProjects\FutileStudio\SolutionsForLanguages_2\venv\lib\site-packages\django\utils\encoding.py" in force_text 94. s = six.text_type(bytes(s), encoding, errors) Exception Type: UnicodeEncodeError at /admin/language_tests/languagequiz/7/ Exception Value: 'ascii' codec can't encode character u'\ufeff' in position 8: ordinal not in range(128) </code></pre>
-1
2016-07-24T21:19:03Z
38,556,976
<p>Well, I can't tell where you're receiving the error. Please post a line where you receive the error.</p> <p>This is a very common error when parsing international text. It's solved with one of the following two methods:</p> <h3>Encoding with UTF8</h3> <pre><code>try: print (myThing) except UnicodeEncodeError: print (myThing).encode('UTF8') </code></pre> <h3>Reading the file as a string</h3> <p>You can also try the following code, <a href="http://dacrook.com/decoding-woes-solved-python/" rel="nofollow">courtesy of David Crook</a>:</p> <pre><code>dataPath = "somepath.csv" # or other type of file fil = open(dataPath) txt = fil.readlines() txt = ''.join(txt) works = pd.read_csv(StringIO(txt), index_col = 0) doesntWork = pd.read_csv(dataPath, index_col = 0) </code></pre>
0
2016-07-24T21:26:58Z
[ "python", "django", "encoding", "django-admin" ]
Python 3 : How to print output to both Console and File
38,557,096
<p>So basically I'm still learning Python programming and currently playing around with some code I found on github.</p> <p>Basically, the code works fine when execute, it print the output to terminal/console. However I would like to save the output to file and therefore followed few tutorials and successfully saved the output to file but the output didn't display in the terminal.</p> <p>My question is, how to execute this python script to display the output on the terminal and at the same time write the output to .txt file?</p> <p>Below are the python code I'm working on:</p> <pre><code>import os import warnings import argparse import sys import unicodedata from PIL import Image COLORS = [ [0, (255,255,255), '97', 'white'], [1, (0,0,0), '30', 'black'], [2, (0,0,127), '34', 'blue'], [3, (0,147,0), '32', 'green'], [4, (255,0,0), '91', 'light red'], [5, (127,0,0), '31', 'brown'], [6, (156,0,156), '35', 'purple'], [7, (252,127,0), '33', 'orange'], [8, (255,255,0), '93', 'yellow'], [9, (0,252,0), '92', 'light green'], [10, (0,147,147), '36', 'cyan'], [11, (0,255,255), '96', 'light cyan'], [12, (0,0,252), '94', 'light blue'], [13, (255,0,255), '95', 'pink'], [14, (127,127,127), '90', 'grey'], [15, (210,210,210), '37', 'light grey'] ] def convert(img, doColor=True, renderIRC=True, cutoff=50, size=1.0, invert=False, alphaColor=(0,0,0)): i = Image.open(img) WIDTH = int(90*size) HIGHT = int(40*size) # Resize the image to fix bounds s = i.size if s[0]==0 or s[1]==0 or (float(s[0])/float(WIDTH))==0 or (float(s[1])/float(HIGHT))==0: return [] ns = (WIDTH,int(s[1]/(float(s[0])/float(WIDTH)))) if ns[1]&gt;HIGHT: ns = (int(s[0]/(float(s[1])/float(HIGHT))),HIGHT) i2 = i.resize(ns) bimg = [] for r in range(0,i2.size[1],4): line = u'' lastCol = -1 for c in range(0,i2.size[0],2): val = 0 i = 0 cavg = [0,0,0] pc = 0 for ci in range(0,4): for ri in range(0,3 if ci&lt;2 else 1): # Convert back for the last two pixels if ci&gt;=2: ci-=2 ri=3 # Retrieve the pixel data if c+ci&lt;i2.size[0] and r+ri&lt;i2.size[1]: p = i2.getpixel((c+ci,r+ri)) alpha = p[3] if len(p)&gt;3 else 1 if invert and alpha&gt;0: p = map(lambda x: 255-x, p) elif alpha==0: p = alphaColor else: p = (0,0,0) # Check the cutoff value and add to unicode value if it passes luma = (0.2126*float(p[0]) + 0.7152*float(p[1]) + 0.0722*float(p[2])) pv = sum(p[:3]) if luma &gt; cutoff: val+=1&lt;&lt;i cavg = map(sum,zip(cavg,p)) pc+=1 i += 1 if doColor and pc&gt;0: # Get the average of the 8 pixels cavg = map(lambda x:x/pc,cavg) # Find the closest color with geometric distances colorDist = lambda c:sum(map(lambda x:(x[0]-x[1])**2,zip(cavg,c[1]))) closest = min(COLORS, key=colorDist) if closest[0]==1 or lastCol==closest[0]: # Check if we need to reset the color code if lastCol!=closest[0] and lastCol!=-1: line+='\x03' if renderIRC else '\033[0m' line += unichr(0x2800+val) else: # Add the color escape to the first character in a set of colors if renderIRC: line += ('\x03%u'%closest[0])+unichr(0x2800+val) else: line += ('\033[%sm'%closest[2])+unichr(0x2800+val) lastCol = closest[0] else: # Add the offset from the base braille character line += unichr(0x2800+val) bimg.append(line) return bimg if __name__=='__main__': ap = argparse.ArgumentParser() ap.add_argument('file', help='The image file to render') ap.add_argument('-c',type=int,default=100, help='The luma cutoff amount, from 0 to 255. Default 50') ap.add_argument('-s', type=float, default=1.0, help='Size modifier. Default 1.0x') ap.add_argument('--nocolor', action="store_true", default=False, help='Don\'t use color') ap.add_argument('--irc', action="store_true", default=False, help='Use IRC color escapes') ap.add_argument('--invert', action="store_true", default=False, help='Invert the image colors') ap.add_argument('--background', default='black', help='The color to display for full alpha transparency') ap.add_argument('-f', help="Write to text file") args = ap.parse_args() alphaColor = (0,0,0) for c in COLORS: if c[3].lower() == args.background: alphaColor = c[1] break for u in convert(args.file,doColor=not args.nocolor, renderIRC=args.irc, cutoff=args.c, size=args.s, invert=args.invert, alphaColor=alphaColor): #sys.stdout = open('I put my path here to .txt file','a') print u.encode('utf-8') #sys.stdout.close() </code></pre> <p>Look at the very few last line statement to print the output.</p> <p>PS: This is not my code, I'm just trying learn some ASCII art through python. PSS: I'm using Windows with Cygwin64 Terminal to execute the code.</p> <p>With Regards.</p>
-3
2016-07-24T21:40:45Z
38,560,894
<p>Instead of setting <code>stdout</code> to be your file, keep it to be the default and use file I/O operations to write to the file while printing.</p> <pre><code># open the file f = open('I put my path here to .txt file','a') for u in convert(args.file,doColor=not args.nocolor, renderIRC=args.irc, cutoff=args.c, size=args.s, invert=args.invert, alphaColor=alphaColor): toWrite = u.encode('utf-8') # write to the file f.write(toWrite) print toWrite # close the file f.close() </code></pre>
1
2016-07-25T06:19:43Z
[ "python", "windows", "file", "python-3.x", "terminal" ]
Keras - Objective function for number in range [0-100]
38,557,107
<p>Lets say I've ground truth (output) of a number in range [0-100]. Is it possible to learn to predict a number that minimize the delta from the original number (gt) according the input ?</p> <p>The objective types of Keras are here <a href="http://keras.io/objectives/" rel="nofollow">http://keras.io/objectives/</a></p>
1
2016-07-24T21:41:40Z
38,557,668
<p>I think your best bet would be to use mean squared error (<code>loss='mse'</code>), which penalizes predictions based on the square of their difference from the ground truth. You would also want to use linear activations (the default) for the last layer. </p> <p>If you're especially concerned about keeping the predictions within the range [0, 100], you could create a modified objective function that penalizes predictions outside [0, 100] even more than quadratically, but that's probably not necessary and you could instead just clip the predictions using <code>np.clip(predictions, 0, 100)</code>.</p>
1
2016-07-24T22:57:58Z
[ "python", "neural-network", "keras" ]
Regex match all non letters excluding diacritics (python)
38,557,116
<p>I have found this excellent guide: <a href="http://www.regular-expressions.info/unicode.html#category" rel="nofollow">http://www.regular-expressions.info/unicode.html#category</a> that gives some hints on how to match <strong>non</strong> letters with the following regex:</p> <pre><code>\P{L} </code></pre> <p>But this regex will consider non letters also <code>à</code> encoded as U+0061 U+0300 (if I understood well). For example using <a href="https://pypi.python.org/pypi/regex" rel="nofollow">regex</a> module in python the following snippet:</p> <pre><code>all_letter_doc = regex.sub(r'\P{L}', ' ', doc) </code></pre> <p>will transform <code>purè</code> in <code>pur</code></p> <p>In the guide is provided how to match all letters with the following:</p> <pre><code>\p{L}\p{M}*+ </code></pre> <p>and in practice I need the negation of that but I do not know how to obtain it. </p>
2
2016-07-24T21:42:40Z
38,557,197
<p>Since you are using Python 2.x, your <code>r'\P{L}'</code> is a byte string, while the input you have is Unicode. You need to make your pattern a Unicode string. See the <a href="https://pypi.python.org/pypi/regex" rel="nofollow">PyPi <code>regex</code> reference</a>:</p> <blockquote> <p>If neither the <code>ASCII</code>, <code>LOCALE</code> nor <code>UNICODE</code> flag is specified, it will default to <code>UNICODE</code> if the regex pattern is a Unicode string and <code>ASCII</code> if it’s a bytestring.</p> </blockquote> <p>Thus, you need to use <code>ur'\P{L}'</code> and a <code>u' '</code> replacement pattern. </p> <p>In case you want to match 1+ chars other than letters and diacritics, you will need <code>ur'[^\p{L}\p{M}]+'</code> regex.</p>
4
2016-07-24T21:52:32Z
[ "python", "regex", "python-2.7", "unicode", "regex-negation" ]
is there any way to directly read Pandas dataframe as a file handler?
38,557,139
<p>I used pandas to load data from a <code>dataSource.cvs</code> file:</p> <p><code>DF = pd.read_csv('dataSoruce.csv')</code></p> <p>In pandas I can clean the data, like filling missing values with 0. </p> <p>Next I use <code>DF.to_csv('temp.csv', sep=',')</code> to write the <code>DF</code> as a temporary cvs file, and then use the python file handler to open the file again</p> <pre><code> hd = open('temp.csv') for line in hd: line = line.split(',')..... </code></pre> <p>to parse the data and associate more information from other data tables. This works. However, if I directly doing</p> <pre><code> hd = DF </code></pre> <p>Then it shows the error message as</p> <pre><code> IndexError: list index out of range </code></pre> <p>Are there any ways to skip saving to cvs and reading csv? i.e. directly open the <code>pandas dataFrame</code> as a file handler?</p> <p>A ton of thanks!</p>
0
2016-07-24T21:45:14Z
38,573,144
<p>suppose <code>DF</code> is a dataframe in pandas, doing the following:</p> <pre><code> for x in DF.values: x = tuple(x) </code></pre> <p>then <code>x</code> will be <code>(x1, x2, x3...)</code> format. </p>
0
2016-07-25T16:35:08Z
[ "python", "pandas", "dataframe", "filehandler" ]
How to automate dictionary creation in Python
38,557,180
<p>I am trying to write a python code that solves a Sudoku puzzle. My code starts by making a list of each row/column combination, or the coordinates of each box. Next, I want to find a way to, for each box, reference its location. This is my current code:</p> <pre><code>boxes = [] for i in range(1, 10): for x in range(1,10): boxes = boxes + ['r'+str(i)+'c'+str(x)] for box in boxes: </code></pre> <p>Next, I was going to create a dictionary for each one, but I would want each to be named by the list item. The dictionaries would be, for example, r1c1 = {'row': '1', 'Column': 1}.</p> <p>What is the best way to separate and store this information?</p>
0
2016-07-24T21:50:46Z
38,557,244
<p>You don't need to create all those dictionaries. You already have your coordinates, just don't lock them up in strings:</p> <pre><code>boxes = [] for i in range(1, 10): for x in range(1,10): boxes.append((i, x)) </code></pre> <p>would create a list of <code>(row, column)</code> tuples instead, and you then wouldn't have to map them back.</p> <p>Even if you needed to associate strings with data, you could do so in a <em>nested</em> dictionary:</p> <pre><code>coordinates = { 'r1c1': {'row': 1, 'column': 1}, # ... } </code></pre> <p>but you could also parse that string and extract the numbers after <code>r</code> and <code>c</code> to produce the row and column numbers again.</p> <p>In fact, I wrote a Sudoku checker on the same principles once; in the following code <code>block_indices</code>, <code>per9()</code> and <code>zip(*per9(s))</code> produce indices for each block, row or column of a puzzle, letting you verify that you have 9 unique values in each. The only difference is that instead of a matrix, I used <em>one long list</em> to represent a puzzle, all elements from row to row included in sequence:</p> <pre><code>from itertools import product block_indices = [[x + y + s for s in (0, 1, 2, 9, 10, 11, 18, 19, 20)] for x, y in product(range(0, 81, 27), range(0, 9, 3))] def per9(iterable): # group iterable in chunks of 9 return zip(*([iter(iterable)] * 9)) def is_valid_sudoku(s): return ( # rows all(len(set(r)) == 9 for r in per9(s)) and # columns all(len(set(c)) == 9 for c in zip(*per9(s))) and # blocks all(len(set(s[i] for i in ix)) == 9 for ix in block_indices) ) </code></pre> <p>So row 1, column 4 is 1 * 9 + 4 = index 13 in a flat list.</p>
1
2016-07-24T21:59:09Z
[ "python", "dictionary" ]
How to automate dictionary creation in Python
38,557,180
<p>I am trying to write a python code that solves a Sudoku puzzle. My code starts by making a list of each row/column combination, or the coordinates of each box. Next, I want to find a way to, for each box, reference its location. This is my current code:</p> <pre><code>boxes = [] for i in range(1, 10): for x in range(1,10): boxes = boxes + ['r'+str(i)+'c'+str(x)] for box in boxes: </code></pre> <p>Next, I was going to create a dictionary for each one, but I would want each to be named by the list item. The dictionaries would be, for example, r1c1 = {'row': '1', 'Column': 1}.</p> <p>What is the best way to separate and store this information?</p>
0
2016-07-24T21:50:46Z
38,557,598
<p>While Martijn's answer is probably better from a "what you should do" perspective, for completeness, you could build that structure pretty easily using <a href="http://www.python.org/dev/peps/pep-0274/" rel="nofollow">dictionary comprehension</a>:</p> <p>The below annotated code will output your desire data structure:</p> <pre><code>boxes = { "r%sc%s"%(i,j): # build the keys in the form "r1c2" {'row':i,"column":j} # build the dictionary of values - {'row':1, 'column': 2} for i in range(1,10) # first level of loop for j in range(1,10) # second level of loop } print boxes </code></pre> <p>This will output in your desired format:</p> <pre><code>{ 'r1c1': { 'column': 1, 'row': 1}, 'r1c2': { 'column': 2, 'row': 1}, 'r1c3': { 'column': 3, 'row': 1}, 'r1c4': { 'column': 4, 'row': 1}, .... } </code></pre>
0
2016-07-24T22:48:16Z
[ "python", "dictionary" ]
unable to install scrapy-deltafetch
38,557,241
<p>I am trying to install scrapy-deltafetch on ubuntu 14 using pip (v8.1.2 on python 2.7). When I run (sudo) pip install scrapy-deltafetch, I get the following error:</p> <p><strong>Update:</strong></p> <pre><code>Complete output from command python setup.py egg_info: Can't find a local Berkeley DB installation. Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-build-TVr3UZ/bsddb3/ </code></pre> <p>Any thoughts on how to resolve this? </p> <p>I have already ran the following:</p> <pre><code>sudo python ez_setup.py pip install --upgrade setuptools </code></pre> <p>as well as</p> <pre><code>sudo apt-get install python-setuptools </code></pre> <p>I do have both python3 and python 2.7 on the computer. </p> <p>I have tried installing bsdb3 but that does not work either. I will look into setting up berkeley db correctly and update here accordingly</p> <p><strong>Update</strong>: Installing berkeley DB did not solve the issue.</p>
0
2016-07-24T21:58:39Z
38,564,458
<p>scrapy-deltafetch requires <code>bsddb3</code>.</p> <p><code>bsddb3</code> itself, on Ubuntu Trusty, <a href="http://packages.ubuntu.com/en/trusty/python-bsddb3" rel="nofollow">depends on <code>libdb5.3</code></a>.</p> <p>You can either install <code>python-bsddb3</code> with <code>apt-get</code>, or only <code>apt-get install libdb5.3</code>. <code>pip install scrapy-deltafetch</code> should work after that.</p>
1
2016-07-25T09:45:45Z
[ "python", "python-2.7", "scrapy" ]
unable to install scrapy-deltafetch
38,557,241
<p>I am trying to install scrapy-deltafetch on ubuntu 14 using pip (v8.1.2 on python 2.7). When I run (sudo) pip install scrapy-deltafetch, I get the following error:</p> <p><strong>Update:</strong></p> <pre><code>Complete output from command python setup.py egg_info: Can't find a local Berkeley DB installation. Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-build-TVr3UZ/bsddb3/ </code></pre> <p>Any thoughts on how to resolve this? </p> <p>I have already ran the following:</p> <pre><code>sudo python ez_setup.py pip install --upgrade setuptools </code></pre> <p>as well as</p> <pre><code>sudo apt-get install python-setuptools </code></pre> <p>I do have both python3 and python 2.7 on the computer. </p> <p>I have tried installing bsdb3 but that does not work either. I will look into setting up berkeley db correctly and update here accordingly</p> <p><strong>Update</strong>: Installing berkeley DB did not solve the issue.</p>
0
2016-07-24T21:58:39Z
40,067,356
<p>Install libbd-dev first,</p> <pre><code>sudo apt-get install libdb-dev </code></pre> <p>then install deltafetch,</p> <pre><code># for python2 sudo -H pip install scrapy-deltafetch # for python3 sudo -H pip3 install scrapy-deltafetch </code></pre>
1
2016-10-16T06:03:48Z
[ "python", "python-2.7", "scrapy" ]
How can I host my Bitcoin API on the 21 market with a Virtual IP?
38,557,245
<p>I'm trying to make my simple Pokemon API available on something other than my localhost. The API has two files, client.py and server.py. I ran the <code>21 market join</code> command and got a virtual IP. (10.244.121.0). </p> <p>I tried modifying my script so that instead of the client.py requesting "<a href="http://localhost:5000/" rel="nofollow">http://localhost:5000/</a>" it would request "<a href="http://10.244.121.0:5000/" rel="nofollow">http://10.244.121.0:5000/</a>", but when I run the client.py I get an error when requesting that url. I'm pretty new to Python so I don't know what I need to do in order to make this API available to anyone who requests it on the <code>10.244.121.0</code> address. </p> <p>client.py:</p> <pre><code>... # server address server_url = 'http://10.244.121.0/' def name(): id = input("Please enter a Pokemon ID: ") sel_url = server_url + 'name?id={0}' answer = requests.get(url=sel_url.format(id)) print(answer.text) if __name__ == '__main__': name() </code></pre> <p>server.py:</p> <pre><code> ... @app.route('/name') @payment.required(1) def answer_question(): # extract answer from client request id = request.args.get('id') url = 'http://pokeapi.co/api/v2/pokemon/' + id response = requests.get(url) pokemonData = json.loads(response.text) pokemonName = pokemonData['name'] print(pokemonName) return pokemonName if __name__ == '__main__': app.run(host='0.0.0.0') </code></pre> <p>Here is the error I get when replacing the host in the <code>app.run</code> function from <code>0.0.0.0</code> to the virtual IP:</p> <pre><code> requests.exceptions.ConnectionError: HTTPConnectionPool(host='10.244.121.0', port=80): Max retries exceeded with url: /name?id=1 (Caused by NewConnectionError('&lt;requests.packages.urllib3.connection.HTTPConnection object at 0x7f98d6b6e470&gt;: Failed to establish a new connection: [Errno 111] Connection refused',)) </code></pre> <p>Any help would be appreciated!</p> <p>Github repo: <a href="https://github.com/LAMike310/pokedex" rel="nofollow">https://github.com/LAMike310/pokedex</a></p>
0
2016-07-24T21:59:12Z
38,557,348
<p>Instead of calling <code>python client.py</code> directly, I can now use <code>21 buy http://10.244.121.0:5000/name?id=1</code> to call my API remotely.</p>
1
2016-07-24T22:12:28Z
[ "python", "ubuntu-14.04", "bitcoin", "virtual-ip-address" ]
Tokenization of text file in python 3.5
38,557,258
<p>I'm trying to do tokenization of words in a text file using python 3.5 but have a couple of errors. Here is the code:</p> <pre><code>import re f = open('/Users/Half_Pint_Boy/Desktop/sentenses.txt', 'r') a=0 c=0 for line in f: b=re.split('[^a-z]', line.lower()) a+=len(filter(None, b)) c = c + 1 d = d + b print (a) print (c) </code></pre> <p>My questions:</p> <ol> <li><p>Construction <code>a+=len(filter(None, b))</code> works fine in python 2.7 but in 3.5 it cause an error of type that object of:</p> <blockquote> <p>type 'filter' has no <code>len()</code></p> </blockquote> <p>How can it be solved using python 3.5?</p></li> <li><p>When I'm doing tokenization, my code counts also empty spaces as word-tokens. How can I delete them?</p></li> </ol> <p>Thanks!</p>
0
2016-07-24T22:01:00Z
38,557,288
<ol> <li><p>You need an explicit cast to list in Python 3.5 to get the length of your sequence, as <code>filter</code> returns an <em>iterator</em> object and not a list as with Python 2.7:</p> <pre><code>a += len(list(filter(None, b))) # ^^ </code></pre></li> <li><p>The empty spaces where returned from your <code>re.split</code>, e.g.:</p> <pre><code>&gt;&gt;&gt; line = 'sdksljd sdjsh 1213hjs sjdks' &gt;&gt;&gt; b=re.split('[^a-z]', line.lower()) &gt;&gt;&gt; b ['sdksljd', 'sdjsh', '', '', '', '', 'hjs', 'sjdks'] </code></pre></li> </ol> <hr> <p>You can remove them using a filter on <code>if</code> in a <em>list comprehension</em> on the results from your <code>re.split</code> like so:</p> <pre><code>b = [i for i in re.split('[^a-z]', line.lower()) if i] </code></pre> <p>The <code>if i</code> part in the list comp. returns <code>False</code> for an empty string because <code>bool('') is False</code>. So empty strings are cleared.</p> <hr> <p>The results from the list comprehension can also be achieved with <code>filter</code> (which you already used with <code>a</code>):</p> <pre><code>b = list(filter(None, re.split('[^a-z]', line.lower()))) # use the list comprehension if you don't like brackets </code></pre> <hr> <p>And finally, <code>a</code> can be computed after any of the two approaches as:</p> <pre><code>a += len(b) </code></pre>
1
2016-07-24T22:05:36Z
[ "python" ]
Use variables from one Screen on another in kivy
38,557,306
<p>I'm making an app with kivy, and in my kv file I have one screen called MainScreen which has two TextInput boxes. When I press a Button, the screen will change to LoggedInScreen. How do I pass the input from the TextInput boxes on MainScreen, to LoggedInScreen, so I can use them as positional arguments on a function I defined in main.py? This is what I've tried (relevant bits of code only):</p> <pre><code>&lt;LoggedInScreen&gt;: name: 'loggedin' FloatLayout: TextInput: #This is not working text: root.auth(MainScreen.ids.username.text, MainScreen.ids.password.txt) font_name: 'PCBius.ttf' background_color: (73/255,73/255,73/255,1) keyboard_mode: 'managed' readonly: True size: 405, self.height pos: 495,0 &lt;MainScreen&gt;: name:'main' FloatLayout: TextInput: id: username multiline: False size_hint: self.width/self.width/5, self.height/self.height/16 pos: 200,292 TextInput: id: password password: True multiline: False size_hint: self.width/self.width/5, self.height/self.height/16 pos: 200,232 </code></pre> <p>But it outputs an error saying that MainScreen is not defined.</p> <p>Thanks for any help!</p>
0
2016-07-24T22:08:03Z
38,557,440
<p>The easiest way would be defining a new method called <code>auth_success</code> in the screen manager, which is in charge of those two screens:</p> <pre><code>class MyScreenManager(ScreenManager): ... def auth_success(self, username, password): self.loggedin.username = username self.loggedin.password = password self.current = 'loggedin' </code></pre> <p>Now, when a user successfully authenticates in the main screen, call <code>self.parent.auth_success(self.ids.username.text, self.ids.username.password)</code>.</p>
0
2016-07-24T22:26:57Z
[ "python", "function", "class", "variables", "kivy" ]
Regex for this date format?
38,557,353
<p>I'm trying to find a regex that will match dates in the following format: <strong>3-Jul-16</strong> or <strong>30-Jun-16</strong></p> <p>I have tried this regex at first:</p> <pre><code>/[0-9]{1,}-[a-zA-Z]{3}-[0-9]{1,}/g </code></pre> <p>But it matches also dates like <strong>947-UfO-104</strong>, and this is not something I want.<br/> First, I got the month:</p> <pre><code>/[0-9]{1,}-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-[0-9]{1,}/g </code></pre> <p>Now, the year is fine, because it could be anything numerical.<br/> For the day part, I have tried:</p> <pre><code>/([1-9]|1[0-9]|2[0-9]|30|31)-(Jan|Feb.../g </code></pre> <p>Now, my problem is that when given something like that: <strong>73-Jul-2015</strong><br/> It matches: <strong>3-Jul-2015</strong></p> <p>I tried making sure that the date is followed by a non-digit char like that:</p> <pre><code>/[^0-9]{1,}([1-9]|1[0-9]|2[0-9]|30|31)-(Jan|Feb.../g </code></pre> <p>But then, when the date is at the beggining of the string, it didn't catch it (because it's not followed by <strong>any</strong> char).</p> <p>So my question is, is there a regex part that says <strong>"An non-numerical char or empty string"</strong>?</p>
-5
2016-07-24T22:13:21Z
38,557,434
<p>Split the task into 3 parts. First, a number in the range of 1-31 (<a href="http://www.regular-expressions.info/numericranges.html" rel="nofollow">tutorial</a>), then a list of possible values for the month, and then two numbers.</p> <pre><code>\b([1-9]|[12][0-9]|3[01])-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-(\d{2})\b </code></pre> <p><a href="https://regex101.com/r/aI3eO8/3" rel="nofollow">Regex101 Demo</a></p>
1
2016-07-24T22:26:12Z
[ "python", "regex", "parsing" ]
Sum of Two Integers without using "+" operator in python
38,557,464
<p>Need some help understanding python solutions of leetcode 371. "Sum of Two Integers". I found <a href="https://discuss.leetcode.com/topic/49900/python-solution/2" rel="nofollow">https://discuss.leetcode.com/topic/49900/python-solution/2</a> is the most voted python solution, but I am having problem understand it.</p> <ul> <li>How to understand the usage of "% MASK" and why "MASK = 0x100000000"?</li> <li>How to understand "~((a % MIN_INT) ^ MAX_INT)"?</li> <li>When sum beyond MAX_INT, the functions yells negative value (for example getSum(2147483647,2) = -2147483647), isn't that incorrect? </li> </ul> <hr> <pre><code>class Solution(object): def getSum(self, a, b): """ :type a: int :type b: int :rtype: int """ MAX_INT = 0x7FFFFFFF MIN_INT = 0x80000000 MASK = 0x100000000 while b: a, b = (a ^ b) % MASK, ((a &amp; b) &lt;&lt; 1) % MASK return a if a &lt;= MAX_INT else ~((a % MIN_INT) ^ MAX_INT) </code></pre>
1
2016-07-24T22:29:36Z
38,558,504
<p>Let's disregard the <code>MASK</code>, <code>MAX_INT</code> and <code>MIN_INT</code> for a second.</p> <p><strong>Why does this black magic bitwise stuff work?</strong></p> <p>The reason why the calculation works is because <code>(a ^ b)</code> is "summing" the bits of <code>a</code> and <code>b</code>. Recall that bitwise or is <code>1</code> when the bits differ, and <code>0</code> when the bits are the same. For example (where D is decimal and B is binary), 20D == 10100B, and 9D = 1001B:</p> <pre><code> 10100 1001 ----- 11101 </code></pre> <p>and 11101B == 29D.</p> <p>But, if you have a case with a carry, it doesn't work so well. For example, consider adding (bitwise or) 20D and 20D.</p> <pre><code>10100 10100 ----- 00000 </code></pre> <p>Oops. 20 + 20 certainly doesn't equal 0. Enter the <code>(a &amp; b) &lt;&lt; 1</code> term. This term represents the "carry" for each position. On the next iteration of the while loop, we add in the carry from the previous loop. So, if we go with the example we had before, we get:</p> <pre><code># First iteration (a is 20, b is 20) 10100 ^ 10100 == 00000 # makes a 0 (10100 &amp; 10100) &lt;&lt; 1 == 101000 # makes b 40 # Second iteration: 000000 ^ 101000 == 101000 # Makes a 40 (000000 &amp; 101000) &lt;&lt; 1 == 0000000 # Makes b 0 </code></pre> <p>Now <code>b</code> is 0, we are done, so return <code>a</code>. This algorithm works in general, not just for the specific cases I've outlined. Proof of correctness is left to the reader as an exercise ;)</p> <p><strong>What do the masks do?</strong></p> <p>All the masks are doing is ensuring that the value is an integer, because your code even has comments stating that <code>a</code>, <code>b</code>, and the return type are of type <code>int</code>. Thus, since the maximum possible <code>int</code> (32 bits) is 2147483647. So, if you add 2 to this value, like you did in your example, the <code>int</code> overflows and you get a negative value. You have to force this in Python, because it doesn't respect this <code>int</code> boundary that other strongly typed languages like Java and C++ have defined. Consider the following:</p> <pre><code>def get_sum(a, b): while b: a, b = (a ^ b), (a &amp; b) &lt;&lt; 1 return a </code></pre> <p>This is the version of <code>getSum</code> without the masks.</p> <pre><code>print get_sum(2147483647, 2) </code></pre> <p>outputs</p> <pre><code>2147483649 </code></pre> <p>while</p> <pre><code> print Solution().getSum(2147483647, 2) </code></pre> <p>outputs</p> <pre><code>-2147483647 </code></pre> <p>due to overflow.</p> <p>The moral of the story is the implementation is correct if you define the <code>int</code> type to only represent 32 bits.</p>
2
2016-07-25T01:24:13Z
[ "python" ]
Cloudant query slow speed using $or or $in
38,557,485
<p>I have an index setup for a field "userid". When I try and query with an and $or, I get a bad request. </p> <pre><code>query = cloudant.query.Query(db,selector={'$or':[{'userid': 35916}, {'userid': 11035}]},fields=['userid']) </code></pre> <p>Adding '_id' first works fine but it takes too long to get all docs first.</p> <pre><code>query = cloudant.query.Query(db,selector={'_id':{'$gt':0},'$or':[{'userid': 35916}, {'userid': 11035}]},fields=['userid']) </code></pre> <p>I get similar results when using $in instead of $or. What am I missing that can make this query quickly?</p>
0
2016-07-24T22:32:59Z
38,575,497
<p>For what it's worth, I created a <code>"type": "json"</code> Cloudant Query index and followed the python-cloudant docs at <a href="http://python-cloudant.readthedocs.io/en/latest/getting_started.html" rel="nofollow">http://python-cloudant.readthedocs.io/en/latest/getting_started.html</a> to write some simple test code. This snippet works for me:</p> <pre><code>import cloudant client = cloudant.Cloudant("username", "password", account="account_name") client.connect() session = client.session() db = client['testdb'] query1 = cloudant.query.Query(db,selector={'$or':[{'userid': 35916}, {'userid': 11035}]},fields=['_id', 'userid']) #query2 = cloudant.query.Query(db,selector={'_id':{'$gt':0},'$or':[{'userid': 35916}, {'userid': 11035}]},fields=['_id', 'userid']) for doc in query1.result: print doc client.disconnect() </code></pre> <p>It returns:</p> <pre><code>{u'_id': u'266f9caae40012a04ce9223ccc67c8bd', u'userid': 35916} {u'_id': u'5ff2cb156d16783492adb3eb8e2e0aec', u'userid': 11035} </code></pre>
1
2016-07-25T18:57:09Z
[ "python", "cloudant" ]
Unable to install xlrd 1.0.0 wheel
38,557,513
<p>I am trying to install the wheel : xlrd-1.0.0-py3-none-any.whl on a 2.7.12 python. windows 7 64 bit and 32 bit cmd.</p> <pre><code>I get the error msg: xlrd-1.0.0-py3-none-any.whl is not a supported wheel for this platform. </code></pre> <p>I downloaded the wheel from <a href="https://pypi.python.org/pypi/xlrd" rel="nofollow">https://pypi.python.org/pypi/xlrd</a> which says that the wheel works for python 2.7+ my cmd command is:</p> <pre><code>c:\python&gt; python -m pip install xlrd-1.0.0-py3-none-any.whl </code></pre> <p>What am I missing??</p>
0
2016-07-24T22:36:03Z
38,557,596
<p>Look the error message:</p> <blockquote> <p>xlrd-1.0.0-<strong>py3</strong>-none-any.whl is not a supported wheel for this platform.</p> </blockquote> <p>I might be wrong, but py3 is Python 3. So not Python 2.7. With Python 2.7+, they maybe mean 2.7.xx+, so that's still Python 3.</p> <p>Try installing it from here: <a href="https://pypi.python.org/pypi/xlutils#downloads" rel="nofollow">https://pypi.python.org/pypi/xlutils#downloads</a> The py2.py3 version supports Python 2 and Python 3.</p> <p>Or, maybe even pip will work fine:</p> <pre><code>pip install xlutils pip install xlrd </code></pre>
2
2016-07-24T22:47:35Z
[ "python", "xlrd" ]
How to get all the unique words in the data frame?
38,557,617
<p>I have a dataframe with a list of products and its respective review</p> <p>+---------+------------------------------------------------+<br> | product | review |<br> +---------+------------------------------------------------+<br> | product_a | It's good for a casual lunch |<br> +---------+------------------------------------------------+<br> | product_b | Avery is one of the most knowledgable baristas |<br> +---------+------------------------------------------------+<br> | product_c | The tour guide told us the secrets |<br> +---------+------------------------------------------------+ </p> <p>How can I get all the unique words in the data frame?</p> <p>I made a function:</p> <pre><code>def count_words(text): try: text = text.lower() words = text.split() count_words = Counter(words) except Exception, AttributeError: count_words = {'':0} return count_words </code></pre> <p>And applied the function to the DataFrame, but that only gives me the words count for each row.</p> <pre><code>reviews['words_count'] = reviews['review'].apply(count_words) </code></pre>
0
2016-07-24T22:50:59Z
38,558,245
<p>Starting with this: </p> <pre><code>dfx review 0 United Kingdom 1 The United Kingdom 2 Dublin, Ireland 3 Mardan, Pakistan </code></pre> <p>To get all words in the "review" column:</p> <pre><code> list(dfx['review'].str.split(' ', expand=True).stack().unique()) ['United', 'Kingdom', 'The', 'Dublin,', 'Ireland', 'Mardan,', 'Pakistan'] </code></pre> <p>To get counts of "review" column:</p> <pre><code>dfx['review'].str.split(' ', expand=True).stack().value_counts() United 2 Kingdom 2 Mardan, 1 The 1 Ireland 1 Dublin, 1 Pakistan 1 dtype: int64 ​ </code></pre>
1
2016-07-25T00:37:02Z
[ "python", "pandas", "dataframe", "count" ]
python windows mouse hook crash
38,557,655
<p>I'm setting up a mouse hook in python like that:</p> <pre><code>def listen(): global hook_id def low_level_handler(aCode, wParam, lParam): if aCode != win32con.HC_ACTION: return ctypes.windll.user32.CallNextHookEx(hook_id, aCode, wParam, lParam) return ctypes.windll.user32.CallNextHookEx(hook_id, aCode, wParam, lParam) # Our low level handler signature. CMPFUNC = ctypes.CFUNCTYPE(ctypes.c_int, ctypes.c_int, ctypes.c_int, ctypes.POINTER(ctypes.c_void_p)) # Convert the Python handler into C pointer. pointer = CMPFUNC(low_level_handler) # Hook both key up and key down events for common keys (non-system). hook_id = ctypes.windll.user32.SetWindowsHookExA(win32con.WH_MOUSE_LL, pointer, GetModuleHandle(None), 0) # Register to remove the hook when the interpreter exits. Unfortunately a # try/finally block doesn't seem to work here. atexit.register(ctypes.windll.user32.UnhookWindowsHookEx, hook_id) def process_msg(): while True: status, msg = PeekMessage(None, 0, 0, win32con.PM_REMOVE) if status == 0: break TranslateMessage(ctypes.byref(msg)) DispatchMessage(ctypes.byref(msg)) </code></pre> <p>process_msg is then later called in a loop</p> <p>Everything seems to be working fine until I do SendInput that simulates a mouse click from within the same app. Once I simulate click, there's a crash. What could possibly be the cause?</p> <p>Thanks.</p>
0
2016-07-24T22:56:34Z
38,563,501
<p>It looks like def low_level_handler was going out of scope and being garbage collected (?) / removed from memory. After I moved it out of def listen, it's all working.</p>
1
2016-07-25T08:59:23Z
[ "python", "windows", "hook", "mouse" ]
python `getattr` like function that accepts dotted string
38,557,707
<p>I would like to implement a function which is similar to <code>getattr</code> but will accept a dotted string and traverse through each attributes.</p> <pre><code>def getattr_multiple_level(obj, attr_string): attr_names = attr_string.split('.') next_level = obj for attr_name in attr_names: next_level = getattr(next_level, attr_name) return next_level class Test(): def make_name(self, pre, suffix=""): return str(pre) + "_my_office_" + suffix p = Test() p.room = Test() p.room.office = Test() attr = getattr_multiple_level(p, 'room.office.make_name') </code></pre> <p>Is there already a built-in way to do this? Or what improvements can be made in above code to handle all possible exceptions and edge cases?</p>
0
2016-07-24T23:03:29Z
38,558,023
<p>Yes, there is "build-in way". You can use property decorator. <a href="https://docs.python.org/2/library/functions.html#property" rel="nofollow">https://docs.python.org/2/library/functions.html#property</a></p> <pre><code>class Author(object): def __init__(self, full_name): self.full_name = full_name class Book(object): def __init__(self, name): self.name = name @property def author(self): return Author("Philip Kindred Dick") class Library(object): @property def book_ubik(self): return Book("ubik") library = Library() print(library.book_ubik.name) print(library.book_ubik.author.full_name) </code></pre> <p>Result:</p> <pre><code>grzegorz@grzegorz-GA-78LMT-USB3:~/tmp$ python3 propery_test.py ubik Philip Kindred Dick </code></pre>
0
2016-07-24T23:56:59Z
[ "python", "oop", "object", "attributes" ]
MultiIndex / Advanced Indexing where a level is not (!=) a value
38,557,709
<p>How do you slice the following df such that the second level != two.</p> <p>In my real world case my second level are date ranges and I want to be able to select everything except for one date.</p> <p>From <a href="http://pandas.pydata.org/pandas-docs/stable/advanced.html" rel="nofollow">MultiIndex / Advanced Indexing</a> </p> <pre><code>In [1]: arrays = [['bar', 'bar', 'baz', 'baz', 'foo', 'foo', 'qux', 'qux'], ['one', 'two', 'one', 'two', 'one', 'two', 'one', 'two']] In [2]: tuples = list(zip(*arrays)) In [4]: index = pd.MultiIndex.from_tuples(tuples, names=['first', 'second']) In [16]: df = pd.DataFrame(np.random.randn(3, 8), index=['A', 'B', 'C'], columns=index) In [38]: df = df.T In [65]: df Out[65]: A B C first second bar one 0.895717 0.410835 -1.413681 two 0.805244 0.813850 1.607920 baz one -1.206412 0.132003 1.024180 two 2.565646 -0.827317 0.569605 foo one 1.431256 -0.076467 0.875906 two 1.340309 -1.187678 -2.211372 qux one -1.170299 1.130127 0.974466 two -0.226169 -1.436737 -2.006747 In [66]: df.xs('one', level='second') Out[66]: A B C first bar 0.895717 0.410835 -1.413681 baz -1.206412 0.132003 1.024180 foo 1.431256 -0.076467 0.875906 qux -1.170299 1.130127 0.974466 </code></pre> <p>I am surprised that the documentation @ pandas.pydata.org is so poor. There are NO explanations for any of the examples. Its like the documentation was written by experts for people who are already well experienced with all features of pandas. </p> <p>Why doesn't the documentation provide the code to re-produce the example? </p>
1
2016-07-24T23:03:47Z
38,557,948
<p>Starting with this: </p> <pre><code> A B C first second bar one -0.350640 -1.761671 0.253923 two -0.036557 0.212322 0.537106 baz one -1.597584 -0.301356 -0.634428 two 2.340900 -0.356272 -0.985386 foo one 0.122753 -0.333827 -0.620175 two 0.423211 -0.570563 -1.245026 qux one -0.972814 -0.878836 -1.030892 two 0.312855 -0.191677 0.700006 df.iloc[df.index.get_level_values('second') != 'one' ] A B C first second bar two -0.036557 0.212322 0.537106 baz two 2.340900 -0.356272 -0.985386 foo two 0.423211 -0.570563 -1.245026 qux two 0.312855 -0.191677 0.700006 df.iloc[df.index.get_level_values('second') != 'two' ] A B C first second bar one -0.350640 -1.761671 0.253923 baz one -1.597584 -0.301356 -0.634428 foo one 0.122753 -0.333827 -0.620175 qux one -0.972814 -0.878836 -1.030892 </code></pre>
2
2016-07-24T23:43:03Z
[ "python", "pandas", "indexing", "slice" ]
how to import python PIL on android and kivy?
38,557,731
<p>I want to create an application that takes photos from camera and show thumbnails of them on android. The related part of my code is:</p> <pre><code>from plyer import camera from PIL import Image . . . def take_photo_from_camera(self, x): filename = str(random.randint(0, 100000000000)) # create random filenames self.camera.take_picture("/storage/sdcard0/MyApp/%s.jpg"%(filename), self.on_success_shot) def on_success_shot(self, path): #Create a thumbnail of taken photo here using PIL </code></pre> <p>I can use android camera without any problem. I've added the PIL/pillow to the requirements of the kivy buildozer.spec file</p> <pre><code>requirements = kivy, openssl, futures, requests, plyer, pyjnius, pillow </code></pre> <p>When i want to create an apk with this configuration, the apk package succesfully builds but if i install apk and run on my android phone, i'm getting this error in logcat:</p> <pre><code>I/python (20188): Traceback (most recent call last): I/python (20188): File "/home/mnrl/teknik/.buildozer/android/app/main.py", line 32, in &lt;module&gt; I/python (20188): File "/home/mnrl/teknik/.buildozer/android/app/_applibs/PIL/Image.py", line 67, in &lt;module&gt; I/python (20188): ImportError: dlopen failed: "/data/data/org.tokerteknik.tokerteknik/files/_applibs/PIL/_imaging.so" is 64-bit instead of 32-bit I/python (20188): Python for android ended. </code></pre> <p>I think the problem related to architecture. I'm using ubuntu 16.04 64 bit and kivy buildozer installs 64 bit libraries with pip while installing requirements. A similar problem here too: <a href="https://github.com/kivy/kivy/issues/4095" rel="nofollow">https://github.com/kivy/kivy/issues/4095</a> but there's not any solution. Briefly how can i import PIL on android with kivy buildozer or how to install 32 bit libraries of PIL on 64 bit system?</p>
0
2016-07-24T23:06:46Z
38,597,155
<p>Use pygame instead of PIL for basic image manipulation processes. Add pygame to the buildozer requirements list, it works without any problem.</p> <pre><code>import pygame picture = pygame.image.load(filepath) picture = pygame.transform.scale(picture, (100, 100)) pygame.image.save(picture, "scaled_image.png") </code></pre>
0
2016-07-26T18:16:27Z
[ "android", "python", "python-imaging-library", "kivy" ]
How do we call a normal function where a coroutine is expected?
38,557,768
<p>Consider a coroutine which calls into another coroutine:</p> <pre><code>async def foo(bar): result = await bar() return result </code></pre> <p>This works fine if <code>bar</code> is a coroutine. What do I need to do (i.e. with what do I need to wrap the call to <code>bar</code>) so that this code does the right thing if <code>bar</code> is a normal function?</p> <p>It is perfectly possible to define a coroutine with <code>async def</code> even if it never does anything asynchronous (i.e. never uses <code>await</code>). However, the question asks how to wrap/modify/call a regular function <code>bar</code> inside the code for <code>foo</code> such that <code>bar</code> can be awaited.</p>
3
2016-07-24T23:12:45Z
38,563,919
<p>Simply wrap your synchronous function with <a href="https://docs.python.org/3.4/library/asyncio-task.html#asyncio.coroutine" rel="nofollow">asyncio.coroutine</a> if needed:</p> <pre><code>if not asyncio.iscoroutinefunction(bar): bar = asyncio.coroutine(bar) </code></pre> <p>Since it is safe to re-wrap a coroutine, the coroutine function test is actually not required:</p> <pre><code>async_bar = asyncio.coroutine(sync_or_async_bar) </code></pre> <p>Therefore, your code can be re-written as follows:</p> <pre><code>async def foo(bar): return await asyncio.coroutine(bar)() </code></pre>
2
2016-07-25T09:18:02Z
[ "python", "concurrency", "python-asyncio" ]
How to reply to a particular user's most recent tweet using Tweepy?
38,557,830
<p>I found this code</p> <pre><code>toReply = "xxx" api = tweepy.API(auth) tweets = api.user_timeline(screen_name = toReply, count=1) for tweet in tweets: api.update_status("@" + toReply + " my reply", in_reply_to_status_id = tweet.id) </code></pre> <p>But it's not what I'm looking for. It just replies to the latest tweet. I want the bot to reply every time xxx tweets. What should I change in my code?</p>
0
2016-07-24T23:22:02Z
38,557,852
<pre><code>while True: for tweet in api.user_timeline(...): </code></pre>
1
2016-07-24T23:25:52Z
[ "python", "twitter", "bots", "tweepy" ]
A simple 1-D peak finding program in python
38,557,849
<p>A peak finding program in a 1-D python list which returns a peak with its index if for an index 'x' in the list 'arr' if (arr[x] > arr[x+1] and arr[x] > arr[x-1]). Special case Case 1 : In case of the first element. Only compare it to the second element. If arr[x] > arr[x+1], peak found. Case 2 : Last element. Compare with the previous element. If arr[x] > arr[x-1], peak found. Below is the code. For some reason it is not working in the case the peak is at index = 0. Its perfectly working for the peak in the middle and peak at the end. Any help is greatly appreciated.</p> <pre><code>import sys def find_peak(lst): for x in lst: if x == 0 and lst[x] &gt; lst[x+1]: print "Peak found at index", x print "Peak :", lst[x] return elif x == len(lst)-1 and lst[x] &gt; lst[x-1]: print "Peak found at index", x print "Peak :", lst[x] return elif x &gt; 0 and x &lt; len(lst)-1: if lst[x] &gt; lst[x+1] and lst[x] &gt; lst[x-1]: print "Peak found at index", x print "Peak :", lst[x] return else : print "No peak found" def main(): lst = [] for x in sys.argv[1:]: lst.append(int(x)) find_peak(lst) if __name__ == '__main__': main() Anuvrats-MacBook-Air:Python anuvrattiku$ python peak_finding_1D.py 1 2 3 4 Peak found at index 3 Peak : 4 Anuvrats-MacBook-Air:Python anuvrattiku$ python peak_finding_1D.py 1 2 3 4 3 Peak found at index 3 Peak : 4 Anuvrats-MacBook-Air:Python anuvrattiku$ python peak_finding_1D.py 4 3 2 1 No peak found </code></pre>
1
2016-07-24T23:25:10Z
38,557,877
<p>Your issue lies in the initialization of your loop</p> <pre><code>for x in lst: </code></pre> <p>With this loop, for your last example, x will be 4, then 3, then 2, then 1.</p> <p>By the looks of your code, it seems you intended to say:</p> <pre><code>for x in range(len(lst)): </code></pre> <p>This will iterate over the indices of the list rather than the values in the list. The reason your code even appeared to work was because in your test cases, the values of the list closely matched the indices of the list - consider more varied tests in the future.</p>
1
2016-07-24T23:29:27Z
[ "python", "arrays", "python-2.7", "python-3.x" ]
A simple 1-D peak finding program in python
38,557,849
<p>A peak finding program in a 1-D python list which returns a peak with its index if for an index 'x' in the list 'arr' if (arr[x] > arr[x+1] and arr[x] > arr[x-1]). Special case Case 1 : In case of the first element. Only compare it to the second element. If arr[x] > arr[x+1], peak found. Case 2 : Last element. Compare with the previous element. If arr[x] > arr[x-1], peak found. Below is the code. For some reason it is not working in the case the peak is at index = 0. Its perfectly working for the peak in the middle and peak at the end. Any help is greatly appreciated.</p> <pre><code>import sys def find_peak(lst): for x in lst: if x == 0 and lst[x] &gt; lst[x+1]: print "Peak found at index", x print "Peak :", lst[x] return elif x == len(lst)-1 and lst[x] &gt; lst[x-1]: print "Peak found at index", x print "Peak :", lst[x] return elif x &gt; 0 and x &lt; len(lst)-1: if lst[x] &gt; lst[x+1] and lst[x] &gt; lst[x-1]: print "Peak found at index", x print "Peak :", lst[x] return else : print "No peak found" def main(): lst = [] for x in sys.argv[1:]: lst.append(int(x)) find_peak(lst) if __name__ == '__main__': main() Anuvrats-MacBook-Air:Python anuvrattiku$ python peak_finding_1D.py 1 2 3 4 Peak found at index 3 Peak : 4 Anuvrats-MacBook-Air:Python anuvrattiku$ python peak_finding_1D.py 1 2 3 4 3 Peak found at index 3 Peak : 4 Anuvrats-MacBook-Air:Python anuvrattiku$ python peak_finding_1D.py 4 3 2 1 No peak found </code></pre>
1
2016-07-24T23:25:10Z
38,557,885
<p>x is a list element in your code and you are using it as an index.</p> <p>you should write:</p> <pre><code>def find_peak(lst): for i,x in enumerate(lst): if i == 0 and x &gt; lst[i+1]: print "Peak found at index", i print "Peak :", x return elif i == len(lst)-1 and x &gt; lst[i-1]: print "Peak found at index", i print "Peak :", x return elif i &gt; 0 and i &lt; len(lst)-1: if x &gt; lst[i+1] and x &gt; lst[i-1]: print "Peak found at index", i print "Peak :", x return else : print "No peak found" </code></pre>
1
2016-07-24T23:31:04Z
[ "python", "arrays", "python-2.7", "python-3.x" ]
Confusions on /account/ vs /admin/ views (any built in way to create these)
38,557,850
<p>I have begun to implement authentication throughout my applications in Django and have done this quite successfully with the Django login_required decorator.</p> <p>However, I notice that this will always reroute to the deafault login URL: <code>/accounts/...</code> which is non-existent for me. I have been doing all my authentication through <code>/admin/...</code></p> <p>I imagine that the two are for different purposes (one for the admin users and allow access to the admin console) however, I cannot find any views for the accounts version (vs. admin). My questions are thus as follows:</p> <ol> <li><p>What is the difference between <code>/accounts/...</code> and <code>/admin/...</code> if they use the same user models?</p></li> <li><p>Are these <code>/accounts/...</code> views built in/templateable? How does one turn them on? Or do I need to create each manually?</p></li> </ol> <p>Unfortunately I have found the documentation on this topic to be rather confusing and as such any help would be greatly appreciated.</p>
0
2016-07-24T23:25:29Z
38,557,915
<p>The '/accounts/' is just a url that out of best practices most people when handling authentication. There are no built in templates for accounts. the '/accounts/' is just a default placed. </p> <p>To change the url to fit your applications url, go to your <em>settings.py</em> file and you can add a <strong>LOGIN_URL</strong> variable to specify which location for the authentication to redirect to. In your case it will look like this.</p> <pre><code>LOGIN_URL = '/admin' </code></pre> <p>This will redirect all unauthenticated requests to '/admin'</p>
1
2016-07-24T23:36:51Z
[ "python", "django", "authentication", "django-models", "django-admin" ]
Confusions on /account/ vs /admin/ views (any built in way to create these)
38,557,850
<p>I have begun to implement authentication throughout my applications in Django and have done this quite successfully with the Django login_required decorator.</p> <p>However, I notice that this will always reroute to the deafault login URL: <code>/accounts/...</code> which is non-existent for me. I have been doing all my authentication through <code>/admin/...</code></p> <p>I imagine that the two are for different purposes (one for the admin users and allow access to the admin console) however, I cannot find any views for the accounts version (vs. admin). My questions are thus as follows:</p> <ol> <li><p>What is the difference between <code>/accounts/...</code> and <code>/admin/...</code> if they use the same user models?</p></li> <li><p>Are these <code>/accounts/...</code> views built in/templateable? How does one turn them on? Or do I need to create each manually?</p></li> </ol> <p>Unfortunately I have found the documentation on this topic to be rather confusing and as such any help would be greatly appreciated.</p>
0
2016-07-24T23:25:29Z
38,557,924
<p>If you are not logged in, Django uses the <a href="https://docs.djangoproject.com/en/1.9/ref/settings/#login-url" rel="nofollow"><code>LOGIN_URL</code></a> to decide which url to redirect to. By default, this is set to <code>'/accounts/login/'</code>.</p> <p>If you use a different login url, then you should update your <code>LOGIN_URL</code> setting.</p> <p>The disadvantage of using the Django admin to log in users, is that non-staff members will not be able to log in using the Django admin.</p> <p>Django comes with <a href="https://docs.djangoproject.com/en/1.9/topics/auth/default/#module-django.contrib.auth.views" rel="nofollow">authentication views</a>, including a <a href="https://docs.djangoproject.com/en/1.9/topics/auth/default/#django.contrib.auth.views.login" rel="nofollow"><code>login</code></a> view. If you want to allow non-staff members to log in, you should enable it.</p>
2
2016-07-24T23:38:25Z
[ "python", "django", "authentication", "django-models", "django-admin" ]
performance of list.remove(value) in Python 2.7
38,557,960
<p>Suppose a list contains a list of integers, if I call <code>list.remove(100)</code> to remove element with value 100, wondering if it is <code>O(n)</code> or <code>O(logN)</code>? I thought it is <code>O(n)</code>, but not sure if Python 2.7 list has any internal optimizations to improve performance even further. Thanks.</p> <p>regards, Lin</p>
0
2016-07-24T23:45:43Z
38,557,982
<p><a href="https://wiki.python.org/moin/TimeComplexity" rel="nofollow">Removing an item from a list in Python is O(n)</a>. This is because the underlying space in memory must be "shifted over" now that an element is missing. There are other implementations of lists, such as a linked list, that you could use in Python for constant time removal, but the built in List data structure is definitively O(n)</p>
1
2016-07-24T23:49:19Z
[ "python", "list", "python-2.7" ]
Python files to class
38,557,972
<p>Would I be able to convert these files:</p> <pre><code>### one.py ### print("one") ### two.py ### print("two") </code></pre> <p>to a Python class so then say I want to import <code>one.py</code>, I would be able to do:</p> <pre><code>importFile(MyClass.one) </code></pre> <p>or something like that?</p>
-1
2016-07-24T23:47:41Z
38,558,158
<p>You can do this by putting those statements into a class or a method and them importing the file. This is what <code>one.py</code> would look like if you wanted to make it into a method and then import it:</p> <h2>one.py</h2> <pre><code>def print_one(): print("one") </code></pre> <h2>Example file with two methods (two.py)</h2> <pre><code>def method_one(): pass def method_two(): print("In method 2!") </code></pre> <h2>How you'd call the file (assuming you're in the same directory)</h2> <pre><code>&gt;&gt;&gt; import one &gt;&gt;&gt; one.print_one() &gt;&gt;&gt; import two &gt;&gt;&gt; two.method_one() # does nothing &gt;&gt;&gt; two.method_two() </code></pre> <p>You can do other more sophisticated things with Python packages by <a href="http://docs.python-guide.org/en/latest/writing/structure/" rel="nofollow">structuring your project</a> and using things like <code>$PYTHONPATH</code> (<a href="http://stackoverflow.com/questions/19917492/how-to-use-pythonpath">documentation</a>).</p>
0
2016-07-25T00:20:46Z
[ "python", "class", "oop" ]
No 'Access-Control-Allow-Origin' header present AngularJS
38,558,014
<p>I am trying to build a quick demo site that I do not have control over the server I am trying to connect to. Here is the code that I am using to build it with AngularJS. I am running the file through a simple Python HTTP Server and viewing it at localhost:8000. var retrieveAppliances = function () { console.log('Attempting to retrieve appliance list.');</p> <pre><code>var requestUrl = '****'; $http({ method: 'GET', url: requestUrl, }) .then(function (response) { console.log(response); }); }; retrieveAppliances(); </code></pre> <p>I have read multiple places to try switching the <code>method</code> to <code>JSONP</code> but doing so resulted in a parsing error. </p> <p>While I have considered trying to build a <code>server.js</code> file and running NodeJS with it, I am unsuccessful in learning the basics of making an AJAX request and proxying that to my app.js.</p> <p>I will greatly appreciate any help that someone may be able to give me, with clear and easy to follow steps.</p>
0
2016-07-24T23:55:33Z
38,558,109
<p>If you're running an Ajax call to a different origin (e.g. different host, port or protocol) and the server at that origin does not have support for cross origin requests, then you cannot fix that from your client. There is nothing you can do from the client.</p> <p>If the server supported JSONP, you could use that, but that also requires specific server support.</p> <p>The only solutions from a browser web page are:</p> <ol> <li>CORS support on the target server.</li> <li>JSONP (also requires support on the target server).</li> <li>Set up your own server that you do have access to (either on your existing page domain or with CORS) and then have that server get the file/data for you and proxy it back to you. You can either write your own proxy or deploy a pre-built proxy.</li> <li>Find some existing third party proxy service that you can use.</li> </ol> <p>If you're interested in making your own node.js proxy, you can see a simple example here: <a href="http://stackoverflow.com/a/20354642/816620">How to create a simple http proxy in node.js?</a>.</p>
3
2016-07-25T00:12:10Z
[ "javascript", "python", "angularjs", "ajax", "node.js" ]
How can I put a Python function to sleep while still calling it (IFTTT)
38,558,029
<p>I have a Python function set up to text me if my house gets above 30 degrees Celsius. The script also drives and LCD display that loops through various bits of weather info: house temp, humidity, outdoor conditions, and the times of streetcars.</p> <p>Because the script is based on a loop, I get a text message every minute or so as long as the temperature is above 30 C. Ideally, I would like to find an elegant way to put the function to sleep while still calling it to check the temperature.</p> <p>Below is an example of the code I'm using to trigger the IFTTT:</p> <pre><code>def send_event(api_key, event, value1=None, value2=None, value3=None): """Send an event to the IFTTT maker channel""" url = "https://maker.ifttt.com/trigger/{e}/with/key/{k}/".format(e=event, k=api_key) payload = {'value1': value1, 'value2': value2, 'value3': value3} return requests.post(url, data=payload) </code></pre> <p>Any and all help appreciated.</p> <p>Thanks!</p>
0
2016-07-24T23:59:30Z
38,558,077
<p>Instead of trying to stop your loop from continuing, you should record when the last alert was sent and only resend if enough time has elapsed since the last alert.</p> <p>Whenever a temperature alert gets sent, have it record the <code>datetime</code> to a variable. Each time the function is called, have it compare the current <code>datetime</code> to the variable to see if the difference is greater than a certain threshold. If it is, re-send the alert and replace the last alert veriable with the current <code>datetime</code>.</p> <pre><code>from datetime import datetime alert_interval = 1800 # 30 minutes in seconds last_alert = datetime(1, 1, 1) # set the initial time to very long ago def send_event(): time_diff = datetime.now() - last_alert # get a timedelta if time_diff.total_seconds() &gt;= alert_interval: last_alert = datetime.now() # call the API to send another alert </code></pre>
0
2016-07-25T00:06:17Z
[ "python", "function", "loops", "ifttt" ]
How can I put a Python function to sleep while still calling it (IFTTT)
38,558,029
<p>I have a Python function set up to text me if my house gets above 30 degrees Celsius. The script also drives and LCD display that loops through various bits of weather info: house temp, humidity, outdoor conditions, and the times of streetcars.</p> <p>Because the script is based on a loop, I get a text message every minute or so as long as the temperature is above 30 C. Ideally, I would like to find an elegant way to put the function to sleep while still calling it to check the temperature.</p> <p>Below is an example of the code I'm using to trigger the IFTTT:</p> <pre><code>def send_event(api_key, event, value1=None, value2=None, value3=None): """Send an event to the IFTTT maker channel""" url = "https://maker.ifttt.com/trigger/{e}/with/key/{k}/".format(e=event, k=api_key) payload = {'value1': value1, 'value2': value2, 'value3': value3} return requests.post(url, data=payload) </code></pre> <p>Any and all help appreciated.</p> <p>Thanks!</p>
0
2016-07-24T23:59:30Z
38,558,097
<p>If I understand correctly, the problem is that you get too many texts. In that case, store some state about the previous events and use that to decide whether or not to send a text.</p> <p>For example, a simple boolean (True/False) variable can be used as a simple flag. You can still use a loop, but only send an event on the first time it gets above 30 degrees and reset when it falls below:</p> <pre><code>temp_is_high = False while True: data = weather.get_data() if data['temp'] &gt; 30: # only send if we are going from "cool" to "hot" # not if we were already in "hot" mode if not temp_is_high: # we are not in "hot" mode: remember for next time temp_is_high = True send_event(...) else: # reset the condition flag temp_is_high = False </code></pre> <p>There are variation on this theme. For example, you might want to add hysteresis in so that if your thermostat is set to 30 degrees, and the house temperature is hovering around that, measurements of [29, 30, 29, 30, 29, 30, ....] won't send a text every time. To do that, only reset the "hot mode" flag when the temperature, having passed 30, falls below (say) 26 degrees. Or 1 hour has passed, or any number of your own requirements.</p>
0
2016-07-25T00:10:11Z
[ "python", "function", "loops", "ifttt" ]
Create dictionary from a list deleting all spaces
38,558,068
<p>sorry for asking but I'm kind of new to these things. I'm doing a splitting words from the text and putting them to dict creating an index for each token:</p> <pre><code>import re f = open('/Users/Half_Pint_Boy/Desktop/sentenses.txt', 'r') a=0 c=0 e=[] for line in f: b=re.split('[^a-z]', line.lower()) a+=len(list(filter(None, b))) c = c + 1 e = e + b d = dict(zip(e, range(len(e)))) </code></pre> <p>But in the end I receive a dict with spaces in it like that:</p> <pre><code>{'': 633, 'a': 617, 'according': 385, 'adjacent': 237, 'allow': 429, 'allows': 459} </code></pre> <p>How can I remove "" from the final result in dict? Also how can I change the indexing after that to not use "" in index counting? (with "" the index count is 633, without-248) Big thanks!</p>
0
2016-07-25T00:04:49Z
38,558,095
<p>How about this?</p> <pre><code>b = list(filter(None, re.split('[^a-z]', line.lower()))) </code></pre> <p>As an alternative:</p> <pre><code>b = re.findall('[a-z]+', line.lower()) </code></pre> <p>Either way, you can then also remove that <code>filter</code> from the next line:</p> <pre><code>a += len(b) </code></pre> <p><strong>EDIT</strong></p> <p>As an aside, I think what you end up with here is a dictionary mapping words to the <strong>last position in which they appear in the text</strong>. I'm not sure if that's what you intended to do. E.g.</p> <pre><code>&gt;&gt;&gt; dict(zip(['hello', 'world', 'hello', 'again'], range(4))) {'world': 1, 'hello': 2, 'again': 3} </code></pre> <p>If you instead want to keep track of <em>all</em> the positions a word occurs, perhaps try this code instead:</p> <pre><code>from collections import defaultdict import re indexes = defaultdict(list) with open('test.txt', 'r') as f: for index, word in enumerate(re.findall(r'[a-z]+', f.read().lower())): indexes[word].append(index) </code></pre> <p><code>indexes</code> then maps each word to a list of indexes at which the word appears.</p> <p><strong>EDIT 2</strong></p> <p>Based on the comment discussion below, I think you want something more like this:</p> <pre><code>from collections import defaultdict import re word_positions = {} with open('test.txt', 'r') as f: index = 0 for word in re.findall(r'[a-z]+', f.read().lower()): if word not in word_positions: word_positions[word] = index index += 1 print(word_positions) # Output: # {'hello': 0, 'goodbye': 2, 'world': 1} </code></pre>
2
2016-07-25T00:09:32Z
[ "python", "dictionary" ]
Create dictionary from a list deleting all spaces
38,558,068
<p>sorry for asking but I'm kind of new to these things. I'm doing a splitting words from the text and putting them to dict creating an index for each token:</p> <pre><code>import re f = open('/Users/Half_Pint_Boy/Desktop/sentenses.txt', 'r') a=0 c=0 e=[] for line in f: b=re.split('[^a-z]', line.lower()) a+=len(list(filter(None, b))) c = c + 1 e = e + b d = dict(zip(e, range(len(e)))) </code></pre> <p>But in the end I receive a dict with spaces in it like that:</p> <pre><code>{'': 633, 'a': 617, 'according': 385, 'adjacent': 237, 'allow': 429, 'allows': 459} </code></pre> <p>How can I remove "" from the final result in dict? Also how can I change the indexing after that to not use "" in index counting? (with "" the index count is 633, without-248) Big thanks!</p>
0
2016-07-25T00:04:49Z
38,558,113
<p>Replace:</p> <pre><code>d = dict(zip(e, range(len(e)))) </code></pre> <p>With:</p> <pre><code>d = {word:n for n, word in enumerate(e) if word} </code></pre> <p>Alternatively, to avoid the empty entries in the first place, replace:</p> <pre><code>b=re.split('[^a-z]', line.lower()) </code></pre> <p>With:</p> <pre><code>b=re.split('[^a-z]+', re.sub('(^[^a-z]+|[^a-z]+$)', '', line.lower())) </code></pre>
1
2016-07-25T00:13:05Z
[ "python", "dictionary" ]
Create dictionary from a list deleting all spaces
38,558,068
<p>sorry for asking but I'm kind of new to these things. I'm doing a splitting words from the text and putting them to dict creating an index for each token:</p> <pre><code>import re f = open('/Users/Half_Pint_Boy/Desktop/sentenses.txt', 'r') a=0 c=0 e=[] for line in f: b=re.split('[^a-z]', line.lower()) a+=len(list(filter(None, b))) c = c + 1 e = e + b d = dict(zip(e, range(len(e)))) </code></pre> <p>But in the end I receive a dict with spaces in it like that:</p> <pre><code>{'': 633, 'a': 617, 'according': 385, 'adjacent': 237, 'allow': 429, 'allows': 459} </code></pre> <p>How can I remove "" from the final result in dict? Also how can I change the indexing after that to not use "" in index counting? (with "" the index count is 633, without-248) Big thanks!</p>
0
2016-07-25T00:04:49Z
38,558,160
<p>Your regex looks not a good one. Consider to use:</p> <pre><code>line = re.sub('[^a-z]*$', '', line.strip()) b = re.split('[^a-z]+', line.lower()) </code></pre>
1
2016-07-25T00:20:57Z
[ "python", "dictionary" ]
Python - Zip code to Barcode
38,558,076
<p>The code is supposed to take a 5 digit zip code input and convert it to bar codes as the output. The bar code for each digit is:</p> <pre><code>{1:'...!!',2:'..!.!',3:'..!!.',4:'.!..!',5:'.!.!.',6:'.!!..',7:'!...!',8:'!..!.',9:'!.!..',0:'!!...'} </code></pre> <p>For example, the zip code 95014 is supposed to produce:</p> <pre><code>!!.!.. .!.!. !!... ...!! .!..! ...!!! </code></pre> <p>There is an extra <code>!</code> at the start and end, that is used to determine where the bar code starts and stops. Notice that at the end of the bar code is an extra <code>...!!</code> which is an 1. This is the check digit and you get the check digit by:</p> <ul> <li>Adding up all the digits in the zipcode to make the sum <em>Z</em></li> <li>Choosing the check digit <em>C</em> so that Z + C is a multiple of 10</li> </ul> <p>For example, the zipcode <code>95014</code> has a sum of <em>Z</em> = 9 + 5 + 0 + 1 + 4 = 19, so the check digit <em>C</em> is 1 to make the total sum <em>Z</em> + <em>C</em> equal to 20, which is a multiple of 10.</p> <pre><code>def printDigit(digit): digit_dict = {1:'...!!',2:'..!.!',3:'..!!.',4:'.!..!',5:'.!.!.',6:'.!!..',7:'!...!',8:'!..!.',9:'!.!..',0:'!!...'} return digit_dict[digit] def printBarCode(zip_code): sum_digits=0 num=zip_code while num!=0: sum_digits+=(num%10) num/=10 rem = 20-(sum_digits%20) answer=[] for i in str(zip_code): answer.append(printDigit(int(i))) final='!'+' '.join(answer)+'!' return final print printBarCode(95014) </code></pre> <p>The code I currently have produces an output of </p> <p><code>!!.!.. .!.!. !!... ...!! .!..!!</code> </p> <p>for the zip code <code>95014</code> which is missing the check digit. Is there something missing in my code that is causing the code not to output the check digit? Also, what to include in my code to have it ask the user for the zip code input? </p>
-1
2016-07-25T00:06:07Z
38,558,273
<p>Your code computes <code>rem</code> based on the sum of the digits, but you never use it to add the check-digit bars to the output (<code>answer</code> and <code>final</code>). You need to add code to do that in order to get the right answer. I suspect you're also not computing <code>rem</code> correctly, since you're using <code>%20</code> rather than <code>%10</code>.</p> <p>I'd replace the last few lines of your function with:</p> <pre><code>rem = (10 - sum_digits) % 10 # correct computation for the check digit answer=[] for i in str(zip_code): answer.append(printDigit(int(i))) answer.append(printDigit(rem)) # add the check digit to the answer! final='!'+' '.join(answer)+'!' return final </code></pre>
1
2016-07-25T00:41:44Z
[ "python", "python-2.7" ]
Python - Zip code to Barcode
38,558,076
<p>The code is supposed to take a 5 digit zip code input and convert it to bar codes as the output. The bar code for each digit is:</p> <pre><code>{1:'...!!',2:'..!.!',3:'..!!.',4:'.!..!',5:'.!.!.',6:'.!!..',7:'!...!',8:'!..!.',9:'!.!..',0:'!!...'} </code></pre> <p>For example, the zip code 95014 is supposed to produce:</p> <pre><code>!!.!.. .!.!. !!... ...!! .!..! ...!!! </code></pre> <p>There is an extra <code>!</code> at the start and end, that is used to determine where the bar code starts and stops. Notice that at the end of the bar code is an extra <code>...!!</code> which is an 1. This is the check digit and you get the check digit by:</p> <ul> <li>Adding up all the digits in the zipcode to make the sum <em>Z</em></li> <li>Choosing the check digit <em>C</em> so that Z + C is a multiple of 10</li> </ul> <p>For example, the zipcode <code>95014</code> has a sum of <em>Z</em> = 9 + 5 + 0 + 1 + 4 = 19, so the check digit <em>C</em> is 1 to make the total sum <em>Z</em> + <em>C</em> equal to 20, which is a multiple of 10.</p> <pre><code>def printDigit(digit): digit_dict = {1:'...!!',2:'..!.!',3:'..!!.',4:'.!..!',5:'.!.!.',6:'.!!..',7:'!...!',8:'!..!.',9:'!.!..',0:'!!...'} return digit_dict[digit] def printBarCode(zip_code): sum_digits=0 num=zip_code while num!=0: sum_digits+=(num%10) num/=10 rem = 20-(sum_digits%20) answer=[] for i in str(zip_code): answer.append(printDigit(int(i))) final='!'+' '.join(answer)+'!' return final print printBarCode(95014) </code></pre> <p>The code I currently have produces an output of </p> <p><code>!!.!.. .!.!. !!... ...!! .!..!!</code> </p> <p>for the zip code <code>95014</code> which is missing the check digit. Is there something missing in my code that is causing the code not to output the check digit? Also, what to include in my code to have it ask the user for the zip code input? </p>
-1
2016-07-25T00:06:07Z
38,558,456
<p>Interesting problem. I noticed that you solved the problem as a C-style programmer. I'm guessing your background is in C/C++. I's like to offer a more Pythonic way:</p> <pre><code>def printBarCode(zip_code): digit_dict = {1:'...!!',2:'..!.!',3:'..!!.',4:'.!..!',5:'.!.!.', 6:'.!!..',7:'!...!',8:'!..!.',9:'!.!..',0:'!!...'} zip_code_list = [int(num) for num in str(zip_code)] bar_code = ' '.join([digit_dict[num] for num in zip_code_list]) check_code = digit_dict[10 - sum(zip_code_list) % 10] return '!{} {}!'.format(bar_code, check_code) print printBarCode(95014) </code></pre> <p>I used list comprehension to work with each digit rather than to iterate. I could have used the map() function to make it more readable, but list comprehension is more Pythonic. Also, I used the Python 3.x format for string formatting. Here is the output:</p> <pre><code>!!.!.. .!.!. !!... ...!! .!..! ...!!! &gt;&gt;&gt; </code></pre>
0
2016-07-25T01:16:09Z
[ "python", "python-2.7" ]
How can I convert Python number to 1 byte C type?
38,558,174
<p>I'm having some issues with communication between python script (on my laptop) and a C program running on a AVR microcontroller. They are communicating through UART. My issue is right now I have the following set up. </p> <p>Python sending data:</p> <pre><code>data = port.write(struct.pack("b", val)) </code></pre> <p>Python reading data:</p> <pre><code>v = struct.unpack('B', d)[0] print "%s: %d" % ( time.ctime(time.time()), v ) </code></pre> <p>C (AVR) reading data:</p> <pre><code>received = (uint8_t) UDR0; </code></pre> <p>C (AVR) writing data (echo):</p> <pre><code>UDR0 = received; </code></pre> <p>My issue is with this set up the numbers my python script are getting back are as follows:</p> <p>send: 0 - 31, receive: 224 - 255 send: 32 - 63 receive: 32 - 63 send: 62 -95 receive: 224 - 255 send: 96 - 100 receive: 224 - 228</p> <p>I don't understand why these numbers are matching up how they are but I suspect it's because of my data types. I thought about using chr() and ord() to convert to and from characters but there has to be an easier (more understandable) way. I started looking into ctypes in python and was looking to use the c_ubyte function but was unable to figure out how to use it correctly. I fairly new to python. Does anyone have any suggestions on where my logic is incorrect? </p> <p>Again, my guess is the conversions and using signed vs unsigned data types. </p> <p>Thanks.</p>
0
2016-07-25T00:24:01Z
38,580,278
<p>I discovered the problem. The code is correct. I have an issue with my AVR board or my UART module. When I was sending values 0 - 31 the board was receiving 0b11100000 - 0b11111111. For 32 - 63 the board was receiving 0b00100000 - 0b00111111. For 64 - 95 the board was receiving 0b11100000 - ob11111111. For 96 - 100 the board was receiving 0b11100000 - 0b11100100.</p> <p>I don't know why I'm getting these values yet. I find it very strange that the 3 most significant bits are flipping the way they are. To solve my problem for now until I figure out what's wrong (looking into if it's my UART module) I'm using a subset of 25 values and incrementing my values by 4 to get the 0 - 100 range I want.</p>
0
2016-07-26T02:46:43Z
[ "python", "c", "ctypes", "avr" ]
How can I convert Python number to 1 byte C type?
38,558,174
<p>I'm having some issues with communication between python script (on my laptop) and a C program running on a AVR microcontroller. They are communicating through UART. My issue is right now I have the following set up. </p> <p>Python sending data:</p> <pre><code>data = port.write(struct.pack("b", val)) </code></pre> <p>Python reading data:</p> <pre><code>v = struct.unpack('B', d)[0] print "%s: %d" % ( time.ctime(time.time()), v ) </code></pre> <p>C (AVR) reading data:</p> <pre><code>received = (uint8_t) UDR0; </code></pre> <p>C (AVR) writing data (echo):</p> <pre><code>UDR0 = received; </code></pre> <p>My issue is with this set up the numbers my python script are getting back are as follows:</p> <p>send: 0 - 31, receive: 224 - 255 send: 32 - 63 receive: 32 - 63 send: 62 -95 receive: 224 - 255 send: 96 - 100 receive: 224 - 228</p> <p>I don't understand why these numbers are matching up how they are but I suspect it's because of my data types. I thought about using chr() and ord() to convert to and from characters but there has to be an easier (more understandable) way. I started looking into ctypes in python and was looking to use the c_ubyte function but was unable to figure out how to use it correctly. I fairly new to python. Does anyone have any suggestions on where my logic is incorrect? </p> <p>Again, my guess is the conversions and using signed vs unsigned data types. </p> <p>Thanks.</p>
0
2016-07-25T00:24:01Z
38,821,422
<p>Let's have a quick look at the wire form of the transmissions. There's always a start bit 0, then eight data bits with LSB first, then a stop bit 1. From the description, we're getting strange data in 3 bits, correct in 5, so there are 8 patterns to compare. I'll write the wire format right to left here. </p> <pre><code>&gt;&gt;&gt; for i,highbits in enumerate('111 001 111 111 111'.split()): ... print '1{:03b}ddddd0\t1{}ddddd0'.format(i,highbits) ... 1000ddddd0 1111ddddd0 1001ddddd0 1001ddddd0 1010ddddd0 1111ddddd0 1011ddddd0 1111ddddd0 1100ddddd0 1111ddddd0 </code></pre> <p>We don't have test data for the whole set. What we see is a whole bunch of combinations where bits are set that shouldn't be, with one set of exceptions that look correct (0x20-0x3f). An analog timing issue could have explained some of the behaviour (at least bit 5 is consistently set), but it seems odd that the second pattern goes low but the fourth doesn't. </p> <p>I'm short on ideas what specifically would be going on. It's too low values to be an issue of things like your file descriptor being set to UTF-8 encoding. The part where you encode as signed and decode as unsigned also doesn't matter since you use values in the range 0..127. Software issues would mostly clear high bits anyway, with format issues generally only varying a single bit for parity. </p> <p>I'd really like an oscilloscope trace as well as a schematic of what's actually connected on the serial lines. Some connections (like through a capacitor or transformer) require patterns that alternate frequently enough, though even with those the shown patterns are surprising. Observing the true wire patterns would at least tell us where the distortion is happening, and with luck point at what sort of change it is. </p>
0
2016-08-08T04:43:04Z
[ "python", "c", "ctypes", "avr" ]
How can I convert Python number to 1 byte C type?
38,558,174
<p>I'm having some issues with communication between python script (on my laptop) and a C program running on a AVR microcontroller. They are communicating through UART. My issue is right now I have the following set up. </p> <p>Python sending data:</p> <pre><code>data = port.write(struct.pack("b", val)) </code></pre> <p>Python reading data:</p> <pre><code>v = struct.unpack('B', d)[0] print "%s: %d" % ( time.ctime(time.time()), v ) </code></pre> <p>C (AVR) reading data:</p> <pre><code>received = (uint8_t) UDR0; </code></pre> <p>C (AVR) writing data (echo):</p> <pre><code>UDR0 = received; </code></pre> <p>My issue is with this set up the numbers my python script are getting back are as follows:</p> <p>send: 0 - 31, receive: 224 - 255 send: 32 - 63 receive: 32 - 63 send: 62 -95 receive: 224 - 255 send: 96 - 100 receive: 224 - 228</p> <p>I don't understand why these numbers are matching up how they are but I suspect it's because of my data types. I thought about using chr() and ord() to convert to and from characters but there has to be an easier (more understandable) way. I started looking into ctypes in python and was looking to use the c_ubyte function but was unable to figure out how to use it correctly. I fairly new to python. Does anyone have any suggestions on where my logic is incorrect? </p> <p>Again, my guess is the conversions and using signed vs unsigned data types. </p> <p>Thanks.</p>
0
2016-07-25T00:24:01Z
38,897,452
<p>Just to exclude the microcontroller-side software from the "suspects" and concentrate on the communication line - connect Rx/Tx on MCU side and try to send and receive what you have just sent. Campare what you have received against what you have sent. Both sent and received buffers should match. Then we know for sure - there is something wrong with the communication line settings between the sensder and the receiver.</p>
0
2016-08-11T13:14:32Z
[ "python", "c", "ctypes", "avr" ]
Python 3 (CherryPy) Server Not Working on Other Computer
38,558,201
<p>I would like to access my CherryPy site on a different computer, but I have tried the answers form <a href="http://stackoverflow.com/questions/7494171/python-cherrypy-web-app-deployed-locally-but-not-visible-over-intranet">here</a> and <a href="http://stackoverflow.com/questions/115773/how-do-i-configure-the-ip-address-with-cherrypy">here</a>, but neither have worked. I am using a Mac with OSX El Capitan, Python 3.5.2, and I believe, the latest version of CherryPy. This is my current code, I do not care what the address is, just that it works. Thanks for any help!</p> <pre><code>import cherrypy class HelloWorld(object): def index(self): return "Hello World!" index.exposed = True # bind to all IPv4 interfaces cherrypy.config.update({'server.socket_host': '0.0.0.0'}) cherrypy.quickstart(HelloWorld()) </code></pre> <p><strong>EDIT:</strong></p> <p>I can access the site from <code>localhost:8080</code> <code>127.0.0.1</code> and <code>0.0.0.0</code>. The console output is this:</p> <pre><code>[26/Jul/2016:19:10:26] ENGINE Listening for SIGTERM. [26/Jul/2016:19:10:26] ENGINE Listening for SIGHUP. [26/Jul/2016:19:10:26] ENGINE Listening for SIGUSR1. [26/Jul/2016:19:10:27] ENGINE Bus STARTING Warning (from warnings module): File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/cherrypy/_cpchecker.py", line 105 warnings.warn(msg) UserWarning: The Application mounted at '' has an empty config. [26/Jul/2016:19:10:27] ENGINE Started monitor thread '_TimeoutMonitor'. [26/Jul/2016:19:10:27] ENGINE Started monitor thread 'Autoreloader'. [26/Jul/2016:19:10:27] ENGINE Serving on http://0.0.0.0:8080 [26/Jul/2016:19:10:27] ENGINE Bus STARTED </code></pre> <p>I run my file using IDLE, and I am not using a firewall.</p>
1
2016-07-25T00:27:29Z
38,999,933
<p>The solution is mentioned in comments below the question so this answer is just for marking this question as answered.</p> <p>Solution: If you want to see your cherrypy application from another computer, find out an IP address on computer where cherrypy is running, using <code>ifconfig</code> on Unix/Linux or <code>ipconfig</code> on Windows. Then set this IP address to your cherrypy config instead of <code>127.0.0.1</code> or <code>0.0.0.0</code>.</p> <pre><code>cherrypy.config.update({'server.socket_host': '192.168.1.123'}) </code></pre> <p>As long as you're on the same network, you should be able to access the application on that IP/port that you set: <a href="http://192.168.1.123:8080/" rel="nofollow">http://192.168.1.123:8080/</a> (or similar)</p> <p>If you need to change IP and port, use this:</p> <pre><code>cherrypy.config.update({ 'server.socket_host' : '127.0.0.1', 'server.socket_port' : 9090, }) </code></pre>
0
2016-08-17T14:51:14Z
[ "python", "python-3.x", "cherrypy" ]
Quandl download wiki EOD stock prices from python - how to?
38,558,318
<ol> <li>Is there a way to do a partial download on Quandl for the Wiki EOD Stock Prices but for a given day in the past - not the most current date e.g. download for 2016-07-20?</li> </ol> <p>Entire database (too large): <a href="https://www.quandl.com/data/WIKI/documentation/bulk-download" rel="nofollow">https://www.quandl.com/data/WIKI/documentation/bulk-download</a></p> <p>Just the last day: <a href="https://www.quandl.com/api/v3/databases/WIKI/data?api_key=myAPIkey&amp;download_type=partial" rel="nofollow">https://www.quandl.com/api/v3/databases/WIKI/data?api_key=myAPIkey&amp;download_type=partial</a></p> <p>One day in the past for all stocks: ?????</p> <ol start="2"> <li>Can this download be triggered from python code to a specified folder? How would one do that?</li> </ol>
0
2016-07-25T00:50:09Z
38,581,313
<ol> <li><p>It does not seem possible according to Quandl. There is no parameter for the date. Only partial or complete.</p></li> <li><p>The python code is: </p></li> </ol> <p>import quandl quandl.ApiConfig.api_key = 'XXXXX' quandl.bulkdownload("WIKI",download_type="partial",filename="./WIKI.zip")</p>
0
2016-07-26T05:00:03Z
[ "python", "quandl" ]
print not working in while loop
38,558,327
<p>I want to check a some value using "time". However when I use the time function, the print is not working. The source code is below.</p> <pre><code>import time def display(): print "Something..." while(1): time.sleep(1) display() </code></pre> <p>My environment is windows 10, mingw, vim, python2.7.</p> <p>How know the solution?</p>
-3
2016-07-25T00:52:38Z
38,558,682
<pre><code>import time def display(something): print something index = 1 while(1): time.sleep(1) display(index) index += 1 </code></pre>
-1
2016-07-25T01:51:55Z
[ "python", "time", "while-loop" ]
Tkinter Text widget : Fetching Cursor Selection
38,558,405
<p>I have a text widget, and I have the text </p> <pre><code>this is some random text </code></pre> <p>With the keyboard cursor in the word "<code>random</code>". How can I get the start and end index of the cursor selection.</p> <p>Thanks in advance!</p>
-1
2016-07-25T01:07:24Z
38,558,437
<p>You can get the index of the start of the word by applying the modifier <code>"wordstart"</code> to an index. To get the end of the word, use <code>"wordend"</code>.</p> <p>For example:</p> <pre><code>start = text.index("insert wordstart") end = text.index("insert wordend") </code></pre>
0
2016-07-25T01:12:57Z
[ "python", "text", "indexing", "tkinter", "cursor" ]
How is it possible to take a slice this way?
38,558,428
<p>I'm taking a course in machine learning and there was a recommendation (about making a balancing of classes) to use the following string: </p> <pre><code>X_train_to_add = X_train[y_train.as_matrix() == 1, :][indices_to_add, :] </code></pre> <p>where <code>y_train</code> is a pandas dataframe (which is converted there to the numpy array via <code>as.matrix()</code>). I don't get how it is possible to use matrix as an index for slicing.</p>
5
2016-07-25T01:11:18Z
39,405,965
<p>It might help to break down the statement into its component parts. This statement is equivalent to the following sequence of statements:</p> <pre><code>y = y_train.as_matrix() row_mask = y == 1 X_masked = X_train[row_mask,:] X_train_to_add = X_masked[indices_to_add, :] </code></pre> <p>Let's look at a concrete example. Let's suppose <code>y</code>, <code>X_train</code>, and <code>indices_to_add</code> have the following values:</p> <pre><code>&gt;&gt;&gt; import numpy as np &gt;&gt;&gt; y = np.array([1, 2, -1, 1, 1]) &gt;&gt;&gt; X_train = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12], [13, 14, 15]]) &gt;&gt;&gt; indices_to_add = np.array([2, 0]) </code></pre> <p>First, we create a boolean array indicating which elements of <code>y</code> are equal to <code>1</code>, which we'll call the "row mask".</p> <pre><code>&gt;&gt;&gt; row_mask = y == 1 &gt;&gt;&gt; row_mask array([ True, False, False, True, True], dtype=bool) </code></pre> <p>Next, we use the row mask to select the rows of <code>X_train</code> such that the corresponding values of <code>row_mask</code> are <code>True</code> (or equivalently, the rows such that the corresponding values of <code>y</code> are equal to <code>1</code>).</p> <pre><code>&gt;&gt;&gt; X_masked = X_train[row_mask,:] &gt;&gt;&gt; X_masked array([[ 1, 2, 3], [10, 11, 12], [13, 14, 15]]) </code></pre> <p>Finally, we use an array of indices to select certain rows from the previous result. Note that these indices refer to rows of <code>X_masked</code>, not the original matrix <code>X_train</code>.</p> <pre><code>&gt;&gt;&gt; X_train_to_add = X_masked[indices_to_add,:] &gt;&gt;&gt; X_train_to_add array([[13, 14, 15], [ 1, 2, 3]]) </code></pre> <p>You can see some more examples of numpy indexing in the <a href="https://docs.scipy.org/doc/numpy/user/basics.indexing.html" rel="nofollow">documentation</a>.</p>
0
2016-09-09T07:21:35Z
[ "python", "numpy" ]
Manipulating/Replacing values in dictionaries within lists
38,558,511
<p>My data looks similar to the data shown below ('snippet.json'). I want to be able to replace values for example, for id:1, replace employee number to 2455. </p> <p>Data Snippet:</p> <blockquote> <p>{"employees": [{"level1":{"id":1, "firstname": "John", "employee number": 2343 },{"level1":{"id":2, "firstname": "Jane", "employee number": 5647 }}]}</p> </blockquote> <p>I understand that it is much easier to replace values when in the form of a list or a dictionary, so I did the following to convert it to a list. </p> <pre><code>import json viewer_string=open('snippet.json','r') data_str = viewer_string.read() data_list = [] data_list.append(data_str) </code></pre> <p>But this doesn't seem to be working. Is there anyway I could convert Snippet.json into a dictionary? Or is there another way to go about this? </p>
0
2016-07-25T01:24:37Z
38,559,256
<p>Since you are importing json, you might want to do something like below,</p> <pre><code>json_data = json.loads(viewer_string.read()) </code></pre> <p>you have your data in dict type and you can loop through and replace values as you wish. Make sure the file has valid json</p>
0
2016-07-25T03:25:12Z
[ "python", "json", "list", "dictionary" ]
Epoch conversion not working as expected
38,558,521
<p>Using the following code I want to convert the input date and time to epoch. The problem is I get an epoch output, but when I test it via conversion online (<a href="http://www.epochconverter.com/" rel="nofollow">http://www.epochconverter.com/</a>), the epoch does not translate to the date and time I input:</p> <pre><code>date_time2 = '09.03.1999' + " " + "13:44:17.000000" pattern2 = '%d.%m.%Y %H:%M:%S.%f' epoch2 = int(time.mktime(time.strptime(date_time2, pattern2))) print epoch2 </code></pre>
0
2016-07-25T01:26:31Z
38,558,696
<p>What is happening here:</p> <ul> <li><code>time.strptime</code> produces a <code>time.struct_time</code> which closely mirrors C's <code>tm</code> struct;</li> <li>The documentation of <a href="https://docs.python.org/2/library/time.html#time.mktime" rel="nofollow"><code>time.mktime</code></a> is then fairly clear that it produces a <strong>local time</strong> from a <code>struct_time</code>, not a GMT time.</li> </ul> <p>So instead you need a function that converts your <code>struct_time</code> into a GMT time. Such a function is hidden away a bit in python, in the <a href="https://docs.python.org/2/library/calendar.html#calendar.timegm" rel="nofollow"><code>calendar</code></a> module.</p> <p>Try instead:</p> <pre><code>date_time2 = '09.03.1999' + " " + "13:44:17.000000" pattern2 = '%d.%m.%Y %H:%M:%S.%f' # get a time structure tm = time.strptime(date_time2, pattern2) # convert to gmt gmt_epoch = int(calendar.timegm(tm)) </code></pre> <p>In this case we end up with:</p> <pre><code>&gt;&gt;&gt; gmt_epoch 920987057 </code></pre> <p>Plugging that into the website you've given produces that this is <strong>GMT:</strong> Tue, 09 Mar 1999 13:44:17 GMT</p>
1
2016-07-25T01:53:26Z
[ "python", "time", "epoch" ]
Epoch conversion not working as expected
38,558,521
<p>Using the following code I want to convert the input date and time to epoch. The problem is I get an epoch output, but when I test it via conversion online (<a href="http://www.epochconverter.com/" rel="nofollow">http://www.epochconverter.com/</a>), the epoch does not translate to the date and time I input:</p> <pre><code>date_time2 = '09.03.1999' + " " + "13:44:17.000000" pattern2 = '%d.%m.%Y %H:%M:%S.%f' epoch2 = int(time.mktime(time.strptime(date_time2, pattern2))) print epoch2 </code></pre>
0
2016-07-25T01:26:31Z
38,559,042
<p>(I already upvoted @donkopotamus' answer here: <a href="http://stackoverflow.com/a/38558696/42346">http://stackoverflow.com/a/38558696/42346</a>)</p> <p>Using this answer: <a href="http://stackoverflow.com/a/19527596/42346">http://stackoverflow.com/a/19527596/42346</a> we can see how you can convert your local time to GMT. This requires <a href="http://pytz.sourceforge.net/" rel="nofollow"><code>pytz</code></a>.</p> <pre><code>import datetime as dt import pytz naive_date = dt.datetime.strptime('09.03.1999' + " " + "13:44:17.000000", '%d.%m.%Y %H:%M:%S.%f') localtz = pytz.timezone('Hongkong') date_aware = localtz.localize(naive_date,is_dst=None) utc_date = date_aware.astimezone(pytz.utc) int(time.mktime(utc_date.utctimetuple())) </code></pre> <p>Result:</p> <pre><code>920987057 </code></pre> <p><a href="http://i.stack.imgur.com/6Hi7h.png" rel="nofollow"><img src="http://i.stack.imgur.com/6Hi7h.png" alt="enter image description here"></a></p>
1
2016-07-25T02:52:54Z
[ "python", "time", "epoch" ]
Probability grid matplotlib
38,558,613
<p>I want to obtain grid with values mapped onto colors. It should be like a probability distribution, where 1.0 corresponds to black and 0.0 to white, grey in between. Reading the answers <a href="http://stackoverflow.com/questions/7229971/2d-grid-data-visualization-in-python">here</a> I try it out for my case:</p> <pre><code>from matplotlib import mpl,pyplot import numpy as np zvals = np.zeros((10,5)) zvals[5,1] = 0.5 zvals[5,2] = 0.3 zvals[5,3] = 0.7 zvals[5,4] = 5.8 cmap = mpl.colors.LinearSegmentedColormap.from_list('my_colormap',['white','black'],256) img = pyplot.imshow(zvals,interpolation='nearest', cmap = cmap) pyplot.colorbar(img,cmap=cmap) pyplot.show() </code></pre> <p>I see the problem, because linear mapping treats maximal value from the 2D array as black. But array not necessarily contains value 1.0. </p> <p>How to set hard boundaries of 0.0 and 1.0, with smooth transition in between?</p>
1
2016-07-25T01:42:44Z
38,559,184
<p>Use the <code>vmin</code> and <code>vmax</code> arguments of <a href="http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.imshow" rel="nofollow"><code>imshow</code></a>:</p> <pre><code>img = pyplot.imshow(zvals, interpolation='nearest', cmap=cmap, vmin=0, vmax=1) </code></pre>
3
2016-07-25T03:14:44Z
[ "python", "numpy", "matplotlib" ]
BlockingSwitchOutError in debugger after upgrading to PyCharm 2016.2
38,558,637
<p>After upgrading from PyCharm 2016.1.4 to 2016.2, when running the debugger and setting any breakpoint, PyCharm halts in various places where I have no breakpoint set, and logs this to stderr:</p> <pre><code>Traceback (most recent call last): File "/usr/local/pycharm/debug-eggs/pycharm-debug.egg/_pydevd_bundle/pydevd_frame.py", line 539, in trace_dispatch self.do_wait_suspend(thread, frame, event, arg) File "/usr/local/pycharm/debug-eggs/pycharm-debug.egg/_pydevd_bundle/pydevd_frame.py", line 71, in do_wait_suspend self._args[0].do_wait_suspend(*args, **kwargs) File "/usr/local/pycharm/debug-eggs/pycharm-debug.egg/pydevd.py", line 714, in do_wait_suspend time.sleep(0.01) File "/home/jaza/mypyapp/mypyfile.py", line 999, in mypyfunc gevent.sleep(seconds) File "/usr/local/lib/python2.7/dist-packages/gevent/hub.py", line 194, in sleep hub.wait(loop.timer(seconds, ref=ref)) File "/usr/local/lib/python2.7/dist-packages/gevent/hub.py", line 630, in wait result = waiter.get() File "/usr/local/lib/python2.7/dist-packages/gevent/hub.py", line 878, in get return self.hub.switch() File "/usr/local/lib/python2.7/dist-packages/gevent/hub.py", line 608, in switch switch_out() File "/usr/local/lib/python2.7/dist-packages/gevent/hub.py", line 612, in switch_out raise BlockingSwitchOutError('Impossible to call blocking function in the event loop callback') BlockingSwitchOutError: Impossible to call blocking function in the event loop callback </code></pre> <p>OS: Linux Mint 17.3 (i.e. almost identical to Ubuntu 14.04). Using latest gevent (1.1.2).</p> <p>If I open my old PyCharm (i.e. 2016.1.4), and do the same thing - i.e. start the debugger, set a breakpoint, run my app - I don't get these errors, and PyCharm doesn't halt anywhere in the code except at my breakpoint.</p> <p>I also tried just "downgrading" the debugger, by renaming the <code>debug-eggs</code> directory and replacing it with a symlink to the old <code>debug-eggs</code> path, and then running the rest of PyCharm on the latest version. This didn't fix the problem, i.e. it still resulted in BlockingSwitchOutError being raised numerous times.</p> <p>Seems likely that this is a bug in PyCharm 2016.2. I've submitted a bug report to JetBrains for this, see <a href="https://youtrack.jetbrains.com/issue/PY-20183" rel="nofollow">https://youtrack.jetbrains.com/issue/PY-20183</a> . But posting here on SO as well, in case anyone sees a problem with the code in my app (the use of <code>gevent.sleep(seconds)</code> ?), meaning that the code happened to work before, but was going to break sooner or later.</p>
3
2016-07-25T01:46:49Z
38,579,291
<p>The solution posted by Elizaveta Shashkova on the PyCharm issue tracker at <a href="https://youtrack.jetbrains.com/issue/PY-20183" rel="nofollow">https://youtrack.jetbrains.com/issue/PY-20183</a> worked for me:</p> <blockquote> <p>The new feature has appeared in PyCharm: breakpoint thread suspend policy. You should go Run | View breakpoints, select the breakpoint and change its threads suspend policy: "Thread" or "All". Also you can set the default policy for all your breakpoints.</p> </blockquote> <p>After changing suspend policy from "All" to "Thread", debugger is no longer breaking outside of my breakpoints nor throwing <code>BlockingSwitchOutError</code>.</p> <p>And, re:</p> <blockquote> <p>Also do you have the setting "gevent compatible" turned on? <a href="https://www.jetbrains.com/help/pycharm/2016.1/python-debugger.html" rel="nofollow">https://www.jetbrains.com/help/pycharm/2016.1/python-debugger.html</a></p> </blockquote> <p>No, I don't have this turned on, and I fixed my issue without turning it on. But will try turning it on if I have similar issues in future.</p>
2
2016-07-26T00:20:46Z
[ "python", "debugging", "pycharm" ]
Generate a pandas dataframe from list of list
38,558,667
<p>I am wondering how to generate a pd DataFrame from a list of list which in this form:</p> <p>Input: </p> <pre><code>A=[['a','b','c'],['c','d','e'],['f','g','h']] </code></pre> <p>Output:(in a dataframe)</p> <pre><code>No content 0 'a' 0 'b' 0 'c' 1 'c' 1 'd' 1 'e' 2 'f' 2 'g' 2 'h' </code></pre>
1
2016-07-25T01:50:18Z
38,558,738
<p>You can try this:</p> <pre><code>import pandas as pd A1 = pd.DataFrame(A).stack().reset_index().drop('level_1', 1).rename(columns = {'level_0': "No", 0: "content"}) A1 # No content #0 0 a #1 0 b #2 0 c #3 1 c #4 1 d #5 1 e #6 2 f #7 2 g #8 2 h </code></pre> <p>Or you can flatten your list firstly and then construct data frame from it:</p> <pre><code>dicA = {"No":[], "content":[]} for i, s in enumerate(A): for e in s: dicA['No'].append(i) dicA['content'].append(e) import pandas as pd pd.DataFrame(dicA) # No content #0 0 a #1 0 b #2 0 c #3 1 c #4 1 d #5 1 e #6 2 f #7 2 g #8 2 h </code></pre>
1
2016-07-25T02:01:08Z
[ "python", "list", "pandas", "dictionary", "dataframe" ]
Generate a pandas dataframe from list of list
38,558,667
<p>I am wondering how to generate a pd DataFrame from a list of list which in this form:</p> <p>Input: </p> <pre><code>A=[['a','b','c'],['c','d','e'],['f','g','h']] </code></pre> <p>Output:(in a dataframe)</p> <pre><code>No content 0 'a' 0 'b' 0 'c' 1 'c' 1 'd' 1 'e' 2 'f' 2 'g' 2 'h' </code></pre>
1
2016-07-25T01:50:18Z
38,558,759
<p>You can melt the transpose of the dataframe to produce your desired result.</p> <pre><code>import pandas as pd &gt;&gt;&gt; pd.melt(pd.DataFrame(A).T, var_name='No.', value_name='content') No. content 0 0 a 1 0 b 2 0 c 3 1 c 4 1 d 5 1 e 6 2 f 7 2 g 8 2 h </code></pre>
2
2016-07-25T02:06:18Z
[ "python", "list", "pandas", "dictionary", "dataframe" ]
Generate a pandas dataframe from list of list
38,558,667
<p>I am wondering how to generate a pd DataFrame from a list of list which in this form:</p> <p>Input: </p> <pre><code>A=[['a','b','c'],['c','d','e'],['f','g','h']] </code></pre> <p>Output:(in a dataframe)</p> <pre><code>No content 0 'a' 0 'b' 0 'c' 1 'c' 1 'd' 1 'e' 2 'f' 2 'g' 2 'h' </code></pre>
1
2016-07-25T01:50:18Z
38,558,806
<p>Try this use zip() on your list:</p> <pre><code>df = pd.melt(pd.DataFrame(zip(*A))).rename(columns= {'variable':'no','value':'content' }) no content 0 0 a 1 0 b 2 0 c 3 1 c 4 1 d 5 1 e 6 2 f 7 2 g 8 2 h </code></pre>
0
2016-07-25T02:13:42Z
[ "python", "list", "pandas", "dictionary", "dataframe" ]
Tensorflow memory leak with Recurrent Neural Network
38,558,680
<p>I'm trying to build a simple Recurrent Neural Network model by using tensorflow on Mac OS X. It is just a toy model and size of input data doesn't exceed 3MB so it should not consume much of memory. However, when I run model, the memory usage significantly increases every training batch and goes above 10GB. It was for only two iterations. I couldn't run it more.</p> <p>Here's the whole code.</p> <pre><code>from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf import numpy as np from pympler import summary class RNN(): """The RNN model.""" #@profile def inference(self): """calculate outputs and loss for a single batch""" total_loss = 0.0 outputs = [] for i in range(self.batch_size): state = self.init_state outputs.append([]) loss = 0.0 for j in range(self.num_steps): state, output = self.next_state(self.x[i,j,:],state) outputs[i].append(output) loss += tf.square(self.y[i,j,:]-output) total_loss+=loss return outputs, total_loss / (self.batch_size*self.num_steps) def __init__(self, is_training, config): self.sess = sess = tf.Session() self.prev_see = prev_see = config.prev_see self.num_steps = num_steps = config.num_steps #maybe "self.num_hidden =" part could be removed self.num_hidden = num_hidden = config.num_hidden self.batch_size = config.batch_size self.epoch = config.epoch self.learning_rate = config.learning_rate self.summaries_dir = config.summaries_dir with tf.name_scope('placeholders'): self.x = tf.placeholder(tf.float32,[None,num_steps,config.prev_see], name='input-x') self.y = tf.placeholder(tf.float32, [None,num_steps,1],name='input-y') default_init_state = tf.zeros([num_hidden]) self.init_state = tf.placeholder_with_default(default_init_state,[num_hidden], name='state_placeholder') def weight_variable(self,shape): """Create a weight variable with appropriate initialization.""" initial = tf.truncated_normal(shape,stddev=0.1) return tf.Variable(initial) def bias_variable(self,shape): """Create a bias variable with appropriate initialization.""" initial = tf.constant(0.1,shape=shape) return tf.Variable(initial) def variable_summaries(self,var,name): """Attach a lot of summaries to a Tensor.""" with tf.name_scope('summaries'): mean = tf.reduce_mean(var) tf.scalar_summary('mean/'+name,mean) with tf.name_scope('stddev'): stddev = tf.sqrt(tf.reduce_sum(tf.square(var-mean))) tf.scalar_summary('stddev/'+name,stddev) tf.scalar_summary('max/'+name, tf.reduce_max(var)) tf.scalar_summary('min/'+name, tf.reduce_min(var)) tf.histogram_summary(name, var) #declare weight variables as property layer_name = 'rnn_layer' with tf.name_scope(layer_name): with tf.name_scope('U'): self.U = U = weight_variable(self,[prev_see,num_hidden]) variable_summaries(self,U,layer_name+'/U') with tf.name_scope('W'): self.W = W = weight_variable(self,[num_hidden,num_hidden]) variable_summaries(self,W,layer_name+'/W') with tf.name_scope('b_W'): self.b_W = b_W = bias_variable(self,[num_hidden]) variable_summaries(self,b_W,layer_name+'/b_W') with tf.name_scope('V'): self.V = V = weight_variable(self,[num_hidden,1]) variable_summaries(self,V,layer_name+'/V') with tf.name_scope('b_V'): self.b_V = b_V = bias_variable(self,[1]) variable_summaries(self,b_V,layer_name+'/b_V') self.merged = tf.merge_all_summaries() self.train_writer = tf.train.SummaryWriter(config.summaries_dir,sess.graph) tf.initialize_all_variables().run(session=sess) _,self.loss = self.inference() def next_state(self,x,s_prev): """calculate next state and output""" x = tf.reshape(x,[1,-1]) s_prev = tf.reshape(s_prev,[1,-1]) s_next = tf.tanh(tf.matmul(x,self.U)+tf.matmul(s_prev,self.W)+self.b_W) output = tf.matmul(s_next,self.V)+self.b_V return s_next, output #@profile def batch_train(self,feed_dict): """train the network for a single batch""" loss = self.loss train_step = tf.train.GradientDescentOptimizer(self.learning_rate).minimize(loss) summary,loss_value, _ = self.sess.run([self.merged,loss, train_step],feed_dict=feed_dict) #self.train_writer.add_summary(summary) print(loss_value) class TrainConfig(): """Train Config.""" total_steps = 245 test_ratio = 0.3 prev_see = 100 num_steps = int(round((total_steps-prev_see)*(1-test_ratio))) num_hidden = 10 batch_size = 5 epoch = 3 learning_rate = 0.1 summaries_dir = '/Users/Kyungsu/StockPrediction/log' class DebugConfig(): """For debugging memory leak.""" total_steps = 100 test_ratio = 0.3 prev_see = 100 num_steps = 10 num_hidden = 10 batch_size = 5 epoch = 2 learning_rate = 0.1 summaries_dir = '/Users/Kyungsu/StockPrediction/log' #@profile def run_epoch(m,x_data,y_data): num_batch = ((len(x_data)-1) // m.batch_size)+1 #num_batch = 100 for i in range(num_batch): x_batch = x_data[i*m.batch_size:(i+1)*m.batch_size,:,:] y_batch = y_data[i*m.batch_size:(i+1)*m.batch_size,:,:] feed_dict = {m.x:x_batch,m.y:y_batch} print("%dth/%dbatches"%(i+1,num_batch)) m.batch_train(feed_dict) def process_data(data,config): data_size = len(data) prev_see = config.prev_see num_steps = config.num_steps x = np.zeros((data_size,num_steps,prev_see)) y = np.zeros((data_size,num_steps,1)) for i in range(data_size): for j in range(num_steps-prev_see): x[i,j,:] = data[i,i:i+prev_see] y[i,j,0] = data[i,i+prev_see] return x,y #@profile def main(): train_config = TrainConfig() debug_config = DebugConfig() data = np.load('processed_data.npy') x,y = process_data(data,train_config) rnn_model = RNN(True,train_config) #training phase for i in range(rnn_model.epoch): print("%dth epoch"%(i+1)) run_epoch(rnn_model,x,y) main() </code></pre> <p>And following is the result of <a href="https://pypi.python.org/pypi/memory_profiler" rel="nofollow">memory_profiler</a>. Weird thing is, most of memory is allocated in <em>for loop</em>. (See line 163,135) I guess it means memory is leaking. </p> <pre><code> Line # Mem usage Increment Line Contents ================================================ 11 53.062 MiB 0.000 MiB @profile 12 def __init__(self, is_training, config): 13 53.875 MiB 0.812 MiB self.sess = sess = tf.Session() 14 15 53.875 MiB 0.000 MiB self.prev_see = prev_see = config.prev_see 16 53.875 MiB 0.000 MiB self.num_steps = num_steps = config.num_steps 17 #maybe "self.num_hidden =" part could be removed 18 53.875 MiB 0.000 MiB self.num_hidden = num_hidden = config.num_hidden 19 53.875 MiB 0.000 MiB self.batch_size = config.batch_size 20 53.875 MiB 0.000 MiB self.epoch = config.epoch 21 53.875 MiB 0.000 MiB self.learning_rate = config.learning_rate 22 53.875 MiB 0.000 MiB self.summaries_dir = config.summaries_dir 23 24 53.875 MiB 0.000 MiB with tf.name_scope('input'): 25 53.875 MiB 0.000 MiB self.x = tf.placeholder(tf.float32,[None,num_steps,config.prev_see], 26 53.957 MiB 0.082 MiB name='input-x') 27 53.973 MiB 0.016 MiB self.y = tf.placeholder(tf.float32, [None,num_steps,1],name='input-y') 28 29 55.316 MiB 1.344 MiB def weight_variable(self,shape): 30 """Create a weight variable with appropriate initialization.""" 31 55.371 MiB 0.055 MiB initial = tf.truncated_normal(shape,stddev=0.1) 32 55.414 MiB 0.043 MiB return tf.Variable(initial) 33 34 55.707 MiB 0.293 MiB def bias_variable(self,shape): 35 """Create a bias variable with appropriate initialization.""" 36 55.727 MiB 0.020 MiB initial = tf.constant(0.1,shape=shape) 37 55.754 MiB 0.027 MiB return tf.Variable(initial) 38 39 55.754 MiB 0.000 MiB def variable_summaries(self,var,name): 40 """Attach a lot of summaries to a Tensor.""" 41 55.754 MiB 0.000 MiB with tf.name_scope('summaries'): 42 55.801 MiB 0.047 MiB mean = tf.reduce_mean(var) 43 55.824 MiB 0.023 MiB tf.scalar_summary('mean/'+name,mean) 44 55.824 MiB 0.000 MiB with tf.name_scope('stddev'): 45 55.883 MiB 0.059 MiB stddev = tf.sqrt(tf.reduce_sum(tf.square(var-mean))) 46 55.906 MiB 0.023 MiB tf.scalar_summary('stddev/'+name,stddev) 47 55.969 MiB 0.062 MiB tf.scalar_summary('max/'+name, tf.reduce_max(var)) 48 56.027 MiB 0.059 MiB tf.scalar_summary('min/'+name, tf.reduce_min(var)) 49 56.055 MiB 0.027 MiB tf.histogram_summary(name, var) 50 51 #declare weight variables as property 52 53.973 MiB -2.082 MiB layer_name = 'rnn_layer' 53 53.973 MiB 0.000 MiB with tf.name_scope(layer_name): 54 53.973 MiB 0.000 MiB with tf.name_scope('U'): 55 54.230 MiB 0.258 MiB self.U = U = weight_variable(self,[prev_see,num_hidden]) 56 54.598 MiB 0.367 MiB variable_summaries(self,U,layer_name+'/U') 57 54.598 MiB 0.000 MiB with tf.name_scope('W'): 58 54.691 MiB 0.094 MiB self.W = W = weight_variable(self,[num_hidden,num_hidden]) 59 54.961 MiB 0.270 MiB variable_summaries(self,W,layer_name+'/W') 60 54.961 MiB 0.000 MiB with tf.name_scope('b_W'): 61 55.012 MiB 0.051 MiB self.b_W = b_W = bias_variable(self,[num_hidden]) 62 55.316 MiB 0.305 MiB variable_summaries(self,b_W,layer_name+'/b_W') 63 55.316 MiB 0.000 MiB with tf.name_scope('V'): 64 55.414 MiB 0.098 MiB self.V = V = weight_variable(self,[num_hidden,1]) 65 55.707 MiB 0.293 MiB variable_summaries(self,V,layer_name+'/V') 66 55.707 MiB 0.000 MiB with tf.name_scope('b_V'): 67 55.754 MiB 0.047 MiB self.b_V = b_V = bias_variable(self,[1]) 68 56.055 MiB 0.301 MiB variable_summaries(self,b_V,layer_name+'/b_V') 69 56.055 MiB 0.000 MiB self.merged = tf.merge_all_summaries() 70 60.348 MiB 4.293 MiB self.train_writer = tf.train.SummaryWriter(config.summaries_dir,sess.graph) 71 62.496 MiB 2.148 MiB tf.initialize_all_variables().run(session=sess) Filename: rnn.py Line # Mem usage Increment Line Contents ================================================ 82 3013.336 MiB 0.000 MiB @profile 83 def inference(self): 84 """calculate outputs and loss for a single batch""" 85 3013.336 MiB 0.000 MiB total_loss = 0.0 86 3013.336 MiB 0.000 MiB outputs = [] 87 3022.352 MiB 9.016 MiB for i in range(self.batch_size): 88 3020.441 MiB -1.910 MiB state = tf.zeros([self.num_hidden]) 89 3020.441 MiB 0.000 MiB outputs.append([]) 90 3020.441 MiB 0.000 MiB loss = 0.0 91 3022.348 MiB 1.906 MiB for j in range(self.num_steps): 92 3022.285 MiB -0.062 MiB state, output = self.next_state(self.x[i,j,:],state) 93 3022.285 MiB 0.000 MiB outputs[i].append(output) 94 3022.348 MiB 0.062 MiB loss += tf.square(self.y[i,j,:]-output) 95 3022.352 MiB 0.004 MiB total_loss+=loss 96 3022.371 MiB 0.020 MiB return outputs, total_loss / (self.batch_size*self.num_steps) Filename: rnn.py Line # Mem usage Increment Line Contents ================================================ 97 3013.336 MiB 0.000 MiB @profile 98 def batch_train(self,feed_dict): 99 """train the network for a single batch""" 100 3022.371 MiB 9.035 MiB _, loss = self.inference() 101 3051.781 MiB 29.410 MiB train_step = tf.train.GradientDescentOptimizer(self.learning_rate).minimize(loss) 102 3149.891 MiB 98.109 MiB summary,loss_value, _ = self.sess.run([self.merged,loss, train_step],feed_dict=feed_dict) 103 #self.train_writer.add_summary(summary) 104 3149.891 MiB 0.000 MiB print(loss_value) Filename: rnn.py Line # Mem usage Increment Line Contents ================================================ 131 1582.758 MiB 0.000 MiB @profile 132 def run_epoch(m,x_data,y_data): 133 1582.758 MiB 0.000 MiB num_batch = ((len(x_data)-1) // m.batch_size)+1 134 #num_batch = 100 135 3149.895 MiB 1567.137 MiB for i in range(num_batch): 136 3013.336 MiB -136.559 MiB x_batch = x_data[i*m.batch_size:(i+1)*m.batch_size,:,:] 137 3013.336 MiB 0.000 MiB y_batch = y_data[i*m.batch_size:(i+1)*m.batch_size,:,:] 138 3013.336 MiB 0.000 MiB feed_dict = {m.x:x_batch,m.y:y_batch} 139 3013.336 MiB 0.000 MiB print("%dth/%dbatches"%(i+1,num_batch)) 140 3149.891 MiB 136.555 MiB m.batch_train(feed_dict) Filename: rnn.py Line # Mem usage Increment Line Contents ================================================ 154 52.914 MiB 0.000 MiB @profile 155 def main(): 156 52.914 MiB 0.000 MiB train_config = TrainConfig() 157 52.914 MiB 0.000 MiB debug_config = DebugConfig() 158 53.059 MiB 0.145 MiB data = np.load('processed_data.npy') 159 53.062 MiB 0.004 MiB x,y = process_data(data,debug_config) 160 62.496 MiB 9.434 MiB rnn_model = RNN(True,debug_config) 161 162 #training phase 163 3149.898 MiB 3087.402 MiB for i in range(rnn_model.epoch): 164 1582.758 MiB -1567.141 MiB print("%dth epoch"%(i+1)) 165 3149.898 MiB 1567.141 MiB run_epoch(rnn_model,x,y) </code></pre> <p>This problem was not occured when I tried simple <a href="https://www.tensorflow.org/versions/r0.9/tutorials/mnist/beginners/index.html" rel="nofollow">MNIST model</a> from tensorflow tutorial. So it should be related with RNN model. Also, I could reproduce this problem on Ubuntu 14.04, so I don't think this problem is caused by OS X things. Thank you for reading. </p>
0
2016-07-25T01:51:40Z
38,564,534
<p>I think the problem is that this line</p> <pre><code>train_step = tf.train.GradientDescentOptimizer(self.learning_rate).minimize(loss) </code></pre> <p>occurs in your batch_train function, so on every iteration, a <strong>new</strong> GradientDescentOptimizer is created. Try moving this to your model's init function just after you define the loss and refer to self.train_step in your batch_train function instead. </p>
0
2016-07-25T09:49:34Z
[ "python", "memory-leaks", "tensorflow", "recurrent-neural-network" ]
Using pytube library to download youtube links from csv
38,558,744
<p>I'm trying to use the <a href="https://github.com/nficano/pytube" rel="nofollow">pytube library</a> to download a bunch of links I have on a .csv file.</p> <p><strong>EDIT:</strong></p> <p><strong>WORKING CODE</strong>:</p> <pre><code> import sys reload(sys) sys.setdefaultencoding('Cp1252') import os.path from pytube import YouTube from pprint import pprint import csv with open('onedialectic.csv', 'rb') as f: reader = csv.reader(f) for row in reader: try: yt = YouTube(row[1]) path = os.path.join('/videos/',row[0]) path2 = os.path.join(path + '.mp4') print(path2) if not os.path.exists(path2) : print(row[0] + '\n') pprint(yt.get_videos()) yt.set_filename(row[0]) video = yt.get('mp4', '360p') video.download('/videos') except Exception as e: print("Passing on exception %s", e) continue </code></pre>
2
2016-07-25T02:02:54Z
38,559,250
<p>To install it you need to use</p> <pre><code>pip install pytube </code></pre> <p>and then in your code run</p> <pre><code>from pytube import YouTube </code></pre> <p>I haven't seen any code examples of using this with csv though, are you sure it's supported?</p> <p>You can download via command line directly using e.g.</p> <pre><code>$ pytube -e mp4 -r 720p -f Dancing Scene from Pulp Fiction http://www.youtube.com/watch?v=Ik-RsDGPI5Y </code></pre> <p><code>-e</code>, <code>-f</code> and <code>-r</code> are optional, (extension, filename and resolution)</p> <p>However for you I would suggest maybe the best thing is to put them all in a playlist and then use Jordan Mear's excellent <a href="https://github.com/jordoncm/youtube-dl-playlist" rel="nofollow">Python Youtube Playlist Downloader</a></p> <p>On a footnote, usually all [external] libraries need to be imported. You can read more about importing <a class='doc-link' href="http://stackoverflow.com/documentation/python/249/importing-modules/893/importing-a-module#t=201607250412491908498">here</a></p> <p>You could maybe do something like this OR use <a class='doc-link' href="http://stackoverflow.com/documentation/numpy/823/introduction-to-numpy/3905/installation-on-windows#t=201607250808587096588">numpy</a></p> <pre><code>import csv from pytube import YouTube vidcsvreader = csv.reader(open("videos.csv"), delimiter=",") header1 = vidcsvreader.next() #header for id, url in vidcsvreader: yt = url #assign url to var #set resolution and filetype video = yt.get('mp4', '720p') # set a destination directory for download video.download('/tmp/') break </code></pre>
3
2016-07-25T03:24:18Z
[ "python", "csv" ]
Django: Reverse for 'delete' with arguments '(49,)' and keyword arguments '{}' not found. 1 pattern(s) tried: ['tidbit/delete_tidbit/']
38,558,755
<p>Can't figure out how to solve this error</p> <p>Here is the urls.py snippet:</p> <pre><code>urlpatterns = [ ... url(r'^delete_tidbit/', views.delete_tidbit, name='delete'), ... ] </code></pre> <p>The view:</p> <pre><code>def delete_tidbit(request, pk): tidbit = Tidbit.objects.get(pk=pk) tidbit.delete() return HttpResponseRedirect(request.META.get('HTTP_REFERER')) </code></pre> <p>And the portion of the template that raises this error:</p> <pre><code>&lt;a href="{% url 'delete' tidbit.pk %}"&gt; </code></pre>
1
2016-07-25T02:04:59Z
38,558,779
<p>The issue is here:</p> <pre><code>url(r'^delete_tidbit/', views.delete_tidbit, name='delete'), </code></pre> <p>This URL doesn't accept an argument, where as you are trying to give it one.</p> <p>Try this instead:</p> <pre><code>url(r'^delete_tidbit/(?P&lt;pk&gt;.*)', views.delete_tidbit, name='delete'), </code></pre> <hr> <p><strong>But beware</strong>: you are accepting GET requests to delete items in your database, any crawler coming across those links may try to follow them and inadvertently delete your data. Consider using a GET that delivers a form to be POSTed to ensure an actual user is doing the action.</p>
2
2016-07-25T02:09:32Z
[ "python", "django", "backend" ]
Using pandas and EWMA
38,558,763
<p>I am accustomed to exponential moving average (EMA) being calculated the <a href="http://stockcharts.com/school/doku.php?id=chart_school:technical_indicators:moving_averages" rel="nofollow">following</a> way:</p> <pre><code>SMA: 10 period sum / 10 Multiplier: (2 / (Time periods + 1) ) = (2 / (10 + 1) ) = 0.1818 (18.18%) EMA: {Close - EMA(previous day)} x multiplier + EMA(previous day). </code></pre> <p>Yet when I run <code>pd.ewma(df['Close'])</code> I do not see the output that matches this approach.</p> <p>The following code gives me the answer I am expecting, but takes a bit longer to run.</p> <p>Anyone have any pointers on what is the proper way to leverage this library to give me the output I am expecting?</p> <pre><code>import pandas.io.data as web import datetime import pandas as pd start = datetime.datetime(2010, 1, 1) end = datetime.datetime.today() f = web.DataReader("SPY", 'yahoo', start, end) f['sma']=pd.rolling_mean(f['Adj Close'],10) days=10. alpha=(2./(days+1.)) d={} for x in f[(f['sma']&gt;0)].index: if len(d)==0: d[x] = f[(f.index==x)]['sma'].values[0] else: d[x] = (f[(f.index==x)]['Adj Close'].values[0] - d[dt_prior])*alpha + d[dt_prior] dt_prior = x pd.Series(d) </code></pre>
0
2016-07-25T02:07:21Z
38,563,432
<p>I think you were almost on there on your own. </p> <pre><code>e = f['Adj Close'].ewm(span=10, min_periods=10) </code></pre> <p>will generate what you are looking for. You may need to play around with adjust=True and other <a href="http://pandas.pydata.org/pandas-docs/version/0.17.0/generated/pandas.ewma.html" rel="nofollow">parameters</a> to get it to exactly match the results of your for loop. But if you compare</p> <pre><code>e.tail(10) d.tail(10) </code></pre> <p>you'll see that the (possibly different) starting point of the ewma doesn't matter anymore and the latest results match exactly. </p>
0
2016-07-25T08:56:13Z
[ "python", "pandas" ]
How to call a model method, using the object as parameter in Django?
38,558,808
<p>I want to generate a table on my template, showing some data that I get from a method declared on my Task class</p> <h1>models.py</h1> <pre><code>class Task(models.Model): ... def check_if_finished(self): resp = requests.get( 'http://my.rest.api/tasks/view/{}'.format(self.task_id)) resp_data = resp.json() resp_finished = resp_data['task']['started_on'] if resp_finished is None: return False else: return resp_finished </code></pre> <p>I know that there is no sense in calling a method on template, but what do I need to use to show this data?</p> <h1>template.html</h1> <blockquote> <p>{{ task.is_finished(task.task_id) }}</p> </blockquote>
0
2016-07-25T02:14:07Z
38,559,010
<p>I don't fully understand your question, why can't you just sent in task_id as a parameter?</p> <pre><code>class Task(models.Model): ... def check_if_finished(self, task_id): resp = requests.get( 'http://my.rest.api/tasks/view/{}'.format(task_id)) resp_data = resp.json() resp_finished = resp_data['task']['started_on'] if resp_finished is None: return False else: return resp_finished </code></pre> <p>then call it anytime:</p> <blockquote> <p>{{ task.check_if_finished(task.task_id) }}</p> </blockquote> <p>Could also make task_id an optional parameter.</p> <pre><code>def check_if_finished(self, task_id=None): task_id = task_id or self.task_id resp = requests.get... </code></pre> <p>I'm not sure why you wouldn't want to use the task_id on the instance though. If you never will then maybe it should be a static method?</p> <pre><code>@staticmethod def check_if_finished(cls, task_id): ... </code></pre> <p>I don't think Django models prevent any of these options. Hopefully something there was helpful, else I need a bit more information and what you are trying to accomplish.</p> <p>Edit: Django templates don't allow calling function/methods with arguments. You need to <a href="https://docs.djangoproject.com/en/dev/howto/custom-template-tags/#howto-custom-template-tags" rel="nofollow">create a custom template tag</a> or just call the function in the view and send the result to the template. <a href="http://stackoverflow.com/questions/1419183/how-to-pass-an-argument-to-a-method-on-a-template-variable-in-django">See previous question</a>.</p>
0
2016-07-25T02:48:39Z
[ "python", "django" ]
How to call a model method, using the object as parameter in Django?
38,558,808
<p>I want to generate a table on my template, showing some data that I get from a method declared on my Task class</p> <h1>models.py</h1> <pre><code>class Task(models.Model): ... def check_if_finished(self): resp = requests.get( 'http://my.rest.api/tasks/view/{}'.format(self.task_id)) resp_data = resp.json() resp_finished = resp_data['task']['started_on'] if resp_finished is None: return False else: return resp_finished </code></pre> <p>I know that there is no sense in calling a method on template, but what do I need to use to show this data?</p> <h1>template.html</h1> <blockquote> <p>{{ task.is_finished(task.task_id) }}</p> </blockquote>
0
2016-07-25T02:14:07Z
38,561,263
<p>When you write a model method you pass on <code>self</code> as parameter, which obviously refers to instance itself. Change your model method to something like this</p> <pre><code>class Task(models.Model): fields def is_finished(self): return appropriate boolean from here </code></pre> <p>Now in your template you can use this simply as <code>{{ task.is_finished }}</code>. Notice that I am not passing any <code>id</code> as a parameter. This is because, when writing a model method you pass <code>self</code> as parameter which refers to instance on which method is being called.</p> <p>I hope this makes sense to you and helps you understand model methods in a simple way.</p>
1
2016-07-25T06:45:55Z
[ "python", "django" ]
Hashing raw bytes in Python and Java produces different results
38,558,820
<p>I'm trying to <strong>replicate the behavior of a Python 2.7 function in Java</strong>, but I'm getting different results when running a (seemingly) identical sequence of bytes through a SHA-256 hash. The bytes are generated by manipulating a very large integer (exactly 2048 bits long) in a specific way (2nd line of my Python code example).</p> <p>For my examples, the original 2048-bit integer is stored as <code>big_int</code> and <code>bigInt</code> in Python and Java respectively, and both variables contain the same number.</p> <p>Python2 code I'm trying to replicate:</p> <pre><code>raw_big_int = ("%x" % big_int).decode("hex") buff = struct.pack("&gt;i", len(raw_big_int) + 1) + "\x00" + raw_big_int pprint("Buffer contains: " + buff) pprint("Encoded: " + buff.encode("hex").upper()) digest = hashlib.sha256(buff).digest() pprint("Digest contains: " + digest) pprint("Encoded: " + digest.encode("hex").upper()) </code></pre> <p>Running this code prints the following (note that <strong>the only result I'm actually interested in is the last one - the hex-encoded digest</strong>. The other 3 prints are just to see what's going on under the hood):</p> <pre class="lang-none prettyprint-override"><code>'Buffer contains: \x00\x00\x01\x01\x00\xe3\xbb\xd3\x84\x94P\xff\x9c\'\xd0P\xf2\xf0s,a^\xf0i\xac~\xeb\xb9_\xb0m\xa2&amp;f\x8d~W\xa0\xb3\xcd\xf9\xf0\xa8\xa2\x8f\x85\x02\xd4&amp;\x7f\xfc\xe8\xd0\xf2\xe2y"\xd0\x84ck\xc2\x18\xad\xf6\x81\xb1\xb0q\x19\xabd\x1b&gt;\xc8$g\xd7\xd2g\xe01\xd4r\xa3\x86"+N\\\x8c\n\xb7q\x1c \x0c\xa8\xbcW\x9bt\xb0\xae\xff\xc3\x8aG\x80\xb6\x9a}\xd9*\x9f\x10\x14\x14\xcc\xc0\xb6\xa9\x18*\x01/eC\x0eQ\x1b]\n\xc2\x1f\x9e\xb6\x8d\xbfb\xc7\xce\x0c\xa1\xa3\x82\x98H\x85\xa1\\\xb2\xf1\'\xafmX|\x82\xe7%\x8f\x0eT\xaa\xe4\x04*\x91\xd9\xf4e\xf7\x8c\xd6\xe5\x84\xa8\x01*\x86\x1cx\x8c\xf0d\x9cOs\xebh\xbc1\xd6\'\xb1\xb0\xcfy\xd7(\x8b\xeaIf6\xb4\xb7p\xcdgc\xca\xbb\x94\x01\xb5&amp;\xd7M\xf9\x9co\xf3\x10\x87U\xc3jB3?vv\xc4JY\xc9&gt;\xa3cec\x01\x86\xe9c\x81F-\x1d\x0f\xdd\xbf\xe8\xe9k\xbd\xe7c5' 'Encoded: 0000010100E3BBD3849450FF9C27D050F2F0732C615EF069AC7EEBB95FB06DA226668D7E57A0B3CDF9F0A8A28F8502D4267FFCE8D0F2E27922D084636BC218ADF681B1B07119AB641B3EC82467D7D267E031D472A386222B4E5C8C0AB7711C200CA8BC579B74B0AEFFC38A4780B69A7DD92A9F101414CCC0B6A9182A012F65430E511B5D0AC21F9EB68DBF62C7CE0CA1A382984885A15CB2F127AF6D587C82E7258F0E54AAE4042A91D9F465F78CD6E584A8012A861C788CF0649C4F73EB68BC31D627B1B0CF79D7288BEA496636B4B770CD6763CABB9401B526D74DF99C6FF3108755C36A42333F7676C44A59C93EA36365630186E96381462D1D0FDDBFE8E96BBDE76335' 'Digest contains: Q\xf9\xb9\xaf\xe1\xbey\xdc\xfa\xc4.\xa9 \xfckz\xfeB\xa0&gt;\xb3\xd6\xd0*S\xff\xe1\xe5*\xf0\xa3i' 'Encoded: 51F9B9AFE1BE79DCFAC42EA920FC6B7AFE42A03EB3D6D02A53FFE1E52AF0A369' </code></pre> <p>Now, below is my Java code so far. When I test it, I get the same value for the input buffer, but a different value for the digest. (<code>bigInt</code> contains a <code>BigInteger</code> object containing the same number as <code>big_int</code> in the Python example above)</p> <pre><code>byte[] rawBigInt = bigInt.toByteArray(); ByteBuffer buff = ByteBuffer.allocate(rawBigInt.length + 4); buff.order(ByteOrder.BIG_ENDIAN); buff.putInt(rawBigInt.length).put(rawBigInt); System.out.print("Buffer contains: "); System.out.println( DatatypeConverter.printHexBinary(buff.array()) ); MessageDigest hash = MessageDigest.getInstance("SHA-256"); hash.update(buff); byte[] digest = hash.digest(); System.out.print("Digest contains: "); System.out.println( DatatypeConverter.printHexBinary(digest) ); </code></pre> <p>Notice that in my Python example, I started the buffer off with <code>len(raw_big_int) + 1</code> packed, where in Java I started with just <code>rawBigInt.length</code>. I also omitted the extra 0-byte (<code>"\x00"</code>) when writing in Java. I did both of these for the same reason - in my tests, calling <code>toByteArray()</code> on a <code>BigInteger</code> returned a <code>byte</code> array <strong>already beginning with a 0-byte</strong> that was exactly 1 byte longer than Python's byte sequence. So, at least in my tests, <code>len(raw_big_int) + 1</code> equaled <code>rawBigInt.length</code>, since <code>rawBigInt</code> began with a 0-byte and <code>raw_big_int</code> did not.</p> <p>Alright, that aside, here is the Java code's output:</p> <pre class="lang-none prettyprint-override"><code>Buffer contains: 0000010100E3BBD3849450FF9C27D050F2F0732C615EF069AC7EEBB95FB06DA226668D7E57A0B3CDF9F0A8A28F8502D4267FFCE8D0F2E27922D084636BC218ADF681B1B07119AB641B3EC82467D7D267E031D472A386222B4E5C8C0AB7711C200CA8BC579B74B0AEFFC38A4780B69A7DD92A9F101414CCC0B6A9182A012F65430E511B5D0AC21F9EB68DBF62C7CE0CA1A382984885A15CB2F127AF6D587C82E7258F0E54AAE4042A91D9F465F78CD6E584A8012A861C788CF0649C4F73EB68BC31D627B1B0CF79D7288BEA496636B4B770CD6763CABB9401B526D74DF99C6FF3108755C36A42333F7676C44A59C93EA36365630186E96381462D1D0FDDBFE8E96BBDE76335 Digest contains: E3B0C44298FC1C149AFBF4C8996FB92427AE41E4649B934CA495991B7852B855 </code></pre> <p>As you can see, the buffer contents appear the same in both Python and Java, but the digests are obviously different. Can someone point out where I'm going wrong?</p> <p>I suspect it has something to do with the strange way Python seems to store bytes - the variables <code>raw_big_int</code> and <code>buff</code> show as type <code>str</code> in the interpreter, and when printed out by themselves have that strange format with the '\x's that is <em>almost</em> the same as the bytes themselves in some places, but is utter gibberish in others. I don't have enough Python experience to understand exactly what's going on here, and my searches have turned up fruitless.</p> <p>Also, since I'm trying to port the Python code into Java, I can't just change the Python - my goal is to write Java code that takes the same input and produces the same output. I've searched around (<a href="http://stackoverflow.com/questions/24554946/android-java-method-equivalent-to-python-hmac-sha256-in-hex">this question</a> in particular seemed related) but didn't find anything to help me out. Thanks in advance, if for nothing else than for reading this long-winded question! :)</p>
0
2016-07-25T02:15:36Z
38,558,996
<p>In Java, you've got the data in the buffer, but the cursor positions are all wrong. After you've written your data to the ByteBuffer it looks like this, where the <em>x</em>'s represent your data and the <em>0</em>'s are unwritten bytes in the buffer:</p> <pre><code>xxxxxxxxxxxxxxxxxxxx00000000000000000000000000000000000000000 ^ position ^ limit </code></pre> <p>The cursor is positioned after the data you've written. A read at this point will read from <code>position</code> to <code>limit</code>, which is the bytes you haven't written.</p> <p>Instead, you want this:</p> <pre><code>xxxxxxxxxxxxxxxxxxxx00000000000000000000000000000000000000000 ^ position ^ limit </code></pre> <p>where the position is 0 and the limit is the number of bytes you've written. To get there, call <a href="https://docs.oracle.com/javase/8/docs/api/java/nio/Buffer.html#flip--" rel="nofollow"><code>flip()</code></a>. Flipping a buffer conceptually switches it from write mode to read mode. I say "conceptually" because ByteBuffers don't have explicit read and write modes, but you should think of them as if they do.</p> <p>(The opposite operation is <a href="https://docs.oracle.com/javase/8/docs/api/java/nio/ByteBuffer.html#compact--" rel="nofollow"><code>compact()</code></a>, which goes back to read mode.)</p>
2
2016-07-25T02:46:33Z
[ "java", "python", "bytebuffer", "hashlib", "message-digest" ]
Use list/set comprehension merely as a "for" loop?
38,558,834
<p>I am creating a set of NUM_RECORDS tuples in Python. This is my code.</p> <pre><code>record_key_list = {(choice(tuple(studentID_list)), choice(tuple(courseID_list)), randint(2012, 2016), choice(semesters), choice(grades)[0]) for no_use in range(NUM_RECORDS)} </code></pre> <p>An alternative is to code the problem like this.</p> <pre><code>record_key_list = set() while len(record_key_list) &lt; NUM_RECORDS: record_key_list.add((choice(tuple(studentID_list)), choice(tuple(courseID_list)), randint(2012, 2016), choice(semesters), choice(grades)[0])) </code></pre> <p>I timed the two code snippets and they are roughly the same as fast for 20000 records. I prefer the first version of the code stylistically. </p> <p>Is the first version of the code a correct usage of set comprehension? Or should I always stick to the second method?</p> <p>EDIT: Improved formatting as suggested. I mostly just copied and pasted from the IDE. Sorry about that, guys. </p>
0
2016-07-25T02:17:47Z
38,839,057
<p>The first code snippet looks totally fine. If anything, I would extract the record creation to a function for clarity and easier refactoring.</p> <pre><code>def random_record(): studentID = choice(studentID_list) courseID = choice(courseID_list) year = randint(2012, 2016) semester = choice(semesters) grade = choice(grades)[0] return (studentID, courseID, year, semester, grade) # ... record_key_list = {random_record() for _ in range(NUM_RECORDS)} </code></pre>
1
2016-08-08T21:51:05Z
[ "python", "python-2.7", "list-comprehension", "set-comprehension" ]
Cannot create dictionary with tuples and values? (list indices must be integers, not str)
38,558,871
<pre><code>q_values_table = {} light = ['red', 'green'] v_actions = ['None','forward','left','right'] for i in v_actions: for j in light: for k in v_actions: for l in v_actions: for m in v_actions: q_values_table[v_actions[i],light[j],v_actions[k],v_actions[l],v_actions[m]] = None print q_values_table </code></pre> <p>I want my output be like <code>{('right','red','forward','right','left') : None}</code> for all the values.</p> <p>But I'm getting this error <code>list indices must be integers, not str</code></p>
1
2016-07-25T02:23:27Z
38,558,888
<p>When you iterate a <code>list</code>, you get values, not indices. If you want indices, use <code>range</code>:</p> <pre><code>for i in range(len(v_actions)): ... </code></pre> <p>If you want indices and values, use <code>enumerate</code>:</p> <pre><code>for i, value in enumerate(v_actions): ... </code></pre> <p>As it stands, you are attempt to access list elements using strings that are contained in the list as an index.</p>
2
2016-07-25T02:28:17Z
[ "python", "python-2.7" ]
Cannot create dictionary with tuples and values? (list indices must be integers, not str)
38,558,871
<pre><code>q_values_table = {} light = ['red', 'green'] v_actions = ['None','forward','left','right'] for i in v_actions: for j in light: for k in v_actions: for l in v_actions: for m in v_actions: q_values_table[v_actions[i],light[j],v_actions[k],v_actions[l],v_actions[m]] = None print q_values_table </code></pre> <p>I want my output be like <code>{('right','red','forward','right','left') : None}</code> for all the values.</p> <p>But I'm getting this error <code>list indices must be integers, not str</code></p>
1
2016-07-25T02:23:27Z
38,558,890
<p>just replace the last line with:</p> <p><code>q_values_table[ i, j, k, l, m ] = None</code></p>
1
2016-07-25T02:28:53Z
[ "python", "python-2.7" ]
Cannot create dictionary with tuples and values? (list indices must be integers, not str)
38,558,871
<pre><code>q_values_table = {} light = ['red', 'green'] v_actions = ['None','forward','left','right'] for i in v_actions: for j in light: for k in v_actions: for l in v_actions: for m in v_actions: q_values_table[v_actions[i],light[j],v_actions[k],v_actions[l],v_actions[m]] = None print q_values_table </code></pre> <p>I want my output be like <code>{('right','red','forward','right','left') : None}</code> for all the values.</p> <p>But I'm getting this error <code>list indices must be integers, not str</code></p>
1
2016-07-25T02:23:27Z
38,558,904
<p>You can also use range(len(lst)) to just iterate over the indices of the list:</p> <pre><code>q_values_table = {} light = ['red', 'green'] v_actions = ['None','forward','left','right'] for i in range(len(v_actions)): for j in range(len(light)): for k in range(len(v_actions)): for l in range(len(v_actions)): for m in range(len(v_actions)): q_values_table[v_actions[i],light[j],v_actions[k],v_actions[l],v_actions[m]] = None print q_values_table </code></pre> <p>This is a bit more verbose than the other options presented but seems to be what you were intending to do: iterate over the indices of a list.</p>
0
2016-07-25T02:31:00Z
[ "python", "python-2.7" ]
Why gevent can speed up requests to download?
38,558,898
<p>I think <code>requests.get</code> should be block, so there should be no difference between run and run2.</p> <pre><code>import sys import gevent import requests from gevent import monkey monkey.patch_all() def download(): requests.get('http://www.baidu.com').status_code def run(): ls = [gevent.spawn(download) for i in range(100)] gevent.joinall(ls) def run2(): for i in range(100): download() if __name__ == '__main__': from timeit import Timer t = Timer(stmt="run();", setup="from __main__ import run") print('good', t.timeit(3)) t = Timer(stmt="run2();", setup="from __main__ import run2") print('bad', t.timeit(3)) sys.exit(0) </code></pre> <p>but result is:</p> <pre><code>good 5.006664161000117 bad 29.077525214999696 </code></pre> <p>so are there all kind read, write could be speed up by gevent?</p> <p>PS: I run it on mac/python3/requests 2.10.0/gevent 1.1.2</p>
0
2016-07-25T02:30:12Z
38,558,952
<p>From the <a href="http://gevent.org" rel="nofollow">gevent website</a>:</p> <blockquote> <p>Fast event loop based on libev (epoll on Linux, kqueue on FreeBSD).</p> <p>Lightweight execution units based on greenlet.</p> <p>API that re-uses concepts from the Python standard library (for example there are gevent.event.Events and gevent.queue.Queues).</p> <p>Cooperative sockets with SSL support</p> <p>DNS queries performed through threadpool or c-ares.</p> <p>Monkey patching utility to get 3rd party modules to become cooperative</p> </blockquote> <p>Basically, just <code>for</code> looping a bunch of <code>requests.get()</code> calls is slow due to the fact that you're, well, <code>for</code> looping through a bunch of <code>requests.get()</code> calls. Gevent'ing a bunch of <code>requests.get()</code> calls isn't slow due to the fact that you're throwing those calls into a threaded Queue instead, which then uses gevent's powerful API to run through those calls incredibly efficiently. </p>
-1
2016-07-25T02:39:00Z
[ "python", "python-requests", "gevent" ]
How to remote access PostgreSQL database and get its dump to local?
38,558,901
<p>I need to access the remote database server(linux) and also take its dump to my local(mac). </p> <pre><code>DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'test-name', 'USER': 'test-user', 'PASSWORD': 'pwd', 'HOST': 'test.amazonaws.com', } } </code></pre>
-1
2016-07-25T02:30:37Z
38,559,183
<p>In local bash, you can connect and dump the remote database with <code>pg_dump</code> command, see <a href="http://stackoverflow.com/questions/1237725/copying-postgresql-database-to-another-server">Copying PostgreSQL database to another server</a></p> <p>Using Python is similar, except that you need to use <code>psycopg2</code> module to connect and send commands to database server. You may find this post useful <a href="http://stackoverflow.com/questions/23732900/postgresql-database-backup-using-python">Postgresql Database Backup Using Python</a></p> <p>Alternatively, if you need to execute the script in the database server, a better idea would be dump it remotely, then fetch it to local machine.</p>
0
2016-07-25T03:14:03Z
[ "python", "django", "database", "postgresql" ]
How to remove 'u' efficiently in django querySet?
38,558,902
<p>I'm making simple django app. I made database and I want to call it from javascript code. Everything was fine, but I had some problem with 'u' string..</p> <p>models.py</p> <pre><code>class FileDB(models.Model): fileName = models.CharField(max_length=200) fileState = models.IntegerField(default=0) </code></pre> <p>views.py</p> <pre><code>from .models import FileDB def GetFileList(request, state): list = FileDB.objects.filter(fileState=state).values() return HttpsResponse(list) </code></pre> <p>urls.py</p> <pre><code>urlpatterns = [ ... url(r^getfilelist/(?P&lt;state&gt;[0-2]+)/$', view.GetFileList), ] </code></pre> <p>In Chrome browser : x.x.x.x:8000/getfilelist/0/</p> <pre><code>{'fileState': 0, u'id': 1, 'fileName': u'image.jpg'}{'fileState': 0, u'id': 2, 'fileName': u'image2.jpg'}{'fileState': 0, u'id': 3, 'fileName': u'picture1.jpg'}{'fileState': 0, u'id': 4, 'fileName': u'video1.avi'} </code></pre> <p>How can I remove annoying 'u' string efficiently?</p>
-2
2016-07-25T02:30:38Z
38,559,287
<p>You can to use <code>json</code> library.</p> <pre><code>import json from .models import FileDB def get_file_list(request, state): list = list(FileDB.objects.filter(fileState=state).values()) return HttpsResponse(json.dumps(list)) </code></pre> <p>This should give you something like this</p> <pre><code>[{"fileState": 0, "id": 1, "fileName": "image.jpg"}, {"fileState": 0, "id": 2, "fileName": "image2.jpg"}, {"fileState": 0, "id": 3, "fileName": "picture1.jpg"}, {"fileState": 0, "id": 4, "fileName": "video1.avi"}] </code></pre>
3
2016-07-25T03:29:39Z
[ "python", "django" ]
How to remove 'u' efficiently in django querySet?
38,558,902
<p>I'm making simple django app. I made database and I want to call it from javascript code. Everything was fine, but I had some problem with 'u' string..</p> <p>models.py</p> <pre><code>class FileDB(models.Model): fileName = models.CharField(max_length=200) fileState = models.IntegerField(default=0) </code></pre> <p>views.py</p> <pre><code>from .models import FileDB def GetFileList(request, state): list = FileDB.objects.filter(fileState=state).values() return HttpsResponse(list) </code></pre> <p>urls.py</p> <pre><code>urlpatterns = [ ... url(r^getfilelist/(?P&lt;state&gt;[0-2]+)/$', view.GetFileList), ] </code></pre> <p>In Chrome browser : x.x.x.x:8000/getfilelist/0/</p> <pre><code>{'fileState': 0, u'id': 1, 'fileName': u'image.jpg'}{'fileState': 0, u'id': 2, 'fileName': u'image2.jpg'}{'fileState': 0, u'id': 3, 'fileName': u'picture1.jpg'}{'fileState': 0, u'id': 4, 'fileName': u'video1.avi'} </code></pre> <p>How can I remove annoying 'u' string efficiently?</p>
-2
2016-07-25T02:30:38Z
38,559,308
<p>You can remove the <code>u</code> characters from the keys and values of a dictionary by using a dictionary comprehension and casting the </p> <pre><code>&gt;&gt;&gt; x = {'fileState': 0, u'id': 1, 'fileName': u'image.jpg'} &gt;&gt;&gt; {str(k): str(v) for k, v in x.iteritems()} {'fileState': '0', 'id': '1', 'fileName': 'image.jpg'} </code></pre> <p>If you have a list of dictionaries, you can simply do the same but for each element in the list.</p> <pre><code>&gt;&gt;&gt; y = [{'fileState': 0, u'id': 1, 'fileName': u'image.jpg'}, {'fileState': 0, u'id': 2, 'fileName': u'image2.jpg'}, {'fileState': 0, u'id': 3, 'fileName': u'picture1.jpg'}, {'fileState': 0, u'id': 4, 'fileName': u'video1.avi'}] &gt;&gt;&gt; newList = [] &gt;&gt;&gt; for dct in y: ... newList.append({str(k): str(v) for k, v in dct.iteritems()}) ... &gt;&gt;&gt; newList [{'fileState': '0', 'id': '1', 'fileName': 'image.jpg'}, {'fileState': '0', 'id': '2', 'fileName': 'image2.jpg'}, {'fileState': '0', 'id': '3', 'fileName': 'picture1.jpg'}, {'fileState': '0', 'id': '4', 'fileName': 'video1.avi'}] </code></pre>
0
2016-07-25T03:32:02Z
[ "python", "django" ]