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 |
|---|---|---|---|---|---|---|---|---|---|
Why can't my variable be changed for kivy animation? | 38,138,535 | <p>I am setting up animations to call another function on_complete and then repeat itself with redefined variables. Except that my variable doesn't change so it applies the repeated animations on the 1st widget spawned. Here is an example:</p>
<pre><code>from kivy.config import Config
Config.set('input', 'mouse', 'mou... | 0 | 2016-07-01T06:31:42Z | 38,152,750 | <p>Ok, so I figured it out! Because I was redefining the self.children list every time instead of .appending, the newest item was always at index 0! So for this, all you have to do is reference index 0 of the list for each run through!</p>
| 0 | 2016-07-01T19:29:02Z | [
"python",
"variables",
"animation",
"kivy"
] |
system freezes on running a python script | 38,138,666 | <p>I am writing a code for baseline correction of multiple signals. The structure of the code is like this.</p>
<pre><code># for each file in a directory
#read file and populate X vector
temp = baseline_als(x,1000,0.00001)
plt.plot(x-temp)
plt.savefig("newbaseline.png")
plt.close()
</code></pre>
<... | 0 | 2016-07-01T06:39:43Z | 38,198,769 | <p>I was able to prevent my CPU from reaching 100% and then getting freezes by using <code>time.sleep(0.02)</code>. It takes a long time but completes execution nonetheless.</p>
<p>Note that you need to <code>import time</code> before using this.</p>
| 0 | 2016-07-05T08:36:01Z | [
"python",
"optimization",
"system",
"freeze",
"code-freeze"
] |
How to find the number of elements in element tree in python? | 38,138,699 | <p>I am new to element tree,here i am trying to find the number of elements in the element tree.</p>
<pre><code>from lxml import etree
root = etree.parse(open("file.xml",'r'))
</code></pre>
<p>is there any way to find the total count of the elements in root?</p>
| 1 | 2016-07-01T06:41:30Z | 38,138,997 | <p>Find all the target elements (there are some ways to do this), and then use built-in function <code>len()</code> to get the count. For example, if you mean to count only direct child elements of root :</p>
<pre><code>from lxml import etree
doc = etree.parse("file.xml")
root = doc.getroot()
result = len(root.getch... | 1 | 2016-07-01T06:59:33Z | [
"python",
"xml",
"lxml",
"elementtree"
] |
How to find the number of elements in element tree in python? | 38,138,699 | <p>I am new to element tree,here i am trying to find the number of elements in the element tree.</p>
<pre><code>from lxml import etree
root = etree.parse(open("file.xml",'r'))
</code></pre>
<p>is there any way to find the total count of the elements in root?</p>
| 1 | 2016-07-01T06:41:30Z | 38,154,979 | <p>You don't have to load all the nodes into a list, you can use sum and lazily iterate:</p>
<pre><code>from lxml import etree
root = etree.parse(open("file.xml",'r'))
count = sum(1 for _ in root.iter("*"))
</code></pre>
| 1 | 2016-07-01T23:25:49Z | [
"python",
"xml",
"lxml",
"elementtree"
] |
Accessing objects and tuples from a function | 38,138,722 | <p>I have a feeling there should be a very easy way to access specific elements from an evaluated function. A very simple example of what I am trying to achieve is</p>
<pre><code>def func(x):
a = 2*x
b = x*x
return 1, 10, 100, (a,b)
</code></pre>
<p>I define a value for x and the function returns a set of... | 3 | 2016-07-01T06:43:01Z | 38,138,972 | <p>So you can unpack and ignore:</p>
<pre><code>hello, _, _, cello = func(2)
</code></pre>
<p>But if the result is more complicated you can use <code>operator.itemgetter</code>:</p>
<pre><code>from operator import itemgetter
hello, cello, bello = itemgetter(0, 3, 15)(func(2))
</code></pre>
<p>Or more verbosely:</p>... | 3 | 2016-07-01T06:58:17Z | [
"python",
"numpy"
] |
Accessing objects and tuples from a function | 38,138,722 | <p>I have a feeling there should be a very easy way to access specific elements from an evaluated function. A very simple example of what I am trying to achieve is</p>
<pre><code>def func(x):
a = 2*x
b = x*x
return 1, 10, 100, (a,b)
</code></pre>
<p>I define a value for x and the function returns a set of... | 3 | 2016-07-01T06:43:01Z | 38,141,755 | <p>Try</p>
<pre><code>hello, cello = [func(2)[i] for i in [0,3]]
</code></pre>
| 0 | 2016-07-01T09:24:28Z | [
"python",
"numpy"
] |
Accessing objects and tuples from a function | 38,138,722 | <p>I have a feeling there should be a very easy way to access specific elements from an evaluated function. A very simple example of what I am trying to achieve is</p>
<pre><code>def func(x):
a = 2*x
b = x*x
return 1, 10, 100, (a,b)
</code></pre>
<p>I define a value for x and the function returns a set of... | 3 | 2016-07-01T06:43:01Z | 38,144,356 | <p>The standard solution would be to pack the returns into a dictionary and use that to separate the results.</p>
<p>In that way you save yourself the counting of the _ and the code is more readable</p>
<p>return {iteration: iter, Result: res....}</p>
<p>Erg=func(....)</p>
<p>And use </p>
<p>Erg[iteration]</p>
<p... | 0 | 2016-07-01T11:30:53Z | [
"python",
"numpy"
] |
Module to make a program in python | 38,138,732 | <p>I've been wondering if there were other types of window-oriented modules than tkinter (too simple in my sense) or pygame (too much game-oriented). For example, if it were possible to display things with coordinates and not Up/Down like tkinter it would be better I guess.</p>
| -3 | 2016-07-01T06:43:37Z | 38,138,950 | <p>Asking for suggestions is not a good fit for Stack Overflow but your other question about grid layouts is a good question!</p>
<p><strong>Grid Layout with tkinter</strong></p>
<p>Tkinter, like other desktop window managers have things called layout managers. Layout managers provide a format for displaying/ organis... | 0 | 2016-07-01T06:57:24Z | [
"python",
"tkinter",
"pygame"
] |
How to check whether two words are anagrams python | 38,138,842 | <p>I'm dealing with simple problem, checking if two strings are anagram.
I write the simple code, that can check, whether two strings, such as
'abcd' and 'dcba' are anagrams, but I have mo idea what to do with more complex one, like "Astronomer" and "Moon starter"</p>
<pre><code>line1 = input('Enter the first word: '... | 2 | 2016-07-01T06:51:32Z | 38,139,559 | <p>Your algorithm is ok. Your problem is that you don't consider upper and lower case letters. Changing the two lines </p>
<pre><code>alist1 = list(deleteSpaces(s1))
alist2 = list(deleteSpaces(s2))
</code></pre>
<p>to</p>
<pre><code>alist1 = list(deleteSpaces(s1).lower())
alist2 = list(deleteSpaces(s2).lower())
</co... | 5 | 2016-07-01T07:31:04Z | [
"python",
"string",
"sorting"
] |
How to check whether two words are anagrams python | 38,138,842 | <p>I'm dealing with simple problem, checking if two strings are anagram.
I write the simple code, that can check, whether two strings, such as
'abcd' and 'dcba' are anagrams, but I have mo idea what to do with more complex one, like "Astronomer" and "Moon starter"</p>
<pre><code>line1 = input('Enter the first word: '... | 2 | 2016-07-01T06:51:32Z | 38,140,531 | <p>As other's have pointed out, your algorithm is given 'false' results as <code>Moon starter</code> and <code>Astronomer</code> are in fact <em>not</em> anagrams.</p>
<p>You can drastically improve your algorithm by simply using the available object methods. They already provide all the functionality.</p>
<pre><code... | 1 | 2016-07-01T08:24:19Z | [
"python",
"string",
"sorting"
] |
How to check whether two words are anagrams python | 38,138,842 | <p>I'm dealing with simple problem, checking if two strings are anagram.
I write the simple code, that can check, whether two strings, such as
'abcd' and 'dcba' are anagrams, but I have mo idea what to do with more complex one, like "Astronomer" and "Moon starter"</p>
<pre><code>line1 = input('Enter the first word: '... | 2 | 2016-07-01T06:51:32Z | 38,159,814 | <p>Something like this?</p>
<pre><code>$ cat /tmp/tmp1.py
#!/usr/bin/env python
def anagram (first, second):
return sorted(first.lower()) == sorted(second.lower())
if __name__ == "__main__":
for first, second in [("abcd rsh", "abcd x rsh"), ("123 456 789", "918273645 ")]:
print("is anagram('{0}', '... | 0 | 2016-07-02T11:50:02Z | [
"python",
"string",
"sorting"
] |
Get required data from multiple table using DRF Serializers | 38,138,931 | <p>i am new to DRF serializers,i am facing small problem here...</p>
<p>models.py</p>
<pre><code>class roles(models.Model):
role = models.IntegerField(primary_key = True)
type = models.CharField(max_length = 20)
one = models.CharField(max_length = 20)
class Meta:
db_t... | 0 | 2016-07-01T06:56:22Z | 38,139,108 | <p>You have to pass <code>rSerializer()</code> in <code>eSerializer()</code> . Please check the updated code as mentioned below:</p>
<pre><code>class eSerializer(serializers.ModelSerializer):
roles = rSerializer()
class Meta:
model = employees
fields = ('name','mobileno', 'roles')
</code></pre... | 2 | 2016-07-01T07:05:53Z | [
"python",
"django",
"serialization"
] |
how to return a dictionary key as a string value Python | 38,139,041 | <p>I'm a beginner programmer and I have a question. I need to return a key value as a string in a dictionary.</p>
<pre><code>choice = skills[(input('which attribute would you like to access: '))]
print('Testing, choice was in word')
user = None
while user != 0:
print('\nyour current', choice[0] ,' skill is:', choi... | -2 | 2016-07-01T07:01:59Z | 38,139,207 | <p>Suppose you have a dictionary as: <code>d = {'X':'x'}</code></p>
<p>You can retrieve a value from dictionary as <code>d['X']</code></p>
<p>The function <code>keys()</code> will return a list of keys in dictionary and <code>values()</code> will return list of values in dictionary. And if you don't know the keys and... | 0 | 2016-07-01T07:11:23Z | [
"python",
"dictionary",
"key"
] |
Python while loop won't end | 38,139,104 | <p>So I have a code that project the user's bill. I put it on a loop so that it keeps repeating itself until the user don't want to continue.</p>
<p>here is my code:</p>
<pre><code>status = True
def kill() :
confirm = input("Again? (Y/N) : ")
if confirm == "n":
status = False
while(status):
plan... | 0 | 2016-07-01T07:05:41Z | 38,139,145 | <p>You have to declare 'status' as a global variable inorder to update value to<br>
<code>"status = False"</code> in your kill method. </p>
<p>You can do 2 things here:<br>
1. Declare status as global variable<br>
2. Return "status" (which is a local variable) from kill method </p>
<p><em>You can check the tutori... | 5 | 2016-07-01T07:08:17Z | [
"python"
] |
Python while loop won't end | 38,139,104 | <p>So I have a code that project the user's bill. I put it on a loop so that it keeps repeating itself until the user don't want to continue.</p>
<p>here is my code:</p>
<pre><code>status = True
def kill() :
confirm = input("Again? (Y/N) : ")
if confirm == "n":
status = False
while(status):
plan... | 0 | 2016-07-01T07:05:41Z | 38,139,153 | <pre><code>def kill() :
confirm = input("Again? (Y/N) : ")
if confirm == "n":
status = False
</code></pre>
<p>This creates a <em>local</em> variable named <code>status</code>, and sets that. The global variable of the same name is unaffected.</p>
<p>Add <code>global status</code> in the function so th... | 3 | 2016-07-01T07:08:52Z | [
"python"
] |
Python while loop won't end | 38,139,104 | <p>So I have a code that project the user's bill. I put it on a loop so that it keeps repeating itself until the user don't want to continue.</p>
<p>here is my code:</p>
<pre><code>status = True
def kill() :
confirm = input("Again? (Y/N) : ")
if confirm == "n":
status = False
while(status):
plan... | 0 | 2016-07-01T07:05:41Z | 38,139,482 | <p>I think that you should use less complicated way:</p>
<p>try this model</p>
<pre><code>===>here your function a()<===
def a():
print("A plan in action")
while True:
===> your loop code <===
your_input = input("> ")
your_input = your_input.upper()
if your_input == 'N':
... | 1 | 2016-07-01T07:26:05Z | [
"python"
] |
Python while loop won't end | 38,139,104 | <p>So I have a code that project the user's bill. I put it on a loop so that it keeps repeating itself until the user don't want to continue.</p>
<p>here is my code:</p>
<pre><code>status = True
def kill() :
confirm = input("Again? (Y/N) : ")
if confirm == "n":
status = False
while(status):
plan... | 0 | 2016-07-01T07:05:41Z | 38,139,588 | <p>Two revisions:</p>
<ol>
<li>Use <code>global status</code> in <code>kill()</code></li>
<li>If you are comparing <code>confirm == "n"</code>, then convert <code>n</code> to lower while taking input</li>
</ol>
<p>Try this:</p>
<pre><code>def kill() :
confirm = input("Again? (Y/N) : ").lower()
if confirm == ... | 0 | 2016-07-01T07:32:27Z | [
"python"
] |
What is the difference between using `[data2]` and `[[data2]]` with `groupby` | 38,139,258 | <p>I am working through a Python for data analysis tutorial and want some clarification on the output I get from using <code>[data2]</code> and <code>[[data2]]</code> when using <code>groupby</code>. </p>
<p><a href="http://i.stack.imgur.com/sM1dl.png" rel="nofollow"><img src="http://i.stack.imgur.com/sM1dl.png" alt="... | 1 | 2016-07-01T07:13:59Z | 38,139,278 | <p>If use:</p>
<pre><code>[data2]
</code></pre>
<p>you get <code>Series</code> with <code>Multiindex</code>.</p>
<p>If use subset</p>
<pre><code>[[data2]]
</code></pre>
<p>you get <code>DataFrame</code> with <code>Multiindex</code>.</p>
<p>And if use:</p>
<pre><code>df.groupby(['key1','key2'], as_index=False)['d... | 3 | 2016-07-01T07:15:13Z | [
"python",
"pandas",
"dataframe",
"group-by"
] |
Split dataframe in 3 subgroups | 38,139,306 | <p>I want to split raw dataframe into 3 subgroups: train, test, validate</p>
<p>I see three solutions, but afraid they are not correct and may cause bottle neck effect</p>
<p>1) add dictionary with keys</p>
<pre><code>my_dict = {'train':raw_df.loc[start:end], 'test':raw_df.loc[start:end],
'val':raw_df.lo... | 0 | 2016-07-01T07:16:30Z | 38,139,624 | <p>Technically, i don't think you need to have three dataframes if you want to test your machine learning model. Why? Because you build you model on your <code>training_set</code> and you need to validate it with your <code>validation_set</code>. You will only use your <code>test_set</code> once your model is validated... | 0 | 2016-07-01T07:34:48Z | [
"python",
"pandas",
"dataframe"
] |
Split dataframe in 3 subgroups | 38,139,306 | <p>I want to split raw dataframe into 3 subgroups: train, test, validate</p>
<p>I see three solutions, but afraid they are not correct and may cause bottle neck effect</p>
<p>1) add dictionary with keys</p>
<pre><code>my_dict = {'train':raw_df.loc[start:end], 'test':raw_df.loc[start:end],
'val':raw_df.lo... | 0 | 2016-07-01T07:16:30Z | 38,139,656 | <p>Adding a new column won't be eating lots of memorys but you will add a slicing cost whenever you want to access one of your three sets. Creating new datraframes leads this slicing part to be done only once.</p>
<p>For this you can use <code>sample</code>. Let's you want 80% of your dataframe in train, and 10% in te... | 2 | 2016-07-01T07:36:08Z | [
"python",
"pandas",
"dataframe"
] |
Split dataframe in 3 subgroups | 38,139,306 | <p>I want to split raw dataframe into 3 subgroups: train, test, validate</p>
<p>I see three solutions, but afraid they are not correct and may cause bottle neck effect</p>
<p>1) add dictionary with keys</p>
<pre><code>my_dict = {'train':raw_df.loc[start:end], 'test':raw_df.loc[start:end],
'val':raw_df.lo... | 0 | 2016-07-01T07:16:30Z | 38,139,718 | <p>A pure pandas solution for only a single iteration would be to use sample, and exclude the index of your sample for your next iteration with <code>pd.Index.difference</code>:</p>
<pre><code>validation = df.sample(validation_size)
# Get the other part of the dataframe
train_test = df.loc[df.index.difference(validati... | 0 | 2016-07-01T07:39:39Z | [
"python",
"pandas",
"dataframe"
] |
Lupa can't find lua on OSX 10.11.4 El Capitan | 38,139,344 | <p>I'm following official docs to install lupa:</p>
<pre><code>brew install lua
brew install pkg-config
pip install lupa
</code></pre>
<p>After I run that I can successfully run lua from command line from any folder. However, when running Django management commands (e.g. <code>python manage.py migrate</code>), I get ... | -1 | 2016-07-01T07:19:03Z | 38,144,320 | <p>Solution is to install lupa with LDFLAGS:</p>
<pre><code>brew install lua
brew install pkg-config
LDFLAGS="-L/usr/local/bin/lua" pip install lupa --no-binary :all:
</code></pre>
| 0 | 2016-07-01T11:28:56Z | [
"python",
"osx",
"lua",
"pip",
"lupa"
] |
Can't display data from one to one relationship, just render from one model | 38,139,363 | <p>Using the django auth user model
And my PROFILE model like this:</p>
<pre><code>// models.py
from django.db import models
from django.contrib.auth.models import User
class PROFILE(models.Model):
userID = models.OneToOneField(
User,
on_delete=models.CASCADE,
primary_key=True
)
id... | 0 | 2016-07-01T07:20:10Z | 38,139,421 | <p>Thats because you don't have an email field. If you're using Django's auth, then the Django <code>User</code> class <em>does</em> have an email, so you can access it via <code>object.userID.email</code>.</p>
<p>Note, including ID in your field names isn't a very good idea since it isn't an id, its an object relatio... | 1 | 2016-07-01T07:23:26Z | [
"python",
"django"
] |
Can not import matplotlib with pyenv ipython notebook | 38,139,387 | <p>I am a ruby developer and I've started learning python for a project. I installed pyenv, pyenv virutualenv, ipython, notebook, matplotlib. Everything worked fine except the part I called </p>
<pre class="lang-python prettyprint-override"><code>import matplotlib.pyplot as plot
</code></pre>
<p>Then I 've got this... | 2 | 2016-07-01T07:21:38Z | 38,140,761 | <p>Matplotlib expects a Framework install on OS X in order to manipulate GUI elements.
You can install Framework versions with a command like this knowing your python version and your environment name :</p>
<pre><code>env PYTHON_CONFIGURE_OPTS="--enable-framework CC=clang" pyenv virtualenv <python_version> <... | 3 | 2016-07-01T08:37:02Z | [
"python",
"matplotlib",
"pyenv"
] |
HappyBase - not showing results | 38,139,408 | <p>Am trying to connect to hbase from python using HappyBase </p>
<p>Here is the code which am trying </p>
<pre><code>>import happybase
>connection = happybase.Connection(host = <myHost>,port = <myPort>)
<happybase.connection.Connection object at 0x7ff46c527bd0>
>connection.tables()
... | 0 | 2016-07-01T07:22:36Z | 38,141,289 | <p>I had to start thrift server & connect to it inorder to connect to hbase. </p>
<p>Hope this helps others !! </p>
| 0 | 2016-07-01T09:01:59Z | [
"python",
"hbase",
"happybase"
] |
float values error after numpy vstack | 38,139,993 | <p><br/>
I have a problem while using numpy vstack for float values with exponent e-5.<br/>
Both item_array and date_array are numpy.ndarray.<br/>
When I use <strong>data = np.vstack((date_array,item_array))</strong>, the element <strong>3.04871703e-05</strong> become to <strong>3.0487170344</strong>. Other elements ar... | 3 | 2016-07-01T07:54:04Z | 38,140,578 | <p>I wrote your script like that :</p>
<pre><code>import numpy as np
item_array = np.array([0.00000000e+00, -1.81992510e-03, -9.44964473e-03,
-3.12464669e-03, -5.42864845e-03, -1.67769866e-03,
3.04871703e-05, -7.81295968e-03, -1.12972557e-02,
-1.697... | 1 | 2016-07-01T08:26:26Z | [
"python",
"numpy"
] |
Does Pandas.Series.unstack() affect data types? | 38,140,025 | <p>I'm working on a MultiIndex Series containing mixed-types values (timedeltas and int): </p>
<pre><code>char
7 a 103 minutes
s 63
9 a 129 minutes
s 211
10 a 106 minutes
s 63
Name: timestamp, dtype: object
</code></pre>
<p>Index :</p>
<pre... | 1 | 2016-07-01T07:55:59Z | 38,141,228 | <p>It looks like bug.</p>
<p>I think you can return from function <code>DataFrame</code> and then <code>unstack</code> is not necessary:</p>
<pre><code>def get_session(ts):
ts = ts.sort_index()
dt = (ts - ts.shift()).fillna(0)
first_logs = dt > '30m'
sessions = first_logs.cumsum() + 1
duration ... | 3 | 2016-07-01T08:58:54Z | [
"python",
"pandas"
] |
Using 'apply' with arrays inside Pandas dataframe elements | 38,140,302 | <p>I am working with pandas dataframes which contain arrays inside the dataframe elements. I'm trying to "apply" a function to these elements, and then return an array. But I have some very inconsistent behavior. The function runs okay the first few times, but then it fails. Here is my code:</p>
<pre><code>import ... | 3 | 2016-07-01T08:11:14Z | 38,140,921 | <p>Between the different times you apply <code>g</code> function, your dataframe changes, then it is not really a surprise that the reaction of pandas won't be the same everytime. If you only need to apply it to the columns <code>B</code> and <code>C</code>, i suggest you type:</p>
<pre><code>df['J'] = df[['B','C']].... | 2 | 2016-07-01T08:46:02Z | [
"python",
"arrays",
"pandas",
"apply"
] |
Django - History breadcrumb "dictionary update sequence element #0 has length 9; 2 is required" | 38,140,425 | <p>I am trying to create a breadcrumb based on user history, i.e it will show in a bread crumb the last x amount of pages visited.</p>
<p>i found a blog which has already done what i wanted (<a href="http://seancode.blogspot.co.uk/2008/10/breadcrumb-history-in-django.html" rel="nofollow">http://seancode.blogspot.co.uk... | 1 | 2016-07-01T08:18:35Z | 38,143,303 | <p>Context processors always need to return a dictionary, but you're returning a list. Instead you should do:</p>
<pre><code>return {'history': history}
</code></pre>
| 1 | 2016-07-01T10:39:41Z | [
"python",
"django"
] |
Deploying django app with gunicorn, Importerror in gunicorn log | 38,140,427 | <p>I'm trying to deploy a django app using gunicorn and nginx based on this tutorial:</p>
<p><a href="https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-ubuntu-14-04" rel="nofollow">https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgre... | 0 | 2016-07-01T08:18:37Z | 38,140,523 | <p>When you run this manually, you are presumably already in the correct directory, so gunicorn can find the myproject.wsgi module. But when running under upstart, it won't be in that directory, so will have no idea where to find the file.</p>
<p>You can solve this by putting <code>chdir /path/to/my/virtualenv</code> ... | 1 | 2016-07-01T08:23:58Z | [
"python",
"django",
"ubuntu",
"wsgi",
"gunicorn"
] |
PostgreSQL / SQLalchemy returns id of object but it is not persisted | 38,140,684 | <p>I am using Pyramid, SQLalchemy (with ZopeTransactionExtension), Postgresql and uwsgi and I have a problem with my web app.</p>
<p>So when I save object using <code>DBSession.add(object)</code> and flush <code>DBSession.flush()</code> I get no error and I even get the id of the newly created object, but when the pag... | -1 | 2016-07-01T08:32:48Z | 38,140,771 | <p>Check out <a href="http://stackoverflow.com/a/4202016/5762711">this answer</a>. Generally, everything that is flushed will be temporarily stored into the database and will be persisted when a .commit() happens.</p>
| 0 | 2016-07-01T08:37:43Z | [
"python",
"postgresql",
"sqlalchemy",
"uwsgi"
] |
Django, GET paramters keeped into the URL after a POST call | 38,140,686 | <p>I'm new to Django!</p>
<p>I'm doing a simple registration form, when it is submitted, it returns a label to the previous page, that is the main page:</p>
<p>The form is submitted like this:</p>
<pre><code> <form method="post"">
</code></pre>
<p>And its mapped in urls.py:</p>
<pre><code>url(r'^userfilt/ins... | 0 | 2016-07-01T08:33:01Z | 38,140,821 | <p>The problem is that you don't have an <code>action=""</code> in your <code>form</code> tag which simply means that you want to post to the existing URL, including any querystring (ie. existing <code>GET</code> parameters). </p>
<p>Just add <code>action=""</code> to the <code>form</code> tag, such as:</p>
<pre><cod... | 0 | 2016-07-01T08:40:32Z | [
"python",
"django",
"post",
"get",
"django-views"
] |
PySpark (Python 2.7): How to flatten values after reduce | 38,140,710 | <p>I'm reading a multiline-record file using SparkContext.newAPIHadoopFile with a customized delimiter. Anyway, I already prepared, reduced my data. But now I want to add the key to every line (entry) again and then write it to a Apache Parquet file, which is then stored into HDFS. </p>
<p>This figure should explain m... | 1 | 2016-07-01T08:34:14Z | 38,143,600 | <p>Simple list comprehension should be more than enough:</p>
<pre><code>from datetime import datetime
def flatten(kvs):
"""
>>> kvs = ("852-YF-008", [
... (datetime(2016, 5, 10, 0, 0), 0.0),
... (datetime(2016, 5, 9, 23, 59), 0.0)])
>>> flat = flatten(kvs)
>>> len(f... | 1 | 2016-07-01T10:54:28Z | [
"python",
"python-2.7",
"hadoop",
"apache-spark",
"pyspark"
] |
Cython Bytes error in Python3 | 38,140,779 | <p>For my open source project (bquery) I'm running into an issue with cython codes that works perfectly fine in Python 2.7, yet in Python 3.x it throws an error.
For the entire code, see: <a href="https://github.com/visualfabriq/bquery/pull/66" rel="nofollow">https://github.com/visualfabriq/bquery/pull/66</a></p>
<p>... | 0 | 2016-07-01T08:38:01Z | 38,141,185 | <p>In Python2.X <code>bytes</code> is an alias to <code>str</code> therefore</p>
<pre><code>>>> bytes(42.0)
'42.0'
</code></pre>
<p>In Python3.X, however, <code>bytes</code> has a new constructor which, given anything other than <code>int</code> or <code>str</code> treats it as an iterable of ints. Thus the ... | 1 | 2016-07-01T08:56:51Z | [
"python",
"python-3.x",
"cython"
] |
Can we send data to online excel sheet using python? | 38,140,877 | <p>I want to send a row of numbers and these should add as a new row in the online excel sheet.</p>
| 0 | 2016-07-01T08:43:36Z | 38,141,976 | <p>You can use <a href="https://pypi.python.org/pypi/openpyxl" rel="nofollow"><code>openpyxl</code></a> library to open & edit an Excel file like this</p>
<pre><code>from openpyxl import load_workbook
url = '/home/alex/test.xls'
workbook = load_workbook(url)
sheet= workbook .get_sheet_by_name("Sheet name")
sheet... | 0 | 2016-07-01T09:35:24Z | [
"python",
"excel"
] |
Convert output of count method into a percentage value | 38,140,910 | <p>If I run .count() on an object:</p>
<pre><code>animals = all_vals[['Dog','Cat','Mouse','Snake']].count()
</code></pre>
<p>and receive this output:</p>
<pre><code>animals
Out[49]:
Dog 173
Cat 13
Mouse 42
Snake 359
dtype: int64
</code></pre>
<p>How do I then get the percentage occurrence of each an... | 2 | 2016-07-01T08:45:38Z | 38,140,984 | <p>You can use:</p>
<pre><code>print (animals)
Dog 173
Cat 13
Mouse 42
Snake 359
Name: animals, dtype: int64
print (100 * animals / animals.sum())
Dog 29.471891
Cat 2.214651
Mouse 7.155026
Snake 61.158433
Name: animals, dtype: float64
</code></pre>
| 3 | 2016-07-01T08:48:49Z | [
"python",
"pandas"
] |
Python at Synology, how to get Python3 modules installed and where is Python2.7 installed? | 38,141,115 | <p>Can you please advise me how to get Python3 with modules running at my Synology (DS214play, with DSM 6.0.1-7393 Update 1)?
What I want: run Tweepy and other modules in Python3 on my Synology.</p>
<p>Where I am stuck:</p>
<ol>
<li><p>how to get PIP3 to install Tweepy, if I try I get: <code>Requirement already up-to... | 0 | 2016-07-01T08:54:18Z | 38,141,879 | <p>I'm not sure you can remove Python 2 altogether, but you can install Python 3 and evoke it specifically instead of Python 2. </p>
<p>First, make sure Python 3 is Installed:
Log into your Synology via the web administration and in the 'Package Center' make sure 'Python 3' is installed. (You will find it under 'Devel... | 0 | 2016-07-01T09:30:51Z | [
"python",
"linux",
"pip",
"tweepy",
"synology"
] |
Python at Synology, how to get Python3 modules installed and where is Python2.7 installed? | 38,141,115 | <p>Can you please advise me how to get Python3 with modules running at my Synology (DS214play, with DSM 6.0.1-7393 Update 1)?
What I want: run Tweepy and other modules in Python3 on my Synology.</p>
<p>Where I am stuck:</p>
<ol>
<li><p>how to get PIP3 to install Tweepy, if I try I get: <code>Requirement already up-to... | 0 | 2016-07-01T08:54:18Z | 38,173,082 | <p>Ok, many thx for the replies, I solved it with:</p>
<ol>
<li><p>Confirmed that Python 2.7.9 is installed by default in Synology DSM 5.2 (and not visible in package center). </p></li>
<li><p>I was able to add modules to Python3 by specifically evoking the pip module installation for Python3 using this command:(thx t... | 0 | 2016-07-03T18:26:45Z | [
"python",
"linux",
"pip",
"tweepy",
"synology"
] |
must be string or read-only buffer, not long | 38,141,290 | <p>I am making a website using flask and MySQLdb below is my python file</p>
<p><strong>init.py</strong></p>
<pre><code>from flask import Flask,render_template,request,url_for,flash,session
from flask_session import Session
from dbconnect import connection
from wtforms importForm,BooleanField,StringField,TextField,Pa... | -1 | 2016-07-01T09:02:03Z | 38,141,622 | <p>your cursor.execute does not look correct to me which is in your case c.execute as the optional value has a extra comma.
please correct me if i am wrong</p>
| 0 | 2016-07-01T09:18:04Z | [
"python",
"phpmyadmin",
"mysql-python"
] |
How to test child class methods only without instantiating base class in Python? | 38,141,328 | <p>I am a newbie of Python, I need to test the child class methods without initializing a base class instance because in the base class , there are lots of dependencies on network and some other components, my child class methods are
standalone.</p>
<p>I tried to create a new child class by removing the base class m... | 0 | 2016-07-01T09:03:57Z | 38,144,153 | <p>You can use the <code>__dict__</code> from <code>B</code> directly:</p>
<pre><code>class A(object):
def add(self, i):
print(i + 1)
class B(A):
def sub(self, i):
print(i - 1)
newB = type("newB", (object, ), dict(B.__dict__))
b = newB()
b.sub(5)
</code></pre>
| 0 | 2016-07-01T11:21:22Z | [
"python",
"unit-testing",
"testing"
] |
How to mock an object attribute, I can't access? | 38,141,480 | <p>I'm trying to <strong>mock the parser.html_source attribute</strong> of the following view in my unit test. I want to overwrite it with a former downloaded html of that page.</p>
<p>views.py:</p>
<pre><code> def parse_online_page(request):
site_manager = SiteManager(Constants.LOGIN)
site_manager... | 2 | 2016-07-01T09:11:37Z | 38,142,331 | <p>Remember the advice in the mock documentation: patch where the class is used, not where it is defined. Here that means you should be mocking <code>'core.views.HeadParser'</code>.</p>
| 3 | 2016-07-01T09:52:15Z | [
"python",
"django",
"unit-testing",
"mocking",
"tdd"
] |
Python files are not displayed while running through another python code | 38,141,562 | <p>I have two python file <code>file1</code> and <code>file2</code> and I want to run these two files simultaneously on RASPBERRY Pi (with Raspian) using another python, and I wrote following python code:</p>
<p><strong>Python code:</strong></p>
<pre><code>import subprocess
print 'Process Start'
subprocess.Popen(["p... | 0 | 2016-07-01T09:15:01Z | 38,141,718 | <p>Quoting from <a href="https://docs.python.org/2/library/subprocess.html" rel="nofollow">https://docs.python.org/2/library/subprocess.html</a>:</p>
<blockquote>
<p>The recommended way to launch subprocesses is to use the following
convenience functions. For more advanced use cases when these do not
meet your n... | 0 | 2016-07-01T09:23:01Z | [
"python",
"file",
"raspberry-pi"
] |
How to permute the elements of a list according to their index modulo 3? | 38,141,633 | <p>I want to permute the elements of a list according to their index modulo 3, so for example the list:</p>
<pre><code>[0,1,2,3,4,5,6,7,8]
</code></pre>
<p>should be reordered into:</p>
<pre><code>[0,3,6,1,4,7,2,5,8]
</code></pre>
<p>and in general:</p>
<pre><code>[A0, A1, A2, A3, A4, A5, A6, A7, A8]
</code></pre>... | 0 | 2016-07-01T09:18:36Z | 38,141,681 | <p>You are reordering on the modulo of <code>3</code>:</p>
<pre><code>l = [0,1,2,3,4,5,6,7,8]
l_sorted = sorted(l, key=lambda x: x%3)
print(l_sorted)
# [0, 3, 6, 1, 4, 7, 2, 5, 8]
</code></pre>
<p>If you're reordering on the index and not on the values, then something more detailed requiring <code>enumerate</code> w... | 5 | 2016-07-01T09:21:30Z | [
"python",
"sorting",
"permutation"
] |
How to permute the elements of a list according to their index modulo 3? | 38,141,633 | <p>I want to permute the elements of a list according to their index modulo 3, so for example the list:</p>
<pre><code>[0,1,2,3,4,5,6,7,8]
</code></pre>
<p>should be reordered into:</p>
<pre><code>[0,3,6,1,4,7,2,5,8]
</code></pre>
<p>and in general:</p>
<pre><code>[A0, A1, A2, A3, A4, A5, A6, A7, A8]
</code></pre>... | 0 | 2016-07-01T09:18:36Z | 38,141,999 | <p>Let <code>a = [0,1,2,3,4,5,6,7,8]</code>.</p>
<p><code>a[::3]</code> will give you every third element: <code>[0, 3, 6]</code></p>
<p><code>a[n::3]</code> will give you every third element starting at <code>n</code>, so <code>a[1::3]</code> becomes <code>[1, 4, 7]</code> and <code>a[2::3]</code> becomes <code>[2, ... | 2 | 2016-07-01T09:36:59Z | [
"python",
"sorting",
"permutation"
] |
How to permute the elements of a list according to their index modulo 3? | 38,141,633 | <p>I want to permute the elements of a list according to their index modulo 3, so for example the list:</p>
<pre><code>[0,1,2,3,4,5,6,7,8]
</code></pre>
<p>should be reordered into:</p>
<pre><code>[0,3,6,1,4,7,2,5,8]
</code></pre>
<p>and in general:</p>
<pre><code>[A0, A1, A2, A3, A4, A5, A6, A7, A8]
</code></pre>... | 0 | 2016-07-01T09:18:36Z | 38,142,056 | <p>Another one based on index is </p>
<pre><code>l_sorted = sum([l[x::3] for x in range(3)],[])
</code></pre>
| 3 | 2016-07-01T09:39:19Z | [
"python",
"sorting",
"permutation"
] |
How to permute the elements of a list according to their index modulo 3? | 38,141,633 | <p>I want to permute the elements of a list according to their index modulo 3, so for example the list:</p>
<pre><code>[0,1,2,3,4,5,6,7,8]
</code></pre>
<p>should be reordered into:</p>
<pre><code>[0,3,6,1,4,7,2,5,8]
</code></pre>
<p>and in general:</p>
<pre><code>[A0, A1, A2, A3, A4, A5, A6, A7, A8]
</code></pre>... | 0 | 2016-07-01T09:18:36Z | 38,142,596 | <p>Here's a generalized solution to chain a list together by grouping on some step. <a href="https://docs.python.org/3.4/library/itertools.html#itertools.chain.from_iterable" rel="nofollow"><code>itertools.chain.from_iterable</code></a> is used to chain the resulting groups from each step together. </p>
<pre><code>fro... | 1 | 2016-07-01T10:05:07Z | [
"python",
"sorting",
"permutation"
] |
In Eclipse I can't get environment variable | 38,141,663 | <p><strong>Ubunto 14.04</strong></p>
<p>I'd like to keep secret info (passwords etc.) in environment variables of Ubuntu. I placed them in user's variables.</p>
<p><strong>/home/michael/.bashrc</strong></p>
<pre><code>export SECRET_KEY=nh9_j12rx4j_zqiw235_klvm183p5g8bz_s2_fl3auc # Django
</code></pre>
<p>In termina... | 0 | 2016-07-01T09:20:15Z | 38,141,723 | <p>Since eclipse does not read your .bashrc, I guess you should specify your environment variables in the context menu where you can set the default interpreter.</p>
<p>Go to Run -> Run Configurations... and Select tab "Environment".</p>
<p>Otherwise, if you want those environment variables available in Eclipse you n... | 1 | 2016-07-01T09:23:10Z | [
"python"
] |
In Eclipse I can't get environment variable | 38,141,663 | <p><strong>Ubunto 14.04</strong></p>
<p>I'd like to keep secret info (passwords etc.) in environment variables of Ubuntu. I placed them in user's variables.</p>
<p><strong>/home/michael/.bashrc</strong></p>
<pre><code>export SECRET_KEY=nh9_j12rx4j_zqiw235_klvm183p5g8bz_s2_fl3auc # Django
</code></pre>
<p>In termina... | 0 | 2016-07-01T09:20:15Z | 38,141,836 | <p>You may consider using <code>profile</code> file or <code>bash_profile</code> to store the environment variables. You can refer more <a href="http://superuser.com/questions/789448/choosing-between-bashrc-profile-bash-profile-etc">here</a></p>
<p>Another approach would be to start Eclipse from an open <code>terminal... | 0 | 2016-07-01T09:29:09Z | [
"python"
] |
Hours, Date, Day Count Calculation | 38,141,665 | <p>I have this huge dataset which has dates for several days and timestamps. The datetime format is in UNIX format. The datasets are logs of some login.</p>
<p>The code is supposed to group start and end time logs and provide log counts and unique id counts.</p>
<p>I am trying to get some stats like:</p>
<pre><code>... | 1 | 2016-07-01T09:20:17Z | 38,161,524 | <p>Unfortunately i couldn't find any elegant solution.</p>
<p>Here is my attempt:</p>
<pre><code>fn = r'D:\temp\.data\dart_small.csv'
cols = ['UserID','StartTime','StopTime','GPS1','GPS2']
df = pd.read_csv(fn, header=None, names=cols)
df['m'] = df.StopTime + df.StartTime
df['d'] = df.StopTime - df.StartTime
# 'star... | 1 | 2016-07-02T15:09:47Z | [
"python",
"datetime",
"pandas",
"dataset",
"python-datetime"
] |
Checking if a word is in a text file in Python | 38,141,911 | <p>I'm not sure why my code won't work. Can anyone help?</p>
<pre><code>userinp = str(input("What is wrong with your phone?\n"))
with open("keywords.txt", "r") as solution:
for line in solution:
if userinp in line:
print("in list")
else:
print("not in list")
</code></pre>
<... | -3 | 2016-07-01T09:32:03Z | 38,142,168 | <p>I ran exactly the same code with some lines content in the keywords.txt file:-</p>
<p>userinp = str(input("What is wrong with your phone?\n"))
with open("keywords.txt", "r") as solution:
for line in solution:
if userinp in line:
print("in list")
else:
print("not in list")... | 0 | 2016-07-01T09:44:19Z | [
"python"
] |
pandas group by: usage in this instance | 38,141,920 | <p>despite the extensive help provided <a href="http://pandas.pydata.org/pandas-docs/stable/groupby.html" rel="nofollow">here</a> and <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.groupby.html" rel="nofollow">here</a> I was unable to figure out how to do the following: </p>
<p>given t... | 1 | 2016-07-01T09:32:32Z | 38,141,946 | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.pivot.html" rel="nofollow"><code>pivot</code></a>:</p>
<pre><code>print (df.pivot(index='name', columns='ptf', values='value'))
ptf CORE1 CORE2 CORE3
name
alfa 0.1 0.3 0.90
beta 0.7 0.4 0... | 3 | 2016-07-01T09:33:40Z | [
"python",
"pandas",
"dataframe",
"order",
"pivot"
] |
Multi-objective optimisation using PyGMO | 38,141,923 | <p>I am using the PyGMO package for Python, for multi-objective optimisation. I am unable to fix the dimension of the fitness function in the constructor, and the documentation is not very descriptive either. I am wondering if anyone here has had experience with PyGMO in the past: this could be fairly simple.</p>
<p>I... | 0 | 2016-07-01T09:32:34Z | 38,143,588 | <p>Are you looking at the <a href="http://pagmo.sourceforge.net/pygmo/documentation/problems.html" rel="nofollow">correct documentation</a>?</p>
<p>There is no <code>fdim</code> (which anyway does nothing in your example since it is only a local variable and is not used). But there is <code>n_obj</code>:</p>
<blockqu... | 1 | 2016-07-01T10:53:30Z | [
"python",
"mathematical-optimization"
] |
Multi-objective optimisation using PyGMO | 38,141,923 | <p>I am using the PyGMO package for Python, for multi-objective optimisation. I am unable to fix the dimension of the fitness function in the constructor, and the documentation is not very descriptive either. I am wondering if anyone here has had experience with PyGMO in the past: this could be fairly simple.</p>
<p>I... | 0 | 2016-07-01T09:32:34Z | 38,164,451 | <p>I modified their example and this seemed to work for me. </p>
<pre><code>#(...)
def __init__(self, fdim=2):
NUM_PARAMS = 4
# We call the base constructor as 'dim' dimensional problem, with 0 integer parts and 2 objectives.
super(my_problem, self).__init__(NUM_PARAMS,0,fdim)
self.set_bounds(0.01, 100... | 1 | 2016-07-02T21:03:27Z | [
"python",
"mathematical-optimization"
] |
How to get a subset of a list based on conditions using python lambdas or list comprehensions | 38,141,939 | <p>I have a list of dictionaries like this. </p>
<pre><code>somelist = [
{ "store" : Amazon, "price": 1000},
{ "store" : Junglee, "price": 1200},
{ "store" : BestBuy, "price": 1300},
{ "store" : Amazon, "price": 900},
{ "store" : BestBuy, "price": 1200}
]
</code></pre>
<p>I want to filter it so th... | 3 | 2016-07-01T09:33:14Z | 38,142,177 | <p>You could collect the dictionaries to <a href="https://docs.python.org/3.5/library/collections.html#collections.OrderedDict" rel="nofollow"><code>OrderedDict</code></a> where key is the store and value is the lowest price. Then you can easily reconstruct the dictionaries with list comprehension:</p>
<pre><code>from... | 3 | 2016-07-01T09:44:40Z | [
"python"
] |
How to get a subset of a list based on conditions using python lambdas or list comprehensions | 38,141,939 | <p>I have a list of dictionaries like this. </p>
<pre><code>somelist = [
{ "store" : Amazon, "price": 1000},
{ "store" : Junglee, "price": 1200},
{ "store" : BestBuy, "price": 1300},
{ "store" : Amazon, "price": 900},
{ "store" : BestBuy, "price": 1200}
]
</code></pre>
<p>I want to filter it so th... | 3 | 2016-07-01T09:33:14Z | 38,143,920 | <p>If <code>store</code> values will be strings like:</p>
<pre><code>somelist =
[
{ "store" : 'Amazon', "price": 1000},
{ "store" : 'Junglee', "price": 1200},
{ "store" : 'BestBuy', "price": 1300},
{ "store" : 'Amazon', "price": 900},
{ "store" : 'BestBuy', "price": 1200}
]
</code></pre>
<p>You can do something... | 0 | 2016-07-01T11:10:37Z | [
"python"
] |
Why does scipy.norm.pdf sometimes give PDF > 1? How to correct it? | 38,141,951 | <p>Given mean and variance of a Gaussian (normal) random variable, I would like to compute its probability density function (PDF). </p>
<p><a href="http://i.stack.imgur.com/XwgLg.gif" rel="nofollow"><img src="http://i.stack.imgur.com/XwgLg.gif" alt="enter image description here"></a></p>
<p>I referred this post: <a h... | 0 | 2016-07-01T09:34:02Z | 38,142,058 | <p>It's not a bug. It's not an incorrect result either. Probability density function's value at some specific point does not give you probability; it is a measure of how <em>dense</em> the distribution is around that value. For continuous random variables, the probability at a given point is equal to zero. Instead of <... | 7 | 2016-07-01T09:39:21Z | [
"python",
"scipy",
"distribution",
"normal-distribution"
] |
I got an error when using apscheduler with mongodb jobstores based on tornado | 38,142,026 | <pre><code># get function like this:
@gen.coroutine
def get(self, url=None):
if not url:
url = "https://www.baidu.com/"
res = yield self.client.fetch(url)
raise gen.Return(res.body)
# add_job method:
self.sdu.add_job(
tornado.ioloop.IOLoop.instance().add_callback,
'interval',
seconds=de... | 1 | 2016-07-01T09:38:02Z | 38,152,745 | <p>You are trying to add a bound method as the target function of a job. That will not work with a persistent job store. Instead, create a new function as the target which will then get the global IOLoop and start the coroutine.</p>
| 0 | 2016-07-01T19:28:33Z | [
"python",
"tornado",
"apscheduler"
] |
Use Apply on a SeriesGroupBy Object where conditions are met | 38,142,129 | <p>I have a DataFrame <code>df1</code>: </p>
<pre><code> df1.head() =
id ret eff
1469 2300 -0.010879 4480.0
328 2300 -0.000692 -4074.0
1376 2300 -0.009551 4350.0
2110 2300 -0.014013 5335.0
849 2300 -0.286490 -9460.0
</code></pre>
<p>I would like to create a new colu... | 1 | 2016-07-01T09:42:56Z | 38,143,113 | <p>You can use custom function <code>f</code>, where is possible easy add <code>print</code>. So <code>x</code> is <code>Series</code> and you need compare each group by <a href="http://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.where.html" rel="nofollow"><code>numpy.where</code></a>. Output is <code>num... | 2 | 2016-07-01T10:30:22Z | [
"python",
"pandas"
] |
how to change serialized JSON structure django rest framwork | 38,142,137 | <p>I'm wondering if it possible to change structure of my JSON that im sedinding out.
currenyly it looks like this:</p>
<pre><code>{
"para_subject": {
"discipline": "MATAN"
},
"para_room": {
"room": "210"
},
"para_professor": {
"user": {
"username": "yyyy",
... | 1 | 2016-07-01T09:43:15Z | 38,142,754 | <p>It depends of the serializers/models you use, but in general can use serializers looking like this:</p>
<pre><code>class Serializer1(serializers.Serializer):
discipline = serializers.CharField()
room = serializers.IntegerField()
para_professer = Serializer2()
class Serializer2(serializers.Serializer):
... | 2 | 2016-07-01T10:11:26Z | [
"python",
"json",
"django",
"serialization",
"django-rest-framework"
] |
how to change serialized JSON structure django rest framwork | 38,142,137 | <p>I'm wondering if it possible to change structure of my JSON that im sedinding out.
currenyly it looks like this:</p>
<pre><code>{
"para_subject": {
"discipline": "MATAN"
},
"para_room": {
"room": "210"
},
"para_professor": {
"user": {
"username": "yyyy",
... | 1 | 2016-07-01T09:43:15Z | 38,143,680 | <p>You can add <code>discipline</code> and <code>room</code> fields with <code>source</code> parameters on <code>ParaSerializer</code>.</p>
<p>These fields will fetch the value from the <code>source</code> mentioned and will be included in the output.</p>
<pre><code>class ParaSerializer(serializers.ModelSerializer)
... | 1 | 2016-07-01T10:58:09Z | [
"python",
"json",
"django",
"serialization",
"django-rest-framework"
] |
python derived class call a global variable which initialized in superclass | 38,142,145 | <p>i tried initialized the derived class by default superclass's __init__function, then i tried to use the global variable which initialized in the init function.
but there was an error message said the variable "dr" in class One is not defined</p>
<p>base.py:</p>
<pre><code>class Base(object):
dr = None
def ... | 0 | 2016-07-01T09:43:29Z | 38,142,507 | <p>You have defined <code>dr</code> as a class variable, a static field available to all classes, and you should see this field from all objects with <code>Base.dr</code>.
<code>global</code> should not be used in methods, but rather in functions. </p>
<p>This class variable is not inherited and <code>One.dr</code> i... | 0 | 2016-07-01T10:00:45Z | [
"python",
"inheritance",
"global-variables"
] |
python derived class call a global variable which initialized in superclass | 38,142,145 | <p>i tried initialized the derived class by default superclass's __init__function, then i tried to use the global variable which initialized in the init function.
but there was an error message said the variable "dr" in class One is not defined</p>
<p>base.py:</p>
<pre><code>class Base(object):
dr = None
def ... | 0 | 2016-07-01T09:43:29Z | 38,142,534 | <p>That's because <code>global</code> stands for the global scope of a module, so the global scope of <code>base.py</code> isn't the same global scope in <code>one.py</code>, thus <code>global</code> won't work. Here's a solution for cross-module variable sharing <a href="http://stackoverflow.com/a/142566/4472389">http... | 1 | 2016-07-01T10:01:45Z | [
"python",
"inheritance",
"global-variables"
] |
python derived class call a global variable which initialized in superclass | 38,142,145 | <p>i tried initialized the derived class by default superclass's __init__function, then i tried to use the global variable which initialized in the init function.
but there was an error message said the variable "dr" in class One is not defined</p>
<p>base.py:</p>
<pre><code>class Base(object):
dr = None
def ... | 0 | 2016-07-01T09:43:29Z | 38,218,964 | <p>Finally, i edit my code like this:</p>
<p>base.py:</p>
<pre><code>class Base(object):
def __init__(self, driver):
self.dr = driver
global dr
dr = driver
</code></pre>
<p>one.py</p>
<pre><code>class One(Base):
def __init__(self, driver):
super().__init__(driver)
glo... | 0 | 2016-07-06T07:59:22Z | [
"python",
"inheritance",
"global-variables"
] |
How to infer Django model from json data? | 38,142,262 | <p>I have a json file and I want to automatically generate Django model class code based on my json data. </p>
<p>What I search for is similar to <a href="https://docs.djangoproject.com/en/1.9/howto/legacy-databases/" rel="nofollow">Integrating Django with a legacy database</a>, but not with database, where I can conn... | 1 | 2016-07-01T09:48:41Z | 38,152,418 | <p>You can use <a href="http://www.django-rest-framework.org/api-guide/serializers/#modelserializer" rel="nofollow">Django Rest Framework</a> model serializers for converting json data from and to a Django model.
Defining a serializer for a model is straightforward and requires only defining the relevant fields for ser... | 0 | 2016-07-01T19:05:08Z | [
"python",
"json",
"django",
"database",
"django-models"
] |
gulp livereload not working | 38,142,365 | <p>I have this weird problem after installing the following gulp packages. Everything renders just fine, but when it gets to the part of the liveReload() it just doesn't reload the page...</p>
<p>I installed the livereload chrome extension (is it necessary?), and it seems like there is nothing to config there...</p>
... | 0 | 2016-07-01T09:54:09Z | 38,143,024 | <p>The only thing that comes to my mind is: did you include the livereload client script into your page? AFAIK you should be supposed to inject this script at the end of your page's body.</p>
<pre><code><script src="http://localhost:35729/livereload.js"></script>
</code></pre>
| 0 | 2016-07-01T10:26:17Z | [
"javascript",
"python",
"gulp",
"gulp-watch"
] |
putting .size() into new column python pandas | 38,142,419 | <p>I am very new to python (and to stack overflow!) so hopefully this makes sense!</p>
<p>I have a dataframe which contains years and names (amongst otherthings however this is all I am interested in working with).
I have done <code>df = df.groupby(['year', 'name']).size()</code> to get the amount of times each names... | 1 | 2016-07-01T09:56:48Z | 38,142,439 | <p>IIUC you want <code>transform</code> to add the result of the groupby with its index aligned to the original df:</p>
<pre><code>df['count'] = df.groupby(['year', 'name']).transform('size')
</code></pre>
<p><strong>EDIT</strong></p>
<p>Looking at your requirements, I suggest calling <code>reset_index</code> on the... | 0 | 2016-07-01T09:57:46Z | [
"python",
"pandas",
"ipython"
] |
Remove leading zero in month in a date python in windows | 38,142,478 | <p>My string is: <code>Nov 05 2016 01:30:00PM</code>
I need to remove leading 0 of month and hour
the output should be like <code>Nov 5 2016 1:30:00PM</code></p>
<p>Adding a hyphen between the % and the letter, you can not remove the leading zero windows..so I cannot use that option.</p>
<pre><code>import time
from_d... | -3 | 2016-07-01T09:59:17Z | 38,143,643 | <p>I don't think there's a simple way to do this. You need to convert the parts separately and then join them together. Here's one way to do that which works on Python 2 and Python 3.</p>
<pre><code>import time
time_formats = ('%b', '%d %Y', '%I:%M:%S%p')
def strip_time(fmt, t):
return time.strftime(fmt, t).lstr... | 0 | 2016-07-01T10:56:31Z | [
"python",
"windows"
] |
Using another foreign key in limit_choices_to of a foreign key | 38,142,613 | <p>I want to use a foreign key in limit_choices_to, but i am getting an error of </p>
<blockquote>
<p>Cannot resolve keyword u'product_type.product_type' into field. Choices are: id, pantvariation, product_brand, product_brand_id, product_id, product_type, product_type_id, shirtvariation</p>
</blockquote>
<pre><cod... | 0 | 2016-07-01T10:06:02Z | 38,144,615 | <p>IMHO you cannot make this work easily that way. However, I would restructure your PantVariation model in this way:</p>
<pre><code>class PantVariation(models.Model):
product = models.ForeignKey(ProductType, related_name="pants", limit_choices_to= {'product_type.': 'pant'}
</code></pre>
<p>)</p>
<p>That should ... | 0 | 2016-07-01T11:44:29Z | [
"python",
"django"
] |
Import data into Elastic Search using Logstash in Python | 38,142,639 | <p>I have imported a JSON file into ElasticSearch index using the command line for logstash. I used the following command:</p>
<blockquote>
<p>.\logstash -f logstash.conf</p>
</blockquote>
<p>The path of the file to be imported has been provided in the logstash.conf file.
I have been able to achieve this using comm... | 0 | 2016-07-01T10:07:01Z | 39,983,241 | <p>You can use bulk loader <a href="http://elasticsearch-py.readthedocs.io/en/master/helpers.html?highlight=bulk#bulk-helpers" rel="nofollow">http://elasticsearch-py.readthedocs.io/en/master/helpers.html?highlight=bulk#bulk-helpers</a> </p>
<p>in case you're not able to fit your file in memory - use streaming option <... | 0 | 2016-10-11T17:35:04Z | [
"python",
"elasticsearch",
"logstash"
] |
updating the progressbar to include some custom text on the same line as the progressbar | 38,142,891 | <p>I would like to include some text on the same line as the below progressbar</p>
<p><a href="https://github.com/niltonvolpato/python-progressbar" rel="nofollow">progress</a></p>
<pre><code>string = ["some","text"]
for text in string:
pbar.update(text, i)
</code></pre>
<p>Would return:</p>
<pre><code>>>> ... | 0 | 2016-07-01T10:18:35Z | 38,144,873 | <p>You can use widgets</p>
<pre><code>from progressbar import ProgressBar, Bar, Percentage
pbar = ProgressBar(widgets=["Hellow Progess: percent:", Percentage(), ", bar: ", Bar()])
for i in pbar(range(100)):
time.sleep(0.01)
</code></pre>
| 0 | 2016-07-01T11:59:02Z | [
"python"
] |
Cairo GTK create a highligther pen | 38,143,037 | <p>I am trying to create a simple drawing application using Python, GTK3 and cairo. The tool should have different brushes and some kind of a <a href="http://www.psdgraphics.com/file/yellow-highlighter-pen.jpg" rel="nofollow">highlighter pen</a>.
I figured I can use the alpha property of the stroke to create it. Howev... | 3 | 2016-07-01T10:26:33Z | 38,149,904 | <p>Each <code>move_to()</code> creates a new sub-path that is drawn separately. What you want is a single, connected path.</p>
<p>As far as I know, cairo turns a <code>line_to()</code>-call into a <code>move_to()</code> if there is no current point yet, so the following should work:</p>
<pre><code>def draw_brush(widg... | 0 | 2016-07-01T16:15:17Z | [
"python",
"gtk3",
"cairo",
"pycairo"
] |
Anti-aliased Arc Pygame | 38,143,135 | <p>I am trying to code a simple circle timer in Python using Pygame.
At the moment it looks like this:
<a href="http://i.stack.imgur.com/pjpXr.gif" rel="nofollow"><img src="http://i.stack.imgur.com/pjpXr.gif" alt="Timer"></a></p>
<p>As you can see, the blue line is very wavy and has white dots in it. I am achieving t... | 0 | 2016-07-01T10:31:15Z | 38,144,518 | <p>I am not aware of any pygame function that would solve this problem, meaning you basically have to program a solution yourself (or use something other than pygame), since <code>draw</code> is broken as you've noted and <code>gfxdraw</code> won't give you the thickness.</p>
<p>One <em>very ugly</em> but simple solut... | 0 | 2016-07-01T11:39:15Z | [
"python",
"pygame",
"antialiasing"
] |
how to change the whole dataframe values based on another one in Python | 38,143,201 | <p>I have two dataframes:</p>
<pre><code>df = pd.DataFrame({'A': [1,2,3,5,4,2], 'B':[1,2,4,1,2,3], 'C':[2,3,1,4,2,3]})
df1 = pd.DataFrame({'num':[1,2,3,4,5],'col':['red','red','blue','orange','orange']})
</code></pre>
<p>They look like this:</p>
<pre><code>df:
A B C
0 1 1 2
1 2 2 3
... | 1 | 2016-07-01T10:34:29Z | 38,143,238 | <p>if you set the index to the <code>num</code> col on <code>df1</code> then you can call <code>apply</code> with a <code>lambda</code> and use <code>map</code> to perform the lookup on each column:</p>
<pre><code>In [11]:
df2 = df1.set_index('num')
df.apply(lambda x: x.map(df2['col']))
Out[11]:
A B ... | 1 | 2016-07-01T10:36:10Z | [
"python",
"python-2.7",
"pandas",
"dataframe"
] |
How to parse and retrieve diameter AVPs in python? | 38,143,219 | <p>I have a diameter packet capture pcap file (using tcpdump) containing some AVPs. I'd like to parse the pcap file and access/retrieve the AVPs.</p>
<p>I'm using python3.5.1. The dpkt library apparently supports diameter well but it's not yet available for python3. I tried converting it via 2to3-3.5 script but the co... | 0 | 2016-07-01T10:35:14Z | 40,066,101 | <p>I would suggest you to use tshark. Using tshark you can convert the pcap files to text files containing the AVPs that you are interested in. Once you have the text file, I believe it would be easy to extract the information using python.</p>
| 0 | 2016-10-16T02:03:25Z | [
"python",
"python-3.x",
"scapy",
"diameter-protocol",
"dpkt"
] |
Communication between Python processes | 38,143,265 | <p>I want to implement a "bus" over which python processes can communicate.
The "bus" B shall run as a python process. Other Python processes C1, C2, ...Cn shall be able to register to the bus by a name. After registration it shall be possible for C1 to send a message to C2 by passing a message to the bus together with... | 0 | 2016-07-01T10:37:40Z | 38,147,330 | <p>If you want to start all processes (c1,c2,bus) separately. Then you should use <a href="https://docs.python.org/3.4/library/os.html#os.mkfifo" rel="nofollow">FIFOs</a> or <a href="https://docs.python.org/3.4/library/socket.html" rel="nofollow">Unix Sockets</a> to communicate. </p>
<p>Pipes and Queues in multiproces... | 0 | 2016-07-01T13:58:36Z | [
"python",
"queue",
"multiprocessing"
] |
How can I rewrite text files into up to down format? (Python 3) | 38,143,289 | <p>I guess I should try and explain what I'm doing, I'm trying to get a text file to be rewritten into a separate file from left-to-right format into up-to-down format. Here is an example:</p>
<p>Hello, <br />
this is a text file</p>
<p>H t<br />
e h<br />
l i<br />
l &nbs... | 0 | 2016-07-01T10:39:07Z | 38,143,492 | <p>you go trought your file <code>r_file</code> the first time in maxLineLeng, so the 'reading cursor' of the file get at the end of your file, you have to put it again at the beginning after your first loop or before the second one</p>
<p><code>r_file.seek(0)</code></p>
| 0 | 2016-07-01T10:48:36Z | [
"python",
"file",
"python-3.x",
"text",
"format"
] |
Optimal way to store a type of a Django model and efficient read from a SQL database | 38,143,291 | <p>I have a model design question concerning storing a type of a model. Here is an example:</p>
<pre><code>class Building(models.Model)
id = models.AutoField(primary_key=True)
address = models.CharField()
class Bar(models.Model)
id = models.AutoField(primary_key=True)
building = models.ForeignKey(Buil... | 1 | 2016-07-01T10:39:11Z | 38,147,687 | <p>Options 1 is the most expensive one, since it requires 3 different SQL join searches (i.e join of Building table with each of the establishments). It also implies that a single building can have more than one establishment from each type.</p>
<p>Option 2 is the cheapest one - after retrieving the building objects, ... | 1 | 2016-07-01T14:15:01Z | [
"python",
"sql",
"django"
] |
Pandas: I am trying to open a specific .txt file stored in a zip file on an ftp site | 38,143,305 | <p>I need to concatenate---into a single frame---every <code>produkt_monat_Monatswerte_18910101_20110331_00003.txt</code> file in each of the zip files from <a href="ftp://ftp-cdc.dwd.de/pub/CDC/observations_germany/climate/monthly/kl/historical/" rel="nofollow">this</a> ftp site. </p>
<p>This is the code that I am ... | 0 | 2016-07-01T10:39:51Z | 38,144,727 | <p>The problem is you can't have pandas extract an inner file from the Zip.
Try the following code:</p>
<pre><code>import pandas as pd
from ftplib import FTP
import os
from zipfile import ZipFile
from io import BytesIO
f_root = 'ftp-cdc.dwd.de'
zips_path = '/pub/CDC/observations_germany/climate/monthly/kl/historical/... | 1 | 2016-07-01T11:51:18Z | [
"python",
"pandas",
"ftp",
"zip"
] |
Concatenate files with different and overlapping columns | 38,143,312 | <p>I have three csv files.</p>
<p>One with tittles:</p>
<pre><code>names1=['Date','Conc','Flow','SZ','SB','RZ','RB','Fraction','Attenuation','Conc_less_-200_flag','Conc_greater_500_flag','Wind Speed','Wind Direction','Wind_direction_Flag','Wind_Speed_Less_than_4','Middle','Wind_Speed_Greater_than_10','Multiple condit... | 0 | 2016-07-01T10:40:03Z | 38,143,456 | <p>This is idea.
First read two files into lists then set and union two list</p>
<p>You can checkout this answer <a href="http://stackoverflow.com/questions/20893916/how-to-get-the-union-of-two-lists-using-list-comprehension">How to get the union of two lists using list comprehension?</a></p>
| 0 | 2016-07-01T10:47:08Z | [
"python",
"csv",
"concatenation"
] |
Loop statement ready for multilevel depth | 38,143,319 | <p>I am trying print category tree (main categories with subcategories), but I have problem with elegant solution which will be ready to infinity level depth.</p>
<p>At this moment I have:</p>
<pre><code>cat_id = '31'
cat = prestashop.get('categories', options={'display':'full', 'filter[id]':'[' + cat_id + ']'})['cat... | 0 | 2016-07-01T10:40:28Z | 38,143,586 | <p>I'm no familiar with prestashop but have you tried a recursive function?</p>
<pre><code>def print_levels(cat, level = 2):
try:
for c in cat:
print((" " * level) + "Level {0}: {1}\n".format(level,c['id']))
new_cat = prestashop.get('categories', options={'display':'full', 'filter[i... | 0 | 2016-07-01T10:53:28Z | [
"python",
"loops",
"for-loop",
"dictionary",
"while-loop"
] |
Complexity of algorithms other than asymptotic (Big-O - notation) | 38,143,386 | <p>What are the mostly adopted concept, other than asymptotic complexity (Big-O notation), used to evaluate algorithms?</p>
<p><strong>Example</strong>:</p>
<p>Supposing I have the following algorithm that calls a function, func, with complexity O(1). Then this algorithm would have complexity O(N1 x N2). But if I kne... | 0 | 2016-07-01T10:43:03Z | 38,143,866 | <p>Your question is very large. Read about algorithm complexity and metrics.</p>
<p>Your problem is that even if you don't use Big-O (there are many others small-o Big-omega, small-omega, theta, etc) you will not be able to easily compare algorithms the way it seems you want! The main reason is that you must first cle... | 1 | 2016-07-01T11:08:15Z | [
"python",
"algorithm",
"performance",
"complexity-theory"
] |
Explicitly set precedence in Django template filters | 38,143,388 | <p>Is there a way to set explicitly set precedence in Django template filters?</p>
<p>Like a sort of brackets system.</p>
<p>I'm trying to say </p>
<pre><code>{{ label | default:( parameter | parse_label ) }}
</code></pre>
<p>A <code>label</code> is some human-friendly string like <code>"Project ID"</code> and a pa... | 1 | 2016-07-01T10:43:12Z | 38,143,597 | <p>If I understand you correctly you can achieve this with the <a href="https://docs.djangoproject.com/en/1.9/ref/templates/builtins/#with" rel="nofollow"><code>with</code></a> tag.</p>
<pre><code>{% with param=parameter|parse_label %}
{{ label | default:param }}
{% endwith %}
</code></pre>
| 0 | 2016-07-01T10:54:17Z | [
"python",
"django",
"django-templates"
] |
How to make text search and similarity computation across millions of records efficient in python | 38,143,421 | <p>I have two tables containing 2 million records each. One has the item names and other item description along with other attributes. I have to match each item in table 1 with each description in table 2 to find maximum similarity matches. So basically, for each of 2 million items, I have to scan the other table to fi... | 1 | 2016-07-01T10:44:56Z | 38,143,628 | <p>You could try the <a href="https://pypi.python.org/pypi/Distance/0.1" rel="nofollow">Distance</a> package to calculate the Levenshtein Distance for similarity.</p>
<p>From the documentation:</p>
<blockquote>
<p>Comparing lists of strings can also be useful for computing
similarities between sentences, paragrap... | 0 | 2016-07-01T10:55:57Z | [
"python",
"performance",
"full-text-search",
"similarity",
"processing-efficiency"
] |
How to make text search and similarity computation across millions of records efficient in python | 38,143,421 | <p>I have two tables containing 2 million records each. One has the item names and other item description along with other attributes. I have to match each item in table 1 with each description in table 2 to find maximum similarity matches. So basically, for each of 2 million items, I have to scan the other table to fi... | 1 | 2016-07-01T10:44:56Z | 38,144,813 | <p>you can use NLTK as well.</p>
<pre><code>from nltk import *
reference = 'DET NN VB DET JJ NN NN IN DET NN'.split()
test = 'DET VB VB DET NN NN NN IN DET NN'.split()
print(accuracy(reference, test))
print edit_distance("rain", "shine")
</code></pre>
| 0 | 2016-07-01T11:55:36Z | [
"python",
"performance",
"full-text-search",
"similarity",
"processing-efficiency"
] |
Odd behaviour of pcolormesh with coordinates | 38,143,466 | <p>I would like to plot a color mesh using matplotlib's <code>pcolormesh</code> function. However, it gives different results depending on whether I specify coordinates or not.</p>
<pre><code>import numpy as np
from matplotlib import pyplot as plt
np.random.seed(9)
x = np.arange(10)
z = np.random.normal(0, 1, (10, 10... | 1 | 2016-07-01T10:47:36Z | 38,145,030 | <p>From help(pcolor)</p>
<pre><code>...
Ideally the dimensions of X and Y should be one greater than those of C;
if the dimensions are the same, then the last row and column of C will be ignored. ...
</code></pre>
<p>The left plot you are getting is a zoom in into the right one with top row and rightmost column remov... | 0 | 2016-07-01T12:07:18Z | [
"python",
"matplotlib"
] |
Move Files that match Regex | 38,143,686 | <p>So I have a system that creates a backup file every day at midnight. It uses the naming convention below; with only the date and the 12 digit number at the end changing (the 53 never changes after hostname).</p>
<p>backup.nightly.hostname_53.28_06_2016.config.1467155154658.tgz
backup.nightly.hostname_53.29_06_2016.... | 0 | 2016-07-01T10:58:33Z | 38,144,736 | <p>Probably not the most prettiest of <code>regex's</code> but works for me. You can use the <code>find</code> in <code>bash</code> to match your back-up files.</p>
<p>Am using the <code>regex</code> (<code>*[0-9][0-9]_[0-9][0-9]_2[0-9][0-9][0-9].config.[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]*</co... | 0 | 2016-07-01T11:51:39Z | [
"python",
"regex",
"bash",
"shell",
"scripting"
] |
Groupby in python pandas: Fast Way | 38,143,717 | <p>I want to improve the time of a <code>groupby</code> in python pandas.
I have this code:</p>
<pre><code>df["Nbcontrats"] = df.groupby(['Client', 'Month'])['Contrat'].transform(len)
</code></pre>
<p>The objective is to count how many contracts a client has in a month and add this information in a new column (<code... | 6 | 2016-07-01T11:00:16Z | 38,145,104 | <p>Here's one way to proceed :</p>
<ul>
<li><p>Slice out the relevant columns (<code>['Client', 'Month']</code>) from the input dataframe into a NumPy array. This is mostly a performance-focused idea as we would be using NumPy functions later on, which are optimized to work with NumPy arrays.</p></li>
<li><p>Convert t... | 7 | 2016-07-01T12:10:26Z | [
"python",
"numpy",
"pandas",
"group"
] |
Groupby in python pandas: Fast Way | 38,143,717 | <p>I want to improve the time of a <code>groupby</code> in python pandas.
I have this code:</p>
<pre><code>df["Nbcontrats"] = df.groupby(['Client', 'Month'])['Contrat'].transform(len)
</code></pre>
<p>The objective is to count how many contracts a client has in a month and add this information in a new column (<code... | 6 | 2016-07-01T11:00:16Z | 38,154,835 | <p>With the <code>DataFrameGroupBy.size</code> method:</p>
<pre><code>df.set_index(['Client', 'Month'], inplace=True)
df['Nbcontrats'] = df.groupby(level=(0,1)).size()
df.reset_index(inplace=True)
</code></pre>
<p>The most work goes into assigning the result back into a column of the source DataFrame.</p>
| 2 | 2016-07-01T23:01:23Z | [
"python",
"numpy",
"pandas",
"group"
] |
How can i parse a txt file into lists in Python | 38,143,721 | <p>I am not far from a new bee in Python and i would like to parse a file
as is :</p>
<pre><code>Paris, 458 boulevard Saint-Germain
Paris, 343 boulevard Saint-Germain
Marseille, 343 boulevard Camille Flammarion
Marseille, 29 rue Camille Desmoulins
Marseille, 1 chemin des Aubagnens
</code></pre>
<p>The file contains :... | 1 | 2016-07-01T11:00:21Z | 38,144,596 | <p>(EDIT)</p>
<p>Actually you don't need any extra libs. It is simple operation which could be done with list comprehension or generator or <code>map</code> function and <code>split</code> , <code>strip</code> <code>str</code> object methods if you could split by the single character</p>
<pre><code>with open(sys.argv... | 2 | 2016-07-01T11:43:16Z | [
"python",
"python-3.x"
] |
How can i parse a txt file into lists in Python | 38,143,721 | <p>I am not far from a new bee in Python and i would like to parse a file
as is :</p>
<pre><code>Paris, 458 boulevard Saint-Germain
Paris, 343 boulevard Saint-Germain
Marseille, 343 boulevard Camille Flammarion
Marseille, 29 rue Camille Desmoulins
Marseille, 1 chemin des Aubagnens
</code></pre>
<p>The file contains :... | 1 | 2016-07-01T11:00:21Z | 38,144,819 | <p>There are various data structures that you could store this data in. You could store the data from each line in a tuple containing (city_name, street_number, street_type, street_name), and then store each of those tuples into a list. A slightly nicer option is to store the data into a list of dictionaries. Here's a ... | 2 | 2016-07-01T11:55:55Z | [
"python",
"python-3.x"
] |
Refactoring code @staticmethod design | 38,143,724 | <p>I have a tornado application that previously had the following structure:</p>
<pre><code>class handler(tornado.websocket.WebSocketHandler):
@tornado.gen.coroutine
def do_something(self,m):
# do something
def on_message(self,msg):
tornado.ioloop.IOLoop.current().spawn_callback(self.do_something,m... | 0 | 2016-07-01T11:00:41Z | 38,154,431 | <p>If you need to extract the methods in order to group them by common functionality, perhaps it might be the best to make your classes into mixins:</p>
<pre><code>class SessionMsgMixin(object):
@tornado.gen.coroutine
def do_something(ws,m):
# do stuff
class MyHandler(tornado.websocket.WebSocketHandl... | 1 | 2016-07-01T22:07:30Z | [
"python",
"tornado"
] |
Python regex to match currency with or without comma or decimal | 38,143,814 | <p>How to write regex that can <code>1.</code> match currency which may or may not include a comma or decimal and <code>2.</code> match the currency code only. What I see is mostly matching currency symbols.
I want to be able to match currency <code>['300,000.00']</code> and currency code <code>['USD']</code> from a co... | 1 | 2016-07-01T11:04:53Z | 38,143,940 | <p><code>'\d+([.,]?\d*)*'</code> that should match all cases.
If you want, you can also add space. Like this: </p>
<pre><code>'\d+([., ]?\d*)*'
</code></pre>
<p>For the currency codes: <code>'[A-Z]{3}'</code> should work.</p>
<p>P.S. As per SilentMonk suggestion for the non-capture groups:</p>
<pre><code>(?:[A-Z]... | 1 | 2016-07-01T11:11:16Z | [
"python",
"regex"
] |
Python regex to match currency with or without comma or decimal | 38,143,814 | <p>How to write regex that can <code>1.</code> match currency which may or may not include a comma or decimal and <code>2.</code> match the currency code only. What I see is mostly matching currency symbols.
I want to be able to match currency <code>['300,000.00']</code> and currency code <code>['USD']</code> from a co... | 1 | 2016-07-01T11:04:53Z | 38,144,017 | <p>To match currency only you can use : <code>(\d[0-9,.]+)</code></p>
<p>and to match currency codes you can use : <code>([A-Z]+)</code></p>
<p><a href="https://regex101.com/r/hU4vO7/12" rel="nofollow">Demo and Explaination</a></p>
| 0 | 2016-07-01T11:15:18Z | [
"python",
"regex"
] |
Python regex to match currency with or without comma or decimal | 38,143,814 | <p>How to write regex that can <code>1.</code> match currency which may or may not include a comma or decimal and <code>2.</code> match the currency code only. What I see is mostly matching currency symbols.
I want to be able to match currency <code>['300,000.00']</code> and currency code <code>['USD']</code> from a co... | 1 | 2016-07-01T11:04:53Z | 38,144,319 | <p><strong>Get the Currency:</strong></p>
<p>Having an exhaustive list of valid currencies might not be feasible but if it is a limited number of currencies then you can do that like this:</p>
<pre><code>re.findall('USD|CAD','USD1 USD1.00 USD100.00 USD1,000 CAD1,000.00 123XXX123')
</code></pre>
<p><strong>Output:</s... | 1 | 2016-07-01T11:28:50Z | [
"python",
"regex"
] |
ordering in boxplot according to an object | 38,143,927 | <p>I would like to have some grouped boxplot in a pandas df.</p>
<p>var2 is an object, and I would like to display the boxplot in alphabetical order according to var2 order</p>
<pre><code>import seaborn as sns
sns.set_style("whitegrid")
ax = sns.boxplot(x="var1", y="var2",order=???, data=df)
</code></pre>
<p>with... | 0 | 2016-07-01T11:10:56Z | 38,145,036 | <p>Not 100% sure what needs to be sorted, but essentially you need to use unique():</p>
<pre><code>order = sorted(df.var1.unique())
ax = sns.boxplot(x="var1", y="var2", order=order, data=df)
</code></pre>
| 1 | 2016-07-01T12:07:32Z | [
"python",
"pandas",
"boxplot",
"seaborn"
] |
importing whole python module doesn't allow using submodules | 38,143,991 | <p>My question is specific to scikit-learn python module, but I had similar issues with matplotlib as well.</p>
<p>When I want to use sklearn, if I just do 'import sklearn' and then call whatever submodule I need, like ' sklearn.preprocessing.scale()', I get an error
"AttributeError: 'module' object has no attribute ... | 1 | 2016-07-01T11:13:48Z | 38,144,150 | <p>Numpy conveniently imports its submodules in its <code>__init__.py</code> file and adds them to <code>__all__</code>. There's not much you can do about it when using a library - it either does it or not. sklearn apparently doesn't.</p>
| 1 | 2016-07-01T11:21:17Z | [
"python",
"numpy",
"import",
"module",
"scikit-learn"
] |
importing whole python module doesn't allow using submodules | 38,143,991 | <p>My question is specific to scikit-learn python module, but I had similar issues with matplotlib as well.</p>
<p>When I want to use sklearn, if I just do 'import sklearn' and then call whatever submodule I need, like ' sklearn.preprocessing.scale()', I get an error
"AttributeError: 'module' object has no attribute ... | 1 | 2016-07-01T11:13:48Z | 38,144,185 | <p>A python package is defined in the <code>__init__.py</code> file inside the directory.
This file determines whether or not submodules are include.</p>
<p>When you do <code>import sklearn</code> python finds the file <code>sklearn/__init__.py</code> and executes it to create the <code>sklearn</code> module. This obj... | 0 | 2016-07-01T11:22:50Z | [
"python",
"numpy",
"import",
"module",
"scikit-learn"
] |
pandas: conditions with str.contains() | 38,144,056 | <p>I have data </p>
<pre><code>url
https://s.youtube.com/api/stats/qoe?fexp=9416891%2C9419451%2C9422596%2C9428269%2C9428398%2C9428492%2C9431012%2C9431657%2C9431674%2C9433096%2C9433380%2C9433946%2C9434803%2C9435467%2C9435526%2C9435876%2C9436275%2C9436302%2C9436484%2C9437553%2C9437967%2C9438327%2C9438699%2C9439362%2C943... | -1 | 2016-07-01T11:17:04Z | 38,144,115 | <p>try</p>
<pre><code>df[df['myurl']=df.url.to_string()
df[df['myurl'].str.contains('youtube', case=False)]
</code></pre>
| 0 | 2016-07-01T11:20:02Z | [
"python",
"pandas"
] |
IndexError: list index out of range in a function using BeautifulSoup | 38,144,244 | <p>I am making a GUI based project in Python with the module tkinter. It fetches basic data from online judge, eg, SPOJ using Beautiful Soup. I am a newbie in Python, so most of the things I have written is with basic tutorials from internet. However, for a particular piece of code, I am totally stuck up.</p>
<pre><co... | 1 | 2016-07-01T11:25:37Z | 38,146,078 | <p>The first step in debugging this is to take the complex line that is throwing an error and make it simpler. You can then inspect the intermediate values so see if the assumptions you're making about the code are true. In this case, your assumption is that <code>soup.find_all('table', ...)</code> is actually finding ... | 3 | 2016-07-01T12:58:37Z | [
"python",
"tkinter",
"beautifulsoup",
"indexoutofrangeexception"
] |
Syntax error while using Foreign Keys in Sqlite 3 in Python. | 38,144,342 | <p>I have a database schema file which I read in my Flask module.</p>
<pre><code>PRAGMA foreign_keys = 1;
drop table if exists user;
create table user(uid integer primary key autoincrement,
username text not null,
password text not null,
email text not null);
drop table if exists asset;
create table asset(aid integ... | 0 | 2016-07-01T11:30:22Z | 38,144,463 | <p>You should replace the underscore between the <code>FOREIGN</code> and <code>KEY</code> with a space. The following diagrams shows the constraint <a href="https://www.sqlite.org/syntax/table-constraint.html" rel="nofollow">syntax</a>:</p>
<p><a href="http://i.stack.imgur.com/1NcES.gif" rel="nofollow"><img src="http... | 0 | 2016-07-01T11:36:24Z | [
"python",
"sqlite"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.