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 |
|---|---|---|---|---|---|---|---|---|---|
Extract specific lines from multiple text files | 38,449,795 | <p>I want to print certain lines from multiple text files in a folder, depending on the file name. Consider the following text files named from 3 words separated by underscore:</p>
<pre><code>Small_Apple_Red.txt
Small_Orange_Yellow.txt
Large_Apple_Green.txt
Large_Orange_Green.txt
</code></pre>
<p>How can the followin... | 1 | 2016-07-19T04:50:55Z | 38,452,522 | <pre><code>use strict;
use warnings;
my @file_names = ("Small_Apple_Red.txt",
"Small_Orange_Yellow.txt",
"Large_Apple_Green.txt",
"Large_Orange_Green.txt");
foreach my $file ( @file_names) {
if ( $file =~ /^Small/){ // "^" marks the begining of the string
... | 0 | 2016-07-19T07:53:16Z | [
"java",
"python",
"perl",
"awk",
"sed"
] |
Extract specific lines from multiple text files | 38,449,795 | <p>I want to print certain lines from multiple text files in a folder, depending on the file name. Consider the following text files named from 3 words separated by underscore:</p>
<pre><code>Small_Apple_Red.txt
Small_Orange_Yellow.txt
Large_Apple_Green.txt
Large_Orange_Green.txt
</code></pre>
<p>How can the followin... | 1 | 2016-07-19T04:50:55Z | 38,452,933 | <p>In Awk:</p>
<pre><code>awk 'FILENAME ~ /^Large/ {print $1,$4}
FILENAME ~ /^Small/ {print $3,$2}' *
</code></pre>
<p>in Perl:</p>
<pre><code>perl -naE 'say "$F[0] $F[3]" if $ARGV =~ /^Large/;
say "$F[2] $F[1]" if $ARGV =~ /^Small/ ' *
</code></pre>
| 0 | 2016-07-19T08:16:14Z | [
"java",
"python",
"perl",
"awk",
"sed"
] |
Extract specific lines from multiple text files | 38,449,795 | <p>I want to print certain lines from multiple text files in a folder, depending on the file name. Consider the following text files named from 3 words separated by underscore:</p>
<pre><code>Small_Apple_Red.txt
Small_Orange_Yellow.txt
Large_Apple_Green.txt
Large_Orange_Green.txt
</code></pre>
<p>How can the followin... | 1 | 2016-07-19T04:50:55Z | 38,453,526 | <p>Try this one:</p>
<pre><code>use strict;
use warnings;
use Cwd;
use File::Basename;
my $dir = getcwd(); #or shift the input values from the user
my @txtfiles = glob("$dir/*.txt");
foreach my $each_txt_file (@txtfiles)
{
open(DATA, $each_txt_file) || die "reason: $!";
my @allLines = <DATA>;
(my ... | 0 | 2016-07-19T08:43:10Z | [
"java",
"python",
"perl",
"awk",
"sed"
] |
Collapsing identical adjacent rows in a Pandas Series | 38,449,806 | <p>Basically if a column of my pandas dataframe looks like this:</p>
<pre><code>[1 1 1 2 2 2 3 3 3 1 1]
</code></pre>
<p>I'd like it to be turned into the following:</p>
<pre><code>[1 2 3 1]
</code></pre>
| 3 | 2016-07-19T04:51:59Z | 38,449,916 | <h3>You can write a simple function that loops through the elements of your series only storing the first element in a run.</h3>
<p>As far as I know, there is no tool built in to pandas to do this. But it is not a lot of code to do it yourself.</p>
<pre><code>import pandas
example_series = pandas.Series([1, 1, 1, 2, ... | 1 | 2016-07-19T05:03:31Z | [
"python",
"pandas"
] |
Collapsing identical adjacent rows in a Pandas Series | 38,449,806 | <p>Basically if a column of my pandas dataframe looks like this:</p>
<pre><code>[1 1 1 2 2 2 3 3 3 1 1]
</code></pre>
<p>I'd like it to be turned into the following:</p>
<pre><code>[1 2 3 1]
</code></pre>
| 3 | 2016-07-19T04:51:59Z | 38,450,743 | <p>You could write a function that does the following:</p>
<pre><code>x = pandas.Series([1 1 1 2 2 2 3 3 3 1 1])
y = x-x.shift(1)
y[0] = 1
result = x[y!=0]
</code></pre>
| 1 | 2016-07-19T06:10:26Z | [
"python",
"pandas"
] |
Collapsing identical adjacent rows in a Pandas Series | 38,449,806 | <p>Basically if a column of my pandas dataframe looks like this:</p>
<pre><code>[1 1 1 2 2 2 3 3 3 1 1]
</code></pre>
<p>I'd like it to be turned into the following:</p>
<pre><code>[1 2 3 1]
</code></pre>
| 3 | 2016-07-19T04:51:59Z | 38,451,484 | <p>You can use DataFrame's diff and indexing:</p>
<pre><code>>>> df = pd.DataFrame([1,1,2,2,2,2,3,3,3,3,1])
>>> df[df[0].diff()!=0]
0
0 1
2 2
6 3
10 1
>>> df[df[0].diff()!=0].values.ravel() # If you need an array
array([1, 2, 3, 1])
</code></pre>
<p>Same works for Series:</p>
<p... | 1 | 2016-07-19T06:57:30Z | [
"python",
"pandas"
] |
Collapsing identical adjacent rows in a Pandas Series | 38,449,806 | <p>Basically if a column of my pandas dataframe looks like this:</p>
<pre><code>[1 1 1 2 2 2 3 3 3 1 1]
</code></pre>
<p>I'd like it to be turned into the following:</p>
<pre><code>[1 2 3 1]
</code></pre>
| 3 | 2016-07-19T04:51:59Z | 38,452,663 | <p>You can use <code>shift</code> to create a boolean mask to compare the row against the previous row:</p>
<pre><code>In [67]:
s = pd.Series([1,1,2,2,2,2,3,3,3,3,4,4,5])
s[s!=s.shift()]
Out[67]:
0 1
2 2
6 3
10 4
12 5
dtype: int64
</code></pre>
| 0 | 2016-07-19T08:01:04Z | [
"python",
"pandas"
] |
Simple ieteration/append loop not returning correct array: | 38,449,886 | <p>I have a six-line section of code:</p>
<pre><code>setA = 101
for i in range(101):
l = [0]
q = i * 3
f = str(q)
print f
</code></pre>
<p>That prints the numbers upwards:</p>
<pre><code>0
3
6
9
12
15
18
21
24
27
30
33
</code></pre>
<p>But I want them in an array, and so I changed it:</p>
<pre><co... | 0 | 2016-07-19T05:00:30Z | 38,449,926 | <p>You're resetting your array with each iteration:</p>
<pre><code>for i in range(101):
l = [0]
</code></pre>
<p>Move that out of your loop and it'll work:</p>
<pre><code>l = []
for i in range(101):
q = i * 3
f = str(q)
l.append(f)
print str(l)
</code></pre>
| 3 | 2016-07-19T05:04:16Z | [
"python",
"arrays",
"loops",
"set",
"range"
] |
Simple ieteration/append loop not returning correct array: | 38,449,886 | <p>I have a six-line section of code:</p>
<pre><code>setA = 101
for i in range(101):
l = [0]
q = i * 3
f = str(q)
print f
</code></pre>
<p>That prints the numbers upwards:</p>
<pre><code>0
3
6
9
12
15
18
21
24
27
30
33
</code></pre>
<p>But I want them in an array, and so I changed it:</p>
<pre><co... | 0 | 2016-07-19T05:00:30Z | 38,452,046 | <p>You could use python's list comprehension:</p>
<pre><code>l = [i*3 for i in range(101)]
# Variable l now contains a list of integers
l_str = [str(i) for i in range(101)]
# l_str is a list of strings (if you need string or going to print them)
# if you need to print it out you can use this construction
print('\n'.... | -1 | 2016-07-19T07:27:36Z | [
"python",
"arrays",
"loops",
"set",
"range"
] |
How to remove english alphabets from list in python | 38,449,902 | <p>I have a list with some English text while in other Hindi. I want to remove all elements in English. How to obtain that? Example: How to remove <code>hello</code> in the list <code>l</code> below?</p>
<pre><code>l = ['मà¥à¤¸à¥à¤','à¤à¥à¤²à¤¨à¤¾','दारा','hello','मà¥à¤¦à¥à¤°à¤£']
for i in range(... | 3 | 2016-07-19T05:01:48Z | 38,450,028 | <p>You can use Python's regular expression module.</p>
<pre><code>import re
l=['मà¥à¤¸à¥à¤','à¤à¥à¤²à¤¨à¤¾','दारा','hello','मà¥à¤¦à¥à¤°à¤£']
for string in l:
if not re.search(r'[a-zA-Z]', string):
print(string)
</code></pre>
| 0 | 2016-07-19T05:14:15Z | [
"python",
"python-unicode",
"hindi",
"non-english"
] |
How to remove english alphabets from list in python | 38,449,902 | <p>I have a list with some English text while in other Hindi. I want to remove all elements in English. How to obtain that? Example: How to remove <code>hello</code> in the list <code>l</code> below?</p>
<pre><code>l = ['मà¥à¤¸à¥à¤','à¤à¥à¤²à¤¨à¤¾','दारा','hello','मà¥à¤¦à¥à¤°à¤£']
for i in range(... | 3 | 2016-07-19T05:01:48Z | 38,450,095 | <p>you can use the isalpha() function </p>
<pre><code>l = ['मà¥à¤¸à¥à¤', 'à¤à¥à¤²à¤¨à¤¾', 'दारा', 'hello', 'मà¥à¤¦à¥à¤°à¤£']
for word in l:
if not word.isalpha():
print word
</code></pre>
<p>will give you the result:</p>
<pre><code>मà¥à¤¸à¥à¤
à¤à¥à¤²à¤¨à¤¾
दारा
मà¥à¤¦... | 6 | 2016-07-19T05:19:16Z | [
"python",
"python-unicode",
"hindi",
"non-english"
] |
How to remove english alphabets from list in python | 38,449,902 | <p>I have a list with some English text while in other Hindi. I want to remove all elements in English. How to obtain that? Example: How to remove <code>hello</code> in the list <code>l</code> below?</p>
<pre><code>l = ['मà¥à¤¸à¥à¤','à¤à¥à¤²à¤¨à¤¾','दारा','hello','मà¥à¤¦à¥à¤°à¤£']
for i in range(... | 3 | 2016-07-19T05:01:48Z | 38,450,107 | <p>You can use <code>filter</code> with regex <code>match</code>:</p>
<pre><code>import re
list(filter(lambda w: not re.match(r'[a-zA-Z]+', w), ['मà¥à¤¸à¥à¤','à¤à¥à¤²à¤¨à¤¾','दारा','hello','मà¥à¤¦à¥à¤°à¤£']))
</code></pre>
| 0 | 2016-07-19T05:21:23Z | [
"python",
"python-unicode",
"hindi",
"non-english"
] |
How to remove english alphabets from list in python | 38,449,902 | <p>I have a list with some English text while in other Hindi. I want to remove all elements in English. How to obtain that? Example: How to remove <code>hello</code> in the list <code>l</code> below?</p>
<pre><code>l = ['मà¥à¤¸à¥à¤','à¤à¥à¤²à¤¨à¤¾','दारा','hello','मà¥à¤¦à¥à¤°à¤£']
for i in range(... | 3 | 2016-07-19T05:01:48Z | 38,450,195 | <p>How about a simple list comprehension:</p>
<pre><code>>>> import re
>>> i = ['मà¥à¤¸à¥à¤','à¤à¥à¤²à¤¨à¤¾','दारा','hello','मà¥à¤¦à¥à¤°à¤£']
>>> [w for w in i if not re.match(r'[A-Z]+', w, re.I)]
['मà¥à¤¸à¥à¤', 'à¤à¥à¤²à¤¨à¤¾', 'दारा', 'मà¥à¤¦à¥à¤°à¤£']... | 2 | 2016-07-19T05:29:15Z | [
"python",
"python-unicode",
"hindi",
"non-english"
] |
Reseting pandas row index to start at number other than 0? | 38,449,955 | <p>Currently I am trying to read in a .csv file and then use the to_html() to create a table with indexing on the side. All lines of code here: </p>
<pre><code>import pandas as pd
df = pd.read_csv('file.csv')
df.to_html('example.html')
</code></pre>
<p>As expected I am currently getting:</p>
<pre><code> Yea... | 2 | 2016-07-19T05:07:10Z | 38,450,122 | <p>I know it looks like a hack, but what if just change index series. For example:</p>
<pre><code>df.index = df.index + 2
</code></pre>
| 2 | 2016-07-19T05:22:27Z | [
"python",
"csv",
"pandas",
"indexing"
] |
Reshaping a pandas dataframe | 38,449,978 | <p>I have a Pandas dataframe which looks like this, where the columns are as follows:</p>
<ol>
<li><code>userid</code> is as the name suggests</li>
<li><code>name</code> is each api event</li>
<li><code>count</code>is the frequency of the event</li>
</ol>
<blockquote>
<p><a href="http://i.stack.imgur.com/xoLEi.png"... | 0 | 2016-07-19T05:08:40Z | 38,450,053 | <p>Use DataFrame's <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.transpose.html" rel="nofollow">transpose</a> method:</p>
<pre><code>print(df.transpose())
</code></pre>
<p>Or just:</p>
<pre><code>print(df.T)
</code></pre>
| 0 | 2016-07-19T05:16:18Z | [
"python",
"pandas"
] |
Reshaping a pandas dataframe | 38,449,978 | <p>I have a Pandas dataframe which looks like this, where the columns are as follows:</p>
<ol>
<li><code>userid</code> is as the name suggests</li>
<li><code>name</code> is each api event</li>
<li><code>count</code>is the frequency of the event</li>
</ol>
<blockquote>
<p><a href="http://i.stack.imgur.com/xoLEi.png"... | 0 | 2016-07-19T05:08:40Z | 38,450,280 | <p>What about </p>
<pre><code>df.pivot(index='userid', columns='name', values='count_of_name')
</code></pre>
<p>Where df is your pandas dataframe
(will insert Nan if some values do not exist. For example if there is no count for event A for user X)</p>
<p>For filling in <code>0</code>instead of a <code>NaN</code> wh... | 3 | 2016-07-19T05:36:19Z | [
"python",
"pandas"
] |
Python Borg Multiple Inheritance and Shared State | 38,450,017 | <p>I have this problem in a fun project where I have to tell a class to execute an operation for a certain time period with the start and end times specified (along with the interval ofc).</p>
<p>For the sake of argument consider that class A (the class that has the API that I call) has to call classes B (which calls ... | 0 | 2016-07-19T05:12:44Z | 38,450,226 | <p>As a general rule of thumb, try to keep things simple. You're considering very complex solutions to a relatively simple problem.</p>
<p>With the information you've given, it seems you could just wrap the request for execution of an operation in an object that also includes the context. Then you'd just be passing ar... | 0 | 2016-07-19T05:31:48Z | [
"python",
"inheritance",
"design-patterns"
] |
How to query from a large amount of information (Python) | 38,450,176 | <p>I've recently been thinking of projects to start, and I've settled on an OS fingerprinting tool. I know that the OS can be determined by matching TTL and TCP window size, but I don't know the most efficient way to cross-reference that information to identify the OS.</p>
<p>My idea so far is to have a text file cont... | -1 | 2016-07-19T05:27:23Z | 38,451,909 | <p>I know it's a <em>headshot answer</em> but I can't keep silent. Answering on your question <strong>How to query from a large amount of information (Python)</strong> <em>literally</em> I would recommend to read from special device <strong>/dev/urandom</strong>. The code can be looks like this:</p>
<pre><code>informa... | 0 | 2016-07-19T07:20:43Z | [
"python",
"operating-system",
"cross-reference"
] |
Redmine API to fetch all issue in python | 38,450,320 | <p>I am trying to fetch all the issue from redmine</p>
<pre><code>list_1 = []
issuess = conn_red.issue.all()
for i in issuess:
list_1.append(i)
print len(list_1)
</code></pre>
<p>The print statement result is 575</p>
<p>But In Redmine, I have 2735 issue.
I wonder,</p>
<ol>
<li>why it is restricting to 575.</li>... | 0 | 2016-07-19T05:39:35Z | 38,452,886 | <p>By default, the REST API only returns open issues. If you want to get all issues, you have to define a filter:</p>
<pre><code>issues = conn_red.issue.filter(status_id='*')
</code></pre>
<p>Please refer to the <a href="http://python-redmine.readthedocs.io/resources/issue.html#filter" rel="nofollow">documentation of... | 4 | 2016-07-19T08:13:46Z | [
"python",
"redmine",
"redmine-api",
"python-redmine"
] |
Best ways to do ssh and scp in Python? | 38,450,526 | <p>What are the best ways to do ssh and scp in Python? I want to eliminate an Apache Ant build like we are doing in Java.</p>
| 0 | 2016-07-19T05:53:55Z | 38,450,692 | <p>Use <code>paramiko</code>. it is one of the best python package for ssh and scp.</p>
<p>link: <a href="http://stackoverflow.com/questions/10745138/python-paramiko-ssh">python paramiko ssh</a></p>
<p><a href="http://www.paramiko.org/" rel="nofollow">http://www.paramiko.org/</a></p>
| 1 | 2016-07-19T06:06:25Z | [
"python",
"ssh",
"scp"
] |
Where to put this class in django? | 38,450,724 | <p>I have a class for data entry that requires <strong>a lot</strong> of input from the user. I use it to semi-automate the process of putting stuff in the db where it is possible. </p>
<p>My instinct is to put it in my model classes, and write tests on it, but it would be an insane amount of work, and I have a lot of... | 0 | 2016-07-19T06:09:03Z | 38,451,212 | <p>Don't try to force a raw python function into a single box.</p>
<p>What you should have done (a <em>long</em> <em>long</em> time ago), is separate it out into separate functions so it would be easier to test and figure things out.</p>
<p>Since you're asking for user input, websites do that through forms, so you're... | 2 | 2016-07-19T06:41:39Z | [
"python",
"django"
] |
Where to put this class in django? | 38,450,724 | <p>I have a class for data entry that requires <strong>a lot</strong> of input from the user. I use it to semi-automate the process of putting stuff in the db where it is possible. </p>
<p>My instinct is to put it in my model classes, and write tests on it, but it would be an insane amount of work, and I have a lot of... | 0 | 2016-07-19T06:09:03Z | 38,453,928 | <p>I would put this into <a href="https://docs.djangoproject.com/en/1.9/howto/custom-management-commands/" rel="nofollow"><code>management/commands</code></a>. Just wrap your functions into a <code>BaseCommand</code> class and you are good to go. And here is <a href="https://docs.djangoproject.com/en/1.9/topics/testing... | 2 | 2016-07-19T09:01:47Z | [
"python",
"django"
] |
Django view showing error in virtual environment | 38,450,917 | <p>I am using virtual Environment to develop the project. Using python3 and Django 1.9.7<br>
I am splitting views into multiple files. Below is the tree structure.</p>
<pre><code>|-- urls.pyc
`-- Views
|-- DashboardView.py
|-- DashboardView.pyc
|-- __init__.py
|-- __init__.pyc
|-- __pycache__
|... | 1 | 2016-07-19T06:22:55Z | 38,451,054 | <p>In your <code>__init__.py</code> try to use local imports instead, this may be a problem if you are using <code>python3</code> in your virtual environment.</p>
<pre><code>from .VehicleView import *
from .DashboardView import *
</code></pre>
<p>Besides file and module names in python should follow snake case conven... | 2 | 2016-07-19T06:31:40Z | [
"python",
"django"
] |
How do i detect multiple languages on the same line? | 38,450,950 | <p>There are a couple of api's in java as well as python and also tried some online demos but all the api's takes the sentence as a whole and give an overall probable language. In my case, i have multiple languages on the same line that needs to be detected and languages except English is to be eliminated while keeping... | 1 | 2016-07-19T06:25:46Z | 38,453,635 | <p>I believe the direction you have taken from reading the comments is the best solution : "i have tried -tokenizing the entire sentence into words and checking language for each words". However you should consider developing a <a href="https://en.wikipedia.org/wiki/Bag-of-words_model" rel="nofollow">bag of words algor... | 0 | 2016-07-19T08:48:43Z | [
"java",
"python",
"language-detection"
] |
How to get the first element of a complex list in Python | 38,451,004 | <p>In Python, I used to get first element of a 2-d list by</p>
<pre><code>a = [[0, 1], [2, 3]]
a[:][0]
# [0, 2]
</code></pre>
<p>Now, the list is sort of complex, the way to get the first elements does not work</p>
<pre><code>a = [['sad', 1], ['dsads', 2]]
a[:][0]
# ['sad', 1]
</code></pre>
<p>I do not know what is... | -2 | 2016-07-19T06:28:47Z | 38,451,157 | <p>you could use in-built <a href="https://docs.python.org/3/library/functions.html#zip" rel="nofollow">zip</a> :</p>
<blockquote>
<p>aggregates elements from each of the iterables</p>
</blockquote>
<pre><code>a = [['sad', 1], ['dsads', 2]]
zip(*a)[0]
#results :
('sad', 'dsads')
</code></pre>
<p>You can convert t... | 4 | 2016-07-19T06:38:22Z | [
"python",
"python-2.7"
] |
How to get the first element of a complex list in Python | 38,451,004 | <p>In Python, I used to get first element of a 2-d list by</p>
<pre><code>a = [[0, 1], [2, 3]]
a[:][0]
# [0, 2]
</code></pre>
<p>Now, the list is sort of complex, the way to get the first elements does not work</p>
<pre><code>a = [['sad', 1], ['dsads', 2]]
a[:][0]
# ['sad', 1]
</code></pre>
<p>I do not know what is... | -2 | 2016-07-19T06:28:47Z | 38,451,292 | <p>Using numpy :</p>
<pre><code>>>> a = [['sad', 1], ['dsads', 2]]
>>> import numpy
>>> my_array = numpy.array(a)
>>> print my_array[:,0]
['sad' 'dsads']
</code></pre>
| 1 | 2016-07-19T06:46:25Z | [
"python",
"python-2.7"
] |
How to visualize multi-index-ed data in orange? | 38,451,029 | <p>I am using <code>pandas</code> library in python to generate a multi-indexed data, i.e., the columns are multi-indexed. The indices are <code>category</code> and <code>source</code>. I save this data as <code>.csv</code> file. In the file, the first row is the <code>category</code> values and second row is correspon... | 0 | 2016-07-19T06:29:59Z | 38,476,233 | <p>According to <a href="http://orange-visual-programming.readthedocs.io/loading-your-data/index.html" rel="nofollow">documentation</a>, Orange does not support reading multi-indexed data.</p>
<p>In order to visualize the data, you will need to convert it to a normal tabular format (one column per feature) before expo... | 0 | 2016-07-20T08:33:59Z | [
"python",
"pandas",
"orange"
] |
How to list available regions with Boto3 (Python) | 38,451,032 | <p>As AWS expands and adds new regions, I'd like to have my code automatically detect that. Currently, the "Select your region" is hard coded but I would like to parse the following for just the <strong>RegionName</strong>.</p>
<pre><code>import boto3
ec2 = boto3.client('ec2')
regions = ec2.describe_regions()
print(r... | 0 | 2016-07-19T06:30:15Z | 38,451,512 | <p>The following will return you the RegionName and Endpoint for each region.</p>
<pre><code># List all regions
client = boto3.client('ec2')
regions = client.describe_regions()['Regions']
for region in regions:
print('Name: %s. Endpoint: %s' % (region['RegionName'], region['Endpoint']))
</code></pre>
| 0 | 2016-07-19T06:59:27Z | [
"python",
"amazon-web-services",
"boto3"
] |
How to list available regions with Boto3 (Python) | 38,451,032 | <p>As AWS expands and adds new regions, I'd like to have my code automatically detect that. Currently, the "Select your region" is hard coded but I would like to parse the following for just the <strong>RegionName</strong>.</p>
<pre><code>import boto3
ec2 = boto3.client('ec2')
regions = ec2.describe_regions()
print(r... | 0 | 2016-07-19T06:30:15Z | 38,464,150 | <p>In addition to Frédéric's answer, you can also get known regions for each service without making any service calls. I will caution you, however, that since this is pulling from botocore's local models rather than hitting an endpoint, it will not always be exhaustive since you need to update botocore to update the ... | 1 | 2016-07-19T16:41:23Z | [
"python",
"amazon-web-services",
"boto3"
] |
How to increment all numbers of a string and insert every of them after every actual number? | 38,451,103 | <p>How can I append incremented numbers to the old ones in Python.
I have a string and a regular expression to find all of its numbers, but when it comes to the task, it doesn't work well. </p>
<p>Here's what I mean:</p>
<p>"This string contains numbers: 4401 4402 4448" -> "This string contains numbers: 4401 4402 440... | -3 | 2016-07-19T06:34:47Z | 38,451,189 | <p>Try <a href="https://docs.python.org/3.5/library/re.html#re.sub" rel="nofollow"><code>re.sub()</code></a>.</p>
<pre><code>import re
line = "This string contains numbers: 4401 4402 4448"
line = re.sub(
'\d+',
lambda m: '{} {}'.format(m.group(), int(m.group())+1),
line)
assert line == "This string conta... | 3 | 2016-07-19T06:40:20Z | [
"python",
"regex",
"python-3.x"
] |
Numpy & Pandas: Return histogram values from pandas histogram plot? | 38,451,407 | <p>I know that I can plot histogram by pandas:</p>
<pre><code>df4 = pd.DataFrame({'a': np.random.randn(1000) + 1})
df4['a'].hist()
</code></pre>
<p><a href="http://i.stack.imgur.com/BCNM8.png" rel="nofollow"><img src="http://i.stack.imgur.com/BCNM8.png" alt="enter image description here"></a></p>
<p>But how can I re... | 2 | 2016-07-19T06:53:06Z | 38,451,632 | <p>The quick answer is:</p>
<pre><code>pd.cut(df4['a'], 10).value_counts().sort_index()
</code></pre>
<p>From the <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.hist.html" rel="nofollow">documentation</a>:</p>
<blockquote>
<pre><code>bins: integer, default 10
Number of histogram bins... | 3 | 2016-07-19T07:05:48Z | [
"python",
"numpy",
"pandas",
"matplotlib"
] |
Project guidance - multiple cvs / modification to data frame | 38,451,449 | <p>Just a quick question on a guidance before having my nerves broken ! :)</p>
<p>I have multiple CSV file that i would like to merge to one BIG new CSV file. </p>
<p>All the files have the same exact structure :</p>
<pre><code>Muzicast V2;;;;;;;;
Zoom mÃdia sur Virgin Radio;;;;;;;;;
Sem. 16 : Du 15 avril 2016 au ... | 0 | 2016-07-19T06:55:24Z | 38,463,931 | <p>I'm assuming all your csv files are in <code>"./data/"</code>, defined in <code>main_dir</code>, and that the sum of all your csv does not exceed your RAM memory. The trick is to use a temporary variable <code>current_df</code> and then to append it to a final dataframe <code>final_df</code> with <code>pd.concat</co... | 0 | 2016-07-19T16:27:46Z | [
"python",
"csv",
"dataframe"
] |
How to fetch whole string from start of comma to next comma or newline when "/" occurs in string | 38,451,529 | <p>I have string in format</p>
<pre><code>,xys=2/3,
d=e,
b*y,
b/e
</code></pre>
<p>I want to fetch <code>xys=2/3</code> and <code>b/e</code>.</p>
<p>Right now I have regular expression which just picks <code>2/3</code> and <code>b/e</code>.</p>
<pre><code> pattern = r'(\S+)\s*(?<![;|<|#])/\s*(\S+)'
regex = r... | 0 | 2016-07-19T07:00:16Z | 38,451,651 | <p>No need for regular expressions.</p>
<pre><code>s = """,xys=2/3,
d=e,
b*y,
b/e
"""
l = s.split("\n")
for line in l:
if '/' in line:
print(line.strip(","))
</code></pre>
| 0 | 2016-07-19T07:06:49Z | [
"python",
"regex"
] |
How to fetch whole string from start of comma to next comma or newline when "/" occurs in string | 38,451,529 | <p>I have string in format</p>
<pre><code>,xys=2/3,
d=e,
b*y,
b/e
</code></pre>
<p>I want to fetch <code>xys=2/3</code> and <code>b/e</code>.</p>
<p>Right now I have regular expression which just picks <code>2/3</code> and <code>b/e</code>.</p>
<pre><code> pattern = r'(\S+)\s*(?<![;|<|#])/\s*(\S+)'
regex = r... | 0 | 2016-07-19T07:00:16Z | 38,451,739 | <p>Just go with StringTokenizer class:</p>
<pre class="lang-java prettyprint-override"><code>import java.util.StringTokenizer;
public class StringTokenTest {
public static void main(String[] args) {
String line="My;Name;Is;Kunal;Kuamr";
StringTokenizer strtokn = new StringTokenizer(line, ";");
... | -1 | 2016-07-19T07:11:29Z | [
"python",
"regex"
] |
How to fetch whole string from start of comma to next comma or newline when "/" occurs in string | 38,451,529 | <p>I have string in format</p>
<pre><code>,xys=2/3,
d=e,
b*y,
b/e
</code></pre>
<p>I want to fetch <code>xys=2/3</code> and <code>b/e</code>.</p>
<p>Right now I have regular expression which just picks <code>2/3</code> and <code>b/e</code>.</p>
<pre><code> pattern = r'(\S+)\s*(?<![;|<|#])/\s*(\S+)'
regex = r... | 0 | 2016-07-19T07:00:16Z | 38,451,859 | <ul>
<li>Match anything but <code>,</code> (or newlines) up until the first slash <code>/</code>: <code>[^,/\n]*/</code></li>
<li>Match the remaining text up to the next comma: <code>[^,\n]*</code></li>
<li>Put the two together: <code>[^,/\n]*/[^,\n]*</code> </li>
</ul>
| 1 | 2016-07-19T07:17:52Z | [
"python",
"regex"
] |
How to fetch whole string from start of comma to next comma or newline when "/" occurs in string | 38,451,529 | <p>I have string in format</p>
<pre><code>,xys=2/3,
d=e,
b*y,
b/e
</code></pre>
<p>I want to fetch <code>xys=2/3</code> and <code>b/e</code>.</p>
<p>Right now I have regular expression which just picks <code>2/3</code> and <code>b/e</code>.</p>
<pre><code> pattern = r'(\S+)\s*(?<![;|<|#])/\s*(\S+)'
regex = r... | 0 | 2016-07-19T07:00:16Z | 38,452,325 | <p>Will this work:</p>
<pre><code>x.split(",")[1].split('\n')[0] if "," in x[:-1] else None
</code></pre>
<p>It ignores (evaluates to None) unles <code>,</code> is present in the non-last position, else extract the part between <code>,</code> and another <code>,</code> or till the end, and again filter until new line... | 0 | 2016-07-19T07:42:10Z | [
"python",
"regex"
] |
Python: Do something then sleep, repeat | 38,451,593 | <p>I'm using a little app for Python called Pythonista which allows me to change text colour on things every few seconds. Here's an example of how I've been trying to go about doing this in an infinite loop;</p>
<pre><code>while True:
v['example'].text_color = 'red'
time.sleep(0.5)
v['example'].text_color ... | 7 | 2016-07-19T07:04:06Z | 38,845,888 | <p>You will need to create a new thread that runs your code. Put your code in its own method some_function() and then start a new thread like this:</p>
<pre><code>thread = Thread(target = some_function)
thread.start()
</code></pre>
| 2 | 2016-08-09T08:39:28Z | [
"python",
"python-3.x",
"sleep"
] |
Django admin doesnot reflect dynmaic choices in choiceField | 38,451,618 | <p>I have 2 projects running on 2 different systems.(call them A and B)</p>
<p>in A I have a model which has one dynamic choice field.</p>
<pre><code>class ModelA(models.Model):
field1 = models.CharField(max_length=255, choices=get_field1_list())
#..some more fields
</code></pre>
<p>and in <code>get_fiel... | 0 | 2016-07-19T07:05:16Z | 38,458,491 | <p>In Django 1.9, I'm doing this way</p>
<pre><code>from django.utils.functional import lazy
class ModelA(models.Model):
field1 = models.CharField(max_length=255, blank=False, null=False)
# ..
def __init__(self, *args, **kwargs):
super(ModelA, self).__init__(*args, **kwargs)
self._meta.g... | 1 | 2016-07-19T12:23:16Z | [
"python",
"django",
"django-models",
"django-forms",
"django-admin"
] |
Create readable words after binarization | 38,451,694 | <p>I am using opencv with Python to cleanup images to be readable for tesseract. I have a black and white image, and after adaptive thresholding, it doesn't look good enough. There is a lot of paper noise and letters are not so clean. How can I fix it?</p>
<p>adaptiveThreshold method:</p>
<pre><code>cv2.adaptiveThres... | 0 | 2016-07-19T07:09:09Z | 38,464,258 | <p>Since you noticed that there's lots of noise, it's always a good idea to try some smoothing to the image.</p>
<p>For example, you can apply a gaussian filter to the original image</p>
<pre><code>smooth_img = cv.GaussianBlur(img, (5, 5), 0, 0)
bin_img = cv.adaptiveThreshold(smooth_img, 255, cv.ADAPTIVE_THRESH_GAUSS... | 2 | 2016-07-19T16:49:29Z | [
"python",
"opencv",
"computer-vision",
"tesseract"
] |
Using BeautifulSoup4 with Google Translate | 38,451,783 | <p>I am currently going through the Web Scraping section of AutomateTheBoringStuff and trying to write a script that extracts translated words from Google Translate using BeautifulSoup4.</p>
<p>I inspected the html content of a page where 'Explanation' is the translated word: </p>
<pre><code><span id="result_box"... | 1 | 2016-07-19T07:13:37Z | 38,453,469 | <p>The <em>result_box</em> div is the correct element but your code only works when you save what you see in your browser as that includes the dynamically generated content, using requests you get only the source itself bar any dynamically generated content. The translation is generated by an ajax call to the url below... | 1 | 2016-07-19T08:40:14Z | [
"python",
"html",
"beautifulsoup",
"bs4"
] |
How to iterate between two geo locations with a certain speed in Python(3) | 38,451,828 | <p>I want to simulate a movement on a real world map (spherical) and represent the actual position on (google|openStreet)maps.</p>
<p>I have an initial lat/long pair e.g. (51.506314, -0.088455) and want to move to e.g. (51.509359, -0.087221) on a certain speed by getting interpolated coordinates periodically.</p>
<p>... | 0 | 2016-07-19T07:16:29Z | 38,456,139 | <p>Solved my problem:</p>
<p>Found a C++ library <a href="http://geographiclib.sourceforge.net/1.46/python/index.html" rel="nofollow"><em>geographiclib</em></a> which was ported to Python doing exactly what I was looking for.
Example code to calculate a inverse geodesic line and get positions for a specific distance:<... | 0 | 2016-07-19T10:38:39Z | [
"python",
"python-3.x",
"geolocation",
"geospatial"
] |
Cannot run matplotlib with Apache Zeppelin | 38,451,831 | <p>I am using Zeppelin and matplotlib to visualize some data. I try them but fail with the error below. Could you give me some guidance how to fix it?</p>
<pre><code>%pyspark
import matplotlib.pyplot as plt
plt.plot([1,2,3,4])
plt.ylabel('some numbers')
plt.show()
</code></pre>
<p>And here is the error I've got</p>
... | 0 | 2016-07-19T07:16:41Z | 38,564,700 | <p>The following works for me with Spark & Python 3:</p>
<pre><code>%pyspark
import matplotlib
import io
# If you use the use() function, this must be done before importing matplotlib.pyplot. Calling use() after pyplot has been imported will have no effect.
# see: http://matplotlib.org/faq/usage_faq.html#what-is... | 1 | 2016-07-25T09:57:44Z | [
"python",
"matplotlib",
"apache-zeppelin"
] |
Get genre from youtube ID | 38,451,895 | <pre><code>def get_data(key, region, *ids):
url = "https://www.googleapis.com/youtube/v3/videos?part=snippet&id={ids}&key={api_key}"
r = requests.get(url.format(ids=",".join(ids), api_key=key))
js = r.json()
items = js["items"]
cat_js = requests.get("https://www.googleapis.com/youtube/v3/vid... | 0 | 2016-07-19T07:20:04Z | 38,452,575 | <p>I don't know if the genre are flagged - probably not.</p>
<p>If not, I would suggest two options.</p>
<p><strong>Easy one</strong>: </p>
<ul>
<li>Get a list of music genres (<a href="http://www.musicgenreslist.com/" rel="nofollow">here</a> for example, but you can define yours according to your task)</li>
<li>Eac... | 2 | 2016-07-19T07:56:15Z | [
"python",
"youtube"
] |
Split string of digits into lists of even and odd integers | 38,451,914 | <p>Having such code</p>
<pre><code>numbers = '1 2 3 4 5 6 7 8'
nums = {'evens': [], 'odds': []}
for number in numbers.split(' '):
if int(number) % 2:
nums['odds'].append(number)
else:
nums['evens'].append(number)
</code></pre>
<p>How can accomplish same on fewer lines?</p>
| 5 | 2016-07-19T07:21:02Z | 38,451,988 | <pre><code>numbers = '1 2 3 4 5 6 7 8'
nums = {}
nums["even"] = [int(i) for i in numbers.split() if int(i) % 2 == 0]
nums["odd"] = [int(i) for i in numbers.split() if int(i) % 2 == 1]
print(nums)
</code></pre>
<p>Output:</p>
<pre><code>{'even': [2, 4, 6, 8], 'odd': [1, 3, 5, 7]}
</code></pre>
| 1 | 2016-07-19T07:24:39Z | [
"python"
] |
Split string of digits into lists of even and odd integers | 38,451,914 | <p>Having such code</p>
<pre><code>numbers = '1 2 3 4 5 6 7 8'
nums = {'evens': [], 'odds': []}
for number in numbers.split(' '):
if int(number) % 2:
nums['odds'].append(number)
else:
nums['evens'].append(number)
</code></pre>
<p>How can accomplish same on fewer lines?</p>
| 5 | 2016-07-19T07:21:02Z | 38,451,997 | <p>If you just want to try it out:</p>
<pre><code>numbers = '1 2 3 4 5 6 7 8'
nums = {'evens': [], 'odds': []}
for number in numbers.split(' '):
category = 'odds' if int(number) % 2 else 'evens'
nums[category].append(number)
</code></pre>
<p>But if you want to use it in production: <strong>Readable code is mo... | 1 | 2016-07-19T07:25:22Z | [
"python"
] |
Split string of digits into lists of even and odd integers | 38,451,914 | <p>Having such code</p>
<pre><code>numbers = '1 2 3 4 5 6 7 8'
nums = {'evens': [], 'odds': []}
for number in numbers.split(' '):
if int(number) % 2:
nums['odds'].append(number)
else:
nums['evens'].append(number)
</code></pre>
<p>How can accomplish same on fewer lines?</p>
| 5 | 2016-07-19T07:21:02Z | 38,452,001 | <p>You can do it as a one-liner, but I wouldn't recommend it. Your code is perfectly fine.</p>
<pre><code>[nums['odds'].append(n) if int(n)%2 else nums['evens'].append(n) for n in numbers.split(' ')]
</code></pre>
| 0 | 2016-07-19T07:25:29Z | [
"python"
] |
Split string of digits into lists of even and odd integers | 38,451,914 | <p>Having such code</p>
<pre><code>numbers = '1 2 3 4 5 6 7 8'
nums = {'evens': [], 'odds': []}
for number in numbers.split(' '):
if int(number) % 2:
nums['odds'].append(number)
else:
nums['evens'].append(number)
</code></pre>
<p>How can accomplish same on fewer lines?</p>
| 5 | 2016-07-19T07:21:02Z | 38,452,141 | <p>A functional aproach:</p>
<pre><code>>>> numbers = '1 2 3 4 5 6 7 8'
>>> numbers = map(int, numbers.split())
>>> nums = {'evens': filter(lambda x: x%2 == 0, numbers), 'odds': filter(lambda x: x%2 != 0, numbers)}
>>> nums
{'evens': [2, 4, 6, 8], 'odds': [1, 3, 5, 7]}
</code></pre>... | 4 | 2016-07-19T07:32:23Z | [
"python"
] |
Split string of digits into lists of even and odd integers | 38,451,914 | <p>Having such code</p>
<pre><code>numbers = '1 2 3 4 5 6 7 8'
nums = {'evens': [], 'odds': []}
for number in numbers.split(' '):
if int(number) % 2:
nums['odds'].append(number)
else:
nums['evens'].append(number)
</code></pre>
<p>How can accomplish same on fewer lines?</p>
| 5 | 2016-07-19T07:21:02Z | 38,452,423 | <p>Short code is not better code. Short code is not faster code. Short code is not maintainable code. Now, that said, it <em>is</em> good to make your individual components concise and simple.</p>
<p>Here's what I would do:</p>
<pre><code>def split_odd_even(number_list):
return {
'odds': filter(lambda n: ... | 5 | 2016-07-19T07:47:26Z | [
"python"
] |
Split string of digits into lists of even and odd integers | 38,451,914 | <p>Having such code</p>
<pre><code>numbers = '1 2 3 4 5 6 7 8'
nums = {'evens': [], 'odds': []}
for number in numbers.split(' '):
if int(number) % 2:
nums['odds'].append(number)
else:
nums['evens'].append(number)
</code></pre>
<p>How can accomplish same on fewer lines?</p>
| 5 | 2016-07-19T07:21:02Z | 38,452,637 | <p>You can accomplish the same results with <a href="https://docs.python.org/3.4/library/itertools.html?highlight=itertools#itertools.groupby" rel="nofollow"><code>itertools.groupby</code></a>, like so:</p>
<pre><code>>>> from itertools import groupby
>>>
>>> numbers = '1 2 3 4 5 6 7 8'
>... | 3 | 2016-07-19T07:59:21Z | [
"python"
] |
Calculate average and total from file | 38,451,962 | <p>Python beginner.
How do I present data from a file and calculate total/average for each person?
How do I add the value to a variable outside of for in every iteration, and once the iteration is over divide it by the number of records?</p>
<p>The data in the file varies since the user can add and delete data, but ... | 0 | 2016-07-19T07:23:07Z | 38,452,086 | <p>To calculate the <code>total</code> you can simply do (assuming that you don't want to include the first index, which contains "PersonA", etc.):</p>
<pre><code>line_total = sum(map(int, line2[1:]))
</code></pre>
<p>From there, the average is also simple:</p>
<pre><code>line_average = line_total / len(line2[1:])
<... | 0 | 2016-07-19T07:29:59Z | [
"python"
] |
Calculate average and total from file | 38,451,962 | <p>Python beginner.
How do I present data from a file and calculate total/average for each person?
How do I add the value to a variable outside of for in every iteration, and once the iteration is over divide it by the number of records?</p>
<p>The data in the file varies since the user can add and delete data, but ... | 0 | 2016-07-19T07:23:07Z | 38,452,127 | <pre><code>s = """PersonA;342;454;559;
PersonB;444;100;545;
PersonC;332;567;491;
PersonD;142;612;666;"""
for line in s.split("\n"):
p, a, b, c, _ = line.strip().split(";")
print("{}\t{}\t{}\t{}\t{}\t{}".format(p, a, b, c,
sum([int(a), int(b), int(c)]),
sum([int(a), int(b), int(c)]) / 3))
</code></p... | 2 | 2016-07-19T07:31:40Z | [
"python"
] |
Calculate average and total from file | 38,451,962 | <p>Python beginner.
How do I present data from a file and calculate total/average for each person?
How do I add the value to a variable outside of for in every iteration, and once the iteration is over divide it by the number of records?</p>
<p>The data in the file varies since the user can add and delete data, but ... | 0 | 2016-07-19T07:23:07Z | 38,452,497 | <p>This how I would do. That said, there are many ways to get this done in Pyhton. </p>
<pre><code>import pandas as pd
df = pd.read_csv('result.txt', sep=';',header=None)
del df[4]
df['AVERAGE'] = df[[1,2,3]].mean(axis = 1)
df['TOTAL'] = df[[1,2,3]].sum(axis = 1)
</code></pre>
<p>I use <a href="http://pandas.pydata... | 0 | 2016-07-19T07:51:51Z | [
"python"
] |
Calculate average and total from file | 38,451,962 | <p>Python beginner.
How do I present data from a file and calculate total/average for each person?
How do I add the value to a variable outside of for in every iteration, and once the iteration is over divide it by the number of records?</p>
<p>The data in the file varies since the user can add and delete data, but ... | 0 | 2016-07-19T07:23:07Z | 38,454,053 | <p>This will work for any values per person, and for any number of persons:</p>
<pre><code>from collections import defaultdict
def myprint(lines):
sum_dict = defaultdict(lambda: ([], 0, 0))
for line in lines:
data = line.strip().split(";")
person = data[0].strip()
values = [int(i) for... | 0 | 2016-07-19T09:06:50Z | [
"python"
] |
ImportError : no module named requests | 38,452,072 | <p>I am trying to retrieve data from a weather website using BeautifulSoup. Sample of the website:</p>
<pre><code><channel>
<title>2 Hour Forecast</title>
<source>Meteorological Services Singapore</source>
<description>2 Hour Forecast</description>
<item>
<title>No... | -1 | 2016-07-19T07:28:53Z | 38,454,812 | <p>Firstly, let me tell about some of my confusions.</p>
<p>In your screen shot:<a href="http://i.stack.imgur.com/0XK6D.png/" rel="nofollow">in the Lib within Python27 folder on my C drive</a>.</p>
<p>First, the folder "ensurepip" means that it will help you to install pip, but you don't have "site-packages" director... | -1 | 2016-07-19T09:40:12Z | [
"python",
"python-requests",
"importerror"
] |
Convert flat CSV to JSON when some fields need to be nested | 38,452,159 | <p>I have a flat csv file with 50 columns (let's call them FirstName, LastName, Address, etc.), that's tab-delimited with quotes around all fields.</p>
<p>I need to convert this to a JSON file, but what's tricky is that some of the CSV columns need to be converted into nested fields, where the nested fields also conta... | 0 | 2016-07-19T07:33:20Z | 38,452,653 | <p>Use a <a href="https://docs.python.org/3/library/csv.html#csv.DictReader" rel="nofollow"><code>DictReader</code></a> and manipulate the row by adding the <code>Shipping Details</code> and removing the <code>Address</code>.</p>
<pre><code>j = []
with open("/tmp/so.csv") as f:
reader = csv.DictReader(f, delimite... | 3 | 2016-07-19T08:00:21Z | [
"python",
"json",
"csv"
] |
Convert flat CSV to JSON when some fields need to be nested | 38,452,159 | <p>I have a flat csv file with 50 columns (let's call them FirstName, LastName, Address, etc.), that's tab-delimited with quotes around all fields.</p>
<p>I need to convert this to a JSON file, but what's tricky is that some of the CSV columns need to be converted into nested fields, where the nested fields also conta... | 0 | 2016-07-19T07:33:20Z | 38,453,018 | <p>to continue @FullName answer, maybe you can have a function that creats the new key:</p>
<pre><code>def nested_key(row,key_to_swap, pre_filled_dict):
pre_filled_dict[key_to_swap]=row[key_to_swap]
row[key_to_swap]=pre_filled_dict[key_to_swap]
</code></pre>
<p>then you just have to creat the pre_filled_dict ... | 1 | 2016-07-19T08:19:37Z | [
"python",
"json",
"csv"
] |
Convert flat CSV to JSON when some fields need to be nested | 38,452,159 | <p>I have a flat csv file with 50 columns (let's call them FirstName, LastName, Address, etc.), that's tab-delimited with quotes around all fields.</p>
<p>I need to convert this to a JSON file, but what's tricky is that some of the CSV columns need to be converted into nested fields, where the nested fields also conta... | 0 | 2016-07-19T07:33:20Z | 38,453,036 | <p>You can create a dictionary defining the columns that have nested dicts and use those to populate that column's value. Keeping your customization to a single consolidated location makes it easier to read/maintain and easier to port to other csv formats.</p>
<pre><code>import copy
CSV_CONFIG = {
2: {
# ... | 1 | 2016-07-19T08:20:38Z | [
"python",
"json",
"csv"
] |
File does not upload and save in the database | 38,452,260 | <p>I've been having problem in saving and uploading files in django. I've been reading the entire tutorial to get this up and running. I've been stuck with this: </p>
<pre><code>'tuple' does not support the buffer interface
</code></pre>
<p>The problem seems to be coming from views.py, it stops somewhere between savi... | 0 | 2016-07-19T07:38:48Z | 38,452,643 | <p>The <code>FileField</code> represents an uploaded file object. So you need to pass it a <em>file</em> and not a <em>path</em>.</p>
<pre><code>def index(request):
# Handle file upload
if request.method == 'POST':
form = DocumentForm(request.POST, request.FILES)
if form.is_valid():
... | 3 | 2016-07-19T07:59:41Z | [
"python",
"django"
] |
File does not upload and save in the database | 38,452,260 | <p>I've been having problem in saving and uploading files in django. I've been reading the entire tutorial to get this up and running. I've been stuck with this: </p>
<pre><code>'tuple' does not support the buffer interface
</code></pre>
<p>The problem seems to be coming from views.py, it stops somewhere between savi... | 0 | 2016-07-19T07:38:48Z | 38,471,230 | <p>I think I've already solved my problem and I am posting this solution in case there are other newbies who's trying to make this work. Note: you better rename the name of the file field from 'file_path' to 'file' which is in my DocumentForm to avoid naming confusion</p>
<pre><code>def index(request):
# Handle fi... | 0 | 2016-07-20T02:12:53Z | [
"python",
"django"
] |
Page not found accounts/signup django allauth | 38,452,348 | <p>I'm trying to incorporate django-allauth on my project. So far so good with the installation, but when I try to access the 'accounts/signup' or 'accounts/login page, I get auto redirect to accounts/profile with page not found </p>
<p>here is the error :</p>
<pre><code> Page not found (404)
> Request Method: ... | 0 | 2016-07-19T07:43:17Z | 38,452,429 | <p><code><a href="http://django-allauth.readthedocs.io/en/latest/faq.html?highlight=LOGIN_REDIRECT_URL%20#when-i-attempt-to-login-i-run-into-a-404-on-accounts-profile" rel="nofollow">Doc</a></code> says you need to implement the <code>/profile/</code> page or simply </p>
<pre><code>LOGIN_REDIRECT_URL = "<your url&g... | 0 | 2016-07-19T07:47:42Z | [
"python",
"django",
"django-allauth"
] |
How to find python and python3 config directories for Homebrew installation? | 38,452,506 | <p>I installed <code>python</code> and <code>python3</code> using Homebrew on Mac OS X (Yosemite 10.10.5). But I don't know where the relevant config directories are. How can I find them? </p>
| 0 | 2016-07-19T07:52:31Z | 38,452,551 | <p>Try using the <code>ls</code> option of <code>brew</code>:</p>
<pre><code>brew ls python
</code></pre>
| 0 | 2016-07-19T07:55:07Z | [
"python",
"python-3.x",
"homebrew"
] |
How to find python and python3 config directories for Homebrew installation? | 38,452,506 | <p>I installed <code>python</code> and <code>python3</code> using Homebrew on Mac OS X (Yosemite 10.10.5). But I don't know where the relevant config directories are. How can I find them? </p>
| 0 | 2016-07-19T07:52:31Z | 38,452,560 | <p>Asking the provider always goes a long way:</p>
<pre><code>$ brew info python3
</code></pre>
<p>On my machine - an El Capitan - it currently states:</p>
<pre><code>python3: stable 3.5.2 (bottled), devel 3.6.0a3, HEAD
Interpreted, interactive, object-oriented programming language
https://www.python.org/
/usr/local... | -1 | 2016-07-19T07:55:41Z | [
"python",
"python-3.x",
"homebrew"
] |
Running hello.py from within an Android Process | 38,452,538 | <p>I'm trying to run a python script <code>hello.py</code> from within an Android Process.</p>
<p>Here are the steps I've followed:</p>
<ol>
<li>I have procured python binaries and need linked libraries. </li>
<li>I have tested them and they are working in the terminal emulator. </li>
<li>I have added them to my asse... | 5 | 2016-07-19T07:54:21Z | 38,682,328 | <p>This was pure idiocy. After days of hair pulling I finally found out what went wrong. I didn't copy the <code>/usr/lib/python3.5</code> folder to the appropriate Android data folder.</p>
<p>This link was extremely helpful - <a href="https://leemendelowitz.github.io/blog/how-does-python-find-packages.html" rel="nofo... | 0 | 2016-07-31T08:51:30Z | [
"android",
"python"
] |
how to print only a certain part of data file mathching our pattern in python | 38,452,625 | <p>i want to print certain blocks of data from a file using python . Basically it should work as a parser and only output the blocks mathcing my criteria .
My file contains logs of a call center . I want the part starting with "####" and ending on <code>"</soap:Body>>"</code> but it should also contain a cert... | -2 | 2016-07-19T07:58:45Z | 38,452,877 | <p>As in the comments suggested: Your XML is not valid. It would be better to ensure valid XML and then use a parser like [etree][1] or [Beautiful Soup][2].</p>
<p>But if you want to use regex anyway, you could try:</p>
<pre><code>import re
mytext = [
'####<Jun 4, 2016 12:05:50 PM IST> <Debug> <Me... | 0 | 2016-07-19T08:13:01Z | [
"python",
"regex",
"parsing"
] |
how to print only a certain part of data file mathching our pattern in python | 38,452,625 | <p>i want to print certain blocks of data from a file using python . Basically it should work as a parser and only output the blocks mathcing my criteria .
My file contains logs of a call center . I want the part starting with "####" and ending on <code>"</soap:Body>>"</code> but it should also contain a cert... | -2 | 2016-07-19T07:58:45Z | 38,454,235 | <p>The canonical way to handle such problems is to write some kind of "event-based" parser (like SAX xml parsers...): your parser reads the file line by line (you don't need to read the whole content in memory), scan the line according to your own rules (that's where you may want to use regexps, but sometimes plain str... | 0 | 2016-07-19T09:14:57Z | [
"python",
"regex",
"parsing"
] |
Elasticsearch insensitive search accents | 38,452,791 | <p>I'm using Elastic search with Python. I can't find a way to make insensitive search with accents.</p>
<p>For example:
I have two words. "<strong>Camión</strong>" and "<strong>Camion</strong>".
When a user search for "camion" I'd like the two results show up.</p>
<p>Creating index:</p>
<pre><code>es = Elasticsear... | 0 | 2016-07-19T08:08:58Z | 38,453,129 | <p>You need to change the mapping of those fields you have in the query. Changing the mapping requires re-indexing so that the fields will be analyzed differently and the query will work.</p>
<p>Basically, you need something like the following below. The field called <code>text</code> is just an example. You need to a... | 2 | 2016-07-19T08:24:50Z | [
"python",
"elasticsearch",
"elasticsearch-2.0"
] |
readline() not outputting correct line | 38,452,938 | <p>I want to make a settings file so my python script can remember settings after a reboot. I used the command <code>f.readline()</code> but the output is different giving the amount of lines I read.</p>
<p>example:
the text document is</p>
<pre><code>1
2
3
</code></pre>
<p>and when I use this script to print out th... | -2 | 2016-07-19T08:16:21Z | 38,453,102 | <p>The parameter of <code>readline</code> isn't the number of line you wish to read but the number of bytes you wish.</p>
<p>To access the file <strong>by line number</strong> you can use <code>readlines()</code>:</p>
<pre><code>f = open("test.txt", "r")
lines = f.readlines()
print(lines[0])
print("-") #i used this t... | 0 | 2016-07-19T08:24:03Z | [
"python",
"readline"
] |
readline() not outputting correct line | 38,452,938 | <p>I want to make a settings file so my python script can remember settings after a reboot. I used the command <code>f.readline()</code> but the output is different giving the amount of lines I read.</p>
<p>example:
the text document is</p>
<pre><code>1
2
3
</code></pre>
<p>and when I use this script to print out th... | -2 | 2016-07-19T08:16:21Z | 38,453,120 | <p>The signature of <code>readline</code> takes an optional <em>size</em> argument which you have specified, which however you do not need if you intend to read the file line by line:</p>
<pre><code>f.readline(1)
# ^ read 1 byte
</code></pre>
<p>The parameter is not synonymous to <em>line number</em> as you ... | 1 | 2016-07-19T08:24:36Z | [
"python",
"readline"
] |
python/pygame error TypeError: 'bool' object is not callable | 38,452,974 | <p>I'm trying to make this object move when you click it in pygame; and it works the first time you click it but after that it gives me this error:</p>
<pre><code>game_loop()
File "C:\Users\MadsK_000\Desktop\spil\Python\spiltest\Test spil.py", line 57, in game_loop
Clicked_ = clicked(x,y,width,height,mouse_pos)
... | 0 | 2016-07-19T08:17:46Z | 38,453,020 | <p>You set a global <code>clicked</code> to a boolean, inside the <code>clicked</code> <em>function</em>:</p>
<pre><code>def clicked(x,y,width,height,mouse_pos):
clicked = False
if mouse_pos[0] > x and x + width > mouse_pos[0] and mouse_pos[1] > y and y + height > mouse_pos[1]:
clicked = Tr... | 3 | 2016-07-19T08:19:48Z | [
"python",
"pygame",
"python-3.4"
] |
python/pygame error TypeError: 'bool' object is not callable | 38,452,974 | <p>I'm trying to make this object move when you click it in pygame; and it works the first time you click it but after that it gives me this error:</p>
<pre><code>game_loop()
File "C:\Users\MadsK_000\Desktop\spil\Python\spiltest\Test spil.py", line 57, in game_loop
Clicked_ = clicked(x,y,width,height,mouse_pos)
... | 0 | 2016-07-19T08:17:46Z | 38,453,078 | <p>There is a name conflict for <code>clicked</code>. Inside the function <code>clicked</code> there is variable with same named (<code>clicked = False</code>) and this is also linked to global scope (<code>global clicked</code>). So, when the function is executed, <code>clicked</code> has been modified to boolean, ins... | 0 | 2016-07-19T08:22:47Z | [
"python",
"pygame",
"python-3.4"
] |
Tensorflow - Making tensor untrainable | 38,452,989 | <p>If I create a tensor using <code>tf.Variable</code>, I can decide whether the tensor will be trainable or not. However how can I set tensor B to be untrainable if I define it in the following way:</p>
<pre><code>A=tf.placeholder(tf.int32,shape=[None,100])
B=tf.zeros_like(A)
</code></pre>
| 0 | 2016-07-19T08:18:23Z | 38,453,485 | <p><code>A=tf.placeholder(tf.int32,shape=[None,100])</code>
A is a placeholder, not a Variable. A placeholder is <em>not</em> trainable.</p>
<p>If you create a variable and set the attribute <code>trainable</code> to <code>False</code></p>
<pre><code>x = tf.Variable(0, trainable=False)
</code></pre>
<p>your variable... | 2 | 2016-07-19T08:41:02Z | [
"python",
"tensorflow"
] |
Python UTF-8 encoded on PC, UnicodeDecodeError on Mac | 38,453,031 | <p>I wrote a script to create a text file on a PC, and it uses these types of commands to open and write it:</p>
<pre><code>newfile = open(r'tweettext.txt','w')
</code></pre>
<p><code>print("\n"+tweet,end=',',file=newfile)</code></p>
<p>And <code>sys.getdefaultencoding()</code> reveals 'utf-8' encoding. But when I t... | -1 | 2016-07-19T08:20:23Z | 38,453,478 | <p><code>sys.getdefaultencoding()</code> only applies to <code>sys.stdout</code>, <code>sys.stderr</code> and <code>sys.stdin</code>.</p>
<p>You opened your file you print to without an encoding set, so the default <em>for files</em> is used, which is whatever the <a href="https://docs.python.org/3/library/locale.html... | 1 | 2016-07-19T08:40:46Z | [
"python",
"osx",
"encoding",
"utf-8",
"pc"
] |
Flask Error Handlers , Rollback mysql exception | 38,453,098 | <p>I have a Flask app and there is an endpoint/resource that inserts a record in <code>candidate_device</code> table using <code>FlaskSqlAlchemy</code> as orm. I am facing a problem that when I run my tests on jenkins, jenkins runs these tests in 48 parallel threads/processes <code>pytest -n 48 some_service/tests</code... | 2 | 2016-07-19T08:23:40Z | 38,517,653 | <p>48 is too high. Earlier versions of MySQL could handle about 8 before actually <em>slowing down</em>. The latest version <em>may</em> be able to handle 48, but only with <em>carefully selected</em> queries.</p>
<p><code>innodb_lock_wait_timeout</code> defaults to 50 seconds. This sounds like the 48 were really s... | 1 | 2016-07-22T03:23:47Z | [
"python",
"mysql",
"transactions",
"sqlalchemy",
"flask-sqlalchemy"
] |
Flask Error Handlers , Rollback mysql exception | 38,453,098 | <p>I have a Flask app and there is an endpoint/resource that inserts a record in <code>candidate_device</code> table using <code>FlaskSqlAlchemy</code> as orm. I am facing a problem that when I run my tests on jenkins, jenkins runs these tests in 48 parallel threads/processes <code>pytest -n 48 some_service/tests</code... | 2 | 2016-07-19T08:23:40Z | 38,606,182 | <p>Your problem must be about connection limit. Depending on how long are your queries execution, you can exceed this number (same queries not always use the same time, this is why sometimes fails and sometimes they dont).</p>
<p>First execute this sql query:</p>
<pre><code>show variables like "max_connections";
</co... | 1 | 2016-07-27T07:13:56Z | [
"python",
"mysql",
"transactions",
"sqlalchemy",
"flask-sqlalchemy"
] |
Split() that recognizes the types | 38,453,105 | <p>I have a phrase like this:</p>
<pre><code>a='Hello I have 4 ducks'
</code></pre>
<p>and I apply <code>str.split</code> to this, so I now I have </p>
<pre><code>>>> a.split()
['Hello','I','have','4','ducks'].
</code></pre>
<p>the problem is that every <code>a.split()[i]</code> is a string, but I need the... | -3 | 2016-07-19T08:24:08Z | 38,453,232 | <p>You did not define the output you wish, thus I am not sure whether this is what you want, yet it works: </p>
<pre><code>a='Hello I have 4 ducks'
a=a.split()
ints=[]
strings=[]
for part in a:
try:
ints.append(int(part))
except:
strings.append(part)
ints,strings
</code></pre>
<p>gives:</p>... | 0 | 2016-07-19T08:30:07Z | [
"python",
"types"
] |
Split() that recognizes the types | 38,453,105 | <p>I have a phrase like this:</p>
<pre><code>a='Hello I have 4 ducks'
</code></pre>
<p>and I apply <code>str.split</code> to this, so I now I have </p>
<pre><code>>>> a.split()
['Hello','I','have','4','ducks'].
</code></pre>
<p>the problem is that every <code>a.split()[i]</code> is a string, but I need the... | -3 | 2016-07-19T08:24:08Z | 38,453,245 | <pre><code>demo_list = ['Hello','I','have','4','ducks']
i=0
for temp in demo_list:
print temp
if temp.isdigit():
print "This is digit"
print "It is present at location - ", i
i=i+1
</code></pre>
<p>Output:
This is digit.</p>
<p>It is present at location - 3</p>
| 0 | 2016-07-19T08:30:27Z | [
"python",
"types"
] |
Split() that recognizes the types | 38,453,105 | <p>I have a phrase like this:</p>
<pre><code>a='Hello I have 4 ducks'
</code></pre>
<p>and I apply <code>str.split</code> to this, so I now I have </p>
<pre><code>>>> a.split()
['Hello','I','have','4','ducks'].
</code></pre>
<p>the problem is that every <code>a.split()[i]</code> is a string, but I need the... | -3 | 2016-07-19T08:24:08Z | 38,453,268 | <p>You can define your own version of <code>split()</code>. Here i named it <code>my_split()</code>.</p>
<pre><code>def my_split(astring):
return [find_type(x) for x in astring.split()]
def find_type(word):
try:
word_type = int(word)
except ValueError:
try:
word_type = float(w... | 0 | 2016-07-19T08:31:25Z | [
"python",
"types"
] |
Split() that recognizes the types | 38,453,105 | <p>I have a phrase like this:</p>
<pre><code>a='Hello I have 4 ducks'
</code></pre>
<p>and I apply <code>str.split</code> to this, so I now I have </p>
<pre><code>>>> a.split()
['Hello','I','have','4','ducks'].
</code></pre>
<p>the problem is that every <code>a.split()[i]</code> is a string, but I need the... | -3 | 2016-07-19T08:24:08Z | 38,453,293 | <p><code>split()</code> won't do this because it is specific to strings.</p>
<p>However you can post-process the output from <code>split</code> to check whether each element of its output could be cast to an integer or not, <a href="http://stackoverflow.com/q/1265665/850883">per this answer</a>. Something like:</p>
<... | 0 | 2016-07-19T08:32:31Z | [
"python",
"types"
] |
Split() that recognizes the types | 38,453,105 | <p>I have a phrase like this:</p>
<pre><code>a='Hello I have 4 ducks'
</code></pre>
<p>and I apply <code>str.split</code> to this, so I now I have </p>
<pre><code>>>> a.split()
['Hello','I','have','4','ducks'].
</code></pre>
<p>the problem is that every <code>a.split()[i]</code> is a string, but I need the... | -3 | 2016-07-19T08:24:08Z | 38,453,333 | <p>you can use isdigit function</p>
<pre><code>a='Hello I have 4 ducks'
i=0
for x in a.split():
i+=1
if x.isdigit():
print "Element:"+x
print "Position:"+i
</code></pre>
| 0 | 2016-07-19T08:34:09Z | [
"python",
"types"
] |
Split() that recognizes the types | 38,453,105 | <p>I have a phrase like this:</p>
<pre><code>a='Hello I have 4 ducks'
</code></pre>
<p>and I apply <code>str.split</code> to this, so I now I have </p>
<pre><code>>>> a.split()
['Hello','I','have','4','ducks'].
</code></pre>
<p>the problem is that every <code>a.split()[i]</code> is a string, but I need the... | -3 | 2016-07-19T08:24:08Z | 38,453,354 | <p>Probably using exception is the best way. (see <a href="http://stackoverflow.com/questions/354038/how-do-i-check-if-a-string-is-a-number-float-in-python">here</a>). Other methods like <code>isdigit</code> do not work with negative numbers.</p>
<pre><code>def is_number(s):
try:
float(s)
return Tr... | 0 | 2016-07-19T08:35:09Z | [
"python",
"types"
] |
Split() that recognizes the types | 38,453,105 | <p>I have a phrase like this:</p>
<pre><code>a='Hello I have 4 ducks'
</code></pre>
<p>and I apply <code>str.split</code> to this, so I now I have </p>
<pre><code>>>> a.split()
['Hello','I','have','4','ducks'].
</code></pre>
<p>the problem is that every <code>a.split()[i]</code> is a string, but I need the... | -3 | 2016-07-19T08:24:08Z | 38,455,111 | <p>You can use the <code>eval</code> function to do it, here is my anwser:</p>
<pre><code>a = 'Hello I have 4 ducks weighing 3 kg each'
a = a.split()
print a
for i in a:
try:
if isinstance(eval(i), int):
print "the index of {i} is {index}".format(i=i, index=a.index(i))
except NameError:
... | 0 | 2016-07-19T09:53:06Z | [
"python",
"types"
] |
Does super try each class in MRO | 38,453,165 | <pre><code>class Base(object):
def m(self):
print 'base'
class MixinA(Base):
def m(self):
super(MixinA, self).m()
print 'mixin a'
class MixinB(Base):
def m(self):
super(MixinB, self).m()
print 'mixin b'
class Top(MixinB, MixinA, Base):
def m(self):
s... | 2 | 2016-07-19T08:26:37Z | 38,453,199 | <p>No, <code>super()</code> does not 'try' each class in the MRO. Your code <strong>chains</strong> the calls, because each method called has <strong>another</strong> <code>super()</code> call in it. <code>Top.m()</code> calls <code>super().m()</code>, which resolves to <code>MixinB.m()</code>; which in turn uses <code... | 6 | 2016-07-19T08:28:36Z | [
"python",
"oop",
"multiple-inheritance",
"super"
] |
Does super try each class in MRO | 38,453,165 | <pre><code>class Base(object):
def m(self):
print 'base'
class MixinA(Base):
def m(self):
super(MixinA, self).m()
print 'mixin a'
class MixinB(Base):
def m(self):
super(MixinB, self).m()
print 'mixin b'
class Top(MixinB, MixinA, Base):
def m(self):
s... | 2 | 2016-07-19T08:26:37Z | 38,453,299 | <p>There is no <em>trying</em> involved, here: Your call order is</p>
<ul>
<li><p><code>Top.m()</code> calling <code>super(Top, self).m()</code> which is <code>MixinB.m()</code>.</p></li>
<li><p><code>MixinB.m()</code> immediately calls <code>super(MixinB, self).m()</code> which is <code>MixinA.m()</code> when called ... | 3 | 2016-07-19T08:32:43Z | [
"python",
"oop",
"multiple-inheritance",
"super"
] |
Is there a Matlab's buffer equivalent in numpy? | 38,453,249 | <p>I see there is an <code>array_split</code> and <code>split</code> <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.split.html" rel="nofollow">methods</a> but these are not very handy when you have to split an array of length which is not integer multiple of the chunk size. Moreover, these methods i... | 1 | 2016-07-19T08:30:37Z | 40,105,995 | <p>I wrote the following routine to handle the use cases I needed, but I have not implemented/tested for "underlap". </p>
<p>Please feel free to make suggestions for improvement.</p>
<pre><code>def buffer(x, n, p=0, opt=None):
'''Mimic MATLAB routine to generate buffer array
MATLAB docs here: https://se.math... | 0 | 2016-10-18T10:38:49Z | [
"python",
"matlab",
"numpy",
"buffer"
] |
Negative lookahead assertion in python | 38,453,278 | <p>I am having below two line of log, where I want to have separate regular expression for finding each of them. There is no problem to trigger on the second log line. But I have problem to design expression for the first line. The name <code>Reset Reason test</code> is just an example of test, number of words in it ma... | 1 | 2016-07-19T08:31:55Z | 38,453,753 | <p>If you want to exclude matching lines with <code> done.</code> at the end, you need to use a negative lookahead, and better anchored at the start of the line:</p>
<pre><code>^(?!.* done\.$)([0-9.]+\s+[\d:]+)\s+SCR_OUTPUT:\s*####\s*(TC_\w+).*
^^^^^^^^^^^^^^
</code></pre>
<p>See the <a href="https://regex101.com/r/... | 1 | 2016-07-19T08:53:46Z | [
"python",
"regex",
"expression"
] |
Appium tap wihout need for element? | 38,453,387 | <p>I have following code to tap on center of screen. I dont want tap on any element. Just on center to dismiss some open panel. How do I do that? </p>
<pre><code> touch = TouchAction()
dimension = driver.get_window_size()
touch.tap(element=None, x=int(dimension['width']/2),y=int(dimension['height']/2)).perform()
</c... | 0 | 2016-07-19T08:36:33Z | 38,460,859 | <p>You can use TouchAction, example is on python client github page</p>
<pre><code>el = self.driver.find_element_by_accessibility_id('Animation')
action = TouchAction(self.driver)
action.tap(el).perform()
el = self.driver.find_element_by_accessibility_id('Bouncing Balls')
self.assertIsNotNone(el)
</code></pre>
<p>You... | 2 | 2016-07-19T14:05:55Z | [
"android",
"python",
"appium"
] |
Get the difference between two datetime fields in days in Python | 38,453,394 | <p>I am trying to get the difference between 2 DateField Objects in my python code and thereafter perform calculation based on the difference.
I am using flask for this project and so far have the following code.
Views:</p>
<pre><code>@admin.route('/approve/loan_payment/<id>', methods=['GET', 'POST'])
@login_req... | -2 | 2016-07-19T08:36:57Z | 38,454,695 | <pre><code>if loan.period == 'Less than 7 days' or \
loan.period == 'less than 7 days':
</code></pre>
<p>You are comparing an integer against a string, that will never be <code>True</code>. Guess this was pseudo code at some point and you forgot to change these bits for something that makes sense. Also, I'... | 0 | 2016-07-19T09:35:33Z | [
"python",
"flask"
] |
homepage login from django | 38,453,666 | <p>I followed the directions in this page
'<a href="http://stackoverflow.com/questions/20208562/homepage-login-form-django/20210318#20210318">homepage login form Django</a>'</p>
<p>in order to put the login forms directly to the main homepage of the site,
rather than having a separate page for login and registration e... | 0 | 2016-07-19T08:49:53Z | 38,455,566 | <p>You first form is not setup right. One solution can be to do something like htis:</p>
<pre><code> <form action="/login/?next=/home/" method="post">
{% csrf_token %}
<input type="text" placeholder="Username" name="username">
<input type="password" placeholder="Password" name="password... | 0 | 2016-07-19T10:11:55Z | [
"python",
"django"
] |
How to keep request.referer value from redirect after a failed login | 38,453,730 | <p>I'm adding authentication to an existing pyramid project. The simplest form that I'm currently trying (will be expending later) is for all pages to raise HTTPForbidden. The exception view is /login, which will ask for login details and, on success, return HTTPFound with request.referer as the location.</p>
<p>So fa... | 2 | 2016-07-19T08:52:45Z | 38,453,860 | <p>I recommend you to pass a parameter like <code>login/?next=pageA.html</code></p>
<p>If the login fails, you could then forward your parameter <code>next</code> to <code>/login</code> again, even if the referrer points now to <code>/login</code>.</p>
<p>Then when the user will successfully log in, you could redirec... | 3 | 2016-07-19T08:58:51Z | [
"python",
"session",
"login",
"form-submit",
"pyramid"
] |
Posting binary file and name in the same request in AngularJS and Flask | 38,453,912 | <p>I am trying to upload (post) a file and its filename in the same request in angular and then receive it in Flask and write to disc. The file is read from local disc using:</p>
<pre><code>reader.readAsArrayBuffer(importData.ruleFile.files[0]);
</code></pre>
<p>The http request is:</p>
<pre><code>$http({
url: b... | 0 | 2016-07-19T09:01:00Z | 38,535,630 | <p>In the end I figured out all I need to transfer is Blob:</p>
<p>angularJS:</p>
<pre><code> // Send file as Blob along with its filename
$http({
url: baseUrlService.baseURL + 'importtifile',
method: 'POST',
headers: {'Content-Type': undefined},
data: { ... | 0 | 2016-07-22T21:39:40Z | [
"python",
"angularjs",
"http",
"flask",
"blob"
] |
Get first time occurence in a pandas dataframe indexed with datetime | 38,453,939 | <p>I have a dataframe that represent scores from player in a game, indexed by time:</p>
<pre><code> player_id
2016-03-01 873970260
2016-03-02 8470693237
2016-03-02 221785899
2016-03-03 569452661
2016-03-04 221785899
2016-03-04 8276343674
</code></pre>
<p>I'd like to add a new column containing a... | 2 | 2016-07-19T09:02:14Z | 38,454,055 | <p>use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.duplicated.html" rel="nofollow"><code>duplicated</code></a> to create a boolean series of the values that are duplicates and invert using <code>~</code>:</p>
<pre><code>In [72]:
df['new_player'] = ~df['player_id'].duplicated()
df
Out[... | 2 | 2016-07-19T09:06:55Z | [
"python",
"pandas",
"time-series"
] |
How to plot a Python Dataframe with category values like this picture? | 38,453,990 | <p><img src="http://i.stack.imgur.com/sXOdd.png" alt="enter image description here"></p>
<p>How can I achieve that using matplotlib?</p>
| -4 | 2016-07-19T09:04:00Z | 38,465,942 | <p>Here is my code with the data you provided. As there's no class [they are all different, despite your first example in your question does have classes], I gave colors based on the numbers. You can definitely start alone from here, whatever result you want to achieve. You just need <code>pandas</code>, <code>seaborn<... | 0 | 2016-07-19T18:27:56Z | [
"python",
"python-2.7",
"python-3.x",
"matplotlib",
"dataframe"
] |
Calculate total/average: ValueError: invalid literal for int() with base 10: '' | 38,454,114 | <p>The user can delete and add data in result.txt, PersonA might not exist but PersonQ might one time, but not the next. How do I get the data from the file, get it into different lines and calculate total/average when I don't know which persons exists in the file from time to time?:</p>
<pre><code>PersonA;342;454;559... | -3 | 2016-07-19T09:09:30Z | 38,454,181 | <p>All the lines contain a trailing <code>';'</code> which adds an empty character to the end of the split. An attempt to convert the empty string <code>''</code> to <code>int</code> raises that error.</p>
<p>You should do a <em>right strip</em> on the last semi-colon before splitting:</p>
<pre><code>line = line.stri... | 2 | 2016-07-19T09:12:33Z | [
"python"
] |
Calculate total/average: ValueError: invalid literal for int() with base 10: '' | 38,454,114 | <p>The user can delete and add data in result.txt, PersonA might not exist but PersonQ might one time, but not the next. How do I get the data from the file, get it into different lines and calculate total/average when I don't know which persons exists in the file from time to time?:</p>
<pre><code>PersonA;342;454;559... | -3 | 2016-07-19T09:09:30Z | 38,454,432 | <p>just change <code>line2 = line.split(";")</code> to <code>line2 = line.split(";")[:-1]</code>,then it will work.</p>
| 1 | 2016-07-19T09:23:42Z | [
"python"
] |
Count character occurrences in a Python string | 38,454,138 | <p>I want to get the each character count in a given sentence. I tried the below code and I got the count of every character but it displays the repeated characters count in the output. How to delete repeated character.</p>
<pre><code>def countwords(x):
x=x.lower()
for i in x:
print(i,'in',x.count(i)) ... | -4 | 2016-07-19T09:10:39Z | 38,454,210 | <p>Use a dict. </p>
<pre><code>def countwords(x):
d = dict()
x=x.lower()
for i in x:
if i in d.keys():
d[i] = d[i] +1;
else:
d[i] = 1;
for i in d.keys():
print i + " " + d[i]
</code></pre>
| 0 | 2016-07-19T09:13:47Z | [
"python",
"count"
] |
Count character occurrences in a Python string | 38,454,138 | <p>I want to get the each character count in a given sentence. I tried the below code and I got the count of every character but it displays the repeated characters count in the output. How to delete repeated character.</p>
<pre><code>def countwords(x):
x=x.lower()
for i in x:
print(i,'in',x.count(i)) ... | -4 | 2016-07-19T09:10:39Z | 38,454,330 | <p>check this code : </p>
<pre><code>my_string = "count a character occurance"
my_list = list(my_string)
print (my_list)
get_unique_char = set(my_list)
print (get_unique_char)
for key in get_unique_char:
print (key, my_string.count(key))
</code></pre>
| 1 | 2016-07-19T09:18:33Z | [
"python",
"count"
] |
Count character occurrences in a Python string | 38,454,138 | <p>I want to get the each character count in a given sentence. I tried the below code and I got the count of every character but it displays the repeated characters count in the output. How to delete repeated character.</p>
<pre><code>def countwords(x):
x=x.lower()
for i in x:
print(i,'in',x.count(i)) ... | -4 | 2016-07-19T09:10:39Z | 38,454,668 | <p>There are a few different approaches, most hinted at by <a href="http://stackoverflow.com/users/3001761/jonrsharpe">jonrsharpe</a>'s comment, but I'd suggest a simple <a href="https://docs.python.org/2/library/stdtypes.html#set" rel="nofollow"><code>set</code></a>.</p>
<p>The set approach, along with a few others a... | 1 | 2016-07-19T09:34:27Z | [
"python",
"count"
] |
How to add custom field attribute in odoo? | 38,454,190 | <p>I want to add some custom attributes to the field label of xml, such as:</p>
<pre><code> <group>
field name="a" custom="value"/>
</group>
</code></pre>
<p>custom="value" is my custom label.</p>
<p>But it seems that odoo will erase the label it can not recognise. </p>
<p>How to add it?</p>
| 0 | 2016-07-19T09:13:04Z | 38,456,423 | <p>Try with <code>string</code> attribute of field tag.</p>
<p>For example:</p>
<pre><code><field name="a" string="Custom Label">
</code></pre>
<p><a href="http://openerp-server.readthedocs.io/en/latest/03_module_dev_03.html#field" rel="nofollow">All attributes of field tag.</a></p>
| 1 | 2016-07-19T10:50:08Z | [
"python",
"openerp"
] |
How to add custom field attribute in odoo? | 38,454,190 | <p>I want to add some custom attributes to the field label of xml, such as:</p>
<pre><code> <group>
field name="a" custom="value"/>
</group>
</code></pre>
<p>custom="value" is my custom label.</p>
<p>But it seems that odoo will erase the label it can not recognise. </p>
<p>How to add it?</p>
| 0 | 2016-07-19T09:13:04Z | 38,456,576 | <p>For add a label in xml file :</p>
<pre><code><label for="a"/>
</code></pre>
<p>But for displaying "Custom Label", modifie in python file :</p>
<pre><code>'a': fields.char('Custom Label', size=64, required=True),
</code></pre>
| 0 | 2016-07-19T10:56:12Z | [
"python",
"openerp"
] |
From Nested Dictionary to CSV File | 38,454,203 | <p>I have nested dictionary (with length > 70.000): </p>
<pre><code>users_item = {
"sessionId1": {
"12345645647": 1.0,
"9798654": 5.0
},
"sessionId2":{
"3445657657": 1.0
},
"sessionId3": {
"87967976": 5.0,
"35325626436": 1.0,
"126789435... | 1 | 2016-07-19T09:13:40Z | 38,454,676 | <p>Just loop through the dictionary and use the <a href="https://docs.python.org/2/library/csv.html#writer-objects" rel="nofollow">Python csv writer</a> to write to the csv file.</p>
<pre><code>with open('output.csv', 'w') as csv_file:
csvwriter = csv.writer(csv_file, delimiter='\t')
for session in users_item:... | 0 | 2016-07-19T09:34:48Z | [
"python",
"python-3.x",
"csv",
"dictionary"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.