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 |
|---|---|---|---|---|---|---|---|---|---|
Converting lists of lists containing various numbers of elements to pairwise tuples | 38,870,233 | <p>I have a list of lists in which <code>[NONE]</code> exists. Also, in the lists of the list, there could be 1, 2, or more elements. What I am attempting to achieve is to get pairwise tuples from these lists with irregular sizes.</p>
<p>Sample data:</p>
<pre><code>collections = [[u'Robert A. M. Stern ', u' James Reg... | -1 | 2016-08-10T10:04:25Z | 38,870,967 | <p>This list comprehension should work.</p>
<pre><code>[tuple(sub) if len(sub) <= 2 else list(itertools.combinations(sub,2))
for sub in collections if sub != [None]]
</code></pre>
<p>Note the use of the ternary operator in the expression.</p>
| 0 | 2016-08-10T10:34:43Z | [
"python",
"list",
"permutation",
"itertools"
] |
How to take information from input out of a while loop? | 38,870,257 | <p>My explaining is horrible so Ill put an example what I mean</p>
<pre><code>s=5
while s >= 3:
name= input("What is the name of your dog")
s = s-1
</code></pre>
<p>this isnt the best piece of code but lets say I wanted to ask the user for a piece of information and they will input 3 different times so how... | 2 | 2016-08-10T10:05:17Z | 38,870,320 | <p>You can create a list before the while loop begins, and append an entry every time the loop runs:</p>
<pre><code>s=5
names = []
while s >= 3:
name= input("What is the name of your dog")
names.append(name)
s = s-1
</code></pre>
| 0 | 2016-08-10T10:08:00Z | [
"python",
"input",
"while-loop"
] |
How to take information from input out of a while loop? | 38,870,257 | <p>My explaining is horrible so Ill put an example what I mean</p>
<pre><code>s=5
while s >= 3:
name= input("What is the name of your dog")
s = s-1
</code></pre>
<p>this isnt the best piece of code but lets say I wanted to ask the user for a piece of information and they will input 3 different times so how... | 2 | 2016-08-10T10:05:17Z | 38,870,345 | <p>using generators:</p>
<pre><code>names = [input("What is the name of your dog") for i in range(3)]
print(names)
</code></pre>
<p>using list:</p>
<pre><code>names = []
s = 5
while s >= 3:
name = input("What is the name of your dog")
names.append(name)
s = s - 1
</code></pre>
<p>using yield:</p>
<... | 1 | 2016-08-10T10:09:12Z | [
"python",
"input",
"while-loop"
] |
How to take information from input out of a while loop? | 38,870,257 | <p>My explaining is horrible so Ill put an example what I mean</p>
<pre><code>s=5
while s >= 3:
name= input("What is the name of your dog")
s = s-1
</code></pre>
<p>this isnt the best piece of code but lets say I wanted to ask the user for a piece of information and they will input 3 different times so how... | 2 | 2016-08-10T10:05:17Z | 38,870,382 | <p>Use List</p>
<pre><code>s=5
name = []
while s >= 3:
name.append(input("What is the name of your dog"))
s -= 1
</code></pre>
| 0 | 2016-08-10T10:11:00Z | [
"python",
"input",
"while-loop"
] |
How to take information from input out of a while loop? | 38,870,257 | <p>My explaining is horrible so Ill put an example what I mean</p>
<pre><code>s=5
while s >= 3:
name= input("What is the name of your dog")
s = s-1
</code></pre>
<p>this isnt the best piece of code but lets say I wanted to ask the user for a piece of information and they will input 3 different times so how... | 2 | 2016-08-10T10:05:17Z | 38,870,393 | <p>You'll need to use a list where you can append the names to.</p>
<pre><code>names = list()
s=5
while s >= 3:
names.append(input("What is the name of your dog"))
s = s-1
print names[0]
print names[1]
print names[2]
</code></pre>
| 0 | 2016-08-10T10:11:27Z | [
"python",
"input",
"while-loop"
] |
Extract after equal sign | 38,870,266 | <p>just started python pandas on Juypter. I am having difficulties trying to get the values after the equal sign. Can anyone help me through?</p>
<pre><code> Hi = 123456
123456 (result i wish to get)
</code></pre>
<p>My current code below returns "<strong>= 123456</strong>".</p>
<pre><code> df[... | 3 | 2016-08-10T10:05:41Z | 38,870,438 | <p>You used a <code>+</code> quantifier on a symbol <code>i</code> making it match 1 or more times, thus <code>\W</code> matches the space after <code>Hi</code>.</p>
<p>You can use</p>
<pre><code>r"Hi *[^\w ] *(.*)"
</code></pre>
<p>where:</p>
<ul>
<li><code>Hi</code> - matches <code>Hi</code></li>
<li><code> *</co... | 4 | 2016-08-10T10:13:25Z | [
"python",
"regex",
"pandas"
] |
Comparing values in a list to create a matching list | 38,870,291 | <p>I have list in this style:</p>
<pre><code>[ [x,y,z] , [x1,y1,z1] , [...]].
</code></pre>
<p>My problem is that I want to make a new list with somehow sorted values. In a first step I want to make a list where for all the same x and y I have the corresponding z values. Here is a example:</p>
<p>raw data:</p>
<pre... | 0 | 2016-08-10T10:06:52Z | 38,870,752 | <p>If you are starting out, it would be useful to break the problem into smaller problems and tackle it bit by bit.</p>
<p>For the first step, the easiest approach might be to first collect the information using a dictionary.</p>
<p>You go through all triplets in the original list and create a dictionary where each k... | 2 | 2016-08-10T10:26:02Z | [
"python"
] |
Can someone explain to me this Turing machine code? | 38,870,330 | <p>I am newbie to Python so I don't really understand this. It's some kind of Turing machine that should write binary number, but I can't figure out what's going on after these rules</p>
<pre><code>from collections import defaultdict
import operator
# Binary counter
# (Current state, Current symbol) : (New State, New... | 1 | 2016-08-10T10:08:47Z | 38,870,683 | <p>It is a state machine.
At each tick a new state is computed based on the old state and the contents of tape at 'tape position' in this line:</p>
<pre><code>state, tape[position], move = rules[(state, tape[position])]
</code></pre>
<p>This statement is a destructuring assignment. The righthand side of the assignmen... | 1 | 2016-08-10T10:23:23Z | [
"python",
"computer-science",
"turing"
] |
Why is pandas creating NaN for resampling of sql data? | 38,870,411 | <p>I am new to pandas and numpy and trying to aggregate measurement values to an equally spaced time series. The input data is not equally spaced and looks like:</p>
<pre><code>timestamp value
2016-08-09 11:55:26 1779.510
2016-08-09 11:55:26 1792.310
2016-08-09 11:55:27 1796.900
2016-08-09 11:55:... | 1 | 2016-08-10T10:12:17Z | 38,872,014 | <p>The issue here is that you're trying to add a new column with data with an incompatible index, when you create an empty df the index type will be <code>object</code> dtype initially, you're adding data where the index is <code>datetimeIndex</code> so you get <code>NaN</code> for all rows.</p>
<p>If you pass the dat... | 1 | 2016-08-10T11:19:39Z | [
"python",
"pandas",
"numpy"
] |
Filtering in pyspark | 38,870,548 | <p>My RDD has TAB delimited strings in it. I'm trying to filter it: if column 5 contains few strings:</p>
<pre><code>filt_data = raw_data.filter(lambda x: '' if len(x.split('\t')) < 5 else "apple" in x.split('\t')[4] or "pear" in x.split('\t')[4] or "berry" in x.split('\t')[4] or "cherry" in x.split('\t')[4])
</cod... | 0 | 2016-08-10T10:17:26Z | 38,871,512 | <p>You can replace the lambda function, with a "real" function which will do whatever you like, in an efficient way.
See below a prototype of the suggested solution</p>
<pre><code>def efficient_func(line):
if len(x.split('\t')) < 5:
return ''
word = line.split('\t')[4]
...
return ...
filt_... | 1 | 2016-08-10T10:59:44Z | [
"python",
"apache-spark",
"pyspark"
] |
How to print an incremented int identifier in a string in Python | 38,870,566 | <p>In Java, If I want to print an incremented int variable, I can do it as:</p>
<pre><code>int age = scn.nextInt();
System.out.println("You are " + age + " years old going on " + (age+1));
</code></pre>
<p><strong>Output:</strong></p>
<pre><code>21
You are 21 years old going on 22
</code></pre>
<p>Is it possible to... | 0 | 2016-08-10T10:18:27Z | 38,870,688 | <p>You need to convert the input to an int :</p>
<pre><code>>>> age = int(input("How old are you?"))
</code></pre>
<p>And then the following work :</p>
<pre><code>print("You are " , age , " years old going on " , str(age+1))
print("You are %d years old going on %d" %(age, age+1))
print("You are " + str(age)... | 1 | 2016-08-10T10:23:38Z | [
"python",
"python-3.x",
"printing",
"string-concatenation"
] |
How to print an incremented int identifier in a string in Python | 38,870,566 | <p>In Java, If I want to print an incremented int variable, I can do it as:</p>
<pre><code>int age = scn.nextInt();
System.out.println("You are " + age + " years old going on " + (age+1));
</code></pre>
<p><strong>Output:</strong></p>
<pre><code>21
You are 21 years old going on 22
</code></pre>
<p>Is it possible to... | 0 | 2016-08-10T10:18:27Z | 38,870,697 | <p>In all <code>print</code> cases you're trying to add a <code>str</code> to an <code>int</code> and the error tells you that that form of implicit convesion is not possible:</p>
<pre><code>'21' +1
TypeErrorTraceback (most recent call last)
<ipython-input-60-3473188b220d> in <module>()
----> 1 '21' +1... | 1 | 2016-08-10T10:24:08Z | [
"python",
"python-3.x",
"printing",
"string-concatenation"
] |
How to print an incremented int identifier in a string in Python | 38,870,566 | <p>In Java, If I want to print an incremented int variable, I can do it as:</p>
<pre><code>int age = scn.nextInt();
System.out.println("You are " + age + " years old going on " + (age+1));
</code></pre>
<p><strong>Output:</strong></p>
<pre><code>21
You are 21 years old going on 22
</code></pre>
<p>Is it possible to... | 0 | 2016-08-10T10:18:27Z | 38,870,794 | <p>There is no need to change it into <code>int</code> it is already.</p>
<pre><code>>>> age = input("age")
age21
>>> age
21
>>> type(age)
<type 'int'>
</code></pre>
<p>As you are concatenating string and integer you are not getting the result </p>
<p><br><strong>Try This</strong>:</... | 0 | 2016-08-10T10:27:46Z | [
"python",
"python-3.x",
"printing",
"string-concatenation"
] |
Can django filter queryset based on a dictionary field? | 38,870,705 | <p>I am diving to a django rest-api framework that someone else wrote and configured, and I came across a problem I could not find any good solution for.</p>
<p>There is a model containing field of type "YAMLField". While trying to retrieve this field member, it is converted to OrderedDict (not quite sure how and wher... | 0 | 2016-08-10T10:24:19Z | 38,873,296 | <p>You need this is possible. For more information see django-rest-framework <a href="http://www.django-rest-framework.org/api-guide/generic-views/#creating-custom-mixins" rel="nofollow">doc</a></p>
<pre><code>class MultipleFieldLookupMixin(object):
"""
Apply this mixin to any view or viewset to get multiple f... | 0 | 2016-08-10T12:20:51Z | [
"python",
"django",
"filter",
"django-rest-framework"
] |
How to add data to the new column in existing CSV using Python script | 38,870,736 | <p>Team,</p>
<p>2 things i am trying to do as per below code</p>
<p>1) write data in column 2,3,4 and 8 of file1 to a new file.<br>
2) data in 1st column(copied in new file)should be searched file2. if found,pick the data in 3rd column of same row of file 2 and write the same to the new column of new file.</p>
<p>po... | 0 | 2016-08-10T10:25:19Z | 38,872,137 | <p>I suspect that your re-use of the "row" variable name in the second for loop is clobbering the one held in "var1". I would always steer clear of that kind of recycling of variable names in nested loops.</p>
<pre><code>for row_f1 in f1:
if not row_f1[0].startswith("-"):
f2.writerow((row_f1[1],row_f1[2]... | 0 | 2016-08-10T11:25:39Z | [
"python",
"python-2.7"
] |
How to add data to the new column in existing CSV using Python script | 38,870,736 | <p>Team,</p>
<p>2 things i am trying to do as per below code</p>
<p>1) write data in column 2,3,4 and 8 of file1 to a new file.<br>
2) data in 1st column(copied in new file)should be searched file2. if found,pick the data in 3rd column of same row of file 2 and write the same to the new column of new file.</p>
<p>po... | 0 | 2016-08-10T10:25:19Z | 38,872,326 | <p>There are several issues with your code:</p>
<ul>
<li>you're opening all files in binary mode.</li>
<li>for each row in <code>f1</code>, you're (potentially) iterating over all rows in <code>f3</code>. This will decrease your performance.</li>
<li>Once you iterate through all rows in <code>f3</code>, you're at the ... | 1 | 2016-08-10T11:34:50Z | [
"python",
"python-2.7"
] |
How to add data to the new column in existing CSV using Python script | 38,870,736 | <p>Team,</p>
<p>2 things i am trying to do as per below code</p>
<p>1) write data in column 2,3,4 and 8 of file1 to a new file.<br>
2) data in 1st column(copied in new file)should be searched file2. if found,pick the data in 3rd column of same row of file 2 and write the same to the new column of new file.</p>
<p>po... | 0 | 2016-08-10T10:25:19Z | 38,889,127 | <p>@Andrew, i have made change in my code as per your input.But the value in 1st row for row_f1[1] is only going to the 2nd for loop.which means the value for row_f1[1] in other rows are not being considered for the 2nd for loop.</p>
<pre><code> for row_f1 in f1:
if not row_f1[0].startswi... | 0 | 2016-08-11T06:47:02Z | [
"python",
"python-2.7"
] |
Python convert string to class | 38,870,797 | <p>I want to do a query on the django User table like this:</p>
<pre><code>u = User.objects.filter(member__in = member_list)
</code></pre>
<p>where:</p>
<pre><code>class Member(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
dob = models.DateField('Date of Birth', blank=True, null=... | 0 | 2016-08-10T10:28:00Z | 38,871,179 | <p>The left hand side of the filter argument is a keyword, not a python object, so x is treated as 'x', and Django expects a field called x.</p>
<p>To get around this, you can ensure that <code>x</code> is a string, and then use the python <code>**kwarg</code> syntax:</p>
<pre><code>s = User.objects.filter(**{x: c.ca... | 2 | 2016-08-10T10:44:06Z | [
"python",
"mysql",
"django",
"python-2.7"
] |
Mapping in Pandas | 38,870,800 | <p>I wanted to do mapping of two Data Frames on a common column.<br>
Lets say, </p>
<p>My First Data Frame:</p>
<pre><code>>>> df
Task Emp
0 1 aa
1 1 bb
2 2 cc
</code></pre>
<p>My second DataFrame:</p>
<pre><code>>>> df1
Task Days
0 1 12
1 2 23
</code></pre>
<p... | 3 | 2016-08-10T10:28:05Z | 38,870,836 | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.map.html" rel="nofollow"><code>map</code></a>:</p>
<pre><code>df.rename(columns={'Task':'Days'}, inplace=True)
df['Days'] = df['Days'].map(df1.set_index('Task')['Days'])
df = df[['Emp','Days']]
print (df)
Emp Days
0 aa 12
1 bb ... | 3 | 2016-08-10T10:29:27Z | [
"python",
"pandas",
"dataframe",
"mapping"
] |
Mapping in Pandas | 38,870,800 | <p>I wanted to do mapping of two Data Frames on a common column.<br>
Lets say, </p>
<p>My First Data Frame:</p>
<pre><code>>>> df
Task Emp
0 1 aa
1 1 bb
2 2 cc
</code></pre>
<p>My second DataFrame:</p>
<pre><code>>>> df1
Task Days
0 1 12
1 2 23
</code></pre>
<p... | 3 | 2016-08-10T10:28:05Z | 38,870,887 | <p>try:</p>
<pre><code>pd.concat([d.set_index('Task') for d in [df, df1]], axis=1).reset_index(drop=True)
</code></pre>
<p><a href="http://i.stack.imgur.com/BnW1Q.png" rel="nofollow"><img src="http://i.stack.imgur.com/BnW1Q.png" alt="enter image description here"></a></p>
<p>As pointed out by @Borja</p>
<blockquote... | 3 | 2016-08-10T10:31:30Z | [
"python",
"pandas",
"dataframe",
"mapping"
] |
Mapping in Pandas | 38,870,800 | <p>I wanted to do mapping of two Data Frames on a common column.<br>
Lets say, </p>
<p>My First Data Frame:</p>
<pre><code>>>> df
Task Emp
0 1 aa
1 1 bb
2 2 cc
</code></pre>
<p>My second DataFrame:</p>
<pre><code>>>> df1
Task Days
0 1 12
1 2 23
</code></pre>
<p... | 3 | 2016-08-10T10:28:05Z | 38,871,344 | <p>I think what you are looking for is a merge:</p>
<pre><code>pd.merge(df, df1, on='Task')
</code></pre>
<p>Output:</p>
<pre><code> Emp Days
0 aa 12
1 bb 12
2 cc 23
</code></pre>
<p>If your dataframes are big (and especially if you have duplicate values of 'Task' in both dataframes) you will run into m... | 2 | 2016-08-10T10:51:49Z | [
"python",
"pandas",
"dataframe",
"mapping"
] |
Mapping in Pandas | 38,870,800 | <p>I wanted to do mapping of two Data Frames on a common column.<br>
Lets say, </p>
<p>My First Data Frame:</p>
<pre><code>>>> df
Task Emp
0 1 aa
1 1 bb
2 2 cc
</code></pre>
<p>My second DataFrame:</p>
<pre><code>>>> df1
Task Days
0 1 12
1 2 23
</code></pre>
<p... | 3 | 2016-08-10T10:28:05Z | 38,874,701 | <p>Additionally to the already given answers I have done a small performance test of the answers by <a href="http://stackoverflow.com/users/2336654/pirsquared">piRSquared</a>, <a href="http://stackoverflow.com/users/5798668/borja">Borja</a>, and <a href="http://stackoverflow.com/users/2901002/jezrael">jezrael</a>:</p>
... | 1 | 2016-08-10T13:22:14Z | [
"python",
"pandas",
"dataframe",
"mapping"
] |
Database to wrapper-classes or direct connectivity to database for time-series simulation application? | 38,870,823 | <p>I am writing an application that uses historical time series data to perform simulations.</p>
<p>Is it better for application to load the data from the database into local data wrapper classes before executing the main loop (up to 30 years day by day) or connect to the database each day to pull the required data?</... | 0 | 2016-08-10T10:28:51Z | 38,870,995 | <p>For current computers 30 years of day by day data amounts to almost nothing if your dayly data remains below say 10kB. Since your simulation may need efficient retrieval, especially if it combines data from different dates, I'd read all the data in memory in one query and then start processing.</p>
<p>What is consi... | 0 | 2016-08-10T10:35:28Z | [
"python",
"database",
"matlab",
"oop",
"time-series"
] |
How to unit test this coroutine without sleeping | 38,870,930 | <p>I'm trying to create function that would add following functionality to existing coroutine.</p>
<ul>
<li>Add cache to original coroutine based on arguments.</li>
<li>Add ttl parameter
that defaults to infinity, so that caller could specify how fresh the
data should be before it's refreshed.</li>
<li>If someone call... | 1 | 2016-08-10T10:33:03Z | 38,871,162 | <p>To unit test such a scenario, you use futures, which you can resolve at will. Using a very simplified <code>@cached</code> decorator and function here:</p>
<pre><code>@cached
async def test_mock(future):
await asyncio.wait_for(future, None)
func1_future = asyncio.Future()
func1_coro = test_mock(func1_future)
f... | 2 | 2016-08-10T10:43:13Z | [
"python",
"unit-testing",
"python-3.5",
"python-asyncio"
] |
Select element not in list | 38,870,938 | <p>I understand how one would normally select an element not in a list. With the code I have though, that method doesn't seem to work.</p>
<p>So I have a text file containing the following data:
Min: 5,6,1
Max: 5,6,1
Avg: 5,6,1</p>
<p>I want to select only the numbers from the file and create a list from them. I've t... | 0 | 2016-08-10T10:33:32Z | 38,871,186 | <p>To be frank, your code is a mess. Why are you wrapping your logic in a while-loop? It is going to terminate after the first iteration anyway.</p>
<p>Simplify by using <code>file.read</code> instead of <code>readlines</code>:</p>
<pre><code>with open('in_test.txt') as f:
data = f.read()
</code></pre>
<p>Then, ... | 1 | 2016-08-10T10:44:18Z | [
"python",
"list",
"python-2.7",
"for-loop",
"sublist"
] |
Select element not in list | 38,870,938 | <p>I understand how one would normally select an element not in a list. With the code I have though, that method doesn't seem to work.</p>
<p>So I have a text file containing the following data:
Min: 5,6,1
Max: 5,6,1
Avg: 5,6,1</p>
<p>I want to select only the numbers from the file and create a list from them. I've t... | 0 | 2016-08-10T10:33:32Z | 38,871,253 | <p>You can use pandas</p>
<pre><code>import pandas as pd
df = pd.read_csv('in_test.txt',sep=r":|,",header=None,index_col=0).T
</code></pre>
<p>If you want to read line by line</p>
<pre><code>with open('in_test.txt','r') as inFile_test:
for line in inFile_test:
word,numbers = line.split(":")
numbe... | 0 | 2016-08-10T10:47:59Z | [
"python",
"list",
"python-2.7",
"for-loop",
"sublist"
] |
django avatar custom template directory | 38,870,960 | <p>I have a new problem with django avatar, can i change template base of django avatar in template custom on my project ?</p>
<p>my current template :</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-h... | 0 | 2016-08-10T10:34:30Z | 38,871,165 | <p>If you want to override <code>django-avatar</code>'s change page, you should place template you present in <code><appname>/templates/avatar/change.html</code> or <code><templates_dir>/avatar/change.html</code> if you have configured one.</p>
| 0 | 2016-08-10T10:43:16Z | [
"python",
"django"
] |
How to handle multiple exceptions? | 38,871,016 | <p>I'm a Python learner, trying to handle a few scenarios:</p>
<ol>
<li>Reading a file.</li>
<li>Formatting Data.</li>
<li>Manipulating/Copying Data.</li>
<li>Writing a file.</li>
</ol>
<p>So far, I have:</p>
<pre><code>try:
# Do all
except Exception as err1:
print err1
#File Reading error/ File Not Present... | 0 | 2016-08-10T10:36:14Z | 38,871,263 | <ol>
<li><p>Your <code>try</code> blocks should be as minimal as possible, so</p>
<pre><code>try:
# do all
except Exception:
pass
</code></pre>
<p>is not something you want to do.</p></li>
<li><p>The code in your example won't work as you expect it to, because in every <code>except</code> block you are catc... | 3 | 2016-08-10T10:48:17Z | [
"python",
"python-2.7"
] |
How to handle multiple exceptions? | 38,871,016 | <p>I'm a Python learner, trying to handle a few scenarios:</p>
<ol>
<li>Reading a file.</li>
<li>Formatting Data.</li>
<li>Manipulating/Copying Data.</li>
<li>Writing a file.</li>
</ol>
<p>So far, I have:</p>
<pre><code>try:
# Do all
except Exception as err1:
print err1
#File Reading error/ File Not Present... | 0 | 2016-08-10T10:36:14Z | 38,871,280 | <p>Yes this is possible.</p>
<p>Just say as example:</p>
<pre><code>try:
...
except RuntimeError:
print err1
except NameError:
print err2
...
</code></pre>
<p>Just define the exact Error you want to intercept.</p>
| 0 | 2016-08-10T10:48:48Z | [
"python",
"python-2.7"
] |
How to handle multiple exceptions? | 38,871,016 | <p>I'm a Python learner, trying to handle a few scenarios:</p>
<ol>
<li>Reading a file.</li>
<li>Formatting Data.</li>
<li>Manipulating/Copying Data.</li>
<li>Writing a file.</li>
</ol>
<p>So far, I have:</p>
<pre><code>try:
# Do all
except Exception as err1:
print err1
#File Reading error/ File Not Present... | 0 | 2016-08-10T10:36:14Z | 38,871,407 | <p>As <a href="http://stackoverflow.com/users/1453822/deepspace">DeepSpace</a> stated, </p>
<blockquote>
<p>Your <code>try</code> blocks should be as minimal as possible.</p>
</blockquote>
<p>If you want to achieve</p>
<pre><code>try:
# do all
except Exception:
pass
</code></pre>
<p>Then you might as we... | 0 | 2016-08-10T10:54:14Z | [
"python",
"python-2.7"
] |
covariance in numpy polyfit for two data points | 38,871,147 | <p>I have two data points, x and y and the associated y error. I want to fit a straight line through the data points and calculate the error in the slope and intercept. When I try to use numpy ployfit with cov=True to get the covariance matrix in order to find the error it gives me the following error:</p>
<pre><code>... | 2 | 2016-08-10T10:42:34Z | 38,892,598 | <p>I don't think this is possible. In order to calculate the covariance matrix, <code>polyfit</code> (which calls <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.linalg.lstsq.html" rel="nofollow"><code>numpy.lstsq</code></a>) needs the residuals. But the residuals for your fit are necessarily zero si... | 1 | 2016-08-11T09:37:06Z | [
"python",
"numpy"
] |
Crawl streaming tweets and historical tweets with python | 38,871,158 | <p>I want to crawl streaming twitter data with python for a search query. One questions here: is it true that data I will collect is generated right from the time I run the script?</p>
<p>Also, how to crawl tweets in the past given day? Is is possible I can get access to all the tweets in that day?</p>
<p>Thanks!</p>... | 0 | 2016-08-10T10:43:02Z | 38,872,490 | <p>Yes <strong>it's true</strong> that if you do streaming it will be collected <strong>from the moment you start that service</strong>. </p>
<p>So what you can do is <strong>get old tweets</strong> by another mechanism, here is a <a href="https://github.com/Jefferson-Henrique/GetOldTweets-python" rel="nofollow"><stro... | 1 | 2016-08-10T11:42:53Z | [
"python",
"twitter",
"web-crawler"
] |
Error with code Python Beautifulsoup extract specific link with text | 38,871,259 | <p>Hello i have a problem with my code, i tried to search one specific url with this code but it doesn't show up anything</p>
<pre><code>from BeautifulSoup import BeautifulSoup
import urllib2
import re
html_page = urllib2.urlopen(url)
soup = BeautifulSoup(html_page)
for link in soup.findAll('a', attrs={'href': re.com... | -2 | 2016-08-10T10:48:07Z | 38,872,709 | <p>Thank you everyone but i solved it myself with selenium, </p>
<pre><code>from selenium import webdriver
driver.get(url)
puntos = driver.find_element_by_link_text(u"10")
print (puntos.get_attribute('href'))
</code></pre>
| 1 | 2016-08-10T11:53:19Z | [
"python",
"url",
"beautifulsoup"
] |
compare two csv files, one line code fails | 38,871,330 | <p>I have the code below (full code also is included) it is responsible for comparing 2 csv files</p>
<p>(I INSIST TO KEEP IT IN THE ONE LINE FORMAT IF POSSIBLE):</p>
<pre><code>master_indices = dict(((r[0]), i) for i, r in enumerate(csv.reader(master)))
</code></pre>
<p>I need to add the statement that if the line ... | 0 | 2016-08-10T10:51:01Z | 38,871,484 | <p>Have you tried this?</p>
<pre><code>master_indices = {r[0]:i for i,r in enumerate(csv.reader(master)) if "/" in r[0]}
</code></pre>
<p>If you want to find "/" in all the line you can do:</p>
<pre><code> master_indices = {r.split(",",1)[0]:i for i,r in enumerate(master) if "/" in r}
</code></pre>
| 0 | 2016-08-10T10:58:19Z | [
"python",
"python-3.x",
"csv",
"parsing"
] |
How can I get the default colors in GTK? | 38,871,450 | <h2>Context</h2>
<p>In GTK 3, people can set their own themes. Even the default theme (Adwaita) is provided with two variants: a light one and a dark one. As I am writing my own widget (in python), I need to get these colors in order to avoid drawing black on black or white on white.</p>
<h2>Question</h2>
<p>How can... | 4 | 2016-08-10T10:56:46Z | 39,382,058 | <p>In your widget's <code>do_draw()</code> implementation, you can read out the theme colors from the widget's style context. For this you use methods such as <code>self.get_style_context().get_color()</code>, <code>...get_border_color()</code>, <code>...get_background_color()</code>.</p>
| 0 | 2016-09-08T03:18:21Z | [
"python",
"python-3.x",
"gtk",
"gtk3",
"pygobject"
] |
breaking up a list entry in several lists at every /n Python 3 | 38,871,497 | <p>I am trying to create several lists by breaking up each list entry. the format is as follows:</p>
<p>LIST ENTRY FORMAT</p>
<pre><code>['Root Cause: Hardware Failure\nAction Completed: Power supply/filter/cable swap\nArrival Time: 02/01/2014 15:54:17\nLeaving Time: 02/01/2014 16:27:44\nWas the job successful: Yes\n... | 1 | 2016-08-10T10:58:56Z | 38,871,559 | <p>Is this what you're looking at??</p>
<pre><code>x = ['Root Cause: Hardware Failure\nAction Completed: Power supply/filter/cable swap\nArrival Time: 02/01/2014 15:54:17\nLeaving Time: 02/01/2014 16:27:44\nWas the job successful: Yes\nNotes:replaced dsl cable and filter. Also rebooted all equipment. All working fine ... | 0 | 2016-08-10T11:01:45Z | [
"python",
"list",
"python-3.x"
] |
breaking up a list entry in several lists at every /n Python 3 | 38,871,497 | <p>I am trying to create several lists by breaking up each list entry. the format is as follows:</p>
<p>LIST ENTRY FORMAT</p>
<pre><code>['Root Cause: Hardware Failure\nAction Completed: Power supply/filter/cable swap\nArrival Time: 02/01/2014 15:54:17\nLeaving Time: 02/01/2014 16:27:44\nWas the job successful: Yes\n... | 1 | 2016-08-10T10:58:56Z | 38,871,581 | <p>if you want list of lists:</p>
<pre><code>list(map(lambda s: [s], old_list[0].splitlines()))
</code></pre>
<p>you can read more about <a href="http://stackoverflow.com/questions/890128/why-are-python-lambdas-useful">lambda functions</a> and <a href="https://docs.python.org/2/library/functions.html#map" rel="nofoll... | 0 | 2016-08-10T11:02:25Z | [
"python",
"list",
"python-3.x"
] |
breaking up a list entry in several lists at every /n Python 3 | 38,871,497 | <p>I am trying to create several lists by breaking up each list entry. the format is as follows:</p>
<p>LIST ENTRY FORMAT</p>
<pre><code>['Root Cause: Hardware Failure\nAction Completed: Power supply/filter/cable swap\nArrival Time: 02/01/2014 15:54:17\nLeaving Time: 02/01/2014 16:27:44\nWas the job successful: Yes\n... | 1 | 2016-08-10T10:58:56Z | 38,871,675 | <p>Use a list comp and <em>str.splitlines</em> to split every string in the lists into sublists of individual lines:</p>
<pre><code>split_lines = [s.splitlines() for s in lst]
</code></pre>
<p>If you want each individual string inside a list:</p>
<pre><code> from itertools import chain
split_lines = [[s] for s i... | 3 | 2016-08-10T11:05:40Z | [
"python",
"list",
"python-3.x"
] |
breaking up a list entry in several lists at every /n Python 3 | 38,871,497 | <p>I am trying to create several lists by breaking up each list entry. the format is as follows:</p>
<p>LIST ENTRY FORMAT</p>
<pre><code>['Root Cause: Hardware Failure\nAction Completed: Power supply/filter/cable swap\nArrival Time: 02/01/2014 15:54:17\nLeaving Time: 02/01/2014 16:27:44\nWas the job successful: Yes\n... | 1 | 2016-08-10T10:58:56Z | 38,871,719 | <p>You can use the <code>split()</code> method to create the items and then place them in a master list like so:</p>
<pre><code>alist = ['Root Cause: Hardware Failure\nAction Completed: Power supply/filter/cable swap\nArrival Time: 02/01/2014 15:54:17\nLeaving Time: 02/01/2014 16:27:44\nWas the job successful: Yes\nNo... | 1 | 2016-08-10T11:07:07Z | [
"python",
"list",
"python-3.x"
] |
breaking up a list entry in several lists at every /n Python 3 | 38,871,497 | <p>I am trying to create several lists by breaking up each list entry. the format is as follows:</p>
<p>LIST ENTRY FORMAT</p>
<pre><code>['Root Cause: Hardware Failure\nAction Completed: Power supply/filter/cable swap\nArrival Time: 02/01/2014 15:54:17\nLeaving Time: 02/01/2014 16:27:44\nWas the job successful: Yes\n... | 1 | 2016-08-10T10:58:56Z | 38,872,409 | <p>here you get a list of all the desired lists</p>
<pre><code>list = ['Root Cause: Hardware Failure\nAction Completed: Power supply/filter/cable swap']
temp = L[0].split('\n')
newList = []
for n in temp:
newList.append([n])
</code></pre>
<p>and you will get:</p>
<pre><code>newList = [['Root Cause: Hardware Fail... | 0 | 2016-08-10T11:38:54Z | [
"python",
"list",
"python-3.x"
] |
Find number of weeks in a month | 38,871,522 | <p>Can someone suggest a function to return number of weeks in a month?
for example:</p>
<pre><code>def num_of_weeks(year, month):
# Do calulation
return int(num)
# In 2016 Julay we had five weeks
print num_of_weeks(2016, 1)
>> 5
print num_of_weeks(2016, 5)
>> 6
</code></pre>
| -3 | 2016-08-10T11:00:13Z | 38,872,361 | <p>You can do it using <em>calendar</em> built-in module. My example looks hackish, but still it handles your task:</p>
<pre><code>def num_of_weeks_in_month(year, month):
import calendar
return calendar.month(year, month).count('\n') - 2
print num_of_weeks_in_month(2016, 8) # print 5
print num_of_weeks_in_mo... | 1 | 2016-08-10T11:36:42Z | [
"python",
"week-number"
] |
Find number of weeks in a month | 38,871,522 | <p>Can someone suggest a function to return number of weeks in a month?
for example:</p>
<pre><code>def num_of_weeks(year, month):
# Do calulation
return int(num)
# In 2016 Julay we had five weeks
print num_of_weeks(2016, 1)
>> 5
print num_of_weeks(2016, 5)
>> 6
</code></pre>
| -3 | 2016-08-10T11:00:13Z | 38,872,827 | <p>Another mathematical solution:</p>
<pre><code>def num_of_weeks_in_month(year, month):
from math import ceil
from calendar import monthrange
return int(ceil(float(monthrange(year, month)[0]+monthrange(year,month)[1])/7))
</code></pre>
| 1 | 2016-08-10T11:58:31Z | [
"python",
"week-number"
] |
Having access to request.authorization.username (BasicAuth) within Database event hooks in Python Eve | 38,871,707 | <p>I'm trying to get access to <strong>request.authorization.username</strong> within the <a href="http://python-eve.org/features.html#database-event-hooks" rel="nofollow">Database Event Hook</a> 'on_insert', but it doesn't seem to be trivial as no access to the request object is available.</p>
<p>The goal is to get t... | 1 | 2016-08-10T11:06:49Z | 39,075,222 | <p>Eve's <code>BasicAuth</code> (<a href="https://github.com/nicolaiarocci/eve/blob/develop/eve/auth.py#L126" rel="nofollow">source</a>) class stores the user name in <code>flask.g</code> object (<a href="http://flask.pocoo.org/docs/0.11/api/#flask.g" rel="nofollow">docs</a>), so all you have to do is:</p>
<pre><code>... | 0 | 2016-08-22T08:59:18Z | [
"python",
"flask",
"eve"
] |
Pandas: delete string with some date | 38,871,775 | <p>I have df:</p>
<pre><code>ID,"address","used_at","active_seconds","pageviews"
71ecd2aa165114e5ee292131f1167d8c,"auto.drom.ru",2014-05-17 10:58:59,166,2
71ecd2aa165114e5ee292131f1167d8c,"auto.drom.ru",2016-07-17 17:34:07,92,4
70150aba267f671045f147767251d169,"avito.ru/*/avtomobili",2014-06-15 11:52:09,837,40
bc779f5... | 3 | 2016-08-10T11:09:32Z | 38,871,892 | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.dt.date.html" rel="nofollow"><code>dt.date</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#boolean-indexing" rel="nofollow"><code>boolean indexing</code></a>:</p>
<pre><code>print (df.used_at.dt.date ... | 4 | 2016-08-10T11:13:47Z | [
"python",
"datetime",
"pandas",
"indexing",
"dataframe"
] |
why windows shows The system cannot find the file specified? | 38,871,809 | <p>As i am a new baby in phython ,i didn't able to find the problem.here is my code..</p>
<pre><code>import os
def rename_files():
#get the all files in the directory
file_list = os.listdir(r'C:\Users\squalporeover\Desktop\prank')
print ( file_list )
#rename each file
for file_name in file_list:
os.rename(file_... | 0 | 2016-08-10T11:10:50Z | 38,871,899 | <p><code>file_list</code> just contains the file names, not the full paths. You need to pass the path+name to os.rename.</p>
<pre><code>path = r'C:\Users\squalporeover\Desktop\prank'
file_list = os.listdir(path)
for file_name in file_list:
full_path = os.path.join(path, file_name)
os.rename(full_path, file_na... | 1 | 2016-08-10T11:14:01Z | [
"python"
] |
python - Write in different files created | 38,871,841 | <p>I would like to create, let's say, 100 folders, and in each folder create a txt file. And I would like to write different things in each text file, because of some conditions. I can create the folders, and create the file in each folder. But by using with <strong>open('...') as f :</strong>, I am not able to write d... | 0 | 2016-08-10T11:12:02Z | 38,872,184 | <pre><code>def writeToFiles():
for i in range(100):
dir_name = (('/home/pi/Project/folder_%s') % (i))
f = open(os.path.join(dir_name, "file_%s" % (i + 1)), "w")
f.write(str(i))
f.close()
</code></pre>
<p>This is one to do it I will prefer that you do that while creating your files ... | 2 | 2016-08-10T11:27:55Z | [
"python",
"loops",
"text"
] |
How is using SQLAlchemy different in Flask framework | 38,871,886 | <p>I've written things in SQLAlchemy that work fine but the same workflow/commands seem to be askew when doing them in Flask. For example, these types of lines are getting flagged as "undefined":</p>
<pre><code>metadata = MetaData(db)
abc = Table('abc', metadata, autoload=True)
s = select([abc.name])
</code></pre>
... | 1 | 2016-08-10T11:13:39Z | 38,872,251 | <p>Importing <code>SQLAlchemy</code> will not give you direct access to the names inside that module. You should also be aware that using the <code>flask_sqlalchemy</code> (formerly <code>flask.ext.sqlalchemy</code>) module uses a somewhat different mechanism to access SQLAlchemy features. This means that any attempt t... | 3 | 2016-08-10T11:31:33Z | [
"python",
"flask",
"sqlalchemy",
"pythonanywhere"
] |
Function generators vs class generators in Python 3 | 38,872,149 | <p>Why do function generators and class generators behave differently? I mean, with class generators I can use generator as many times as I want, but with function generators, I can only use it once? Why so?</p>
<pre><code>def f_counter(low,high):
counter=low
while counter<=high:
yield counter
... | 1 | 2016-08-10T11:25:56Z | 38,872,272 | <p>Calling the <code>f_gen()</code> function produces an <a href="https://docs.python.org/3/glossary.html#term-iterator" rel="nofollow"><em>iterator</em></a> (specifically, a <a href="https://docs.python.org/3/glossary.html#term-generator-iterator" rel="nofollow"><em>generator iterator</em></a>). Iterators can only eve... | 4 | 2016-08-10T11:32:39Z | [
"python",
"python-3.x",
"generator"
] |
Function generators vs class generators in Python 3 | 38,872,149 | <p>Why do function generators and class generators behave differently? I mean, with class generators I can use generator as many times as I want, but with function generators, I can only use it once? Why so?</p>
<pre><code>def f_counter(low,high):
counter=low
while counter<=high:
yield counter
... | 1 | 2016-08-10T11:25:56Z | 38,872,275 | <p>Your class is an iterable, but not an iterator itself. Each time you call <code>iter</code> on it, you get a new iterator.</p>
<p>If you want to replicate the behavior of the generator function with a class, then you want an iterator like this:</p>
<pre><code>class CCounter(object):
def __init__(self, low, hig... | 2 | 2016-08-10T11:32:46Z | [
"python",
"python-3.x",
"generator"
] |
Submitting a form, and getting the result using mechanise in python | 38,872,187 | <p>I am trying to use mechanise to submit a web-form and print out the results for me. The input coordinates are being fed from a CSV file. </p>
<pre><code>def form_scraper(xcord,ycord):
br = mechanize.Browser()
br.set_handle_refresh(False)
br.open('http://www.whoi.edu/marine/ndsf/cgi-bin/NDSFutility.cgi?f... | 0 | 2016-08-10T11:27:58Z | 38,876,812 | <p>The <code>action</code> attribute of the form you are using specifies a location that does not exist. The form does not have a submit button. The reason the form works when you use it in your browser is that clicking the "Convert" button runs a JavaScript function which will do the actual calculation and write the r... | 0 | 2016-08-10T14:51:07Z | [
"python",
"forms",
"web-scraping",
"mechanize"
] |
Tweepy - Exclude Retweets | 38,872,195 | <p>Ultimate goal is to use the tweepy api search to focus on topics (i.e docker) and to EXCLUDE retweets. I have looked at other threads that mention excluding retweets but they were completely applicable. I have tried to incorporate what I've learned into the code below but I believe the "if not" piece of code is in t... | 1 | 2016-08-10T11:28:33Z | 38,874,835 | <p>So <code>tweet</code> is an object not a JSON or dict, you should not access it like <code>tweet['retweeted']</code> and <code>tweet['text']</code></p>
<p>Instead use this line : </p>
<pre><code>if not tweet.retweeted:
</code></pre>
<p>Or for your use case :</p>
<pre><code>if (not tweet.retweeted) and ('RT @' no... | 1 | 2016-08-10T13:28:06Z | [
"python",
"python-2.7",
"twitter",
"tweepy",
"api-design"
] |
Tweepy - Exclude Retweets | 38,872,195 | <p>Ultimate goal is to use the tweepy api search to focus on topics (i.e docker) and to EXCLUDE retweets. I have looked at other threads that mention excluding retweets but they were completely applicable. I have tried to incorporate what I've learned into the code below but I believe the "if not" piece of code is in t... | 1 | 2016-08-10T11:28:33Z | 38,976,513 | <p>In addition to the accepted answer, I would suggest that you change the request you make, from <code>q="docker"</code> to <code>q="docker -filter:retweets"</code></p>
<p>This will prevent most retweets from even appearing in the results.</p>
| 1 | 2016-08-16T13:39:25Z | [
"python",
"python-2.7",
"twitter",
"tweepy",
"api-design"
] |
How to plot HAC result as scatter plot (scipy linkage) | 38,872,288 | <p>I'm using <code>scipy</code> linkage for clustering. I'd like to know what's the easiest way to plot the result into a scatter plot:</p>
<pre><code>%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
from scipy.cluster.hierarchy import dendrogram, linkage
from sklearn.manifold import MDS
n = 10... | 0 | 2016-08-10T11:33:25Z | 38,873,540 | <p>You can use <a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.cluster.hierarchy.fcluster.html" rel="nofollow"><code>fcluster</code></a> with <code>lnk</code> assuming there are two clusters,</p>
<pre><code># Plot 'lnk' into scatter plot ..
from scipy.cluster.hierarchy import fcluster
fc = fcluster(... | 0 | 2016-08-10T12:32:11Z | [
"python",
"matplotlib",
"plot",
"scipy"
] |
Print list of lists in separate lines | 38,872,341 | <p>I have a list of lists:
<code>[[1, 3, 4], [2, 5, 7]]</code></p>
<p>I want the output in the following format</p>
<pre><code>1 3 4
2 5 7
</code></pre>
<p>I have tried it the following way , but the outputs are not in the desired way</p>
<pre><code>for i in a:
for j in i:
print(j,sep=' ')
#Output: ... | 3 | 2016-08-10T11:35:50Z | 38,872,499 | <p>Iterate through every sub-list in your original list and unpack it in the print call with <code>*</code>:</p>
<pre><code>l = [[1, 3, 4], [2, 5, 7]]
for s in l:
print(*s)
</code></pre>
<p>The separation is by default set to <code>' '</code> so there's no need to explicitly provide it. This prints:</p>
<pre><co... | 4 | 2016-08-10T11:43:26Z | [
"python",
"list",
"python-3.x",
"printing",
"nested-lists"
] |
Print list of lists in separate lines | 38,872,341 | <p>I have a list of lists:
<code>[[1, 3, 4], [2, 5, 7]]</code></p>
<p>I want the output in the following format</p>
<pre><code>1 3 4
2 5 7
</code></pre>
<p>I have tried it the following way , but the outputs are not in the desired way</p>
<pre><code>for i in a:
for j in i:
print(j,sep=' ')
#Output: ... | 3 | 2016-08-10T11:35:50Z | 38,872,552 | <p>oneliner:</p>
<pre><code>print('\n'.join(' '.join(map(str,sl)) for sl in l))
</code></pre>
<p>explanation:<br>
you can convert <code>list</code> into <code>str</code> by using join function:</p>
<pre><code>l = ['1','2','3']
' '.join(l) # will give you a next string: '1 2 3'
'.'.join(l) # and it will give you '1.2... | 5 | 2016-08-10T11:45:18Z | [
"python",
"list",
"python-3.x",
"printing",
"nested-lists"
] |
Print list of lists in separate lines | 38,872,341 | <p>I have a list of lists:
<code>[[1, 3, 4], [2, 5, 7]]</code></p>
<p>I want the output in the following format</p>
<pre><code>1 3 4
2 5 7
</code></pre>
<p>I have tried it the following way , but the outputs are not in the desired way</p>
<pre><code>for i in a:
for j in i:
print(j,sep=' ')
#Output: ... | 3 | 2016-08-10T11:35:50Z | 38,873,065 | <p>You can do this:</p>
<pre><code>>>> lst = [[1, 3, 4], [2, 5, 7]]
>>> for sublst in lst:
... for item in sublst:
... print item, # note the ending ','
... print # print a newline
...
1 3 4
2 5 7
</code></pre>
| 1 | 2016-08-10T12:09:20Z | [
"python",
"list",
"python-3.x",
"printing",
"nested-lists"
] |
Configuration to perform only 30 tasks per minute using python-rq | 38,872,373 | <p>I'm building a distributed crawling mechanism and want to make sure that no more than 30 requests are made to the server in one minute. Each enqued task makes a request.</p>
<p>All tasks are enqued in redis and are dequed using api provided by <a href="http://python-rq.org/" rel="nofollow">python-rq</a>.</p>
<p>Th... | 1 | 2016-08-10T11:37:18Z | 38,888,280 | <p>After reviewing <code>worker.py</code> source, the mistake in my thought process was evident. The <code>w.work()</code> function initiates a loop and continuously dequeues tasks. </p>
<p>Because this process cannot be controlled, without re-writing the worker class, and the next best way is to control the enqueuing... | 0 | 2016-08-11T05:57:11Z | [
"python",
"python-rq"
] |
matplotlib animation doesn't work | 38,872,493 | <p>I wrote this code for plotting a dynamic diagram using matplotlib, but it doesn't work:</p>
<pre><code>from matplotlib import style
import matplotlib.pyplot as plt
import matplotlib.animation as animation
fig = plt.figure()
ax1 = fig.add_subplot(1,1,1)
def animate(i):
graph_data = open ('data.txt','r').read()
lines... | 0 | 2016-08-10T11:43:10Z | 38,873,339 | <p>You need to have ax1.plot inside of animate.</p>
<pre><code>def animate(i):
graph_data = open ('data.txt','r').read()
lines = graph_data.split('\n')
xs = []
ys = []
for line in lines:
if len(line) > 1:
x, y = line.split(',')
xs.append(x)
ys.append(y)
ax1.plot(xs, ys)
</c... | 0 | 2016-08-10T12:23:18Z | [
"python",
"matplotlib"
] |
plotting pandas intraday time series only for periods with data | 38,872,579 | <p>I have a series of intraday measurements. measurements are only taken during daytime on weekdays. when I plot the data, pandas extends the xaxis over the full time horizont, so the plot shows data gaps</p>
<pre><code>dfb.loc[:,("value", "exp_1")].plot()
</code></pre>
<p><a href="http://i.stack.imgur.com/zL4ow.png"... | 1 | 2016-08-10T11:46:44Z | 38,922,526 | <p>It looks a bit like a bug. You may also consider creating an issue on <a href="https://github.com/pydata/pandas/" rel="nofollow">https://github.com/pydata/pandas/</a></p>
<p>When I tried it with a DatetimeIndex with frequency set to days or business days then the x axis isn't affected. But if the frequency is finer... | 0 | 2016-08-12T16:21:54Z | [
"python",
"pandas",
"matplotlib"
] |
Get the same shift left in Python as Java | 38,872,627 | <p>Specifically I want to take this number:</p>
<pre><code>x = 1452610545672622396
</code></pre>
<p>and perform</p>
<pre><code>x ^= (x << 21) // In Python I do x ^= (x << 21) & 0xffffffffffffffff
</code></pre>
<p><strong>I want to get:</strong> <code>-6403331237455490756</code>, which is what I get ... | 2 | 2016-08-10T11:49:43Z | 38,874,735 | <p>You might cause an overflow. Java long is 64 bit long while python has no size limit. Try using Long wrapper class of long. The Long object has also no limits (Well technicially everything has its limits...).</p>
| 0 | 2016-08-10T13:23:44Z | [
"java",
"python",
"bit-shift"
] |
Get the same shift left in Python as Java | 38,872,627 | <p>Specifically I want to take this number:</p>
<pre><code>x = 1452610545672622396
</code></pre>
<p>and perform</p>
<pre><code>x ^= (x << 21) // In Python I do x ^= (x << 21) & 0xffffffffffffffff
</code></pre>
<p><strong>I want to get:</strong> <code>-6403331237455490756</code>, which is what I get ... | 2 | 2016-08-10T11:49:43Z | 38,875,294 | <p>You can use 64bit signed int like java using <a href="https://docs.python.org/3.1/library/ctypes.html#ctypes.c%5Flonglong" rel="nofollow">ctypes.c_longlong</a>, please see example below:</p>
<pre><code>from ctypes import c_longlong as ll
x = 1452610545672622396
output = ll(x^(x<<21))
print output
print out... | 3 | 2016-08-10T13:47:19Z | [
"java",
"python",
"bit-shift"
] |
How to incrementally create an sparse matrix on python? | 38,872,659 | <p>I am creating a co-occurring matrix, which is of size 1M by 1M integer numbers.
After the matrix is created, the only operation I will do on it is to get top N values per each row (or column. as it is a symmetric matrix).</p>
<p>I have to create matrix as sparse to be able to fit it in memory. I read input data fr... | 1 | 2016-08-10T11:51:24Z | 38,878,974 | <p>A SO question from a couple of days ago, <a href="http://stackoverflow.com/questions/38820079/creating-sparse-matrix-of-unknown-size">creating sparse matrix of unknown size</a>, talks about creating a sparse matrix from data read from a file. There the OP wanted to use <code>lil</code> format; I recommended buildi... | 2 | 2016-08-10T16:31:15Z | [
"python",
"numpy",
"scipy",
"bigdata",
"sparse-matrix"
] |
Login in a website with requests | 38,872,733 | <p>I need to log me in a website with requests, but all I have try don't work :</p>
<pre><code>from bs4 import BeautifulSoup as bs
import requests
s = requests.session()
url = 'https://www.ent-place.fr/CookieAuth.dll?GetLogon?curl=Z2F&reason=0&formdir=5'
def authenticate():
headers = {'username': 'myuser... | -1 | 2016-08-10T11:54:20Z | 38,874,802 | <p>When you submit the logon, the POST request is sent to <code>https://www.ent-place.fr/CookieAuth.dll?Logon</code> not <code>https://www.ent-place.fr/CookieAuth.dll?GetLogon?curl=Z2F&reason=0&formdir=5</code> -- You get redirected to that URL afterwards.</p>
<p>When I tested this, the post request contains t... | 0 | 2016-08-10T13:27:07Z | [
"python",
"python-2.7",
"python-3.x",
"python-requests"
] |
URLs and Regex in Django | 38,872,755 | <p>I want my link detail url like this: /subreddit/pk/slug</p>
<p>Subreddit(category) is variable of course. </p>
<p>In Reddit if you click the comments of the link, you are going to detail of it. But detail page is mix of subreddit. How can I do that?</p>
<p>I hope I made myself clear. Thanks in advance.</p>
<p>I'... | 0 | 2016-08-10T11:55:13Z | 38,873,155 | <p>you have to change the order of URL include. It take priority as first come first server.In you case it running the links URL,because there is match to your URL pattern. If you declare like below.</p>
<pre><code> urlpatterns = [
url(r'^k/', include("x.subreddit.urls", namespace="sub")),
url(r'^', i... | 0 | 2016-08-10T12:13:31Z | [
"python",
"regex",
"django"
] |
URLs and Regex in Django | 38,872,755 | <p>I want my link detail url like this: /subreddit/pk/slug</p>
<p>Subreddit(category) is variable of course. </p>
<p>In Reddit if you click the comments of the link, you are going to detail of it. But detail page is mix of subreddit. How can I do that?</p>
<p>I hope I made myself clear. Thanks in advance.</p>
<p>I'... | 0 | 2016-08-10T11:55:13Z | 38,873,665 | <p>In <code>link/urls.py</code> try to add regex that parses arguments of your desired url:</p>
<pre><code>urlpatterns = [
url(
regex=r'^(?P<pk>\d+)(?:/(?P<slug>[\w\d-]+))?/$',
view=views.LinkDetailView.as_view(),
name='link_detail'
),
url(
regex=r'^(?P<subred... | 0 | 2016-08-10T12:38:09Z | [
"python",
"regex",
"django"
] |
Merging/Append a DataFrame with itself results in new columns | 38,872,881 | <p>I have the following merge operation:</p>
<pre><code>data_static = pandas.merge(data_static, data_output[['TICKER', 'DATE', 'rolling_vola_40', 'rolling_vola_80', 'f_rolling_vola_40', 'f_rolling_vola_80', 'rolling_vola_prev_annum', 'rolling_vola_post_annum']], how='left', on=['TICKER', 'DATE'])
</code></pre>
<p>My ... | 0 | 2016-08-10T12:00:48Z | 38,875,853 | <p>The work around here is to use <code>append</code> first and then <code>merge</code> them at the end:</p>
<pre><code>data_store = pandas.DataFrame(columns=('TICKER', 'DATE', 'rolling_vola_40', 'rolling_vola_80', 'f_rolling_vola_40', 'f_rolling_vola_80', 'rolling_vola_prev_annum', 'rolling_vola_post_annum'))
for in... | 0 | 2016-08-10T14:11:31Z | [
"python",
"pandas",
"join",
"merge",
"append"
] |
Django: How can I write a forms.SelectMultiple? | 38,873,035 | <p>I was searching for an example for my problem, unfortunately I wasn't able to find a suitable one.</p>
<p>I know I have to edit the form.py, the view.py and my html file, but I am not sure how.
My html file looks like this:</p>
<pre><code><div class="form-group">
<label class="col-sm-2 control-label"... | 0 | 2016-08-10T12:07:58Z | 38,890,734 | <p>I think the problem is that you're iterating over the form widget and not its choices. So try this instead:</p>
<pre><code>{% for id, country in form.country.choices %}
<option value="{{ id }}">{{country}}</option>
{% endfor %}
</code></pre>
| 0 | 2016-08-11T08:08:17Z | [
"python",
"html",
"django"
] |
configure Pycharm to debug Odoo 8 | 38,873,238 | <p>i've installed pycharm community edition 2016.</p>
<p>I tried to configure it to debug Odoo as illustrated in the capture</p>
<p><a href="http://i.stack.imgur.com/WqyCt.png" rel="nofollow"><img src="http://i.stack.imgur.com/WqyCt.png" alt="enter image description here"></a></p>
<p>When i open a python file set a ... | 2 | 2016-08-10T12:17:44Z | 38,874,608 | <p>First question - you are not supposed to run it from exe file, but from openerp-server, which is located in odoo installation folder via python interpreter. What is more, your configuration is wrong, because Odoo does not work with Python 3.4.1
My configuration looks like this:
<a href="http://i.stack.imgur.com/JtXS... | 1 | 2016-08-10T13:17:23Z | [
"python",
"openerp",
"pycharm",
"odoo-8"
] |
configure Pycharm to debug Odoo 8 | 38,873,238 | <p>i've installed pycharm community edition 2016.</p>
<p>I tried to configure it to debug Odoo as illustrated in the capture</p>
<p><a href="http://i.stack.imgur.com/WqyCt.png" rel="nofollow"><img src="http://i.stack.imgur.com/WqyCt.png" alt="enter image description here"></a></p>
<p>When i open a python file set a ... | 2 | 2016-08-10T12:17:44Z | 38,902,393 | <p>To be able to reach breakpoint you have to disable gevent. At the moment of writing you can do it by commenting this piece of code in <a href="https://github.com/odoo/odoo/blob/8.0.0/openerp/__init__.py#L28" rel="nofollow">openerp/__init__.py</a></p>
<pre class="lang-py prettyprint-override"><code>import sys
evente... | 0 | 2016-08-11T17:12:03Z | [
"python",
"openerp",
"pycharm",
"odoo-8"
] |
How do I generate a histogram from a list of values using matplotlib? | 38,873,259 | <p>so I've been trying to plot a histogram using python with mathplotlib.
So I've got two datasets, basically the heights of a sample of men and women as a list in python, imported off a csv file.</p>
<p>The code that I'm using:</p>
<pre><code>import csv
import numpy as np
from matplotlib import pyplot as plt
men=[]
... | 2 | 2016-08-10T12:18:52Z | 38,873,637 | <p>NOTE:assume your files contain multiple lines (comma separated) and the first entry in each line is the height.</p>
<p>The bug is when you append "data" into the <code>women</code> and <code>men</code> list. <code>row[0]</code> is actually a string. Hence matplotlib is confused. I suggest you run this code before p... | 1 | 2016-08-10T12:36:43Z | [
"python",
"list",
"matplotlib",
"plot"
] |
Extract year from YYYYMMDD column in Pandas DataFrame | 38,873,337 | <p>I have a pandas DataFrame in which I would like to create an additional column containing only the year which I extract from a column in YYYYMMDD format.
When searching the forum I found the <code>to_datetime</code> command, but for my case it didn't work.</p>
<p>I tried the following:</p>
<pre><code>df = pd.DataF... | 0 | 2016-08-10T12:23:11Z | 38,873,515 | <p>This is what you need, to specify the format in which you're providing the date.</p>
<pre><code> df['date'] = pd.to_datetime(df['date'],format='%Y%m%d')
</code></pre>
| 0 | 2016-08-10T12:31:26Z | [
"python",
"date",
"pandas",
"python-datetime"
] |
Replace regions in a raster image with values from another image in python | 38,873,345 | <p>I have two raster images of the same area and x,y dimensions as numpy arrays. Image 1 is a land-use classification (e.g. with classes 0 to 5) and image 2 is a cloud-shadow mask (with the values: 0 = cloudfree, 255 = cloud/ shadow areas). <br>
I want to combine those images. Either take/clip all the 255 values from ... | 0 | 2016-08-10T12:23:41Z | 38,873,821 | <p>You can do this with numpy's boolean indexing feature. </p>
<pre><code>img1 = np.array([[0, 1, 0, 1],[1, 0, 1, 0]])
img2 = np.array([[1, 2, 3, 4],[5, 6, 7, 8]])
bool_arr = img1 == 0
img1[bool_arr] = img2[bool_arr]
print(img1)
# outputs: [[1 1 3 1]
# [1 6 1 8]]
</code></pre>
| 0 | 2016-08-10T12:44:31Z | [
"python",
"numpy",
"open-source",
"gdal"
] |
Generating square subplots without gaps between them | 38,873,354 | <p>I'm trying to reproduce an example by Thucydides411 on <a href="http://stackoverflow.com/questions/20057260/how-to-remove-gaps-between-subplots-in-matplotlib">How to remove gaps between subplots in matplotlib?</a> using the following code:</p>
<pre><code>import matplotlib.pyplot as plt
fig = plt.figure(figsize=(8,... | 1 | 2016-08-10T12:23:57Z | 38,873,461 | <p>One way to solve it is to use <code>tight_layout</code> instead of <code>subplots_adjust</code>:</p>
<pre><code>fig.tight_layout(h_pad=0, w_pad=0)
</code></pre>
<p>The resulting figure now has no gaps:</p>
<p><a href="http://i.stack.imgur.com/wpSzO.png" rel="nofollow"><img src="http://i.stack.imgur.com/wpSzO.png"... | 1 | 2016-08-10T12:29:03Z | [
"python",
"matplotlib"
] |
Pandas Row wise division | 38,873,458 | <p>Suppose i have this dataframe</p>
<pre><code> A B C
0 1 2 3
1 4 5 6
2 7 8 9
SUM 12 15 18
</code></pre>
<p>now i want to divide each element by their respective column <code>"SUM"</code>. Example (1/12),(8/15) etc, and fill it up in place of the numbers.
I can loop it, but that ... | 1 | 2016-08-10T12:29:00Z | 38,873,531 | <p>If you select the last row using <code>iloc</code> then you can pass this to <code>div</code>:</p>
<pre><code>In [20]:
df.div(df.iloc[-1])
Out[20]:
A B C
0 0.083333 0.133333 0.166667
1 0.333333 0.333333 0.333333
2 0.583333 0.533333 0.500000
SUM 1.000000 1.000000 1.0000... | 1 | 2016-08-10T12:32:00Z | [
"python",
"pandas"
] |
How to get django user after channels.Demultiplexer? | 38,873,590 | <p>I'm trying to build user related websocket service with Django Channels.
I have this Demultiplexer at first line of my routing.py:</p>
<pre><code>def checkauth(f):
def wrapper(*args, **kwargs):
if args[0].message.user.is_anonymous():
args[0].send(stream="auth", payload = {'m':'pissof... | 0 | 2016-08-10T12:34:27Z | 38,881,086 | <p>I had similar problem with accessing user in my consumer function and I ended up decorating it with</p>
<pre><code>@channel_session_user
def ws_my_consumer(message):
</code></pre>
<p>I didn't find a way to do it using my custom Demultiplexer class. I'm not so sure that there exists another solution because even <a... | 0 | 2016-08-10T18:35:18Z | [
"python",
"django",
"django-channels"
] |
can not connect to phoenix using python phoenixdb library | 38,873,593 | <p>I have Phoenix which is integrated with HBase.
I am trying to access phoenix from python code using pythondb library, and I have started the QueryServer using</p>
<pre><code>bin/queryserver.py start
</code></pre>
<p>But after the connect statement I get the following error:</p>
<pre><code>database_url = 'http://l... | 0 | 2016-08-10T12:34:28Z | 38,874,884 | <p>The problem was because I was using Phoenix 4.7 even I have started the server using </p>
<pre><code>./bin/queryserver.py start -Dphoenix.queryserver.serialization=JSON
</code></pre>
<p>After remove Phoenix 4.7 and install 4.6 the connection from python can be established successfully.</p>
<p>I hope someone will ... | 1 | 2016-08-10T13:30:23Z | [
"python",
"phoenix"
] |
Can a pip install have detrimental effects to your computer? | 38,873,603 | <p>Recently, I have been exploring github and went on an install spree using "pip install -r requirements.txt". Today, I came across one that required my antivirus to give permission. Felt suspicious, but I installed it anyway. <code>pip install git+https://github.com/something</code></p>
<p>Usually, command "python s... | 0 | 2016-08-10T12:35:07Z | 38,873,722 | <p>Yes, <code>pip install</code> will execute remote code with your user access; anything could have happened that you as a user can do on your computer without admin access.</p>
<p>Now, <em>usually</em> the <code>setup.py</code> file of a project does nothing more than just install the project files into your Python ... | 0 | 2016-08-10T12:40:14Z | [
"python",
"pip"
] |
Can a pip install have detrimental effects to your computer? | 38,873,603 | <p>Recently, I have been exploring github and went on an install spree using "pip install -r requirements.txt". Today, I came across one that required my antivirus to give permission. Felt suspicious, but I installed it anyway. <code>pip install git+https://github.com/something</code></p>
<p>Usually, command "python s... | 0 | 2016-08-10T12:35:07Z | 38,874,499 | <p>Generally, when you stick to the well known packages used and reviewed by many people, you should be safe and the package install script will not do any harm.</p>
<p>However, you should watch out for typos. It is really easy to compromise the <code>pip</code> central repository with packages that can do anything on... | 0 | 2016-08-10T13:12:59Z | [
"python",
"pip"
] |
Python importing submodules from submodule | 38,873,614 | <p>I have got a problem when using python imports. I wrote a finished module, that itself uses several submodules (those are imported).</p>
<p>e.g.</p>
<pre><code>module:
main_class.py
submodule1.py
....
</code></pre>
<p>Now I want to use this finished module by another supermodule, so the folder structure ... | 0 | 2016-08-10T12:35:35Z | 38,874,148 | <p>If you are on python 2 you should add <code>from __future__ import absolute_import</code> to your files (not needed on 3) so you can do the imports like <a href="https://www.python.org/dev/peps/pep-0328/#guido-s-decision" rel="nofollow">Guido states in PEP 328</a></p>
<p>According to this you should</p>
<ul>
<li>... | 1 | 2016-08-10T12:59:15Z | [
"python",
"import"
] |
Access denied for user (1044) - Django & MariaDB | 38,873,680 | <p>Trying to run some simple queries against a remote MariaDB instance. (Note: I'm not trying to apply models etc.)</p>
<p>I've quadruple checked spellings and I can connect with other applications on the same user/pass/port/hostname etc.</p>
<p>But whenever I try to run a query I get:</p>
<pre><code>(1044, "Access ... | 0 | 2016-08-10T12:38:37Z | 38,896,798 | <p>Found the problem (user error, of course...)</p>
<p>For the key/value <code>'NAME' : 'xyz_name'</code> I had mistakenly added the 'Connection Name', not a database name. In this case there is only one database on this host.</p>
<p>Therefore:</p>
<pre><code>'xyz_db': {
'ENGINE': 'django.db.backends.mysql',
... | 0 | 2016-08-11T12:45:26Z | [
"python",
"django",
"mariadb"
] |
How to find outliers in a given dataset using python | 38,873,705 | <p><strong>coordinates = [(259, 168), (62, 133), (143, 163), (174, 270), (321, 385)]</strong></p>
<p><strong>slope = 0.76083799<br>
intercept = 77.87127406</strong></p>
<p><a href="http://i.stack.imgur.com/UWxav.png" rel="nofollow"><img src="http://i.stack.imgur.com/UWxav.png" alt="enter image description here"></a><... | 0 | 2016-08-10T12:39:31Z | 38,877,556 | <p>x and y are placed into <code>np.ndarrays</code> at the start.</p>
<p>Input:</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
coordinates = [(259, 168), (62, 133), (143, 163), (174, 270), (321, 385)]
x=np.array([x1[0] for x1 in coordinates]) #Placed into array
y=np.array([x1[1] for x1 in coordin... | 1 | 2016-08-10T15:21:53Z | [
"python",
"python-2.7",
"statistics",
"linear-regression",
"outliers"
] |
Referencing the function argument inside the same call | 38,873,776 | <p>I have this kind of a function call in Python:</p>
<pre><code>foo(["A", "B", "X", "Y", "Z"], SomeClass("m", ["A", "B", "X", "Y", "Z"]), SomeClass("n",["A", "B", "X", "Y", "Z"]))
</code></pre>
<p>In general, foo can have arbitrary number of arguments, so there can be many SomeClass objects passed, but when calling ... | 1 | 2016-08-10T12:42:36Z | 38,873,832 | <p>No, there are no such references; you passed in a list literal object, there are no other references to it other than the internal interpreter stack.</p>
<p>Simply create your own reference; store that first list in a variable <em>first</em>, then reference that:</p>
<pre><code>arg1 = ["A", "B", "X", "Y", "Z"]
foo... | 2 | 2016-08-10T12:45:08Z | [
"python"
] |
Referencing the function argument inside the same call | 38,873,776 | <p>I have this kind of a function call in Python:</p>
<pre><code>foo(["A", "B", "X", "Y", "Z"], SomeClass("m", ["A", "B", "X", "Y", "Z"]), SomeClass("n",["A", "B", "X", "Y", "Z"]))
</code></pre>
<p>In general, foo can have arbitrary number of arguments, so there can be many SomeClass objects passed, but when calling ... | 1 | 2016-08-10T12:42:36Z | 38,873,843 | <p>Why not to use variable:</p>
<pre><code>arg1 = ["A", "B", "X", "Y", "Z"]
foo(arg1, SomeClass("m", arg1), SomeClass("n", arg1))
</code></pre>
<p><strong>NOTE</strong>: lists passed by reference so if you modify it within <code>foo</code> or while initializing <code>SomeClass</code> you could get unpredictable resul... | 4 | 2016-08-10T12:45:28Z | [
"python"
] |
Is it possible to call an Entity Framework Data Access Assembly from Python? | 38,873,827 | <p>I'm experimenting with using Robot Framework for testing .NET applications. It uses Python so I've been using PythonNet to call methods in the .NET assemblies. Now I've struck a problem: Calling an assembly that calls down into an Entity Framework-based data access assembly.</p>
<p>I'm not calling the data acces... | 2 | 2016-08-10T12:44:46Z | 39,008,878 | <p>The way the paths are treated in interactive python and script/module mode are slightly different:</p>
<p><a href="https://github.com/pythonnet/pythonnet/issues/98" rel="nofollow">https://github.com/pythonnet/pythonnet/issues/98</a></p>
| 1 | 2016-08-18T02:06:16Z | [
"c#",
"python",
".net",
"entity-framework",
"python.net"
] |
How to see variable content in debuging Eclipse PyDev? | 38,873,912 | <p>I used to have this ability but for some reason it is gone.</p>
<p>When debugging I used to hover over variable and see its content.. how do I restore this ability?</p>
| 0 | 2016-08-10T12:48:13Z | 38,875,200 | <p>I just checked it here and it's working for me... In the latest versions, some changes were done to the hover, so, make sure you have it properly configured to show the debug hover.</p>
<p>I.e.: in preferences > pydev > editor > hover </p>
<p>If you have "combine hovers" selected and the "pydev debug hover" checke... | 1 | 2016-08-10T13:43:29Z | [
"python",
"eclipse",
"pydev"
] |
IBpy python structure query | 38,874,035 | <p>Hi Guys I am not a trained coder, but am trying to figure out this issue, can you guys advise me how to fix this error please?</p>
<p>As per below am trying to construct a code, the bottom shows an error</p>
<pre><code>from __future__ import print_function #I'm using 3.x style print
from ib.opt import ibConnection... | 0 | 2016-08-10T12:54:10Z | 38,895,418 | <p>With regard to this
error id=-1, errorCode=2104, errorMsg=Market data farm connection is OK:usfarm</p>
<p>I managed to get the datam the error seems to suggest that connection is OK, so maybe its not error, but just an information message?</p>
<p>From account_update().main() I convert to account_update()</p>
<... | 0 | 2016-08-11T11:43:04Z | [
"python",
"python-2.7",
"ibpy",
"pyalgotrade"
] |
Correct interpretation of hex byte, convert it to float | 38,874,139 | <p>I am currently trying to connect to an electric meter via RS485.
It works quite well so far, except that I have problems reading what the meter is writing back on the RS485 line.</p>
<p>I know that the data from the electric meter is correct since I can read it with Docklight and the internal programm of the manufa... | 0 | 2016-08-10T12:58:15Z | 38,874,168 | <p><code>C</code>, <code>e</code> and <code>/</code> are bytes too; they are <em>ASCII characters</em> so don't need to be displayed with <code>\x..</code> hex escapes.</p>
<p>You don't need to decode the <code>\x..</code> hex escapes either, they are just how Python gives you the debugging representation of a <code>b... | 1 | 2016-08-10T12:59:44Z | [
"python",
"python-3.x",
"hex",
"binascii"
] |
Correct interpretation of hex byte, convert it to float | 38,874,139 | <p>I am currently trying to connect to an electric meter via RS485.
It works quite well so far, except that I have problems reading what the meter is writing back on the RS485 line.</p>
<p>I know that the data from the electric meter is correct since I can read it with Docklight and the internal programm of the manufa... | 0 | 2016-08-10T12:58:15Z | 38,874,745 | <p>You can use <code>struct.unpack()</code> to get the numbers from the data. Here is the way:</p>
<pre><code>In [171]: import struct
In [190]: b2
Out[190]: b'\x01\x03J8\x00\x02S\xde'
In [191]: struct.unpack('B'*len(b2), b2)
Out[191]: (1, 3, 74, 56, 0, 2, 83, 222)
In [192]: [*map(hex, struct.unpack('B'*len(b2), b2)... | 1 | 2016-08-10T13:24:06Z | [
"python",
"python-3.x",
"hex",
"binascii"
] |
Python for Network Engineers - Router Config Parsing | 38,874,154 | <p>I could use some help in parsing a config file where I create lists, where each list has the following format; from the config file (shown below). I am trying to get my script to read the config file and list interfaces details, for each interface that comes after hostname.</p>
<pre><code>PE1-Loopback0-1.1.1.1 255... | -1 | 2016-08-10T12:59:26Z | 39,234,123 | <p><strong>!!!SOLVED!!!</strong></p>
<pre><code>'''
Created on Aug 9, 2016
@author: adrian
'''
import random, re, pprint
from collections import defaultdict
DOT1Q=''
Routers={}
routerconfig = open('configfile.txt', 'r')
for line1 in iter(routerconfig):
line1 = line1.rstrip('\n')
if re.match(r'hostname.*', l... | 0 | 2016-08-30T17:56:44Z | [
"python",
"cisco"
] |
Django ArrayField | 38,874,228 | <p>I have problem with ArrayField in django admin. When I trying save object with <code>None</code> values, even it wasn't changed, I get error: <code>Item 5 in the array did not validate: Enter a whole number.</code> Model looks like this:</p>
<pre><code>class MyModel(models.Model):
rank = ArrayField(
mod... | 0 | 2016-08-10T13:02:13Z | 38,874,804 | <p>Django form fields will only set null values if it matches one of <code>EMPTY_VALUES</code> from validators</p>
<pre><code>EMPTY_VALUES = (None, '', [], (), {})
</code></pre>
<p><code>SimpleArrayField</code> first splits the incoming data resulting in <code>['4', '4', '4', '4', '4', 'None', '4', '4']</code>, the s... | 1 | 2016-08-10T13:27:07Z | [
"python",
"django",
"postgresql",
"django-models",
"django-admin"
] |
Reportlab does not reset sequences when creating multiple documents with table of contents | 38,874,329 | <p>I am using a template function that creates multiple PDF documents in one program execution using reportlab. </p>
<p>These documents are identical by structure and have identical headings. They only differ in content below the headings. All of these documents contain a table of contents element. </p>
<p>I am using... | 1 | 2016-08-10T13:06:12Z | 38,950,294 | <p>I have found a quick solution which solves my problem but which I don't like as a final solution. </p>
<p>The problem is that I am using global sequences with the same name. <code>h1</code>, <code>h2</code> and <code>h3</code> appear in every document. And reportlab doesn't seem to reset them when a new document is... | 1 | 2016-08-15T06:31:34Z | [
"python",
"python-3.x",
"reportlab"
] |
Python - Fastest way to create a tuple from a list with computations | 38,874,387 | <p>I need to create in the fastest way possible a Python tuple from a list, but with intermediate computations. To be clearer I put a code snippet:</p>
<pre><code>a=[1,2,3,4]
b=tuple([id(x) for x in a])
</code></pre>
<p>This is what I have by now.
Is there something better than this? This code creates a list and then... | 1 | 2016-08-10T13:08:47Z | 38,874,700 | <p>Using the list comprehension is <em>faster</em>. This is because the size of the tuple is known beforehand (memory can be allocated for <code>len(list)</code> items).</p>
<p>With generator, the generator needs to be converted to a sequence first so that a tuple can be allocated. This will be slower because of the ... | 4 | 2016-08-10T13:22:12Z | [
"python",
"list",
"tuples"
] |
Trouble with running cron job in GAE python | 38,874,418 | <p>So I made a cron job to update my news aggregator app with new stories every 1 minute. I should say I'm a complete novice to cron jobs, with very limited experience running GAE.</p>
<p>This is my folder structure:</p>
<ul>
<li>news.py</li>
<li>index.yaml</li>
<li>feedparser.py</li>
<li>cron.yaml</li>
<li>app.yaml<... | 0 | 2016-08-10T13:09:51Z | 38,875,271 | <p>The problem is that you indicated the handler to be a CGI app in your <code>app.yaml</code> file:</p>
<pre><code>script: news.py
</code></pre>
<p>From <a href="https://cloud.google.com/appengine/docs/python/how-requests-are-handled#Python_Requests" rel="nofollow">Request handlers</a>:</p>
<blockquote>
<p>When A... | 1 | 2016-08-10T13:46:23Z | [
"python",
"python-2.7",
"google-app-engine",
"cron"
] |
PyPandoc in combination with PyInstaller | 38,874,563 | <p>I installed PyInstaller to create executables for my python scripts, and that works fine. I used PyPandoc to create <code>.docx</code> reports, which also run fine when the normal python files are run, but not from the PyInstaller generated executable. It gives the error:</p>
<pre><code>Traceback (most recent call ... | 2 | 2016-08-10T13:15:38Z | 38,957,523 | <p>There are two issues here. The first one is that <code>pypandoc</code> needs <code>pandoc.exe</code> to work. This is not picked up by <code>pyinstaller</code> automatically, but you can specify it manually.</p>
<p>To do this you you have to <a href="https://pythonhosted.org/PyInstaller/spec-files.html#using-spec-f... | 3 | 2016-08-15T14:54:48Z | [
"python",
"pyinstaller",
"pandoc",
"pypandoc"
] |
How to make proper server tick with python? | 38,874,597 | <p>I am trying to make a game server which updates after a certain period.</p>
<pre><code>import time
last_time = time.time()
tick = 1
time_since_last_update = 0
while True:
new_time = time.time()
dt = new_time - last_time
time_since_last_update += dt
last_time = new_time
if time_since_last_update ... | 2 | 2016-08-10T13:16:58Z | 38,874,657 | <p>Insert a <code>time.sleep(0.01)</code> to wait 10 millis between each time poll otherwise your loop polls time continuously without releasing power to the cpu.</p>
<p>Edit: That is better, only waits once if needed. Should a huge CPU overload occur, the time to wait could be negative, and in that case 2 actions cou... | 3 | 2016-08-10T13:20:06Z | [
"python"
] |
QPython Android Kivy, launch python script from a python script | 38,874,680 | <p>I'm getting a permission denied error when my QPython android script tries to launch another qpython script.
I'm assuming that this can be done - right?</p>
<p>I've tried subprocess.call, whic seems like the right thing to do.
But, the script doesn't run, and the log shows the permission denied error.</p>
<p>The o... | 0 | 2016-08-10T13:21:10Z | 38,876,003 | <p>Once you know where the script is, just move to that folder and then use the following command to list the files:</p>
<pre><code>ls -l
</code></pre>
<p>the command outputs all the files together with permission (first column).
Now, to change the permission to "execution" you can use:</p>
<pre><code>chmod 755 [you... | 0 | 2016-08-10T14:17:50Z | [
"android",
"python",
"qpython"
] |
How do i split the text part of a tweet to have each word of the text in a new column in a CSV file | 38,874,687 | <p>Outputting tweets to a CSV file and want to separate the text portion to have each word in a new column so i can run it through a classifier using python</p>
<pre><code>for tweet in alltweets:
#Loop to only return the tweets that have been posted in the last 24 hours
if (datetime.datetime.now() - twee... | 0 | 2016-08-10T13:21:39Z | 38,875,382 | <p>Since tweet.text.encode("utf-8") is one string, you can split it (by space) to convert it into individual words before writing it out.</p>
<pre><code>tweets = [['user1','text of tweet 1'],['user2','text of tweet2']]
import itertools
for tweet in tweets:
print list(itertools.chain([tweet[0]], tweet[1].split(' '... | 1 | 2016-08-10T13:51:06Z | [
"python",
"csv",
"twitter",
"tweepy"
] |
Getting wrong output while validating python syntax using pep8 | 38,874,839 | <p>I want to validate python syntax using pep8 module using flake8 API. In order to validate, string is created which contains code those are to be ignored and later will be converted into tuple while passing to function to validate syntax.</p>
<pre><code>ignore_code = """
'E101','E111','E112','E113','E114','E... | 2 | 2016-08-10T13:28:20Z | 38,875,118 | <p>Your problem is that when you do <code>tuple(ignore_code)</code> that's what you're passing in.</p>
<pre><code>>>> tuple(ignore_code)
(' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', "'", 'E', '1', '0', '1', "'", ',', "'", 'E', '1', '1', '1', "'", ',', "'", 'E', '1', '1', '2', "'", ',', "'", 'E', '1', '1', '3... | 2 | 2016-08-10T13:40:05Z | [
"python"
] |
BigQuery triggers for a data notification server | 38,874,883 | <p>I am writing a notification server to provide real time updates to ui. This is done using <a href="http://autobahn.ws/" rel="nofollow">autobahn</a> with python to achieve something like <a href="https://www.youtube.com/watch?v=yIdmk2doU8w&feature=youtu.be" rel="nofollow">this</a>. So my data resides in Bigquery.... | 0 | 2016-08-10T13:30:19Z | 38,879,998 | <p>as per table decoration use:<br>
relative value for time in decorator must be in milliseconds </p>
<pre><code>eg: SELECT COUNT(*) FROM [digin_duosoftware_com.test123@-1000-]
</code></pre>
<blockquote>
<p>I want to send notifications to ui as soon as data updates in my table</p>
</blockquote>
<p>Instead of poll... | 1 | 2016-08-10T17:33:36Z | [
"python",
"python-2.7",
"google-app-engine",
"google-bigquery",
"autobahn"
] |
resampling dataframe with pandas | 38,874,907 | <p>I have a dataframe called df1</p>
<pre><code>import numpy as np
import matplotlib.pylab as plt
import matplotlib.dates as mdates
from matplotlib import style
import pandas as pd
%pylab inline
import seaborn as sns
sns.set_style('darkgrid')
import io
style.use('ggplot')
from datetime import datetime
import time
... | 1 | 2016-08-10T13:31:29Z | 38,875,388 | <p>It picks up the default integer index and hence you get those strange values when you perform <code>pd.to_datetime</code> of those indices. You need to set <code>TIMESTAMP</code> as the index.</p>
<pre><code>In [2]: df1 = df1.set_index('TIMESTAMP')
In [3]: df1.resample('30min').mean()
Out[3]:
... | 0 | 2016-08-10T13:51:24Z | [
"python",
"pandas",
"seaborn",
"resampling"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.