title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
list
Include one python file B inside file A where B uses variables defined in A
39,166,308
<p>I have a Django project where I have multiple settings file which has lot of redundant data. The structure is as follows</p> <p><strong>development.py</strong></p> <pre><code>app_one = 'http://localhost:8000' app_two = 'http://localhost:9999' abc_url = '{0}/some-url/'.format(app_one) xyz_url = '{0}/some-url/'.for...
1
2016-08-26T12:25:03Z
39,166,687
<p>There is no need to maintain separate files, you can define the configuration in dictionary, with <code>key</code> based on the environment type.</p> <p>Here I am demonstrating based on <code>hostname</code>, as hostnames of my server differs like: <code>my-host-prod</code>, <code>my-host-staging</code>, <code>my-h...
1
2016-08-26T12:44:37Z
[ "python", "django" ]
Include one python file B inside file A where B uses variables defined in A
39,166,308
<p>I have a Django project where I have multiple settings file which has lot of redundant data. The structure is as follows</p> <p><strong>development.py</strong></p> <pre><code>app_one = 'http://localhost:8000' app_two = 'http://localhost:9999' abc_url = '{0}/some-url/'.format(app_one) xyz_url = '{0}/some-url/'.for...
1
2016-08-26T12:25:03Z
39,166,701
<p>Yes, this is feasible. You will need to arrange your settings as a module:</p> <pre><code>settings/ /__init__.py /development.py /staging.py /production.py /base.py </code></pre> <p>Contents of base.py :</p> <pre><code>SOME_ENVIRONMENT_INDEPENDENT_SETTING = 1 </code></pre> ...
0
2016-08-26T12:45:48Z
[ "python", "django" ]
Verify Python Passlib generated PBKDF2 SHA512 Hash in .NET
39,166,372
<p>I am migrating a platform which used <a href="http://pythonhosted.org/passlib/" rel="nofollow">Passlib 1.6.2</a> to generate password hashes. The code to encrypt the password is (hash is called with default value for rounds):</p> <pre><code>from passlib.hash import pbkdf2_sha512 as pb def hash(cleartext, rounds=10...
2
2016-08-26T12:27:59Z
39,169,566
<p>The hash is verified by passing the password into the PBKDF HMAC-SHA-256 hash method and then comparing the resulting hash to the saved hash portion, converted back from the Base64 version.</p> <p>Saved hash to binary, then separate the hash Convert the password to binary using UTF-8 encoding PBKDF2,HMAC,SHA-256(to...
1
2016-08-26T15:16:39Z
[ "python", ".net", "hash", "cryptography", "pbkdf2" ]
Verify Python Passlib generated PBKDF2 SHA512 Hash in .NET
39,166,372
<p>I am migrating a platform which used <a href="http://pythonhosted.org/passlib/" rel="nofollow">Passlib 1.6.2</a> to generate password hashes. The code to encrypt the password is (hash is called with default value for rounds):</p> <pre><code>from passlib.hash import pbkdf2_sha512 as pb def hash(cleartext, rounds=10...
2
2016-08-26T12:27:59Z
39,258,700
<p>I quickly knocked together a .NET implementation using zaph's logic and using the code from JimmiTh on <a href="http://stackoverflow.com/questions/16341676/how-can-i-hash-passwords-with-salt-and-iterations-using-pbkdf2-hmac-sha-256-or-s">SO answer</a>. I have put the code on <a href="https://github.com/johnmark13/Pa...
0
2016-08-31T20:45:25Z
[ "python", ".net", "hash", "cryptography", "pbkdf2" ]
Python ocr pdf extraction with multiple languages
39,166,423
<p>Hello i have a pdf file with 2 languages (English, Greek) and i want to extract it via python ocr. Until now i have this code but it works only for one language only (Greek)</p> <p>How to run ocr extract in pdf file which has 2 languages? </p> <pre><code>#!/usr/bin/python # -*- coding: utf-8 -*- import sys from pd...
0
2016-08-26T12:30:23Z
39,170,265
<p>I'm venturing an answer here. Try <code>lang = 'eng+ell'</code>. Make sure you have both <code>eng.traineddata</code> and <code>ell.traineddata</code> files are in your <code>tessdata</code> folder.</p> <p><a href="https://github.com/tesseract-ocr/tessdata" rel="nofollow">https://github.com/tesseract-ocr/tessdata</...
0
2016-08-26T15:55:57Z
[ "python", "extract", "ocr" ]
How to find rows that differ by only one column in pandas?
39,166,436
<p>I have a dataframe, with three columns. I have grouped them based on two of the 3 columns. Now I need to find only those rows where the two columns <code>word1,word2</code> are same but the column <code>Tag</code>,the third column, is different.</p> <p>This something like I need to find those columns, where for the...
2
2016-08-26T12:31:24Z
39,166,605
<p><a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.drop_duplicates.html" rel="nofollow">http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.drop_duplicates.html</a></p> <p>look at the <code>subset</code> and the <code>keep</code> option</p>
2
2016-08-26T12:40:53Z
[ "python", "pandas" ]
Cannot read information from Windows Registry
39,166,487
<p>I would like to print the recent wireless network I used by reading from Windows Registry. I running windows 8. I have the following code but when I run it does not do anything! could you please help in this?</p> <pre><code>from _winreg import * def val2addr(val): addr = '' for ch in val: addr +...
1
2016-08-26T12:34:09Z
39,167,392
<p>Please have a look here for more precise <a href="http://stackoverflow.com/questions/28128446/how-do-i-use-python-to-retrieve-registry-values">solution explication</a></p> <pre><code>key = OpenKey(HKEY_LOCAL_MACHINE, net, 0, KEY_READ | KEY_WOW64_64KEY) </code></pre> <p>If my understanding is correct it's because y...
0
2016-08-26T13:22:23Z
[ "python", "windows", "security", "registry", "wireless" ]
What to do when searching on more than one word with django filter
39,166,490
<p>I made a filter where you can search on different keywords and it works. </p> <p>My problem is that when i am trying to search on more than one keyword. </p> <p>How do I make it possible to filter the search so it can separate each word?</p> <p>Here is a picture how it looks:</p> <p>First picture shows when i on...
1
2016-08-26T12:34:18Z
39,166,717
<p>Lets suppose you are searching for the following Keywords: <code>foo</code> and <code>boo</code>. And you have the following relation:</p> <pre><code>search['foo','boo'] object.keywords['foo','boo','woo'] </code></pre> <p>You can iterate over <code>object.keywords</code> and see if one of the search objects you ha...
1
2016-08-26T12:46:44Z
[ "python", "regex", "django", "django-filters" ]
How to replace the for loop by faster option in Python
39,166,546
<p>I have two data frames, which have approximately 10 000 rows. They are similar as a and b below but with more rows.</p> <pre><code> a Out[9]: end start 0 4.0 3 1 5.5 5 2 7.5 7 3 9.5 9 4 11.5 11 5 15.0 14 6 18.0 17 7 21.0 20 8 26.0 25 9 31.0 ...
2
2016-08-26T12:37:22Z
39,166,693
<p>Your solution is <code>O(n^2)</code> in running time. As far as i see all of the dataframes are sorted, if this is the case for the whole <code>DF</code> you can do a divide and conquer method to make it <code>O(nlogn)</code>. However coding it is not easy, you will have to look it up, understand the D&amp;C methods...
0
2016-08-26T12:44:57Z
[ "python", "pandas" ]
How to replace the for loop by faster option in Python
39,166,546
<p>I have two data frames, which have approximately 10 000 rows. They are similar as a and b below but with more rows.</p> <pre><code> a Out[9]: end start 0 4.0 3 1 5.5 5 2 7.5 7 3 9.5 9 4 11.5 11 5 15.0 14 6 18.0 17 7 21.0 20 8 26.0 25 9 31.0 ...
2
2016-08-26T12:37:22Z
39,167,350
<p>Here is an option without a <code>for</code> loop, which doesn't avoid vector scan but is vectorized:</p> <pre><code>b[b.index.map(lambda m: ((m &gt; a.start) &amp; (m &lt; a.end)).any())] = "m" b # status # moment # 8.0 o # 10.0 o # 14.5 m # 16.0 o # 19.0 o # 27.0 o # 28.0 o # 30.5 m # 35.0 o # 4...
1
2016-08-26T13:20:12Z
[ "python", "pandas" ]
Display 2 decimal places, and use commas to separate thousands, in Jupyter/pandas?
39,166,689
<p>I'm working with pandas 0.18 in Jupyter. </p> <p>I'd like to configure Jupyter/pandas to display 2 decimal places throughout, and to use comma separators in thousands. </p> <p>How can I do this?</p>
1
2016-08-26T12:44:40Z
39,167,299
<p>Configure the following <a href="http://pandas.pydata.org/pandas-docs/stable/options.html#available-options" rel="nofollow">option</a> in any cell:</p> <pre><code>pandas.options.display.float_format = '{:,.2f}'.format </code></pre> <p>You can also format the output for any float throughout the notebook with this <...
2
2016-08-26T13:18:02Z
[ "python", "pandas", "jupyter" ]
Switch from linux distro package manager to Anaconda
39,166,725
<p>I am using openSUSE Leap 42.1 and do some data analysis work in python. Most of the python packages I use are available in the standard openSUSE repositories (e.g. obs://build.opensuse.org/devel:languages:python); however sometimes they aren't, whereas they are available in Anaconda. I would like to replace all of t...
1
2016-08-26T12:47:06Z
39,167,113
<p>I read the anaconda documentation, and there is no evidence of anaconda packages replacing your openSUSE packages. There isn't a reason for it to do so. If I got it right, then Conda is very similar to ruby's gem and similar tools, which definitely don't replace the installed packages. I think you can feel free to i...
1
2016-08-26T13:08:57Z
[ "python", "anaconda", "opensuse" ]
Converting WindowsError to OSError in python
39,166,817
<p>In the (legacy) code I maintain people are using <code>WindowsError</code>. I could go ahead and replace all occurrences with <code>OSError</code> but alas the <code>winerror</code> attribute is used, happily only in three cases - namely 123:</p> <pre><code>try: mtime = int(os.path.getmtime(self._s)) except Win...
0
2016-08-26T12:52:10Z
39,337,429
<p>Turns out winerror and the errno attribute have different values - in good code practices I did not use the magic number but the constants from the errno module. So 32:</p> <pre><code>- except WindowsError as werr: - if werr.winerror == 32: + except OSError as werr: + ...
0
2016-09-05T20:39:25Z
[ "python", "python-2.7", "exception-handling", "cross-platform", "windowserror" ]
Real time Moving Averages in Python
39,166,941
<p>I need to calculate a moving average in Python of a sensor data that is coming on on the serial port. All the samples I can find about numpy use data from a file or that is in an array hard coded before the program starts. </p> <p>In my case I do not have any data when the program starts. The data comes in over tim...
-6
2016-08-26T12:59:34Z
39,167,754
<p>Here's how you would add one reading at a time to a running collection of readings and return the average. I prepopulated the readings list to show it in action, but in your program, you'd just start off with an empty list: <code>readings = []</code></p> <p>I made the assumption that you want to include the last x ...
0
2016-08-26T13:40:00Z
[ "python", "average" ]
Better way to swap elements in a list?
39,167,057
<p>I have a bunch of lists that look like this one:</p> <pre><code>l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] </code></pre> <p>I want to swap elements as follows:</p> <pre><code>final_l = [2, 1, 4, 3, 6, 5, 8, 7, 10, 9] </code></pre> <p>The size of the lists may vary, but they will always contain an even number of element...
47
2016-08-26T13:05:46Z
39,167,147
<p>I don't see anything wrong with your implementation at all. But you could perhaps do a simple swap instead.</p> <pre><code>l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] for i in range(0, len(l), 2): old = l[i] l[i] = l[i+1] l[i+1] = old </code></pre> <p><strong>EDIT</strong> Apparently, Python has a nicer way t...
-1
2016-08-26T13:10:53Z
[ "python" ]
Better way to swap elements in a list?
39,167,057
<p>I have a bunch of lists that look like this one:</p> <pre><code>l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] </code></pre> <p>I want to swap elements as follows:</p> <pre><code>final_l = [2, 1, 4, 3, 6, 5, 8, 7, 10, 9] </code></pre> <p>The size of the lists may vary, but they will always contain an even number of element...
47
2016-08-26T13:05:46Z
39,167,227
<p>Here a single list comprehension that does the trick:</p> <pre><code>In [1]: l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] In [2]: [l[i^1] for i in range(len(l))] Out[2]: [2, 1, 4, 3, 6, 5, 8, 7, 10, 9] </code></pre> <p>The key to understanding it is the following demonstration of how it permutes the list indices:</p> <pr...
29
2016-08-26T13:13:46Z
[ "python" ]
Better way to swap elements in a list?
39,167,057
<p>I have a bunch of lists that look like this one:</p> <pre><code>l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] </code></pre> <p>I want to swap elements as follows:</p> <pre><code>final_l = [2, 1, 4, 3, 6, 5, 8, 7, 10, 9] </code></pre> <p>The size of the lists may vary, but they will always contain an even number of element...
47
2016-08-26T13:05:46Z
39,167,243
<p>You can use the <a href="http://stackoverflow.com/questions/5389507/iterating-over-every-two-elements-in-a-list">pairwise iteration</a> and chaining to <a href="http://stackoverflow.com/questions/952914/making-a-flat-list-out-of-list-of-lists-in-python">flatten the list</a>:</p> <pre><code>&gt;&gt;&gt; from itertoo...
19
2016-08-26T13:14:37Z
[ "python" ]
Better way to swap elements in a list?
39,167,057
<p>I have a bunch of lists that look like this one:</p> <pre><code>l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] </code></pre> <p>I want to swap elements as follows:</p> <pre><code>final_l = [2, 1, 4, 3, 6, 5, 8, 7, 10, 9] </code></pre> <p>The size of the lists may vary, but they will always contain an even number of element...
47
2016-08-26T13:05:46Z
39,167,384
<pre><code>newList = [(x[2*i+1], x[2*i]) for i in range(0, len(x)/2)] </code></pre> <p>Now find a way to unzip the tuples. I won't do all of your homework.</p>
-3
2016-08-26T13:21:54Z
[ "python" ]
Better way to swap elements in a list?
39,167,057
<p>I have a bunch of lists that look like this one:</p> <pre><code>l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] </code></pre> <p>I want to swap elements as follows:</p> <pre><code>final_l = [2, 1, 4, 3, 6, 5, 8, 7, 10, 9] </code></pre> <p>The size of the lists may vary, but they will always contain an even number of element...
47
2016-08-26T13:05:46Z
39,167,400
<p>Another way, create nested lists with pairs reversing their order, then flatten the lists with <code>itertools.chain.from_iterable</code></p> <pre><code>&gt;&gt;&gt; from itertools import chain &gt;&gt;&gt; l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] &gt;&gt;&gt; list(chain.from_iterable([[l[i+1],l[i]] for i in range(0,(le...
4
2016-08-26T13:22:36Z
[ "python" ]
Better way to swap elements in a list?
39,167,057
<p>I have a bunch of lists that look like this one:</p> <pre><code>l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] </code></pre> <p>I want to swap elements as follows:</p> <pre><code>final_l = [2, 1, 4, 3, 6, 5, 8, 7, 10, 9] </code></pre> <p>The size of the lists may vary, but they will always contain an even number of element...
47
2016-08-26T13:05:46Z
39,167,486
<p>Here a solution based in the <code>modulo</code> operator:</p> <pre><code>l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] even = [] uneven = [] for i,item in enumerate(l): if i % 2 == 0: even.append(item) else: uneven.append(item) list(itertools.chain.from_iterable(zip(uneven, even))) </code></pre>
-3
2016-08-26T13:26:57Z
[ "python" ]
Better way to swap elements in a list?
39,167,057
<p>I have a bunch of lists that look like this one:</p> <pre><code>l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] </code></pre> <p>I want to swap elements as follows:</p> <pre><code>final_l = [2, 1, 4, 3, 6, 5, 8, 7, 10, 9] </code></pre> <p>The size of the lists may vary, but they will always contain an even number of element...
47
2016-08-26T13:05:46Z
39,167,545
<p>No need for complicated logic, simply rearrange the list with slicing and step:</p> <pre><code>In [1]: l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] In [2]: l[::2], l[1::2] = l[1::2], l[::2] In [3]: l Out[3]: [2, 1, 4, 3, 6, 5, 8, 7, 10, 9] </code></pre> <hr> <h2> TLDR;</h2> <p><strong>Edited with explanation</strong><...
93
2016-08-26T13:29:52Z
[ "python" ]
Better way to swap elements in a list?
39,167,057
<p>I have a bunch of lists that look like this one:</p> <pre><code>l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] </code></pre> <p>I want to swap elements as follows:</p> <pre><code>final_l = [2, 1, 4, 3, 6, 5, 8, 7, 10, 9] </code></pre> <p>The size of the lists may vary, but they will always contain an even number of element...
47
2016-08-26T13:05:46Z
39,167,669
<p>One of the possible answer using <code>chain</code> and <code>list comprehension</code></p> <pre><code>&gt;&gt;&gt; l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] &gt;&gt;&gt; list(chain([(l[2*i+1], l[2*i]) for i in range(0, len(l)/2)])) [(2, 1), (4, 3), (6, 5), (8, 7), (10, 9)] </code></pre>
3
2016-08-26T13:35:30Z
[ "python" ]
Better way to swap elements in a list?
39,167,057
<p>I have a bunch of lists that look like this one:</p> <pre><code>l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] </code></pre> <p>I want to swap elements as follows:</p> <pre><code>final_l = [2, 1, 4, 3, 6, 5, 8, 7, 10, 9] </code></pre> <p>The size of the lists may vary, but they will always contain an even number of element...
47
2016-08-26T13:05:46Z
39,167,859
<p>Another approach with simply re-assigning and slicing technique</p> <pre><code>l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] for a in range(0,len(l),2): l[a:a+2] = l[a-len(l)+1:a-1-len(l):-1] print l </code></pre> <p>output</p> <pre><code>[2, 1, 4, 3, 6, 5, 8, 7, 10, 9] </code></pre>
2
2016-08-26T13:45:14Z
[ "python" ]
Better way to swap elements in a list?
39,167,057
<p>I have a bunch of lists that look like this one:</p> <pre><code>l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] </code></pre> <p>I want to swap elements as follows:</p> <pre><code>final_l = [2, 1, 4, 3, 6, 5, 8, 7, 10, 9] </code></pre> <p>The size of the lists may vary, but they will always contain an even number of element...
47
2016-08-26T13:05:46Z
39,168,029
<h2>A benchmark between top answers:</h2> <p>Python 2.7:</p> <pre><code>('inp1 -&gt;', 15.302665948867798) # NPE's answer ('inp2a -&gt;', 10.626379013061523) # alecxe's answer with chain ('inp2b -&gt;', 9.739919185638428) # alecxe's answer with chain.from_iterable ('inp3 -&gt;', 2.6654279232025146) # Anzel's answer ...
7
2016-08-26T13:54:30Z
[ "python" ]
Better way to swap elements in a list?
39,167,057
<p>I have a bunch of lists that look like this one:</p> <pre><code>l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] </code></pre> <p>I want to swap elements as follows:</p> <pre><code>final_l = [2, 1, 4, 3, 6, 5, 8, 7, 10, 9] </code></pre> <p>The size of the lists may vary, but they will always contain an even number of element...
47
2016-08-26T13:05:46Z
39,170,408
<p>For fun, if we interpret "swap" to mean "reverse" in a more general scope, the <code>itertools.chain.from_iterable</code> approach can be used for subsequences of longer lengths.</p> <pre><code>l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] def chunk(list_, n): return (list_[i:i+n] for i in range(0, len(list_), n)) list...
2
2016-08-26T16:03:44Z
[ "python" ]
Better way to swap elements in a list?
39,167,057
<p>I have a bunch of lists that look like this one:</p> <pre><code>l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] </code></pre> <p>I want to swap elements as follows:</p> <pre><code>final_l = [2, 1, 4, 3, 6, 5, 8, 7, 10, 9] </code></pre> <p>The size of the lists may vary, but they will always contain an even number of element...
47
2016-08-26T13:05:46Z
39,170,492
<p>An(other) alternative:</p> <pre><code>final_l = list() # make an empty list for i in range(len(l)): # for as many items there are in the original list if i % 2 == 0: # if the item is even final_l.append(l[i+1]) # make this item in the new list equal to the next in the original list else: # else, so ...
2
2016-08-26T16:09:06Z
[ "python" ]
Python decorators: howto list wrapped functions by decorator
39,167,171
<p>Is that possible to use python decorators to mark a method, and get it for the later use, if I don't know the name of the wrapped function?</p> <p>Here is the example, and I don't know the name of method_with_custom_name:</p> <pre><code>@run_this_method def method_with_custom_name(my_arg): return "The args is:...
1
2016-08-26T13:11:44Z
39,167,274
<p>If I understand your question correctly (how to decorate a method with an unknown name?) then it is totally possible.</p> <pre><code>@decorator def foo(bar): pass </code></pre> <p>is syntastic sugar for</p> <pre><code>def foo(bar): pass foo = decorator(foo) </code></pre> <p>So in your case you should just do...
1
2016-08-26T13:16:17Z
[ "python", "python-decorators" ]
Python decorators: howto list wrapped functions by decorator
39,167,171
<p>Is that possible to use python decorators to mark a method, and get it for the later use, if I don't know the name of the wrapped function?</p> <p>Here is the example, and I don't know the name of method_with_custom_name:</p> <pre><code>@run_this_method def method_with_custom_name(my_arg): return "The args is:...
1
2016-08-26T13:11:44Z
39,168,080
<p>If you need to track all functions and methods decorated with your decorator you need to create global variable to register all such functions and methods. I've modified your code:</p> <pre><code>funcs_registry = [] #List of all functions decorated with @run_this_method def run_this_method(m): global functions_...
1
2016-08-26T13:58:06Z
[ "python", "python-decorators" ]
YAML file update and delete using python?
39,167,440
<p>I have a YAML file and it looks like below</p> <pre><code>test: - exam.com - exam1.com - exam2.com test2: - examp.com - examp1.com - examp2.com </code></pre> <p>I like to manage this file using python. Task is, I like to add an entry under "test2" and delete entry from "test".</p>
1
2016-08-26T13:24:38Z
39,168,727
<p>You first have to load the data, which will give you a top-level dict (in a variable called <code>data</code> in the following example), the values for the keys will be lists. On those lists you can do the <code>del</code> resp. <code>insert()</code> (or <code>append()</code>)</p> <pre><code>import sys import ruame...
0
2016-08-26T14:31:29Z
[ "python", "yaml", "pyyaml" ]
Python Pandas Custom DateTime Index
39,167,518
<p>I'm looking to reindex my data using a custom DateTime index. I would like the index to be: Sun 5pm-Mon 4PM; Mon 5PM-Tues 4PM;Tues 5PM-Wed 4PM; Wed 5PM-Thurs 4pm; Thurs 5PM-Fri 4PM, in a 1 minute interval. I have been playing around with the code below but I cant seem to get any data to populate in time_stamps. It...
1
2016-08-26T13:28:27Z
39,168,714
<p>Similar to my answer <a href="http://stackoverflow.com/a/36794030/5276797">here</a>, you could generate the full range of timestamps, then remove those you are not interested in:</p> <pre><code>time_stamps = pd.date_range('2016-07-11', '2016-07-21', freq='1min') mask = ~((time_stamps.hour &gt; 16) &amp; (time_stamp...
2
2016-08-26T14:30:56Z
[ "python", "datetime", "pandas" ]
scikit very low accuracy on classifiers(Naive Bayes, DecissionTreeClassifier)
39,167,586
<p>I am using this dataset <a href="http://archive.ics.uci.edu/ml/datasets/Adult" rel="nofollow">Weath Based on age</a> and the documentation states that the accuracy should be around <code>84%</code>. Unfortunately, the accuracy of my program is at <code>25%</code></p> <p>To process the data I did the following:</p> ...
0
2016-08-26T13:31:58Z
39,173,259
<p>I guess the problem is in preprocessing. It is better to encode the categorical variables as one_hot vectors (vectors with only zero or ones where one corresponds to the desired value for that class) instead of raw numbers. Sklearn <a href="https://github.com/zygmuntz/kaggle-happiness/blob/master/vectorize_validatio...
1
2016-08-26T19:11:41Z
[ "python", "machine-learning", "scipy", "scikit-learn" ]
Ruby pass numbers as key (key-value) to **kwargs
39,167,635
<p>How to pass numbers as key (key-value) to **kwargs? In other words, why can't numbers be passed as key (key-value) to **kwargs? Here's the error:</p> <p><strong>Edit:</strong></p> <pre><code>def func(**kwargs) puts kwargs.class p kwargs end func(a={:alpha =&gt; 1, :beta =&gt; 2, :gamma =&gt; 3}) # wrong number ...
-1
2016-08-26T13:34:23Z
39,167,965
<p>kwargs means: <strong>K</strong>ey<strong>w</strong>ord<strong>A</strong>rguments</p> <p>In ruby's case you can only pass a symbol as the key. (Correct me if there's anything else)</p> <p>So Things like that won't work:</p> <pre><code>func("a" =&gt; "foo") func(1 =&gt; "bar") func(Object.new =&gt; "baz") </code><...
1
2016-08-26T13:51:12Z
[ "python", "ruby" ]
NLTK BigramTagger does not tag half of the sentence
39,167,671
<p>Can someone please explain the behaviour of NLTK's BigramTagger in these examples?</p> <p>I instantiated the tagger by </p> <pre><code>bi= BigramTagger(brown.tagged_sents(categories='news')[:500]) </code></pre> <p>Now, I want to use this on one specific sentence.</p> <pre><code>&gt;&gt;&gt; bi.tag(brown_sents[2]...
2
2016-08-26T13:35:40Z
39,170,704
<p>You have to set a backoff tagger when using *gramTagger so that if the specific ngram is not seen in the training data, it will backoff to a tagger trained on a lower order ngram. See "Combining Taggers" section in <a href="http://www.nltk.org/book/ch05.html" rel="nofollow">http://www.nltk.org/book/ch05.html</a></p>...
2
2016-08-26T16:21:11Z
[ "python", "nlp", "nltk", "n-gram", "pos-tagger" ]
How to get all data from qt model
39,167,722
<p>I have created a QIdentityProxyModel called proxymodel that extends a QSqlTableModel called sourcemodel by adding 3 calculated columns. The calculated columns are made by traversing the sourcemodel and storing the data in a list that is mapped by the proxymodel. The proxymodel is displayed in a TableView.</p> <p>T...
1
2016-08-26T13:38:43Z
39,171,449
<p>SQL models use the progressive fetch. The source model returns <code>true</code> from <code>canFetchMore</code>. The view calls <code>fetchMore</code>, and then more rows are added to the source model by fetching them from the database - only when the view needs them.</p> <p>Since your proxy needs all the data, it ...
0
2016-08-26T17:09:02Z
[ "python", "c++", "qt", "model" ]
Python/Django convert/humanize specific dictionary items on django view?
39,167,753
<p>I am creating a variable queryset and then passing the values into a dictionary context variable. I am able to convert dates but I'm not sure how to convert specific fields to currency (example: $1,000 instead of 1000) or even just humanize specific fields with commas (1,000 instead of 1000) below is my code from my...
-1
2016-08-26T13:40:00Z
39,169,675
<p>First and foremost, you should use a <a href="https://docs.djangoproject.com/en/1.10/ref/models/fields/#decimalfield" rel="nofollow">decimal field</a> for your currency values if you can. This is not a django convention, <a href="http://stackoverflow.com/questions/1165761/decimal-vs-double-which-one-should-i-use-and...
1
2016-08-26T15:23:03Z
[ "python", "django", "dictionary", "type-conversion" ]
Python/Django convert/humanize specific dictionary items on django view?
39,167,753
<p>I am creating a variable queryset and then passing the values into a dictionary context variable. I am able to convert dates but I'm not sure how to convert specific fields to currency (example: $1,000 instead of 1000) or even just humanize specific fields with commas (1,000 instead of 1000) below is my code from my...
-1
2016-08-26T13:40:00Z
39,170,137
<p>I would install <code>humanize</code> app and then extend its <code>intcomma</code> method to create my own templatetag:</p> <pre><code>from django import template from django.contrib.humanize.templatetags.humanize import intcomma register = template.Library() @register.filter def prepend_dollars(dollars): if...
0
2016-08-26T15:49:08Z
[ "python", "django", "dictionary", "type-conversion" ]
Python/Django convert/humanize specific dictionary items on django view?
39,167,753
<p>I am creating a variable queryset and then passing the values into a dictionary context variable. I am able to convert dates but I'm not sure how to convert specific fields to currency (example: $1,000 instead of 1000) or even just humanize specific fields with commas (1,000 instead of 1000) below is my code from my...
-1
2016-08-26T13:40:00Z
39,170,847
<p>Usually it's a payment processor headache. But if you want to localize your currency value I'd suggest sth like that:</p> <p>Use <a href="http://babel.pocoo.org/en/latest/index.html" rel="nofollow">'babel'</a> app as a base &amp; implement the following filter:</p> <pre><code>from decimal import Decimal from decim...
0
2016-08-26T16:29:22Z
[ "python", "django", "dictionary", "type-conversion" ]
How to specify which python to use when writing vim script in python
39,167,814
<p>I started to learn how to write vim script in python.</p> <p>I come across of this tutorial</p> <p><a href="https://dzone.com/articles/how-write-vim-plugins-python" rel="nofollow">https://dzone.com/articles/how-write-vim-plugins-python</a></p> <p>and my first vim script looks like the following</p> <pre><code>fu...
0
2016-08-26T13:42:57Z
39,259,443
<p>If you don’t mind using Neovim instead of vim, you would be able to select which Python interpreter to use via:</p> <pre><code>let g:python_host_prog = '/path/to/your/interpreter/python' let g:python3_host_prog = '/path/to/your/interpreter/python3' </code></pre>
0
2016-08-31T21:40:37Z
[ "python", "vim" ]
Cannot parse table using BeautifulSoup
39,168,000
<p>I have been trying to parse the table <a href="http://podaac.jpl.nasa.gov/ws/search/granule/index.html" rel="nofollow">here</a> with table id = "tblDataset2" and trying to access the rows in the table, but I only get a single row when I parse the webpage using beautifulsoup. Here's my code : </p> <pre><code>from b...
1
2016-08-26T13:52:52Z
39,168,175
<p>This particular dataset is being asynchronously loaded by the browser from a different endpoint which returns a JSON response. Make the request directly to that endpoint:</p> <pre><code>import requests URL = 'http://podaac.jpl.nasa.gov/l2ssIngest/datasets' response = requests.get(URL) data = response.json() for i...
1
2016-08-26T14:02:43Z
[ "python", "html", "parsing", "beautifulsoup", "inspect-element" ]
Tensorflow: show or save forget gate values in LSTM
39,168,025
<p>I am using the LSTM model that comes by default in tensorflow. I would like to check or to know how to save or show the values of the forget gate in each step, has anyone done this before or at least something similar to this?</p> <p>Till now I have tried with tf.print but many values appear (even more than the one...
2
2016-08-26T13:54:13Z
39,177,157
<p>If you are using <code>tf.rnn_cell.BasicLSTMCell</code> , the variable you are looking for will have the following suffix in its name : <code>&lt;parent_variable_scope&gt;/BasicLSTMCell/Linear/Matrix</code> . This is a concatenated matrix for all the four gates. Its first dimension matches the sum of the second dime...
0
2016-08-27T03:25:44Z
[ "python", "neural-network", "tensorflow", "lstm" ]
Generating 2d numpy arrays from random columns
39,168,050
<p>I need to generate an 3xn matrix having random columns ensuring that each column does not contain the same number more than once. I am currently using the below code:</p> <pre><code>n=10 set = np.arange(0, 10) matrix = np.random.choice(set, size=3, replace=False)[:, None] for i in range(n): column = np.random.c...
0
2016-08-26T13:56:21Z
39,168,933
<p>As was already mentioned in the comments, concatenating repeatedly to a <code>numpy</code> array is a bad idea, as you will have to reallocate memory a lot. As you already know the final size of your result array, you could simply allocate it in the begin and then just iterate over the columns:</p> <pre><code>matri...
0
2016-08-26T14:41:36Z
[ "python", "numpy" ]
Generating 2d numpy arrays from random columns
39,168,050
<p>I need to generate an 3xn matrix having random columns ensuring that each column does not contain the same number more than once. I am currently using the below code:</p> <pre><code>n=10 set = np.arange(0, 10) matrix = np.random.choice(set, size=3, replace=False)[:, None] for i in range(n): column = np.random.c...
0
2016-08-26T13:56:21Z
39,173,381
<p>You can speed it up further with Python's random module (probably due to this <a href="https://github.com/numpy/numpy/issues/2764" rel="nofollow">issue</a>):</p> <pre><code>import random np.array([random.sample(range(10), 3) for _ in range(n)]).T </code></pre> <hr> <pre><code>n = 10**6 %timeit t = np.array([rand...
0
2016-08-26T19:21:25Z
[ "python", "numpy" ]
Python regex parsing of syslog
39,168,177
<p>I have a syslog file with this format.</p> <pre><code>Mar 7 13:44:55 host.domain.example.net/10.10.10.10 Application: Info: MODULE: Startup MESSAGE: Application Version: 8.44.0 Mar 7 13:44:55 host.domain.example.net/10.10.10.10 Application: Info: MODULE: Startup MESSAGE: Run on system: host Mar 7 13:44:55 host.d...
-4
2016-08-26T14:02:47Z
39,182,376
<p>Please check below links before going through code. It will help you greatly.</p> <ol> <li><a href="https://pymotw.com/2/re/" rel="nofollow">re module</a> - The module used. This link given has great explanation along with examples</li> <li><a href="http://www.pyregex.com/" rel="nofollow">Python Regex Tester</a> - ...
0
2016-08-27T14:45:54Z
[ "python", "regex", "syslog" ]
Infinite recursion on adding days to a SimpleDate python object created from UTC
39,168,209
<p>I am using the python library simple-date. I created a SimpleDate object by initializing with a string representing a UTC date. When I try to add days to it, using timedelta, it seems to work fine but then when I try to print it, it recurses infinitely. I inspected the object resulting from the addition with p in th...
1
2016-08-26T14:04:30Z
39,260,310
<p>So, there were two issues here.</p> <p>The first is easy to explain. Generating a message for a certain error caused the same error it was trying to report. That caused a new message to be generated, which caused a new error, which ... eventually exhausted the stack. That is now fixed.</p> <p>The second is hard...
1
2016-08-31T23:01:25Z
[ "python", "recursion", "timedelta" ]
Sybase numeric datatype and Python
39,168,251
<p>I have encountered a problem that I can not figure out.</p> <p>I'm working on an application written in Python and a Sybase ASE database using sybpydb to communicate with the datbase. Now I need to update a post where one of the columns in the where clause is of numeric(10) data type. When selecting the post Python...
0
2016-08-26T14:06:32Z
39,202,310
<p>You need to capture the actual SQL query text which is sent to the ASE server before conclusions can be drawn. </p>
0
2016-08-29T09:04:05Z
[ "python", "sybase-ase" ]
Python encode an image in base 64 after a html upload
39,168,318
<p>I have an input for images upload in my page. When you click on "send image" the post request is received in my back-end.</p> <p><strong>I don't, and I don't want to, save the image.</strong></p> <p>What I do, from the back, is: I send the image to an API which will return me the image's tags and then I will displ...
0
2016-08-26T14:09:53Z
39,169,817
<p>Ok, as I'm not saving the image, once I send it to the API the object in itself isn't available anymore.</p> <p>Not sure to understand why I still can print it, I had to make a copy of it:</p> <pre><code>if form.is_valid(): imageUploaded = request.FILES['image_file'] imageCopy = copy.deepco...
0
2016-08-26T15:30:18Z
[ "python", "django", "base64" ]
Pygame for Python 3 - "Setup.py build" command error
39,168,330
<p>I am following these directions: <a href="http://www.pygame.org/wiki/CompileUbuntu?parent=Compilation" rel="nofollow">http://www.pygame.org/wiki/CompileUbuntu?parent=Compilation</a></p> <p>The instructions give the steps in installing Pygame for Python 3 on Ubuntu. </p> <p>I am having no problems with it until i r...
0
2016-08-26T14:10:50Z
39,168,546
<p>Try to install setuptools, e.g. with pip from the command line: <code>pip install setuptools</code></p>
-1
2016-08-26T14:22:45Z
[ "python", "python-3.x", "pygame" ]
Pygame for Python 3 - "Setup.py build" command error
39,168,330
<p>I am following these directions: <a href="http://www.pygame.org/wiki/CompileUbuntu?parent=Compilation" rel="nofollow">http://www.pygame.org/wiki/CompileUbuntu?parent=Compilation</a></p> <p>The instructions give the steps in installing Pygame for Python 3 on Ubuntu. </p> <p>I am having no problems with it until i r...
0
2016-08-26T14:10:50Z
39,170,260
<pre><code>sudo apt install python3-setuptools ^ separate from Python 2 setuptools. </code></pre> <p>Per <a href="http://stackoverflow.com/a/14426553/2877364">this answer</a>.</p>
0
2016-08-26T15:55:46Z
[ "python", "python-3.x", "pygame" ]
AWS ElasticBeanstalk update without modifing Django wsgi.conf
39,168,351
<p>I have a django app deployed in AWS EB using autoscaling. This app uses Django Rest with Token Authentication. In order for this to work, I have to add the following lines in etc/httpd/conf.d/wsgi.conf file:</p> <pre><code>RewriteEngine on RewriteCond %{HTTP:Authorization} ^(.*) RewriteRule .* - [e=HTTP_AUTHORIZATI...
0
2016-08-26T14:12:00Z
39,193,069
<p>To avoid ElasticBeanstalk erasing your custom settings while autoscaling or re-initializing any instance in your environment you should use your <code>.ebextensions</code> scripts to do any durable modification to your ec2 instance's <code>config</code> files.</p> <p>(After having tested these modifications as you ...
2
2016-08-28T15:52:14Z
[ "python", "django", "apache", "amazon-web-services", "mod-wsgi" ]
Python Regex stop on string
39,168,468
<p>So I want to search using regex for seasons which are not followed by episode number and I have the following list :</p> <pre><code>string = ['Fear the walking dead Season 2 Episode 9', 'Veep Season 5', 'Martine Season 2 (unknown number of episodes)', 'New Girl Season 5 Episode 16'] </code></pre> <p>I've written t...
1
2016-08-26T14:18:30Z
39,168,744
<p>I would recommend using <code>^</code> and <code>$</code> to match from the beginning of a line to the end. So you can change your regex to:</p> <pre><code>re.search('^(.+?Season\s[0-9]{1,2})$', string, re.I | re.M) </code></pre>
3
2016-08-26T14:32:22Z
[ "python", "regex" ]
Python Regex stop on string
39,168,468
<p>So I want to search using regex for seasons which are not followed by episode number and I have the following list :</p> <pre><code>string = ['Fear the walking dead Season 2 Episode 9', 'Veep Season 5', 'Martine Season 2 (unknown number of episodes)', 'New Girl Season 5 Episode 16'] </code></pre> <p>I've written t...
1
2016-08-26T14:18:30Z
39,168,934
<p>From previous experience, I'd suggest not solely doing this with regex, but I've quickly thrown together the following snippet (after which no_episode_string will contain all of the ones without episodes).</p> <p>For each season we match against ".<em>?[0-9]</em>(.*)", which simply grabs everything up to and includ...
2
2016-08-26T14:41:40Z
[ "python", "regex" ]
How can I generate a list and flatten it the same time in python?
39,168,499
<p>This is more of a refactoring question, as the code works as is. But since I am still learning <code>Python</code>, I thought there would be a better way to do this, and I spent a few hours now digging into the other possibilities, but can't get anywhere.</p> <p>So I have the following statement:</p> <p><code>numb...
-2
2016-08-26T14:19:49Z
39,168,544
<p>Just substitute the first expression for <code>numbers</code> in the second expression:</p> <pre><code>flat = [item for setlist in [re.split(' ?- ?', ticket.text.strip()) for ticket in tickets] for item in setlist] </code></pre>
-2
2016-08-26T14:22:41Z
[ "python" ]
How can I generate a list and flatten it the same time in python?
39,168,499
<p>This is more of a refactoring question, as the code works as is. But since I am still learning <code>Python</code>, I thought there would be a better way to do this, and I spent a few hours now digging into the other possibilities, but can't get anywhere.</p> <p>So I have the following statement:</p> <p><code>numb...
-2
2016-08-26T14:19:49Z
39,168,566
<p>You can achieve it using <code>chain</code> and <code>map</code> in single line as:</p> <pre><code>list(chain(*map(lambda x: re.split(' ?- ?', x.text.strip()), tickets))) </code></pre> <p><strong>Suggestion:</strong></p> <p>There is no need to use <code>regex</code> here, because you may achieve the same using <c...
-1
2016-08-26T14:23:43Z
[ "python" ]
How can I generate a list and flatten it the same time in python?
39,168,499
<p>This is more of a refactoring question, as the code works as is. But since I am still learning <code>Python</code>, I thought there would be a better way to do this, and I spent a few hours now digging into the other possibilities, but can't get anywhere.</p> <p>So I have the following statement:</p> <p><code>numb...
-2
2016-08-26T14:19:49Z
39,168,595
<pre><code>sum([re.split(' ?- ?', ticket.text.strip()) for ticket in tickets], []) </code></pre>
-1
2016-08-26T14:24:44Z
[ "python" ]
How can I generate a list and flatten it the same time in python?
39,168,499
<p>This is more of a refactoring question, as the code works as is. But since I am still learning <code>Python</code>, I thought there would be a better way to do this, and I spent a few hours now digging into the other possibilities, but can't get anywhere.</p> <p>So I have the following statement:</p> <p><code>numb...
-2
2016-08-26T14:19:49Z
39,168,608
<p>A better idea is to add another loop over <code>re.split(' ?- ?', ticket.text.strip())</code> in the list comprehension:</p> <pre><code>flat = [x for ticket in tickets for x in re.split(' ?- ?', ticket.text.strip())] </code></pre> <p>It's also more efficient and cleaner.</p> <p>By the way, you should use string m...
1
2016-08-26T14:25:23Z
[ "python" ]
How can I generate a list and flatten it the same time in python?
39,168,499
<p>This is more of a refactoring question, as the code works as is. But since I am still learning <code>Python</code>, I thought there would be a better way to do this, and I spent a few hours now digging into the other possibilities, but can't get anywhere.</p> <p>So I have the following statement:</p> <p><code>numb...
-2
2016-08-26T14:19:49Z
39,169,729
<p>Well, let's work through this one step at a time. As a set of partially-nested for-loops, your code would be:</p> <pre><code>numbers = [] for ticket in tickets: numbers.append(re.split(' ?- ?', ticket.text.strip()) flat = [] for setlist in numbers: for item in setlist: flat.append(item) </code></pre...
0
2016-08-26T15:26:06Z
[ "python" ]
index 1 / 2nd list item being skipped for no apparent reason
39,168,652
<p>I have a function that takes a list and removes (one instance of) the smallest and largest elements, then takes the average of the remaining elements. Running it doesnt bring up any errors, although on checking the results I realised they were incorrect. Here's the program:</p> <pre><code>def centered_average(x): ...
1
2016-08-26T14:27:38Z
39,168,848
<p>You need to take special care when removing elements of a list that you are already iterating over in Python, as you are doing in your function. Python is looking at the indices of the list and using those, but when you remove the first element and the list is updated in place, the previous second element (<code>x[...
3
2016-08-26T14:37:37Z
[ "python", "list" ]
index 1 / 2nd list item being skipped for no apparent reason
39,168,652
<p>I have a function that takes a list and removes (one instance of) the smallest and largest elements, then takes the average of the remaining elements. Running it doesnt bring up any errors, although on checking the results I realised they were incorrect. Here's the program:</p> <pre><code>def centered_average(x): ...
1
2016-08-26T14:27:38Z
39,168,984
<p>The issue comes from the <code>for i in x:</code>. When you remove the first element, the second element (2) becomes the first element of the list. This means that on the next iteration, you will look for the second element, and find 3, because the list is now [2, 3, 4, 5].</p> <p>Instead, you could start by removi...
1
2016-08-26T14:44:10Z
[ "python", "list" ]
SQL double join in python
39,168,703
<p>i have two tables, a and b each with many rows. i have an SQL code saying </p> <pre><code>SELECT* FROM a INNER JOIN b ON (a.names = b.names) and (a.age = b.age) </code></pre> <p>im trying to make this in python using the .merge() function, and by making a mid-table from the first join and then trying to make it b...
1
2016-08-26T14:30:08Z
39,169,705
<pre><code>a.merge(b, how='inner', on=['name','age']) </code></pre> <p>and if say your column for ages in b had a different name say years, which mine did i did this</p> <pre><code>b['age'] = b['years'] </code></pre> <p>and then i could use the above. i also could have renamed that column but wanted to keep all ori...
0
2016-08-26T15:24:53Z
[ "python", "mysql", "join" ]
Where to catch a KeyboardInterrupt in unittests?
39,168,757
<p>I'm UI testing on mobile devices using an Appium server. I want to be able to cancel the testing process while developing the tests. Currently, when I <code>CTRL-C</code> out of the process (the python unittest), I have to restart the appium server, since the session was not shut down properly (this would have been ...
0
2016-08-26T14:33:01Z
39,168,986
<p>You can change the default behaviour of Python regarding SIGINT to suit your needs:</p> <pre><code>import signal def my_ctrlc_handler(signal, frame): driver_class.quit() raise KeyboardInterrupt signal.signal(signal.SIGINT, my_ctrlc_handler) </code></pre>
2
2016-08-26T14:44:17Z
[ "python", "unit-testing", "python-unittest" ]
'[08001][TPT] [ODBC SQL Server Wire Protocol driver] Invalid connection Data
39,168,850
<p>I have a python program that implies connecting to a teradata database. The server name is defaulted. Two people can succesfully use the python program but one person can't and gets the following error message:</p> <pre><code>'[08001][TPT] [ODBC SQL Server Wire Protocol driver] Invalid connection Data ., [TPT][ODB...
0
2016-08-26T14:37:43Z
39,245,228
<p>If you check the log you can see that probably you have more than one driver for Teradata set into your ODBC configuration.</p> <p>To set your correct Teradata driver you can add driver property to connect method:</p> <pre><code>session = udaExec.connect(method="odbc", system="servername", username=user1, password...
0
2016-08-31T09:04:51Z
[ "python", "teradata" ]
Python Regular Expression Index Numbers
39,168,866
<p>Just looking for some confirmation on this, but it appears that the index/position numbers for regular expressions do not follow the same rules used in the rest of python.</p> <p>Example:</p> <pre><code>pattern=re.compile('&lt;HTML&gt;') pattern.search("&lt;HTML&gt;") </code></pre> <p>output:</p> <pre><code>&lt;...
1
2016-08-26T14:38:41Z
39,168,972
<p>Well a slice (span) in Python is open ended. So <code>"&lt;HTML&gt;and much more"[0:6]</code> actually returns <code>"&lt;HTML&gt;"</code>.</p>
2
2016-08-26T14:43:47Z
[ "python", "regex" ]
Why do Python and wc disagree on byte count?
39,169,080
<p>Python and <code>wc</code> disagree drastically on the byte count (length) of a given string:</p> <pre><code>with open("commedia.pfc", "w") as f: t = ''.join(chr(int(b, base=2)) for b in chunks(compressed, 8)) print(len(t)) f.write(t) Output : 318885 </code></pre> <hr> <pre><code>$&gt; wc commedia.pf...
0
2016-08-26T14:49:06Z
39,169,892
<p>You are using Python3 and an <code>str</code> object - that means the count you see in <code>len(t)</code> is the number of <em>characters</em> in the string. Now, characters are not bytes - <a href="http://www.joelonsoftware.com/articles/Unicode.html" rel="nofollow">and it is so since the 90's</a> . </p> <p>Since...
4
2016-08-26T15:35:14Z
[ "python", "file", "python-3.x", "byte", "wc" ]
Why do Python and wc disagree on byte count?
39,169,080
<p>Python and <code>wc</code> disagree drastically on the byte count (length) of a given string:</p> <pre><code>with open("commedia.pfc", "w") as f: t = ''.join(chr(int(b, base=2)) for b in chunks(compressed, 8)) print(len(t)) f.write(t) Output : 318885 </code></pre> <hr> <pre><code>$&gt; wc commedia.pf...
0
2016-08-26T14:49:06Z
39,169,943
<p>@jsbueno is right. Moreover, if you open the resulting file in <em>binary read</em> mode, you get the good result:</p> <pre><code>&gt;&gt;&gt; with open('commedia.pfc', 'rb') as f: &gt;&gt;&gt; print(len(f.read())) 461491 </code></pre>
0
2016-08-26T15:38:17Z
[ "python", "file", "python-3.x", "byte", "wc" ]
Running a part of python code in background
39,169,120
<p>I am writing a python script which provides two options to the user. In one option, the user input is used to run a function in background. In other, the user input is used to run a function in foreground. How can I achieve both? I don't want to use the "nohup" command to run the full script in background. I only wa...
0
2016-08-26T14:51:49Z
39,172,011
<p>1.<code>threading.Thread</code> maybe help you, and<code>threading.Lock()</code> will lock your data. </p> <p>I just have a idea about it,you can use <code>global input data</code> to check user input and two threads will check it,and determine who locks your output data and the main thread will print it,and also ...
1
2016-08-26T17:46:35Z
[ "python", "nohup" ]
Python bokeh: Multiple color segments on same line
39,169,197
<p>I am using python 3.5 and bokeh 0.12.1, and I am trying to plot a simple line with multiple colors on separate segments. Basically I want the line to have different colors based on a column value. Here is a simplified version of my code:</p> <pre><code>import numpy as np from numpy import vectorize import pandas as...
1
2016-08-26T14:55:36Z
39,169,669
<p>As of Bokeh <code>0.12.1</code> this is not currently supported. Lines can only have one color at a time. Your next best bet is to try the <code>multi_line</code> or <code>segments</code> glyph functions, but doing that will be a bit more verbose (you will have to compute and provide the start/end points of eery ind...
0
2016-08-26T15:22:53Z
[ "python", "bokeh" ]
Python List Iterate Trouble
39,169,214
<p>I'm having a very hard time figuring out I'm doing wrong running my python script in Windows to get the expected result.</p> <p>I have a directory with <strong>list1.txt, list2.txt, list3.txt, list4.txt</strong>, and <strong>list5.txt</strong>. Each list contains separate line strings that are unique such as list1...
1
2016-08-26T14:56:39Z
39,169,340
<p>Your second <code>for</code> loop needs to be a sub-loop of the primary one. Also, do not <code>import os</code> each time you loop through, just do it once. Your code should look like this:</p> <pre><code>def my_range(start, end, step): while start &lt;= end: yield start start += step import o...
4
2016-08-26T15:04:19Z
[ "python", "windows" ]
Python List Iterate Trouble
39,169,214
<p>I'm having a very hard time figuring out I'm doing wrong running my python script in Windows to get the expected result.</p> <p>I have a directory with <strong>list1.txt, list2.txt, list3.txt, list4.txt</strong>, and <strong>list5.txt</strong>. Each list contains separate line strings that are unique such as list1...
1
2016-08-26T14:56:39Z
39,169,365
<p>You're looping through all your files but then only displaying the results of the last file. You need to indent the second for loop:</p> <pre><code>for x in my_range(1, 5, 1): import os rootdir = os.getcwd() fis = rootdir + "\list\list" + str(x) + ".txt" files = open(fis,'rU') lines = files.read...
0
2016-08-26T15:05:37Z
[ "python", "windows" ]
Python List Iterate Trouble
39,169,214
<p>I'm having a very hard time figuring out I'm doing wrong running my python script in Windows to get the expected result.</p> <p>I have a directory with <strong>list1.txt, list2.txt, list3.txt, list4.txt</strong>, and <strong>list5.txt</strong>. Each list contains separate line strings that are unique such as list1...
1
2016-08-26T14:56:39Z
39,169,399
<p>It looks like your indentation is off:</p> <pre><code>for x in my_range(1, 5, 1): import os ... for line in lines: # this should be inside the loop print("Item = " + line) </code></pre> <p>However, you are going about this is a very roundabout way, I would recommend something like this:</...
1
2016-08-26T15:07:30Z
[ "python", "windows" ]
Python List Iterate Trouble
39,169,214
<p>I'm having a very hard time figuring out I'm doing wrong running my python script in Windows to get the expected result.</p> <p>I have a directory with <strong>list1.txt, list2.txt, list3.txt, list4.txt</strong>, and <strong>list5.txt</strong>. Each list contains separate line strings that are unique such as list1...
1
2016-08-26T14:56:39Z
39,169,472
<p>Use <code>os.path.join</code> to create path to a file. I've made some improvement's I'll talk about below.</p> <pre><code>#!/usr/bin/env python import os rootdir = os.getcwd() for x in range(1, 4): filename = 'list' + str(x) + '.txt' fis = os.path.join(rootdir, 'list', filename) files = open(fis,'rU') ...
1
2016-08-26T15:11:11Z
[ "python", "windows" ]
Happybase filtering using rows function
39,169,216
<p>I would like to perform a <code>rows</code> query with Happybase for some known row keys and add a value filter so that only rows matching the filter are returned.</p> <p>In HBase shell you can supply a filter to a get command, like so:</p> <pre><code>get 'meta', 'someuser', {FILTER =&gt; "SingleColumnValueFilter ...
1
2016-08-26T14:56:45Z
39,204,042
<p><strong>Get with filter is equal to Scan with start/stop row.</strong></p> <pre><code>rows = tab.scan(filter="SingleColumnValueFilter('cf','gender',=,'regexstring:^male$')", row_start="someuser", row_stop="someuser") </code></pre> <p>In Java, a <code>FilterList</code> combined <code>MultiRowRa...
0
2016-08-29T10:30:15Z
[ "python", "hbase", "happybase" ]
In Python 3, how to swap two sub-arrays in a 2-dimensional numpy array?
39,169,268
<p>Suppose there is an 2-dimensional numpy array (or matrix in maths) named "A", I want to swap its 1st row with another row "n". n is can be any natural number. The following codes do not work</p> <pre><code>A = np.eye(3) n = 2 A[0], A[n] = A[n], A[0] print(A) </code></pre> <p>you can see it gives (I show the matrix...
0
2016-08-26T15:00:20Z
39,169,495
<p>Try this:</p> <pre><code>import numpy as np A = np.eye(3) A[[0, 2]] = A[[2, 0]] print(A) </code></pre>
1
2016-08-26T15:12:29Z
[ "python", "arrays", "numpy", "matrix" ]
In Python 3, how to swap two sub-arrays in a 2-dimensional numpy array?
39,169,268
<p>Suppose there is an 2-dimensional numpy array (or matrix in maths) named "A", I want to swap its 1st row with another row "n". n is can be any natural number. The following codes do not work</p> <pre><code>A = np.eye(3) n = 2 A[0], A[n] = A[n], A[0] print(A) </code></pre> <p>you can see it gives (I show the matrix...
0
2016-08-26T15:00:20Z
39,169,536
<p>List swapping swaps the variable through pass by reference. So, it does not work to do the inner element swapping by traditional swap by value which is <code>a,b=b,a</code></p> <p>Here you can do the inner list modifications. That performs one after another which eliminates the overwriting problem.</p> <p><strong>...
3
2016-08-26T15:14:11Z
[ "python", "arrays", "numpy", "matrix" ]
In Python 3, how to swap two sub-arrays in a 2-dimensional numpy array?
39,169,268
<p>Suppose there is an 2-dimensional numpy array (or matrix in maths) named "A", I want to swap its 1st row with another row "n". n is can be any natural number. The following codes do not work</p> <pre><code>A = np.eye(3) n = 2 A[0], A[n] = A[n], A[0] print(A) </code></pre> <p>you can see it gives (I show the matrix...
0
2016-08-26T15:00:20Z
39,169,730
<p>Sub-arrays or slices of numpy arrays create views of the data rather than copies. Sometimes numpy can detect this and prevent corruption of data. However, numpy is unable to detect when using the python idiom for swapping. You need to copy at least one of the views before swapping. </p> <pre><code>tmp = A[0].copy()...
0
2016-08-26T15:26:06Z
[ "python", "arrays", "numpy", "matrix" ]
Collections Counter module issue with most_common class
39,169,274
<p>I have a dictionary made from a List called ltst3_upper, and now I am trying to use the class most_common to get only the top 10 key:values with the below code:</p> <pre><code>result3 = Counter(list3_upper).most_common(10) sort_result3 = OrderedDict(sorted(result3.items(), key=operator.itemgetter(1), reverse=True)...
-1
2016-08-26T15:00:51Z
39,169,516
<p><a href="https://docs.python.org/2/library/collections.html#collections.Counter.most_common" rel="nofollow">As the documentation states,</a><code>most_common</code> returns a list of the most common elements. <code>.items</code> is a <code>dict</code> method - lists don't have items. If you want to do something to...
1
2016-08-26T15:13:08Z
[ "python" ]
PyQt4 how does model gets executed?
39,169,332
<p>I am trying to understand PyQt4 model views. I have built simple list model view. Then I used “step” variable to see how the model gets executed.</p> <p>What I can’t understand is: why every time the new loop gets executed, rowCount method gets called 5 times, and from then every 2 times? It is independent fr...
0
2016-08-26T15:03:48Z
39,170,884
<p>The only way to answer this question would be to get the Qt source code for <code>QAbstractItemModel</code> and <code>QAbstractListModel</code>, and create a call graph for the <code>rowCount</code> function. I image it would be quite extensive, because Qt will call <code>rowCount</code> every time it needs to do an...
0
2016-08-26T16:32:26Z
[ "python", "pyqt4", "model-view" ]
PyCharm: How do I call frameworkpython so that it will use the framework python instead of the virtualenv python?
39,169,359
<p>I'm using matplotlib library with my virtualenv. If you use it this way, matplotlib will not plot the graph because it is not the python framework, but the python as per the virtualenv. This problem has been documented on the matplotlib website: <a href="http://matplotlib.org/faq/virtualenv_faq.html" rel="nofollow">...
0
2016-08-26T15:05:20Z
39,170,013
<p>You can set your Python interpreter in Pycharm. See: <a href="https://www.jetbrains.com/help/pycharm/2016.1/configuring-available-python-interpreters.html" rel="nofollow">https://www.jetbrains.com/help/pycharm/2016.1/configuring-available-python-interpreters.html</a></p>
0
2016-08-26T15:42:02Z
[ "python", "osx", "python-2.7", "matplotlib", "pycharm" ]
Python unformatted save
39,169,362
<p>I am using python to create the input for a program. This program takes an unformatted binary file as input. If I were using fortran I would create this file with</p> <pre><code> open (10,file=outfile,status='unknown',form='unformatted') write(10) int1,int2,int3,int4,list0 write (10) list1 write (10) lis...
0
2016-08-26T15:05:27Z
39,171,956
<p>A code like the following shall be a good starting point for what you are trying to do. The structure of your data is not complicated as what I expected to be from your explanation. I wrote a small function to write on list as it is pretty repetitive. The most important thing to notice is that fortran unformatted fi...
1
2016-08-26T17:43:24Z
[ "python", "io", "binary", "fortran", "read-write" ]
What should I do about object from modules not imported in the current module?
39,169,368
<p>I do not know if this is really a technical question but maybe more a question about good practices.</p> <p>Suppose you write a module with several functions which work with Figure object of matplotlib. The functions get the fig object as arguments and return this fig object. For example :</p> <pre><code>def do_sm...
1
2016-08-26T15:05:45Z
39,170,198
<p>If the module is expected to work with objects from another module, I would say you should import that other module for the sake of clarity.</p> <p>After all, Python caches imports. If the other module was already imported, attempting to import it again has no cost. If the other module was not already imported... t...
0
2016-08-26T15:52:10Z
[ "python", "matplotlib", "module" ]
ImproperlyConfigured at **The included urlconf ****does not appear to have any patterns in it
39,169,395
<p>I am working on a django project and facing an issue. The name of my main project is testproject. In <strong>settings.py</strong> I have :</p> <pre><code>ROOT_URLCONF = 'testproject.urls' </code></pre> <p>There are two apps in the project too. One is <strong>example</strong>, other is <strong>new</strong>.</p> <p...
0
2016-08-26T15:07:26Z
39,169,642
<p>In the project's urls.py try:</p> <pre><code>urlpatterns = [ url(r'^new/$', include('new.urls')), url(r'^example/$', include('example.urls')), ] </code></pre> <p>In the example's urls.py:</p> <pre><code>urlpatterns = [ url(r'^$', views.Example.as_view()), ] </code></pre> <p>And the last one:</p> <pre><code>url...
0
2016-08-26T15:21:18Z
[ "python", "django", "url" ]
Scraping JS-fueled webpages with python 3.x on windows computer
39,169,411
<p>This is my first post here, so I hope you'll be kind enough to point out my mistakes if ever I crossed any rules of this website.</p> <p>First off, I'm quite "self-taught" in both english and python, so I apologize in advance if I make any language mistakes.</p> <p>So, I'm learning Python as I said, and I was tryi...
0
2016-08-26T15:08:04Z
39,169,584
<p>There are already full solutions out there like <a href="http://scrapy.org/" rel="nofollow">scrapy</a>.</p> <p>Instead going that route, I'd recommend you give it a shot to libraries like <a href="http://lxml.de/" rel="nofollow">lxml</a> and <a href="http://docs.python-requests.org/en/master/" rel="nofollow">reques...
0
2016-08-26T15:17:32Z
[ "javascript", "python" ]
Scraping JS-fueled webpages with python 3.x on windows computer
39,169,411
<p>This is my first post here, so I hope you'll be kind enough to point out my mistakes if ever I crossed any rules of this website.</p> <p>First off, I'm quite "self-taught" in both english and python, so I apologize in advance if I make any language mistakes.</p> <p>So, I'm learning Python as I said, and I was tryi...
0
2016-08-26T15:08:04Z
39,169,925
<p>I would suggest you try <a href="https://www.crummy.com/software/BeautifulSoup/" rel="nofollow">Beautiful Soup</a></p>
0
2016-08-26T15:37:23Z
[ "javascript", "python" ]
Pytest works with old mock, but not unittest.mock
39,169,563
<p>I'm porting some code from Python 2 to 3, and <code>py.test</code> isn't playing well with the <code>patch</code> decorator from <code>unittest.mock</code>. When I use the <code>patch</code> decorator to pass a mock into the arguments of a test function, <code>py.test</code> instead interprets that argument to be a ...
1
2016-08-26T15:16:21Z
39,177,118
<p>Yes, mock decorators are not supported. It's not such bad -- changing function signature by decorator appliance is considered as bad idea. But you still may use <code>with mock.patch(...)</code> syntax.</p> <p>Also as an option there is <a href="https://pypi.python.org/pypi/pytest-mock" rel="nofollow">pytest-mock<...
1
2016-08-27T03:17:49Z
[ "python", "unit-testing", "python-3.x", "mocking", "py.test" ]
class attribute lookup rule?
39,169,600
<pre><code>&gt;&gt;&gt; class D: ... __class__ = 1 ... __name__ = 2 ... &gt;&gt;&gt; D.__class__ &lt;class 'type'&gt; &gt;&gt;&gt; D().__class__ 1 &gt;&gt;&gt; D.__name__ 'D' &gt;&gt;&gt; D().__name__ 2 </code></pre> <p><strong>Why does <code>D.__class__</code> return the name of the class, while <code>D().__c...
4
2016-08-26T15:18:39Z
39,169,745
<p>The names <code>__class__</code> and <code>__name__</code> are special. Both are <em>data descriptors</em>. <code>__name__</code> is defined on the <code>type</code> object, <code>__class__</code> is defined on <code>object</code> (a base-class of all new-style classes):</p> <pre><code>&gt;&gt;&gt; type.__dict__['_...
6
2016-08-26T15:26:55Z
[ "python", "python-internals" ]
Convert string to dict, then access key:values??? How to access data in a <class 'dict'> for Python?
39,169,718
<p>I am having issues accessing data inside a dictionary. </p> <blockquote> <p>Sys: Macbook 2012 <br> Python: Python 3.5.1 :: Continuum Analytics, Inc.</p> </blockquote> <p>I am working with a <a href="http://dask.pydata.org/en/latest/dataframe-create.html" rel="nofollow">dask.dataframe</a> created from a csv. ...
3
2016-08-26T15:25:32Z
39,169,871
<p>It looks like you end up with something like this</p> <pre><code>s = pd.Series([ dict(type='Point', coordinates=[1, 1]), dict(type='Point', coordinates=[1, 2]), dict(type='Point', coordinates=[1, 3]), dict(type='Point', coordinates=[1, 4]), dict(type='Point', coordinates=[1, ...
1
2016-08-26T15:33:44Z
[ "python", "pandas", "dictionary", "data-manipulation", "dask" ]
Convert string to dict, then access key:values??? How to access data in a <class 'dict'> for Python?
39,169,718
<p>I am having issues accessing data inside a dictionary. </p> <blockquote> <p>Sys: Macbook 2012 <br> Python: Python 3.5.1 :: Continuum Analytics, Inc.</p> </blockquote> <p>I am working with a <a href="http://dask.pydata.org/en/latest/dataframe-create.html" rel="nofollow">dask.dataframe</a> created from a csv. ...
3
2016-08-26T15:25:32Z
39,177,065
<p>My first instinct is to use the <code>json.loads</code> to cast the strings into dicts. But the example you've posted does not follow the json standard since it uses single instead of double quotes. So you have to convert the strings first. </p> <p>A second option is to just use regex to parse the strings. If the d...
1
2016-08-27T03:05:37Z
[ "python", "pandas", "dictionary", "data-manipulation", "dask" ]
Update root in XML after the childs got processed
39,169,735
<p>Related to <a href="http://stackoverflow.com/q/38974656/3316077">this SO question</a> I managed to accomplish what's been asked with the following snippet:</p> <pre><code>import xml.etree.ElementTree as ET def read_xml(): with open('test.xml') as xml_file: return xml_file.read() xml_file = read_xml(...
1
2016-08-26T15:26:18Z
39,192,877
<p>Consider <a href="https://www.w3.org/Style/XSL/" rel="nofollow">XSLT</a>, the transformation language used to manipulate XML documents. Specifically, your re-ordering actually requires the <a href="http://www.jenitennison.com/xslt/grouping/muenchian.html" rel="nofollow">Muenchian Method</a>, a 1.0 procedure to index...
2
2016-08-28T15:29:27Z
[ "python", "xml", "python-3.x" ]
how get input of multiple lines
39,169,764
<p><strong>I have written code to take input as list of string</strong></p> <pre><code>d=["","","","","","","","","",""] i=0 while(True): s=input() d[i]=s i=i+1 if s=="": break </code></pre> <p>But I am not able to process list <code>d</code> to obtain required output. <code>d[0]</code> is storing <code>D...
-4
2016-08-26T15:27:53Z
39,170,392
<p>Is this what you are after?</p> <pre><code>&gt;&gt;&gt; d=[] &gt;&gt;&gt; while(True): ... s=raw_input() ... if s=="":break ... temp = [s] ... d.append(temp) ... a,b,7-6,7-6,6-3 c,d,7-4,7-6,6-2 e,f,6-4,7-6,6-2 &gt;&gt;&gt; d [['a,b,7-6,7-6,6-3'], ['c,d,7-4,7-6,6-2'], ['e,f,6-4,7-6,6-2']] </code></pre> <p...
0
2016-08-26T16:02:56Z
[ "python", "python-2.7", "python-3.x" ]
how get input of multiple lines
39,169,764
<p><strong>I have written code to take input as list of string</strong></p> <pre><code>d=["","","","","","","","","",""] i=0 while(True): s=input() d[i]=s i=i+1 if s=="": break </code></pre> <p>But I am not able to process list <code>d</code> to obtain required output. <code>d[0]</code> is storing <code>D...
-4
2016-08-26T15:27:53Z
39,170,655
<p>Since your stats seem to be separated by a whitespace delimiter, you can use <code>str.split()</code> to separate each of your stats into a list. here is a demo:</p> <pre><code>stats = "Djokovic:Murray:2-6,6-7,7-6,6-3,6-1 Murray:Djokovic:6-3,4-6,6-4,6-3" def compile_stats(stats): stats_lst = list(stats.split("...
0
2016-08-26T16:17:42Z
[ "python", "python-2.7", "python-3.x" ]
Dynamically Splitting Rows in dataframe
39,169,867
<p>I need to take a CSV file and split the rows and have them cascade. The input CSV can have a varying amount of columns(always even), but will always be split the same way. I decided to use Pandas because with some files the output will be 500,000 rows and I thought it would speed things up.</p> <p>Input:</p> <pre...
3
2016-08-26T15:33:29Z
39,170,633
<pre><code># take number of columns and divide by 2 # this is the number of pairs pairs = df.shape[1] // 2 # np.repeat takes the number of rows and returns an object to slice # the dataframe array df.values... then slice... result should be # of length pairs * len(df) a = df.values[np.repeat(np.arange(df.shape[0]), p...
4
2016-08-26T16:16:32Z
[ "python", "csv", "pandas" ]
Dynamically Splitting Rows in dataframe
39,169,867
<p>I need to take a CSV file and split the rows and have them cascade. The input CSV can have a varying amount of columns(always even), but will always be split the same way. I decided to use Pandas because with some files the output will be 500,000 rows and I thought it would speed things up.</p> <p>Input:</p> <pre...
3
2016-08-26T15:33:29Z
39,170,943
<p>Try this:</p> <pre><code>dfNew = pd.DataFrame() ct = 1 while ct &lt;= df.shape[1]/2 : dfNew = dfNew.append(df[df.columns[:2*ct]]) ct +=1 dfNew.sort_values(['h1'], ascending=[True]).reset_index(drop=True).fillna("") print df h1 h2 h3 h4 h5 h6 0 A1 A2 1 A1 A2 A3 A4 2 A...
3
2016-08-26T16:35:48Z
[ "python", "csv", "pandas" ]
Remove empty spaces or NaNs from lists in column of lists in Python/Pandas Dataframe
39,169,905
<p>I have a Pandas dataframe <code>df</code> that looks like this:</p> <pre><code> A B 1 1 [a,b,d,d] 2 6 [,1,4,d,g] 3 a [w,1,NaN,x,y,2] </code></pre> <p>I need to remove the blank in row 2, and the NaN in row 3 to get:</p> <pre><code> A B 1 1 [a,b,d,d] 2 6 [1,4,d,g] 3 a [w,1,x,y,2] </code></pre> <...
1
2016-08-26T15:35:56Z
39,170,109
<p>You need to work on your comprehension skills :)</p> <pre><code>import numpy as np df = pd.DataFrame([ [1, ['a','b','d','d']], [6, ['',1,4,'d','g']], ['a', ['w',1,np.nan,'x','y',2]] ], columns=['A', 'B']) df.B.apply(lambda l: [x for x in l if x not in ['', np.nan]]) </code></pre> <p>w...
3
2016-08-26T15:47:32Z
[ "python", "pandas", null ]
Compare two distributions with different sizes using Python
39,169,913
<p>I want to compare two different distributions, where one has 100 data points, the other 150 data points.</p> <p>In <code>seaborn</code> I am able to do it using <code>lmplot</code> in this way:</p> <pre><code>import pandas as pd import seaborn as sns df = pd.DataFrame(data) sns.lmplot(x="dist1", y="dist2", data=d...
1
2016-08-26T15:36:17Z
39,171,822
<p>Assuming that want the two data sets on the same axis, see <a href="http://stackoverflow.com/questions/4270301/matplotlib-multiple-datasets-on-the-same-scatter-plot">this</a>. You need a reference to the axis to which you want to draw.</p> <p>sample:</p> <pre><code>a = [1.1, 2.8, 14, 21, 23] b = [1, 2, 3, 4, 5, 6,...
0
2016-08-26T17:33:07Z
[ "python", "matplotlib", "distribution", "seaborn", "percentile" ]
pandas: all NaNs when subtracting two dataframes
39,169,923
<p>I have two series. I want to subtract one dataframe from another dataframe, even though they have a different number of columns.</p> <pre><code>&gt;df1 index 0 1 2 3 4 5 TOTAL 5 46 56 110 185 629 &gt;df2 index 1 2 3 4 5 Use 25 37 86 151 512 </code></pre> <p>I would assu...
3
2016-08-26T15:37:15Z
39,170,178
<p>You are subtracting two dataframes. <strong><em>Both</em></strong> column and row indices must match. In your case, the row indices <code>TOTAL</code> and <code>Use</code> do not match.</p> <p>To get what you're looking for, you want to subtract the series <code>df2.ix['Use']</code> from <code>df1</code> </p> <...
3
2016-08-26T15:51:19Z
[ "python", "pandas" ]
How do I produce a sound signal from an array?
39,169,933
<p>I'm working on a project which requires some sound processing. I know how to record the sound and convert the signal into a float in order to process it. The problem is, that I don't know how to convert those numbers back to bytes in order to play the final processed sound.</p> <p>Imagine an array like this one:</p...
0
2016-08-26T15:37:42Z
39,202,731
<p>First, you'll need to know the maximum range of your values. Given your values, that might be from <code>-2000.0</code> to <code>2000.0</code>, but I have no idea, so my guess is most likely wrong. Typically, the numbers in a floating point audio signal range from <code>-1.0</code> to <code>1.0</code>. Obviously, yo...
0
2016-08-29T09:25:25Z
[ "python", "audio", "byte" ]
Change an XML Value in Python
39,169,961
<p>If I have an XML file such as below, how would I be able to change the version from 50 to 51?</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;config&gt; &lt;updateCheck seconds="2" /&gt; &lt;unturnedVersion version="50" /&gt; &lt;unturnedFolder recoveryBundlesAfterUpdates="false" /&gt; ...
1
2016-08-26T15:39:31Z
39,170,010
<p>Use <a href="https://docs.python.org/2/library/xml.etree.elementtree.html" rel="nofollow"><code>xml.etree.ElementTree</code></a>. Locate the element via, for example, <code>find()</code>, update the <code>version</code> attribute through the <a href="https://docs.python.org/2/library/xml.etree.elementtree.html#xml.e...
4
2016-08-26T15:41:59Z
[ "python", "xml" ]
Unable to append data to array
39,169,980
<p>I am retrieving a record set from a database.<br> Then using a <strong>for</strong> statement I am trying to construct my data to match a 3rd party API.</p> <p>But I get this error and can't figure it out: </p> <blockquote> <p>"errorType": "TypeError", "errorMessage": "list indices must be integers, not str...
1
2016-08-26T15:40:30Z
39,170,069
<p>What the error is saying is that you are trying to access an array element with the help of string not index (int).</p> <p>I believe your mistake is in this line:</p> <pre><code>messages['english']['merge_vars']['vars'].append({..}) </code></pre> <p>You declared <code>merge_vars</code> as array like so:</p> <pre...
0
2016-08-26T15:45:08Z
[ "python", "python-2.7" ]
Unable to append data to array
39,169,980
<p>I am retrieving a record set from a database.<br> Then using a <strong>for</strong> statement I am trying to construct my data to match a 3rd party API.</p> <p>But I get this error and can't figure it out: </p> <blockquote> <p>"errorType": "TypeError", "errorMessage": "list indices must be integers, not str...
1
2016-08-26T15:40:30Z
39,170,078
<p>This code seems to indicate that <code>messages['english']['merge_vars']</code> is a list, since you initialize it as such:</p> <pre><code>messages['english'] = { ... 'merge_vars': [], ... } </code></pre> <p>And call <code>append</code> on it:</p> <pre><code>messages['english']['merge_vars'].append({ ...
2
2016-08-26T15:45:56Z
[ "python", "python-2.7" ]
Unable to append data to array
39,169,980
<p>I am retrieving a record set from a database.<br> Then using a <strong>for</strong> statement I am trying to construct my data to match a 3rd party API.</p> <p>But I get this error and can't figure it out: </p> <blockquote> <p>"errorType": "TypeError", "errorMessage": "list indices must be integers, not str...
1
2016-08-26T15:40:30Z
39,170,114
<p>Your issues, as the Error Message is saying, is here: <code>messages['english']['merge_vars']['vars'].append({'name': key,'content': value})</code></p> <p>The item <code>messages['english']['merge_vars']</code> is a <code>list</code> and thus you're trying to access an element when you do something like <code>list...
0
2016-08-26T15:47:51Z
[ "python", "python-2.7" ]
regular expression unicode character does not match
39,170,123
<p>I am trying to use regular expression over a text that contains some special character like à,è,ù etc. </p> <pre><code>filter_2 = ur'(?:^\|\s+)?(?:(?:main_interests)|(?:influenced)|(?:influences))\s+?=[\s\W]+?(?:[\w}])*?([\d\w\s\-()*–&amp;;\[\]|.&lt;&gt;:/",\']*)(?=\n)' compiled = re.compile(filter_2, flags=re...
1
2016-08-26T15:48:26Z
39,170,277
<p>In <strong>Python 3</strong>, the regex doesn't compile. This seemed to work for me when I changed:</p> <pre><code>filter_6 = ur'(?&lt;=\[\[)([\w\s.-]+)((?=]])|(?=|))' </code></pre> <p>to just a unicode (not raw) string:</p> <pre><code>filter_6 = u'(?&lt;=\[\[)([\w\s.-]+)((?=]])|(?=|))' </code></pre> <p>In <stro...
2
2016-08-26T15:56:56Z
[ "python", "regex", "unicode" ]