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 |
|---|---|---|---|---|---|---|---|---|---|
Pandas DataFrame plotting - Tick labels | 39,697,683 | <p>this is a follow-up question on a piece of code I have <a href="http://stackoverflow.com/questions/39561248/python-plotting-pandas-pivot-table-from-long-data">posted previously here</a>. </p>
<p>I am plotting a Dataframe object using <code>data_CO2_PBPROD.T.plot(marker='o', color='k', alpha=0.3, lw=2)</code> but I ... | 0 | 2016-09-26T08:08:55Z | 39,697,870 | <p>You can use the argument <strong>xticks</strong> to set the values of your axis as explained in the documentation <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.plot.html" rel="nofollow">here</a>:</p>
<pre><code>xticks = [date for _ ,date in data_CO2_PBPROD.Column1]
</code></pre>
<... | 0 | 2016-09-26T08:22:20Z | [
"python",
"pandas",
"matplotlib",
"plot"
] |
django admin list_display - returning multiple column values with single callable (django 1.9, python=2.7.x) | 39,697,892 | <p>So my Django code for <code>admin.py</code> looks something like this:</p>
<pre><code>class MyUserAdmin(UserAdmin):
form = MyUseChangeForm
list_display = ('email', 'is_admin', 'is_superuser',
'total_tasks', 'total_tests')
list_filter = ('is_admin', 'is_superuser')
ordering = ('e... | 0 | 2016-09-26T08:24:14Z | 39,698,010 | <p>First of all tune tune your code.</p>
<ol>
<li><code>total_tasks</code> - should be <code>OtherObject.objects.filter(user_id=obj.pk).count()</code> - it will boost you a bit.</li>
<li>You've hidden the body of for loop in <code>total_tests</code>. I am afraid that you refer to some objects connected with <code>Othe... | 1 | 2016-09-26T08:30:43Z | [
"python",
"django"
] |
django admin list_display - returning multiple column values with single callable (django 1.9, python=2.7.x) | 39,697,892 | <p>So my Django code for <code>admin.py</code> looks something like this:</p>
<pre><code>class MyUserAdmin(UserAdmin):
form = MyUseChangeForm
list_display = ('email', 'is_admin', 'is_superuser',
'total_tasks', 'total_tests')
list_filter = ('is_admin', 'is_superuser')
ordering = ('e... | 0 | 2016-09-26T08:24:14Z | 39,698,396 | <p>Override the <a href="https://docs.djangoproject.com/en/1.10/ref/contrib/admin/#django.contrib.admin.ModelAdmin.get_queryset" rel="nofollow"><code>get_queryset</code></a> method for your <a href="https://docs.djangoproject.com/en/1.10/ref/models/querysets/#prefetch-related" rel="nofollow"><code>prefetch_related</cod... | 1 | 2016-09-26T08:51:07Z | [
"python",
"django"
] |
python matplotlib bars don't change when running script multiple times | 39,697,937 | <p>I've been writing a post-processing script for a model we have at work, which worked fine. Recently I re-structured the script for clarity and re-usability.</p>
<p>General background: we have pickle-stored arrays as output from a model, for each "main parameter" <code>(N:nitrogen, P:phosporus)</code>. There are a b... | -1 | 2016-09-26T08:26:37Z | 39,698,730 | <p>I guess the only thing you need is a new figure... so try to place <code>plt.figure()</code> right after <code>if figure == True:</code> like this:</p>
<pre><code> ...
j+=1
if figure==True:
plt.figure()
S = len(dates)/len(parameters[2])
...
</code></pre>
<p>and see if it ... | 0 | 2016-09-26T09:06:52Z | [
"python",
"matplotlib"
] |
How to split comma delimited values into multiple rows using Python | 39,697,974 | <p>I'm using Python and SQLite to manipulate a database. </p>
<p>I have an SQLite Table <code>Movies</code> that looks like this:</p>
<pre><code>| ID | Country
+----------------+-------------
| 1 | USA, Germany, Mexico
| 2 | Brazil, Canada
| 3 | Peru
</code></p... | 0 | 2016-09-26T08:28:42Z | 39,698,740 | <p>Using Python,</p>
<pre><code>cursor.execute("""Select * from Movies""")
all_data = cursor.fetchall()
cursor.execute("""CREATE TABLE IF NOT EXISTS Countries
(ID TEXT,
Country TEXT)""")
for single_data in all_data:
countries = single_data[1].split()
for single_country i... | 0 | 2016-09-26T09:07:24Z | [
"python",
"sqlite"
] |
Decorators on bound methods with access to class and his ancestors | 39,698,045 | <p>When I decorated the bound method in Python class, I need get some info in this decorator from outer class. Is that possible?</p>
<p>For example:</p>
<pre><code>def modifier(func):
import sys
cls_namespace = sys._getframe(1).f_locals
cls_namespace['data'] # dictonary has no key 'data'
...
retu... | 2 | 2016-09-26T08:32:15Z | 39,698,115 | <p>Function decoration takes place when the class body is being executed, nothing is known about the class itself or its base classes at this time. This means that <code>modifier</code> decorates the <em>unbound function object</em> and only when <code>func</code> is actually called on an instance will it be bound.</p>... | 3 | 2016-09-26T08:35:10Z | [
"python",
"class",
"reflection",
"decorator",
"python-decorators"
] |
Decorators on bound methods with access to class and his ancestors | 39,698,045 | <p>When I decorated the bound method in Python class, I need get some info in this decorator from outer class. Is that possible?</p>
<p>For example:</p>
<pre><code>def modifier(func):
import sys
cls_namespace = sys._getframe(1).f_locals
cls_namespace['data'] # dictonary has no key 'data'
...
retu... | 2 | 2016-09-26T08:32:15Z | 39,698,136 | <p>Not that the very first arg passed to your decorator's wrapper will be an objects instance (<code>self</code>). Thanks to it you can access w=everything you need. </p>
<p>See Raphaels response:
<a href="http://stackoverflow.com/questions/11731136/python-class-method-decorator-w-self-arguments">Related issue</a></p... | -1 | 2016-09-26T08:36:07Z | [
"python",
"class",
"reflection",
"decorator",
"python-decorators"
] |
How to mock self in python? | 39,698,094 | <p>Consider the following code. I want to mock <code>self.get_value</code>, which is invoked in <code>foo.verify_client()</code></p>
<pre><code>import unittest
import mock
def mock_get_value(self, value):
return 'client'
class Foo:
def __init__(self):
pass
def get_value(self, value):
retu... | 1 | 2016-09-26T08:34:15Z | 39,698,604 | <p>I figured it out. Changing this line</p>
<pre><code>@mock.patch('self.get_value', side_effect = mock_get_value, autospec = True)
</code></pre>
<p>to</p>
<pre><code>@mock.patch('test.Foo.get_value', mock_get_value)
</code></pre>
<p>worked.</p>
<p>Especially, the format of the patched function should be <code>mod... | 1 | 2016-09-26T09:00:28Z | [
"python",
"unit-testing",
"mocking"
] |
Python Pandas convert column data type | 39,698,097 | <p>I know a question like this has been asked zillion types, but so far I have not been able to find an answer to this question.</p>
<p>I have joined two .csv files together with Pandas and now I would like to add some more columns to the new joined .csv file and the values calculate based on the already available dat... | 1 | 2016-09-26T08:34:17Z | 39,698,318 | <p>As with @EdChum's comment, you need to use <code>clip(upper=13)</code> or <code>clip_upper(13)</code>. One other option which can help you in the long run with instances like this is to use <code>apply</code> with a lambda function. This is a really nifty all-around method.</p>
<pre><code>import pandas as pd
import... | 1 | 2016-09-26T08:46:20Z | [
"python",
"python-2.7",
"csv",
"pandas"
] |
Python Pandas convert column data type | 39,698,097 | <p>I know a question like this has been asked zillion types, but so far I have not been able to find an answer to this question.</p>
<p>I have joined two .csv files together with Pandas and now I would like to add some more columns to the new joined .csv file and the values calculate based on the already available dat... | 1 | 2016-09-26T08:34:17Z | 39,698,394 | <p>(Your code is missing a parenthesis at the end of <code>nscap(df_joined["NS"]</code>.)</p>
<p>As @EdChum and @TheLaughingMan write, <code>clip_upper</code> is what you want here. This answer just addresses the direct reason for the error you're getting. </p>
<p>In the function</p>
<pre><code>def nscap(ns):
if... | 1 | 2016-09-26T08:50:51Z | [
"python",
"python-2.7",
"csv",
"pandas"
] |
Python - "Undo" text-wrap | 39,698,100 | <p>I need to take a text and remove the \n character, which I believe I've done. The next task is to remove the hyphen from words where it should not appear but to leave the hyphen in compound words where it should appear. For example, 'encyclo-\npedia to 'encyclopedia' and 'long-\nterm' to 'long-term'. The suggestion ... | 1 | 2016-09-26T08:34:29Z | 39,698,262 | <p>A first pass would be to keep a set of valid words around and de-hyphenate if your de-hyphenated word is in the set of valid words. Ubuntu has a list of valid words at /usr/share/dict/american-english. An overly simple version might look like:</p>
<pre><code>valid_words = set(line.strip() for line in open(valid_wor... | 0 | 2016-09-26T08:43:30Z | [
"python",
"nlp",
"nltk"
] |
Python - "Undo" text-wrap | 39,698,100 | <p>I need to take a text and remove the \n character, which I believe I've done. The next task is to remove the hyphen from words where it should not appear but to leave the hyphen in compound words where it should appear. For example, 'encyclo-\npedia to 'encyclopedia' and 'long-\nterm' to 'long-term'. The suggestion ... | 1 | 2016-09-26T08:34:29Z | 39,701,733 | <pre><code>import re
with open('C:\Users\Paul\BROWN_A1.txt', 'rU') as truefile:
true_corpus = truefile.read()
true_tokens = true_corpus.split(' ')
with open('C:\Users\Paul\Desktop\Comp_Ling_Research_1\BROWN_A1_hypenated.txt', 'rU') as myfile:
my_corpus = myfile.read()
my_tokens = my_corpus.split(' ')
</code><... | -1 | 2016-09-26T11:33:43Z | [
"python",
"nlp",
"nltk"
] |
How to create an array of linearly spaced points using numpy? | 39,698,121 | <p>I am trying to create an array of equally spaced points using numpy, as below:</p>
<pre><code>array([ 0. , 0.05263158, 0.10526316, 0.15789474, 0.21052632,
0.26315789, 0.31578947, 0.36842105, 0.42105263, 0.47368421,
0.52631579, 0.57894737, 0.63157895, 0.68421053, 0.73684211,
0.78947368... | -3 | 2016-09-26T08:35:30Z | 39,698,173 | <p>Use linspace.</p>
<pre><code>np.linspace(0, 1, 20)
</code></pre>
<p><a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.linspace.html" rel="nofollow">http://docs.scipy.org/doc/numpy/reference/generated/numpy.linspace.html</a></p>
| 2 | 2016-09-26T08:37:54Z | [
"python",
"arrays",
"numpy"
] |
DRF does not work with wagtail | 39,698,187 | <p>I have used DRF for rest api and puput for blog which is built on top of the wagtail. Before using puput, my rest api used to work but not now. For example when i try to open the url <strong><a href="http://localhost:8000/rest-api/ui/tab/" rel="nofollow">http://localhost:8000/rest-api/ui/tab/</a></strong> i get foll... | 1 | 2016-09-26T08:38:31Z | 39,698,389 | <p>change the order of your url patterns.. puput should (probablly) the last element</p>
<pre><code>urlpatterns = [
url(r'^accounts/', include(allauth_urls)),
url(r'^admin/', admin.site.urls),
url(r'^forum/', include(board.urls)),
url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),
... | 3 | 2016-09-26T08:50:27Z | [
"python",
"django",
"python-3.x",
"django-rest-framework",
"wagtail"
] |
Accessing all function argmuments | 39,698,190 | <p>I have a function with 4 arguments and want to check those 4 arguments for something.
Currently I do it like this:</p>
<pre><code>def function1(arg1, arg2, arg3, arg4):
arg1 = function2(arg1)
arg2 = function2(arg2)
arg3 = function2(arg3)
arg4 = function2(arg4)
def function2(arg):
arg = dosometh... | 2 | 2016-09-26T08:38:42Z | 39,698,226 | <p>Yes, use <code>*args</code>:</p>
<pre><code>In [1]: def func(*args):
...: print(len(args), args)
...:
In [2]: func(1, 2, 3, 4)
4 (1, 2, 3, 4)
</code></pre>
<p>More information can be found <a href="https://pythontips.com/2013/08/04/args-and-kwargs-in-python-explained/" rel="nofollow">here.</a></p>
| 3 | 2016-09-26T08:41:11Z | [
"python",
"function",
"python-3.x"
] |
Accessing all function argmuments | 39,698,190 | <p>I have a function with 4 arguments and want to check those 4 arguments for something.
Currently I do it like this:</p>
<pre><code>def function1(arg1, arg2, arg3, arg4):
arg1 = function2(arg1)
arg2 = function2(arg2)
arg3 = function2(arg3)
arg4 = function2(arg4)
def function2(arg):
arg = dosometh... | 2 | 2016-09-26T08:38:42Z | 39,698,236 | <p>Since you have a <em>set</em> number of arguments <em>just create an iterable out of them</em>, for example, wrap the argument names in a tuple literal:</p>
<pre><code>for arg in (arg1, arg2, arg3, arg4):
# do stuff
</code></pre>
<p>If you don't mind your function being capable of being called with more args j... | 6 | 2016-09-26T08:41:48Z | [
"python",
"function",
"python-3.x"
] |
python 3.x what is -> annotation | 39,698,290 | <p>In the following snippet what is <code>-></code> operator ,does it indicate the return type of the function also is it mandatory to use it in python 3.x ? Please point me to few docs for the same</p>
<pre><code> def g() -> str :
...
return 'hello world'
</code></pre>
| -5 | 2016-09-26T08:45:22Z | 39,698,327 | <p>This is type of return value: <a href="https://docs.python.org/3/library/typing.html" rel="nofollow">https://docs.python.org/3/library/typing.html</a> :) It's not mandatory, but might be usefull.</p>
| 1 | 2016-09-26T08:46:44Z | [
"python"
] |
python 3.x what is -> annotation | 39,698,290 | <p>In the following snippet what is <code>-></code> operator ,does it indicate the return type of the function also is it mandatory to use it in python 3.x ? Please point me to few docs for the same</p>
<pre><code> def g() -> str :
...
return 'hello world'
</code></pre>
| -5 | 2016-09-26T08:45:22Z | 39,698,353 | <p><code>-></code> is an <a href="https://www.python.org/dev/peps/pep-3107/" rel="nofollow"><em>annotation</em></a>, attached to the function <em>return value</em>. Annotations are optional, but you can use the syntax to attach arbitrary objects to a function. You can attach more annotations by using <code>name : an... | 4 | 2016-09-26T08:48:06Z | [
"python"
] |
Extracting Keywords using TF-IDF | 39,698,538 | <p>I'm tackling the problem of Keyword Extraction using TF-IDF in an article .
The pipeline that I follow goes as follows :</p>
<ol>
<li>Input Text</li>
<li>Tokenize into sentences to build vocabulary</li>
<li>Apply CountVectorizer to build a count vector for each sentence .</li>
<li>Apply TfidfTransformer to assign w... | 0 | 2016-09-26T08:57:11Z | 39,785,761 | <p>TfidfVectorizer is equivalent to Applying a CountVectorizer and then TfidfTransformer as given <a href="http://scikit-learn.org/stable/modules/generated/sklearn.feature_extraction.text.TfidfVectorizer.html" rel="nofollow">here</a>. If i understood you correctly, you passed an article and it returned a matrix of weig... | 0 | 2016-09-30T07:14:05Z | [
"python",
"scikit-learn",
"nlp",
"tf-idf"
] |
string reversal function using reversed indexing | 39,698,619 | <p>Could someone please help me understand why the following function does not print out the reverse of the string? What am I doing wrong?</p>
<pre><code>def myReverse(data):
for index in range( len(data)-1, -1, -1 ):
return data[index]
print( data[index] )
myReverse('blahblah')
</code></pre>
| -5 | 2016-09-26T09:01:19Z | 39,698,707 | <p>When you make a <code>return</code> call within the function, the control comes back to parent (which executed the function) ignoring the code within the scope of function after <code>return</code>. In your case, that is why <code>print</code> is not getting executed by your code.</p>
<p>Move the line containing <c... | 2 | 2016-09-26T09:05:35Z | [
"python"
] |
string reversal function using reversed indexing | 39,698,619 | <p>Could someone please help me understand why the following function does not print out the reverse of the string? What am I doing wrong?</p>
<pre><code>def myReverse(data):
for index in range( len(data)-1, -1, -1 ):
return data[index]
print( data[index] )
myReverse('blahblah')
</code></pre>
| -5 | 2016-09-26T09:01:19Z | 39,698,712 | <p>You are returning before print. So the line <code>print( data[index] )</code> is never get executed. </p>
<p>Below code wil work just fine. </p>
<pre><code>def myReverse(data):
for index in range( len(data)-1, -1, -1 ):
print( data[index] , end = '')
</code></pre>
<p>Notice that this is a python3 solu... | 1 | 2016-09-26T09:05:52Z | [
"python"
] |
string reversal function using reversed indexing | 39,698,619 | <p>Could someone please help me understand why the following function does not print out the reverse of the string? What am I doing wrong?</p>
<pre><code>def myReverse(data):
for index in range( len(data)-1, -1, -1 ):
return data[index]
print( data[index] )
myReverse('blahblah')
</code></pre>
| -5 | 2016-09-26T09:01:19Z | 39,698,759 | <p><em>Intro:</em> the execution of a <code>for</code> loop will stop once a <code>return</code> statement or <code>break</code> statement is encountered or there is an exception.</p>
<p>You have a <code>return</code> statement which makes the <code>for</code> loop stop (<em>returning</em> control to the caller) as so... | 1 | 2016-09-26T09:08:29Z | [
"python"
] |
TypeError: can only concatenate tuple (not "str") to tuple line 6 | 39,698,773 | <pre><code>import os
import time
source = [r'C:\\Documents','/home/swaroop/byte', '/home/swaroop/bin']
target_dir =r'C:\\Documents','/mnt/e/backup/'
today = target_dir + time.strftime("%Y%m%d")
now = time.strftime('%H%M%S')
os.path.exists(today)
os.mkdir(today)
print 'Successful created directory', today
targ... | -6 | 2016-09-26T09:09:24Z | 39,699,216 | <p>Check the comma as @MosesKoledoye said, the <a href="http://files.swaroopch.com/python/byte_of_python.pdf" rel="nofollow">book</a> has:</p>
<pre><code># 1. The files and directories to be backed up are
# specified in a list.
# Example on Windows:
# source = ['"C:\\My Documents"', 'C:\\Code'] # Example on Mac OS... | 0 | 2016-09-26T09:30:16Z | [
"python"
] |
python: Google Street View url request cannot load as json() | 39,698,881 | <p>I want to use python to grab Google Street View image.
For example:</p>
<pre><code>'url=https://maps.googleapis.com/maps/api/streetview?location=48.15763817939112,11.533002555370581&size=512x512&key=
</code></pre>
<p>I run the following code:</p>
<pre><code>import requests
result = requests.get(url)
resu... | -1 | 2016-09-26T09:14:32Z | 39,718,856 | <p>There is no JSON in the response that is coming back to you, which is why it is giving the error. </p>
| 0 | 2016-09-27T07:40:16Z | [
"python",
"json",
"api",
"google-maps-api-3",
"google-street-view"
] |
HttpIO - Consuming external resources in a Dataflow transform | 39,698,886 | <p>I'm trying to write a custom <code>Source</code> using the Python Dataflow SDK to read JSON data in parallel from a REST endpoint.</p>
<p>E.g. for a given set of IDs, I need to retrieve the data from:
<code>
https://foo.com/api/results/1
https://foo.com/api/results/2
...
https://foo.com/api/results/{maxID}
</code><... | 0 | 2016-09-26T09:14:41Z | 39,776,506 | <p>Dataflow does not currently have a built-in way of doing global rate-limiting, but you can use the Source API to do this. The key concept is that each split of a Source will be processed by a single thread at most, so you can implement local rate limiting separately for each split.</p>
<p>This solution does not us... | 1 | 2016-09-29T17:26:13Z | [
"python",
"google-cloud-dataflow",
"google-cloud-pubsub",
"airflow"
] |
how to properly use a unicode string in python regex | 39,698,935 | <p>I am getting an input regular expression from a user which is saved as a unicode string. Do I have to turn the input string into a raw string before compliling it as a regex object? Or is it unnecessary? Am I converting it to raw string properly?</p>
<pre><code>import re
input_regex_as_unicode = u"^(.){1,36}$"
stri... | -1 | 2016-09-26T09:16:46Z | 39,700,258 | <p>The <code>re</code> module handles both unicode strings and normal strings properly, you do not need to convert them to anything (but you should be consistent in your use of strings).</p>
<p>There is no such a thing like "raw strings". You can use raw string notation in your code if it helps you with strings contai... | 1 | 2016-09-26T10:20:02Z | [
"python",
"regex",
"python-2.7"
] |
How to store output of a python program in command prompt? | 39,699,061 | <p>I'm passing run time variable from command prompt to python to execute there (im=n python). Now I want to store the result of python program and use those results back into command prompt. Sample is as follows</p>
<pre><code>set input=
set /P input=Enter Layer Name:%=%
C:\Python27\python.exe F:\xampp\htdocs\flood_p... | 0 | 2016-09-26T09:23:10Z | 39,699,140 | <p>Assuming its a bash script from where you are calling the python function, it should be done like:</p>
<pre><code>function callPython()
{
local pythonResult=<code for calling python>
echo $pythonResult
}
local pythonReturnOutput = $(callPython)
</code></pre>
<p>and you can now use pythonReturnOutput... | -1 | 2016-09-26T09:26:37Z | [
"python",
"shell",
"cmd",
"runtime",
"parameter-passing"
] |
How to store output of a python program in command prompt? | 39,699,061 | <p>I'm passing run time variable from command prompt to python to execute there (im=n python). Now I want to store the result of python program and use those results back into command prompt. Sample is as follows</p>
<pre><code>set input=
set /P input=Enter Layer Name:%=%
C:\Python27\python.exe F:\xampp\htdocs\flood_p... | 0 | 2016-09-26T09:23:10Z | 39,699,297 | <p>Let me know if this helps.</p>
<p><strong>Code of python file (c.py):</strong></p>
<pre><code>import sys
print('You passed ',sys.argv[1])
</code></pre>
<p><strong>Windows Batch Code (a.bat) :</strong></p>
<pre><code>@echo off
set input=
set /P input=Enter Layer Name:%=%
(python c.py %input%) > tmp.txt
se... | 1 | 2016-09-26T09:34:26Z | [
"python",
"shell",
"cmd",
"runtime",
"parameter-passing"
] |
How to store output of a python program in command prompt? | 39,699,061 | <p>I'm passing run time variable from command prompt to python to execute there (im=n python). Now I want to store the result of python program and use those results back into command prompt. Sample is as follows</p>
<pre><code>set input=
set /P input=Enter Layer Name:%=%
C:\Python27\python.exe F:\xampp\htdocs\flood_p... | 0 | 2016-09-26T09:23:10Z | 39,699,455 | <p>It is depending on the case. If your Python code is exiting a value (with <code>exit(<returncode>)</code>), you can retrieve it from the <code>%ERRORLEVEL%</code> environment variable.</p>
<pre><code><yourpythoncommand>
echo Return code: %ERRORLEVEL%
</code></pre>
<p>If you are willing to capture and p... | 0 | 2016-09-26T09:41:56Z | [
"python",
"shell",
"cmd",
"runtime",
"parameter-passing"
] |
Spark RDD to DataFrame python | 39,699,107 | <p>I am trying to convert the Spark RDD to a DataFrame. I have seen the documentation and example where the scheme is passed to
<code>sqlContext.CreateDataFrame(rdd,schema)</code> function. </p>
<p>But I have 38 columns or fields and this will increase further. If I manually give the schema specifying each field info... | 0 | 2016-09-26T09:24:49Z | 39,705,464 | <p>See,</p>
<p>There is two ways of convert an RDD to DF in spark.</p>
<p><code>toDF()</code> and <code>createDataFrame(rdd, schema)</code></p>
<p>I will show you how you can do that dynamically.</p>
<h2>toDF()</h2>
<p>The <code>toDF()</code> command gives you the way to convert an <code>RDD[Row]</code> to a Dataf... | 0 | 2016-09-26T14:25:32Z | [
"python",
"apache-spark",
"pyspark",
"spark-dataframe"
] |
Create a function that sorts customers of the bank by amount of money | 39,699,257 | <p>I'm learning how to use Classes, so far I have achieved the following:</p>
<pre><code>class customer:
def __init__ (self, name, ID, money):
self.name = name
self.ID = ID
self.money = money
def deposit(self, amount):
self.money = self.money+amount
def withdraw(self, amount... | 0 | 2016-09-26T09:32:20Z | 39,699,423 | <pre><code>def sort_by_money(customer)
for index in range(1,len(customer)):
currentvalue = customer[index].money
position = index
while position>0 and customer[position-1].money > currentvalue:
alist[position]=alist[position-1]
position = position-1
cu... | -1 | 2016-09-26T09:40:15Z | [
"python",
"python-2.7",
"function",
"class",
"initialization"
] |
Create a function that sorts customers of the bank by amount of money | 39,699,257 | <p>I'm learning how to use Classes, so far I have achieved the following:</p>
<pre><code>class customer:
def __init__ (self, name, ID, money):
self.name = name
self.ID = ID
self.money = money
def deposit(self, amount):
self.money = self.money+amount
def withdraw(self, amount... | 0 | 2016-09-26T09:32:20Z | 39,699,532 | <p>You can sort a list of objects in place by an attribute like this:</p>
<pre><code>your_list.sort(key=lambda x: x.attribute_name, reverse=True)
</code></pre>
<p>If you set <code>reverse=False</code>, the list is ordered ascending, with <code>reverse=True</code> it is sorted from highest amount to lowest.</p>
<p>So... | 3 | 2016-09-26T09:45:21Z | [
"python",
"python-2.7",
"function",
"class",
"initialization"
] |
How to check whether particular column completely match or not | 39,699,312 | <p>I would like to compare particular column with the other one.
For instance,when I compare A column with B by using some method,
it should return False.</p>
<pre><code> A B
0 1 2
1 2 2
2 3 3
3 4 4
</code></pre>
<p>when I try</p>
<pre><code>df.A==df.B
</code></pre>
<p>But this returns whether ... | 1 | 2016-09-26T09:35:25Z | 39,699,332 | <p>You want to use <code>all</code></p>
<pre><code>(df.A == df.B).all()
</code></pre>
<hr>
<pre><code>df.A.eq(df.B)
0 False
1 True
2 True
3 True
dtype: bool
</code></pre>
<hr>
<pre><code>df.A.eq(df.B).all()
False
</code></pre>
| 5 | 2016-09-26T09:36:18Z | [
"python",
"pandas",
"dataframe"
] |
How to check whether particular column completely match or not | 39,699,312 | <p>I would like to compare particular column with the other one.
For instance,when I compare A column with B by using some method,
it should return False.</p>
<pre><code> A B
0 1 2
1 2 2
2 3 3
3 4 4
</code></pre>
<p>when I try</p>
<pre><code>df.A==df.B
</code></pre>
<p>But this returns whether ... | 1 | 2016-09-26T09:35:25Z | 39,699,360 | <p>You can use <code>equals</code>:</p>
<pre><code>df['A'].equals(df['B'])
Out: False
</code></pre>
<p>This checks whether two Series are exactly the same - labels included.</p>
| 6 | 2016-09-26T09:37:37Z | [
"python",
"pandas",
"dataframe"
] |
Function to return elements from a list in Python | 39,699,418 | <p>I have a function:</p>
<pre><code>def funky(a):
c = [4,5,6]
return c[a]
</code></pre>
<p>I would like to be able to call:</p>
<pre><code>funky(0:1)
</code></pre>
<p>And</p>
<pre><code>funky(0,1)
</code></pre>
<p>To get the same response [4,5]. How do I modify 'funky' to do this?</p>
| 0 | 2016-09-26T09:39:59Z | 39,699,508 | <p>Enter slice(0, 1) as a parameter to your function as is. 0:1 won't work ever as it is not a passable parameter. </p>
| 1 | 2016-09-26T09:44:25Z | [
"python",
"list"
] |
Function to return elements from a list in Python | 39,699,418 | <p>I have a function:</p>
<pre><code>def funky(a):
c = [4,5,6]
return c[a]
</code></pre>
<p>I would like to be able to call:</p>
<pre><code>funky(0:1)
</code></pre>
<p>And</p>
<pre><code>funky(0,1)
</code></pre>
<p>To get the same response [4,5]. How do I modify 'funky' to do this?</p>
| 0 | 2016-09-26T09:39:59Z | 39,699,519 | <p>You can use the slice method directly on the list:</p>
<pre><code>def funky(*a):
c = [4,5,6]
return c.__getitem__(*a)
print(funky(1, 3))
>>> [5, 6]
</code></pre>
| 4 | 2016-09-26T09:44:58Z | [
"python",
"list"
] |
Function to return elements from a list in Python | 39,699,418 | <p>I have a function:</p>
<pre><code>def funky(a):
c = [4,5,6]
return c[a]
</code></pre>
<p>I would like to be able to call:</p>
<pre><code>funky(0:1)
</code></pre>
<p>And</p>
<pre><code>funky(0,1)
</code></pre>
<p>To get the same response [4,5]. How do I modify 'funky' to do this?</p>
| 0 | 2016-09-26T09:39:59Z | 39,699,521 | <pre><code>def funky(a,b):
c = [4,5,6]
return c[a:b+1]
</code></pre>
<p>And you can call <code>funky(0,1)</code>, And you cant't call like <code>funky(</code>0:1<code>)</code>. It's not a valid parameter.</p>
<p>You can call like <code>funky('0:1')</code> Because. If you need to take that kind of input take a... | 1 | 2016-09-26T09:45:08Z | [
"python",
"list"
] |
Push notifications with minimal data usage | 39,699,461 | <p>In my project, I want to call an action on a Raspberry Pi from the Internet. Somehow like that:</p>
<ol>
<li>Visit webpage</li>
<li>Hit a button on the webpage</li>
<li>Raspberry pi executes a script</li>
</ol>
<p>The difficult part is, that the raspberry pi only has a mobile Internet connection <em>without a flat... | 1 | 2016-09-26T09:42:09Z | 39,701,872 | <p>Start off by creating or starting something that accepts incoming connections on your RPi. Something small as the below example would do:</p>
<pre><code>#!/usr/bin/python
from socket import *
s = socket()
s.bind(('', 8001))
s.listen(4)
while 1:
ns, na = s.accept()
print(na,'sent you:',ns.recv(8192))
</code>... | 1 | 2016-09-26T11:40:34Z | [
"python",
"web",
"push-notification",
"connection",
"network-protocols"
] |
Creating a list based on column conditions | 39,699,659 | <p>I have a DataFrame <code>df</code></p>
<pre><code>>>df
LED CFL Incan Hall Reading
0 3 2 1 100 150
1 2 3 1 150 100
2 0 1 3 200 150
3 1 2 4 300 250
4 3 3 1 170 100
</code></pre>
<p>I want to create two more column which contain <code>... | 1 | 2016-09-26T09:52:18Z | 39,708,691 | <p>I shorten your formula for simplicity sake but you should use df.apply(axis=1)</p>
<p>this take every row and return and ndarray, then you can apply whatever function you want such has :</p>
<pre><code>df = pd.DataFrame([[3, 2, 1, 100, 150], [2, 3, 1, 150, 100]], columns=['LED', 'CFL', 'Incan', 'Hall', 'Reading'])... | 0 | 2016-09-26T17:16:55Z | [
"python",
"pandas"
] |
pyqtgraph custom scaling issue | 39,699,702 | <p>I use the pyqtgraph library for plotting. I really like the mouse interaction on the plot (zoom, pan, ...).</p>
<p>For some of my plots I would like to change the zoom behaviour when you scroll the mousewheel. The standard implementation is a scaling in both x- and y-direction simultaneously. Scaling in the x-direc... | 0 | 2016-09-26T09:54:32Z | 39,702,394 | <p>My collegue pointed out that I have to add <code>self</code> as first argument when overriding the <code>wheelEvent</code> function:</p>
<pre><code># Override the pg.ViewBox class to add custom
# implementations to the wheelEvent
class CustomViewBox(pg.ViewBox):
def __init__(self, *args, **kwds):
pg.Vie... | 0 | 2016-09-26T12:07:42Z | [
"python",
"python-3.x",
"pyqt4",
"pyqtgraph"
] |
How to create multiple VideoCapture Obejcts | 39,699,796 | <p>I wanted to create multiple VideoCapture Objects for stitching video from multiple cameras to a single video mashup.</p>
<p>for example: I have path for three videos that I wanted to be read using Video Capture object shown below to get the frames from individual videos,so they can be used for writing.</p>
<p>Expe... | -1 | 2016-09-26T09:58:33Z | 39,702,933 | <p>I'm not a python pgogrammer, but probably the solution is something like:</p>
<pre><code>frames=[]
caps=[]
for path in videoList:
indices=[]
caps.append (cv2.VideoCapture(path) )
for cap in caps:
frames=[]
if(cap.isOpened()):
ret,frame=cap.read()
frames.append(frame)
else
... | 1 | 2016-09-26T12:32:34Z | [
"python",
"opencv",
"video",
"video-capture",
"video-processing"
] |
Access denied to Azure storage | 39,699,809 | <p>I am storing images on Azure storage. BUt after storing images when I am trying to access bob url it is giving me access denied error. </p>
<p>My code : </p>
<pre><code>block_blob_service = BlockBlobService(account_name=ACCOUNT_NAME, account_key=ACCOUNT_KEY)
block_blob_service.create_container('organisation', publ... | 0 | 2016-09-26T09:59:19Z | 39,721,864 | <p>Per my experience, the reason for this issue may be that your code does some suspicious access to the on-premises site directory. You could test whether you could get the image URL by running the following code. If you could see the image URL in the console, that indicates you have the access to your azure storage.... | 0 | 2016-09-27T10:06:59Z | [
"python",
"django",
"azure",
"windows-azure-storage",
"azure-storage-blobs"
] |
Adding results from a for loop to a dictionary , and then appending to a list | 39,699,827 | <p>I'm aware that this is really simply , but I'm struggling with this. Basically I want to add the results of a for loop inside a dicionary, so i can work the results on another function, which i can print the desired field based on the key value, </p>
<p>Example:</p>
<pre><code> i = 0
b = 0
cc = []
w... | 0 | 2016-09-26T09:59:55Z | 39,699,942 | <p>Based on your expected outcome, I would suggest this:</p>
<pre><code>cc = []
for i in range(0,3):
cc.append({str(i): i})
</code></pre>
<p>But please note that you do <strong>NOT</strong> get a dictionary at the end of this loop... What you get is a list of dictionaries, each dictionary featuring only one key-v... | 4 | 2016-09-26T10:05:28Z | [
"python",
"python-2.7"
] |
Python: extract text from string | 39,699,853 | <p>I try to extract text from url request, but not all dict contain key with text, and when I try to use <code>{k: v[0] for k, v in parse_qs(str).items()}</code> to urls, I lose a lot of requests, so I try <code>str = urllib.unquote(u[0])</code>.
After that I get strings like</p>
<pre><code>ÑмоÑÑеÑÑ Ð»ÑÑÑе... | 0 | 2016-09-26T10:01:27Z | 39,700,043 | <p>Just split by <code>&</code> and take the first part:</p>
<pre><code>txt = urllib.unquote(u[0]).split("&")[0]
</code></pre>
<p>And don't use <code>str</code> as a variable name - it's a built-in type name in Python.</p>
<p><strong>EDIT:</strong>
Unfortunatelly this <code>2&clid=1976874&win=85&... | 1 | 2016-09-26T10:09:48Z | [
"python",
"regex",
"urlparse"
] |
Excel cell values filled with 0 | 39,699,960 | <p>The part of code shown below </p>
<pre><code>import collections
import csv
import sys
with open("321.csv","r") as f:
cr = csv.reader(f,delimiter=",")
d=collections.defaultdict(lambda : list())
header=next(cr) # read title. Retrieve the next item from the iterator by calling its __next__() method.
... | 0 | 2016-09-26T10:06:11Z | 39,700,331 | <p>I have not tested but perhaps this?</p>
<pre><code>import collections
import csv
import sys
max_len = 0
with open("321.csv","r") as f:
cr = csv.reader(f,delimiter=",")
d=collections.defaultdict(lambda : list())
header=next(cr) # read title. Retrieve the next item from the iterator by calling its __ne... | 2 | 2016-09-26T10:23:39Z | [
"python",
"excel"
] |
Excel cell values filled with 0 | 39,699,960 | <p>The part of code shown below </p>
<pre><code>import collections
import csv
import sys
with open("321.csv","r") as f:
cr = csv.reader(f,delimiter=",")
d=collections.defaultdict(lambda : list())
header=next(cr) # read title. Retrieve the next item from the iterator by calling its __next__() method.
... | 0 | 2016-09-26T10:06:11Z | 39,700,830 | <p>I'm not quite sure if I understand your question correctly. Here is an attempt:</p>
<p>To create a xls file that has just 0's an alternative could be to use pandas and numpy as follows:</p>
<pre><code>import pandas as pd
import numpy as np
import io
number_of_rows = 30
number_of_columns = 24
# Create a dataframe... | 1 | 2016-09-26T10:47:57Z | [
"python",
"excel"
] |
xml minidom - get the full content of childnodes text | 39,700,025 | <p>I have a Test.xml file as:</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<SetupConf>
<LocSetup>
<Src>
<Dir1>C:\User1\test1</Dir1>
<Dir2>C:\User2\log</Dir2>
<Dir3>D:\Users\Checkup</Dir3>
<Dir4>D:\Work1</Dir4&... | -1 | 2016-09-26T10:08:59Z | 39,701,330 | <p>Well it's solved by myself:</p>
<pre><code>from xml.dom import minidom
DOMTree = minidom.parse('Test0001.xml')
dom = DOMTree.documentElement
Src = dom.getElementsByTagName('Src')
for node in Src:
output = [a.childNodes[0].nodeValue for a in node.getElementsByTagName('Dir')]
print output
</code></pre>
<h... | 0 | 2016-09-26T11:13:25Z | [
"python",
"xml"
] |
For Loops in Python (Output Smallest Input) | 39,700,100 | <p>Okay so I am practicing for loops in Python and I was wondering how could I make a user input 10 intergers then it would output the smallest one. I would know how to do this with a while loop for example: </p>
<pre><code>Smallest = 0
count = 0
while count < 10:
Number = int(input("Enter a number >> ")... | 1 | 2016-09-26T10:12:56Z | 39,700,199 | <p>What you have there, other than the fact you should initialise <code>Smallest</code>, is equivalent to the solution using your <code>while</code> statement.</p>
<p>So, assuming the <code>while</code> variant is considered correct, the <code>for</code> variant you have will suffice.</p>
<p>The reason I qualify it i... | 2 | 2016-09-26T10:17:20Z | [
"python",
"loops",
"for-loop"
] |
For Loops in Python (Output Smallest Input) | 39,700,100 | <p>Okay so I am practicing for loops in Python and I was wondering how could I make a user input 10 intergers then it would output the smallest one. I would know how to do this with a while loop for example: </p>
<pre><code>Smallest = 0
count = 0
while count < 10:
Number = int(input("Enter a number >> ")... | 1 | 2016-09-26T10:12:56Z | 39,700,256 | <p>If you want to get the smallest of the input numbers, you need to start with a minimum a bit bigger than 0... and that is a problem you have with your while loop. It will only work if the user inputs at least one negative number, else it will return <code>0</code>.</p>
<p>Here is what I suggest:</p>
<pre><code>sma... | 1 | 2016-09-26T10:19:57Z | [
"python",
"loops",
"for-loop"
] |
For Loops in Python (Output Smallest Input) | 39,700,100 | <p>Okay so I am practicing for loops in Python and I was wondering how could I make a user input 10 intergers then it would output the smallest one. I would know how to do this with a while loop for example: </p>
<pre><code>Smallest = 0
count = 0
while count < 10:
Number = int(input("Enter a number >> ")... | 1 | 2016-09-26T10:12:56Z | 39,700,332 | <p>Initialize your Smallest variable and all will works!</p>
<pre><code>Smallest = int(input("Enter a Number >> "))
for i in range(9):
Number = int(input("Enter a Number >> "))
if Number < Smallest:
Smallest = Number
print("{0} is the smallest value you have entered.".format(Smallest))
... | 3 | 2016-09-26T10:23:40Z | [
"python",
"loops",
"for-loop"
] |
For Loops in Python (Output Smallest Input) | 39,700,100 | <p>Okay so I am practicing for loops in Python and I was wondering how could I make a user input 10 intergers then it would output the smallest one. I would know how to do this with a while loop for example: </p>
<pre><code>Smallest = 0
count = 0
while count < 10:
Number = int(input("Enter a number >> ")... | 1 | 2016-09-26T10:12:56Z | 39,700,631 | <p>Since you are finding the Smallest values out of the input values from the user it is good practice to initially initialize the Smallest variable as maximum possible integer as below.</p>
<pre><code>import sys
Smallest = sys.maxint
</code></pre>
<p>Then the rest of your loop will work as properly as it is.</p>
| 0 | 2016-09-26T10:38:01Z | [
"python",
"loops",
"for-loop"
] |
Python: subprocess Popen requires to be joined? | 39,700,122 | <p>i have a daemon running which gets command and executes it by:</p>
<pre><code>subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
</code></pre>
<p>I never do anything with it afterwards, no <code>wait()</code>, no <code>communicate()</code></p>
<p>is that okay to do so?<br>
or are joining of the... | 0 | 2016-09-26T10:14:12Z | 39,700,493 | <p>Since you set <code>stdout=subprocess.PIPE, stderr=subprocess.PIPE</code>, and if you want to get the stdout, you can do this:</p>
<pre><code>p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
for line in p.stdout:
# do something here
#...
</code></pre>
<p>As you say the <code>cmd</c... | 0 | 2016-09-26T10:31:20Z | [
"python",
"subprocess"
] |
How can I get Python to plugin my password and Username for an .exe file it opened | 39,700,155 | <p>Hey guys I'm new to programming and I would appreciate some help. My program can open an application I have but to enter the application it requires a password and username which I don't know how to make my program plug in automatically.</p>
<pre><code>os.system('"C:\\abc\\123\\Filepath\\File.exe"')
</code></pre>
... | 0 | 2016-09-26T10:15:20Z | 39,700,745 | <p>What you need is Pywinauto, which can make simple windows operations automatically. Please have a look at below Pywinauto website, there is an example to open Notepad and input "Hello World" automatically.
<a href="https://pywinauto.github.io/" rel="nofollow">https://pywinauto.github.io/</a></p>
<p>I have another e... | 1 | 2016-09-26T10:43:43Z | [
"python",
"passwords",
"username",
"os.system"
] |
Django save Base64 image | 39,700,158 | <p>I am accepting a POST from iOS and my django code is</p>
<pre><code> image =self.request.DATA.get('image')
image_data =base64.b64decode(image)
img=ContentFile(image_data,'myImage.jpg')
</code></pre>
<p>but when i save it in django it is currupted any ideas why</p>
<p>Here is my base64image<... | 1 | 2016-09-26T10:15:29Z | 39,700,328 | <pre><code># Python 2.7
f = open("yourfile.png", "wb")
f.write(your_base_string.decode('base64'))
f.close()
# or
with open("yourfile.png", "wb") as f:
fhfwrite(imgData.decode('base64'))
</code></pre>
| 1 | 2016-09-26T10:23:30Z | [
"python",
"django",
"base64"
] |
Django 1.8 startup delay troubleshooting | 39,700,254 | <p>I'm trying to discover the cause of delays in Django 1.8 startup, especially, but not only, when run in a debugger (WingIDE 5 and 6 in my case).</p>
<p>Minimal test case: the Django 1.8 tutorial "poll" example, completed just to the first point where 'manage.py runserver' works. All default configuration, using SQL... | 0 | 2016-09-26T10:19:51Z | 39,736,367 | <p>A partial answer.</p>
<p>After some time with WingIDE IDE's debugger, and some profiling with cProfile, I have located the main CPU hogging issue. </p>
<p>During initial django startup there's a cascade of imports, in which module validators.py prepares some compiled regular expressions for later use. One in parti... | 0 | 2016-09-28T00:47:06Z | [
"python",
"django"
] |
Search Keys and Replace Values in XML | 39,700,390 | <p>I have an xml file which looks like below</p>
<pre><code><name>abcdefg</name>
<value>123456</value>
</code></pre>
<p>I am trying to write a script using sed to search for the tag "abcdefg" and then <strong>replace the corresponding value</strong> "123456" but unfortunately I am not able to ... | 0 | 2016-09-26T10:26:53Z | 39,700,635 | <p>Sample data used:</p>
<pre><code> cat key
<name>abcdaaefg</name>
<value>123456</value>
<name>abcdefg</name>
<value>123456</value>
<name>abcdaaefg</name>
<value>123456</value>
</code></pre>
<p><code>sed</code> solution:</p>
<pre><code> sed '/a... | 2 | 2016-09-26T10:38:12Z | [
"python",
"xml",
"shell",
"replace",
"sed"
] |
Search Keys and Replace Values in XML | 39,700,390 | <p>I have an xml file which looks like below</p>
<pre><code><name>abcdefg</name>
<value>123456</value>
</code></pre>
<p>I am trying to write a script using sed to search for the tag "abcdefg" and then <strong>replace the corresponding value</strong> "123456" but unfortunately I am not able to ... | 0 | 2016-09-26T10:26:53Z | 39,710,159 | <p>Whenever you have tag->value pairs in your data it's a good idea to create a tag->value array in your code:</p>
<pre><code>$ awk -F'[<>]' '{tag=$2; v[tag]=$3} tag=="value" && v["name"]=="abcdefg" {sub(/>.*</,">blahblah<")} 1' file
<name>abcdefg</name>
<value>blahblah</... | 0 | 2016-09-26T18:46:01Z | [
"python",
"xml",
"shell",
"replace",
"sed"
] |
Search Keys and Replace Values in XML | 39,700,390 | <p>I have an xml file which looks like below</p>
<pre><code><name>abcdefg</name>
<value>123456</value>
</code></pre>
<p>I am trying to write a script using sed to search for the tag "abcdefg" and then <strong>replace the corresponding value</strong> "123456" but unfortunately I am not able to ... | 0 | 2016-09-26T10:26:53Z | 39,710,416 | <p>Use an XML-aware tool. This will make your approach far more robust: It means that tiny changes in the textual description (like added or removed newlines, or extra attributes added to a preexisting element) won't break your script.</p>
<p>Assuming that your input's structure looks like this (with being under a sin... | 0 | 2016-09-26T19:02:24Z | [
"python",
"xml",
"shell",
"replace",
"sed"
] |
regex to find all words after specific word? | 39,700,416 | <p>I have a string like below:</p>
<pre><code>Features: -Includes hanging accessories. -Artist: William-Adolphe Bouguereau. -Made with 100pct cotton canvas. -100pct Anti-shrink pine wood bars and Epson anti-fade ultra chrome inks. -100pct Hand-made and inspected in the U.S.A. -Orientation: Horizontal. **Subject... | 0 | 2016-09-26T10:28:06Z | 39,700,520 | <p>Your <code>(?<=subject)(.{30}(?:\s|.))</code> regex asserts the position after <code>subject</code>. then grabs 30 characters other than a linebreak symbol and then matches either a whitespace or any character but a linebreak symbol. This does not really fit your requirements as the substring can be of any length... | 1 | 2016-09-26T10:32:26Z | [
"python",
"regex",
"python-3.x",
"pattern-matching"
] |
regex to find all words after specific word? | 39,700,416 | <p>I have a string like below:</p>
<pre><code>Features: -Includes hanging accessories. -Artist: William-Adolphe Bouguereau. -Made with 100pct cotton canvas. -100pct Anti-shrink pine wood bars and Epson anti-fade ultra chrome inks. -100pct Hand-made and inspected in the U.S.A. -Orientation: Horizontal. **Subject... | 0 | 2016-09-26T10:28:06Z | 39,700,572 | <p>Try:</p>
<pre><code>re.compile('Subject: [^*]+')
</code></pre>
<p><a href="http://pythex.org/?regex=Subject%3A%20%5B%5E%5C*%5D%2B&test_string=Features%3A%20%20-Includes%20hanging%20accessories.%20%20-Artist%3A%20William-Adolphe%20Bouguereau.%20%20-Made%20with%20100pct%20cotton%20canvas.%20%20-100pct%20Anti-shr... | 0 | 2016-09-26T10:34:43Z | [
"python",
"regex",
"python-3.x",
"pattern-matching"
] |
regex to find all words after specific word? | 39,700,416 | <p>I have a string like below:</p>
<pre><code>Features: -Includes hanging accessories. -Artist: William-Adolphe Bouguereau. -Made with 100pct cotton canvas. -100pct Anti-shrink pine wood bars and Epson anti-fade ultra chrome inks. -100pct Hand-made and inspected in the U.S.A. -Orientation: Horizontal. **Subject... | 0 | 2016-09-26T10:28:06Z | 39,700,850 | <p><strong>Regex:</strong></p>
<pre><code>(Subject:.+)\*\*
Match Subject and content after that till '**'
</code></pre>
<p><strong>Code:</strong></p>
<pre><code>str = 'Features: -Includes hanging accessories. -Artist: William-Adolphe Bouguereau. -Made with 100pct cotton canvas. -100pct Anti-shrink pine wood bar... | 0 | 2016-09-26T10:49:09Z | [
"python",
"regex",
"python-3.x",
"pattern-matching"
] |
Python Statsmodels: Using SARIMAX with exogenous regressors to get predicted mean and confidence intervals | 39,700,424 | <p>I'm using statsmodels.tsa.SARIMAX() to train a model with exogenous variables. Is there an equivalent of get_prediction() when a model is trained with exogenous variables so that the object returned contains the predicted mean and confidence interval rather than just an array of predicted mean results? The predict()... | 1 | 2016-09-26T10:28:24Z | 40,032,857 | <p>There has been some backward compatibility related issues due to which full results (with pred intervals etc) are not being exposed. </p>
<p>To get you what you want now: Use get_prediction and get_forecast functions with parameters described below</p>
<pre><code> pred_res = sarimax_model.get_prediction(exog=Ex... | 1 | 2016-10-13T23:55:36Z | [
"python",
"time-series",
"forecasting",
"statsmodels",
"confidence-interval"
] |
Application started in Crontab, problems in communication between Nodejs and python | 39,700,599 | <p>I have developed an Bluetooth peripheral software (app.js) for Raspberry Pi using <a href="https://github.com/sandeepmistry/bleno" rel="nofollow">BLENO </a>NodeJS library. Inside my NodeJS application I'm calling some python script using <a href="https://github.com/extrabacon/python-shell" rel="nofollow">python-shel... | 0 | 2016-09-26T10:36:26Z | 39,703,232 | <p>Found a solution to my problem. Originally I started application from crontab using @reboot field. Instead of crontab, I started my application from /etc/init.d/. That fixed the problem. Maybe someone could explain the reason.</p>
| 0 | 2016-09-26T12:45:22Z | [
"python",
"node.js",
"raspberry-pi",
"bleno"
] |
Define date format in Python / Pandas | 39,700,636 | <p>I have two .csv files joined in Python with the Pandas module. One column is date with the format "dd.mm.yyyy".</p>
<p>Now I would like to extract only the month (as 2 digit integer with leading zero) from it for further use.</p>
<p>I have so far accomplished the job but I had to cheat. Python thinks the string th... | 0 | 2016-09-26T10:38:14Z | 39,700,874 | <p>First it seems you have swap month and day in datetime, so you need add argument <code>format='%Y-%d-%m'</code> to <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_datetime.html" rel="nofollow"><code>to_datetime</code></a> (<a href="http://strftime.org/" rel="nofollow">Python's strftime direc... | 1 | 2016-09-26T10:50:09Z | [
"python",
"python-2.7",
"csv",
"pandas"
] |
Define date format in Python / Pandas | 39,700,636 | <p>I have two .csv files joined in Python with the Pandas module. One column is date with the format "dd.mm.yyyy".</p>
<p>Now I would like to extract only the month (as 2 digit integer with leading zero) from it for further use.</p>
<p>I have so far accomplished the job but I had to cheat. Python thinks the string th... | 0 | 2016-09-26T10:38:14Z | 39,700,945 | <p>You could supply the format you want to keep in the arg of <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_datetime.html" rel="nofollow"><code>to_datetime</code></a>:</p>
<pre><code>pd.to_datetime(df['date_col'], format="%d.%m.%Y").dt.month.astype(str).str.zfill(2)
</code></pre>
| 1 | 2016-09-26T10:53:54Z | [
"python",
"python-2.7",
"csv",
"pandas"
] |
Understanding Django queryset field lookup in | 39,700,644 | <p>Short version: Why does Model.objects.exclude(..__in=[None]) exclude every object?</p>
<p>I have encountered an interesting behaviour of django field lookup that I do not understand. Let's say I have 21 objects of a given model:</p>
<pre><code>>>> Model.objects.count()
21
</code></pre>
<p>If I exclude a ... | 1 | 2016-09-26T10:38:28Z | 39,701,025 | <p>I suspect this is because of the way SQL treats NULL. The query compiles to <code>SELECT COUNT(*) FROM mymodel WHERE NOT (id IN (NULL));</code>.</p>
<p>See for example <a href="http://stackoverflow.com/questions/129077/not-in-clause-and-null-values">this question</a> for a discussion of why NOT IN with NULL always ... | 2 | 2016-09-26T10:57:27Z | [
"python",
"django-queryset"
] |
Remove duplicates of IP addresses by netmask | 39,700,746 | <p>I have got an Array: </p>
<pre><code>[192.0.0.3, 0.0.0.0 , 192.0.10.24, ...]
</code></pre>
<p>With IP addresses and i want to remove duplicates for the /16 netmasks, so i got 192.0.0.3 but 192.0.10.24 will be removed (i don't mind which one of them, it would also be okay if the first one is removed). </p>
<p>My f... | 1 | 2016-09-26T10:43:46Z | 39,700,881 | <p>You could remove duplicates using a set, with the keys being tuples of the first two parts:</p>
<pre><code>>>> ips = ["192.0.0.3", "0.0.0.0", "192.0.10.24"]
>>> seen = set()
>>> for ip in ips:
... key = tuple(ip.split(".")[:2])
... if key not in seen:
... print(ip)
... ... | 1 | 2016-09-26T10:50:42Z | [
"python",
"arrays",
"set"
] |
Remove duplicates of IP addresses by netmask | 39,700,746 | <p>I have got an Array: </p>
<pre><code>[192.0.0.3, 0.0.0.0 , 192.0.10.24, ...]
</code></pre>
<p>With IP addresses and i want to remove duplicates for the /16 netmasks, so i got 192.0.0.3 but 192.0.10.24 will be removed (i don't mind which one of them, it would also be okay if the first one is removed). </p>
<p>My f... | 1 | 2016-09-26T10:43:46Z | 39,701,492 | <p>You could use a dictionary:</p>
<pre><code>>>> res = {}
>>> for ip in ["192.0.0.3", "0.0.0.0", "192.0.10.24"]:
... res[tuple(ip.split('.',2)[0:2])]=ip
>>> res.values()
['0.0.0.0', '192.0.10.24']
</code></pre>
<p>If you need the first occurence rather than the last one, a quick and dir... | 1 | 2016-09-26T11:21:14Z | [
"python",
"arrays",
"set"
] |
How to sum values in treeview line using onchange event in odoo 9 | 39,700,777 | <p>I got a parent model and a child model, here is the code :</p>
<pre><code>class parent_model(osv.osv):
_name = 'parent_model'
_columns = {
'line_ids' : fields.one2many('child_model', 'line_id', 'Line ID', ondelete='cascade'),
'description' : fields.text('Description', required=True),
... | 1 | 2016-09-26T10:45:31Z | 39,717,880 | <p>1st: move everything to new api.</p>
<p>Add an onchange <strong>to the parent model</strong> hooked to <code>line_ids</code>, like:
<code>
@api.onchange('line_ids')
def _onchange_line_ids(self):
</code></p>
| 0 | 2016-09-27T06:50:36Z | [
"python",
"openerp",
"odoo-9"
] |
I am using jinja and want to pass a variable into a URL but it is now happening. | 39,700,818 | <pre><code>{% for x in data %}
<tr class="table-row">
<td>{{ forloop.counter }}</td>
<td><label>{{ x.0 }}</label></td>
<td><img src="{% static 'lang/hi_IN/font/**x.1**' %}"></td>
<td><label style="font-size:20px"> {{ x.2 ... | 0 | 2016-09-26T10:47:24Z | 39,700,908 | <p>I have never used jinja or django, but I believe you just need to separate the variable form the string.</p>
<pre><code><td><img src="{% static 'lang/hi_IN/font/' + x.1 %}"></td>
</code></pre>
<p>or the equivalent of this in jinja.</p>
| 0 | 2016-09-26T10:51:59Z | [
"python",
"html",
"django-templates",
"jinja2"
] |
I am using jinja and want to pass a variable into a URL but it is now happening. | 39,700,818 | <pre><code>{% for x in data %}
<tr class="table-row">
<td>{{ forloop.counter }}</td>
<td><label>{{ x.0 }}</label></td>
<td><img src="{% static 'lang/hi_IN/font/**x.1**' %}"></td>
<td><label style="font-size:20px"> {{ x.2 ... | 0 | 2016-09-26T10:47:24Z | 39,701,196 | <p>I don't know <code>static</code> keyword in Jinja2. Maybe everything is much simpler:</p>
<pre><code><td><img src="lang/hi_IN/font/{{ x.1 }}"></td>
</code></pre>
<p>Or the problem may be deeper. Did you implement serving methods? It should looks like:</p>
<pre><code>@app.route('/media/<path:f... | 0 | 2016-09-26T11:06:50Z | [
"python",
"html",
"django-templates",
"jinja2"
] |
I am using jinja and want to pass a variable into a URL but it is now happening. | 39,700,818 | <pre><code>{% for x in data %}
<tr class="table-row">
<td>{{ forloop.counter }}</td>
<td><label>{{ x.0 }}</label></td>
<td><img src="{% static 'lang/hi_IN/font/**x.1**' %}"></td>
<td><label style="font-size:20px"> {{ x.2 ... | 0 | 2016-09-26T10:47:24Z | 39,706,022 | <p>I'm new to jinja2 templates and mostly I work with Flask, but with jinja2 I would try this:</p>
<pre><code><img src="{{ url_for('static', filename='lang/hi_IN/font/')}}{{x.1}}">
</code></pre>
<p>And this is blind guess that I came up after reading about <strong>static</strong> in Django-Templates (from this... | 0 | 2016-09-26T14:53:53Z | [
"python",
"html",
"django-templates",
"jinja2"
] |
How to get and ascribe irregular numbers to objects? | 39,700,896 | <p>I am a beginner and I have a question.
I have datas in csv file, I can find 100 objects and irregular number of size number for each object. In one row I have a name of the object, its size and then these irregular numbers- for one name it can be 20 of then and for the other 40. </p>
<pre><code>import glob
import c... | 0 | 2016-09-26T10:51:38Z | 39,701,969 | <pre><code>with open('data.csv') as fp:
for line in fp:
data = line.split(',')
if data[0] == 'name':
result[name] = init_dict(name)
elif data[0] == 'weight' :
update_dict(data[1])
else:
update_dict(data[0])
</code></pre>
<p>basically you can just loop through the file and whe... | 0 | 2016-09-26T11:45:36Z | [
"python"
] |
Why use pandas.DataFrame.copy() for column extraction | 39,700,904 | <p>I've recently seen this kind of code:</p>
<pre><code>import pandas as pd
data = pd.read_csv('/path/to/some/data.csv')
colX = data['colX'].copy()
data.drop(labels=['colX'], inplace=True, axis=1)
</code></pre>
<p>I know that, to make an explicit copy of an object, I need <code>copy()</code>, but in this case, when e... | -1 | 2016-09-26T10:51:56Z | 39,720,157 | <p>@EdChum statet in the comments:</p>
<blockquote>
<p>the user may want to separate that column from the main df, of course if the user just wanted to delete that column then taking a copy is pointless if their intention is to delete the column but for instance they didn't take a copy and instead took a reference t... | 0 | 2016-09-27T08:48:09Z | [
"python",
"pandas"
] |
Find all the 'h2' tags that are children of a specific div with attribute 'id' and value 'column-left' | 39,701,173 | <p>Using BeautifulSoup, I tried the following:</p>
<pre><code>q = soup.div.find_all("div", { "id" : "column-left" }, "h2")
</code></pre>
<p>But this gives me the text of the <code><p></code> as well. I just want the h2 that are children of a specific div.</p>
| 0 | 2016-09-26T11:05:56Z | 39,701,237 | <p>Why are you accessing <code>soup.div</code>?</p>
<p>Try this:</p>
<pre><code>q = soup.find('div', { 'id' : 'column-left' }).find_all('h2')
</code></pre>
<p>Also find_all has optional parameter 'id', so you do not have to write attributes map</p>
<pre><code>q = soup.find('div', id='column-left').find_all('h2')
... | 0 | 2016-09-26T11:08:54Z | [
"python",
"web-scraping",
"beautifulsoup"
] |
Find all the 'h2' tags that are children of a specific div with attribute 'id' and value 'column-left' | 39,701,173 | <p>Using BeautifulSoup, I tried the following:</p>
<pre><code>q = soup.div.find_all("div", { "id" : "column-left" }, "h2")
</code></pre>
<p>But this gives me the text of the <code><p></code> as well. I just want the h2 that are children of a specific div.</p>
| 0 | 2016-09-26T11:05:56Z | 39,702,207 | <p>If you use a recent version of BeautifulSoup (and you should) you can just use a CSS selector, which might be easier to write and maintain anyway. e.g.:</p>
<pre><code>>>> from bs4 import beautifulsoup
>>> soup = BeautifulSoup('<div id=column-left><h2>Header</h2><p>Paragrap... | 0 | 2016-09-26T11:56:58Z | [
"python",
"web-scraping",
"beautifulsoup"
] |
How do I print out individual words within my list? | 39,701,500 | <p>I am trying to print each word from my list onto separate lines, however it is printing each letter onto individual lines</p>
<pre><code>Words = sentence.strip()
for word in sentence:
print (word)
</code></pre>
<p>My full code (for anyone wondering) is:</p>
<pre><code>import csv
file = open("Task2.csv", "w")
... | 0 | 2016-09-26T11:21:45Z | 39,701,541 | <p>You forgot to split sentence and use "Words" not "sentence" in first for loop.</p>
<pre><code>#file = open("Task2.csv", "w")
sentence = input("Please enter a sentence: ")
Words = sentence.split()
for word in Words:
print (word)
for s in Words:
Positions = Words.index(s)+1
#file.write(str(Words) + (str(... | 0 | 2016-09-26T11:23:54Z | [
"python"
] |
How do I print out individual words within my list? | 39,701,500 | <p>I am trying to print each word from my list onto separate lines, however it is printing each letter onto individual lines</p>
<pre><code>Words = sentence.strip()
for word in sentence:
print (word)
</code></pre>
<p>My full code (for anyone wondering) is:</p>
<pre><code>import csv
file = open("Task2.csv", "w")
... | 0 | 2016-09-26T11:21:45Z | 39,701,711 | <p>You need to used <a href="https://docs.python.org/3.6/library/stdtypes.html#str.split" rel="nofollow"><code>str.split()</code></a> instead of <a href="https://docs.python.org/3.6/library/stdtypes.html#str.strip" rel="nofollow"><code>str.strip()</code></a>.</p>
<p><a href="https://docs.python.org/3.6/library/stdtype... | 0 | 2016-09-26T11:32:35Z | [
"python"
] |
Export Python-Scopus API results into CSV | 39,701,525 | <p>I'm very new to Python so not sure if this can be done but I hope it can!</p>
<p>I have accessed the Scopus API and managed to run a search query which gives me the following results in a pandas dataframe:</p>
<pre><code> search-results
entry ... | 0 | 2016-09-26T11:23:12Z | 39,857,382 | <p>first you need to get all the results (see comments under question).
The data you need (search results) is inside the "entry" list.
You can extract that list and append it to a support list, iterating until you got all the results. Here i cycle and at every round i subtract the downloaded items (count) from the tota... | 0 | 2016-10-04T16:25:08Z | [
"python",
"csv",
"python-3.5",
"scopus"
] |
Python Script to Read CSV file and send birthday mail | 39,701,687 | <p>i need a help with writing a python script to send a Happy Birthday email after reading CSV file . The CSV file contains this </p>
<pre><code>user1,13-September-2016,email1
user2,19-October-2016,email2
user3,13-September-2016,email3
user4,25-August-2016,email44
</code></pre>
<p>So the script should match the birth... | -1 | 2016-09-26T11:31:39Z | 39,701,807 | <p>I think you should consider several modules:
1. pandas (to read and extract some data from csv)
2. time (to match the current date with the dates in the file)
3. smtplib (to send a mail)</p>
| 0 | 2016-09-26T11:37:18Z | [
"python",
"csv",
"smtp"
] |
Pretty print a JSON in Python 3.5 | 39,701,740 | <p>I want to pretty print a JSON file, but popular solutions: <a href="http://stackoverflow.com/questions/12943819/how-to-python-prettyprint-a-json-file">How to Python prettyprint a JSON file</a> dont work for me. </p>
<p>Code:</p>
<pre><code>import json, os
def load_data(filepath):
if not os.path.exists(filepat... | -1 | 2016-09-26T11:34:03Z | 39,701,858 | <p><code>json.dumps()</code> produces ASCII-safe JSON by default. If you want to retain non-ASCII data as Unicode codepoints, disable that default by setting <code>ensure_ascii=False</code>:</p>
<pre><code>print(json.dumps(data, indent=4, sort_keys=True, ensure_ascii=False))
</code></pre>
<p>which, for your sample da... | 3 | 2016-09-26T11:39:58Z | [
"python",
"json",
"pretty-print"
] |
Mapping multiple dataframe based on the matching columns | 39,701,779 | <p>I have 25 data frames which I need to merge and find recurrently occurring rows from all 25 data frames,
For example, my data frame looks like following, </p>
<pre><code>df1
chr start end name
1 12334 12334 AAA
1 2342 2342 SAP
2 3456 3456 SOS
3 4537 4537 ABR
df2
chr start end ... | 1 | 2016-09-26T11:35:38Z | 39,701,957 | <p>Using the <a href="https://docs.python.org/2/library/glob.html" rel="nofollow"><code>glob</code></a> module, you can use</p>
<pre><code>import os
from glob import glob
path = 'Fltered_vcfs'
f_names = glob(os.path.join(path, 'vcf_filtered*.*'))
</code></pre>
<p>Then, your dictionary can be created with <a href="... | 1 | 2016-09-26T11:44:50Z | [
"python",
"pandas",
"numpy",
"dataframe"
] |
How to screen print two columns of values from Pandas? | 39,701,881 | <p>Say I have a distribution which I have loaded in a <code>pandas</code> DataFrame. My data frame consists of 5 columns A to E, and I want to screen print the average and standard deviation next to each other:</p>
<pre><code>avg=df.mean()
stdev=df.std()
Avg St Dev
A 87.1717 A 1.354
B 87.... | 1 | 2016-09-26T11:40:54Z | 39,702,045 | <p>My suggestion would be creating a new DataFrame with 2 columns(Avg & St Dev), and then just print the new DataFrame.</p>
| 1 | 2016-09-26T11:49:16Z | [
"python",
"formatting",
"special-characters"
] |
How to screen print two columns of values from Pandas? | 39,701,881 | <p>Say I have a distribution which I have loaded in a <code>pandas</code> DataFrame. My data frame consists of 5 columns A to E, and I want to screen print the average and standard deviation next to each other:</p>
<pre><code>avg=df.mean()
stdev=df.std()
Avg St Dev
A 87.1717 A 1.354
B 87.... | 1 | 2016-09-26T11:40:54Z | 39,702,099 | <p>Maybe you could combine the two separate columns in a new dataframe (use pd.DataFrame(means,stds)). It should be easy to print this new dataframe with the columns next to each other (even though not most efficient).</p>
<p>Not sure if relevant, but you could use the pandas describe functionality? You can find it he... | 1 | 2016-09-26T11:51:49Z | [
"python",
"formatting",
"special-characters"
] |
Calling class that initiates UI class in python | 39,701,920 | <p>I have an issue while creating my small Python project. I am used to Java and this is still quite new to me.
The problem is i create a UI class from QtCreator. Then convert it to <code>.py</code> and import to my project. I have a class that for now is considered <code>main</code> that initiates and runs the UI cla... | 1 | 2016-09-26T11:42:47Z | 39,730,444 | <p>I'm not exactly sure I understand what you're asking for, but it would seem to be as simple as this:</p>
<pre><code>class Main(object):
def __init__(self):
self.window = MainPanelManager()
self.window.show()
class MainPanelManager(QtWidgets.QMainWindow, Ui_MainWindow):
def __in... | 0 | 2016-09-27T17:01:12Z | [
"python",
"pyqt",
"qt5",
"qt-creator"
] |
List length check not working in Sudoku checker | 39,701,964 | <p>I want to write some Python code to check that whether a matrix accords with the rule of Sudoku. My code is presented below:</p>
<pre><code>correct = [[1,2,3],
[2,3,1],
[3,1,2]]
incorrect = [[1,2,3,4],
[2,3,1,3],
[3,1,2,3],
[4,4,4,4]]
incorrect2 = [[1,2... | -1 | 2016-09-26T11:45:26Z | 39,702,280 | <p>You don't zeroing <code>j</code> variable in inner loops (both inner loops).</p>
<pre><code>i, j = 0, 0
while i < n:
checked = []
j = 0 # you need set j to zero in each run
# if you don't do this: j will be equal to n in second run
while j < n:
if matrix[i][j] not in checked:
... | 0 | 2016-09-26T12:00:18Z | [
"python"
] |
List length check not working in Sudoku checker | 39,701,964 | <p>I want to write some Python code to check that whether a matrix accords with the rule of Sudoku. My code is presented below:</p>
<pre><code>correct = [[1,2,3],
[2,3,1],
[3,1,2]]
incorrect = [[1,2,3,4],
[2,3,1,3],
[3,1,2,3],
[4,4,4,4]]
incorrect2 = [[1,2... | -1 | 2016-09-26T11:45:26Z | 39,702,462 | <p>The problem is you're not initializing <code>j</code> properly for the two inner while loops. Here's your code and the indicated modifications to make it work:</p>
<pre><code>def check_sudoku(matrix):
n = len(matrix)
# check each row
# i, j = 0, 0
i = 0
while i < n:
j = 0 # added
... | 0 | 2016-09-26T12:11:19Z | [
"python"
] |
List length check not working in Sudoku checker | 39,701,964 | <p>I want to write some Python code to check that whether a matrix accords with the rule of Sudoku. My code is presented below:</p>
<pre><code>correct = [[1,2,3],
[2,3,1],
[3,1,2]]
incorrect = [[1,2,3,4],
[2,3,1,3],
[3,1,2,3],
[4,4,4,4]]
incorrect2 = [[1,2... | -1 | 2016-09-26T11:45:26Z | 39,702,684 | <p>The main problem with your code is that you don't reset <code>j</code> to zero at the end of the inner loops. So when you try to check the second row (and subsequent rows) the <code>j</code> values are too big. The same problem occurs when you're testing the columns.</p>
<p>However, there are other problems with th... | 0 | 2016-09-26T12:21:34Z | [
"python"
] |
import another module or implement an existing call | 39,702,025 | <p>This may be a subjective question so I understand if it gets shut down, but this is something I've been wondering about ever since I started to learn python in a more serious way.</p>
<p>Is there a generally accepted 'best practice' about whether importing an additional module to accomplish a task more cleanly is b... | 0 | 2016-09-26T11:48:29Z | 39,702,233 | <p>This is quite a broad question, but I'll try to answer it succinctly.</p>
<p>There is no real best practice, however, it is generally a good idea to recycle code that's already been written by others. If you find a bug in the imported code, it's more beneficial than finding one in your own code because you can subm... | 1 | 2016-09-26T11:58:18Z | [
"python"
] |
Confused as to where to use return statement in Python | 39,702,039 | <p>Sometimes I get confused as to <em>where</em> to use the return statement. I've done the Python track on codecademy and I'm halfway through an Intro to CS class online and <em>still</em> I get it wrong sometimes. I get what it does, it's just that I don't 'get' its placement properly :/</p>
<p>Here's a short exampl... | 1 | 2016-09-26T11:48:57Z | 39,702,267 | <p><code>return</code> in a function means you are leaving the function immediately and returning to the place where you call it.
So you should use <code>return</code> when you are 100% certain that you wanna exit the function immediately.</p>
<p>In your example, I think you don't want to exit the function until you g... | 3 | 2016-09-26T11:59:25Z | [
"python"
] |
Confused as to where to use return statement in Python | 39,702,039 | <p>Sometimes I get confused as to <em>where</em> to use the return statement. I've done the Python track on codecademy and I'm halfway through an Intro to CS class online and <em>still</em> I get it wrong sometimes. I get what it does, it's just that I don't 'get' its placement properly :/</p>
<p>Here's a short exampl... | 1 | 2016-09-26T11:48:57Z | 39,703,342 | <p>You're putting too much emphasis on the impact of <code>return</code> on controlling the behaviour of the <code>for</code> loop. Instead, <code>return</code> applies to the function and happens to terminate the <code>for</code> loop prematurely by primarily bringing an end to the function. </p>
<p>Instead, you can ... | 1 | 2016-09-26T12:50:29Z | [
"python"
] |
How to open .bashrc in python | 39,702,043 | <p>I have a problem with opening the <code>.bashrc</code> file in python. I have written the following code:</p>
<pre><code>mydata = open ('/home/lpp/.bashrc', 'r')
</code></pre>
<p>and I get this:</p>
<pre><code>$ /usr/bin/python2.7 /home/lpp/lpp2016/Handin3.py
Process finished with exit code 0
</code></pre>
<p>Py... | 0 | 2016-09-26T11:49:08Z | 39,702,100 | <pre><code>fp = open(os.path.join((os.path.expanduser('~'), '.bashrc'))
fp.read()
</code></pre>
<p>it is opening and reading all the content</p>
| 0 | 2016-09-26T11:51:55Z | [
"python",
"python-2.7"
] |
Task Scheduling in amazon EC2 ubuntu instance | 39,702,113 | <p>I'm trying to run a python script every 2 minutes in an amazon EC2 ubuntu instance and i've tried a lot of things that just aren't working.</p>
<p>Could someone help me? </p>
<p>Thanks!</p>
| -1 | 2016-09-26T11:52:23Z | 39,702,478 | <p>What you want to use is cron, a Unix service that allows you to schedule commands to be executed at certain times or intervals.</p>
<p>It is based on a simple configuration text file, the crontab (from "cron table", as in, the table with scheduled commands), which coincidentally is also the name of the tool to edit... | 1 | 2016-09-26T12:11:59Z | [
"python",
"amazon-web-services",
"amazon-ec2",
"task",
"schedule"
] |
Django model which could be associated with two parents | 39,702,138 | <p>I've got a model in Django that I think it needs to be associated with two parents, but I'm trying to figure out how to code it.</p>
<p>The main problem is that we've got <code>Building</code> models that are linked with a <code>Headquarter</code>. Each <code>Headquarter</code> usually have an <code>ElectricSupply<... | 0 | 2016-09-26T11:53:18Z | 39,702,236 | <p>I think that every building should have ElectricSupply, so you should point to Building from ElectricSupply, and then if you want to find Headquarter you can easily get that from Building where you also have foreign key pointed to Headquarted. Also I think that every building should be in relationship with ElectricB... | 0 | 2016-09-26T11:58:21Z | [
"python",
"django",
"design",
"foreign-keys",
"models"
] |
Cannot import matplotlib with ipython/jupyter notebook | 39,702,152 | <p>Cannot import matplotlib with ipython/jupyter notebook through a virtual environment.</p>
<p>I'm able to import matplotlib just fine using the console. Having seen other SO posts I can't seem to get this set up right.</p>
<p>I followed <a href="http://help.pythonanywhere.com/pages/IPythonNotebookVirtualenvs" rel="... | 0 | 2016-09-26T11:54:00Z | 39,702,510 | <p>Ok I fixed this by using the tutorial properly (<a href="http://help.pythonanywhere.com/pages/IPythonNotebookVirtualenvs" rel="nofollow">http://help.pythonanywhere.com/pages/IPythonNotebookVirtualenvs</a>)</p>
<p>You need to set up a virtualenv, then make sure that you install jupyter within it. I was using the glo... | 0 | 2016-09-26T12:13:43Z | [
"python",
"python-2.7",
"matplotlib",
"virtualenv",
"jupyter"
] |
Python Flask + Threaded function | 39,702,242 | <p>I would like to make a function, that runs in background and updates a variable every X minutes for my website. </p>
<p>Basically what I need is to cache some json data and update it every X minutes.</p>
<p>What would be the best way to do it? I tried "threading" and it seems to work, but when I run it with Flask,... | 0 | 2016-09-26T11:58:31Z | 39,703,250 | <p>Well, you may use <a href="http://flask.pocoo.org/docs/0.11/patterns/celery/" rel="nofollow">Celery</a> to create delayed tasks to update your data.</p>
<p>But I don't think, that update variable directly is a good idea. So, store your data in cache or database. It depends on the frequency of how you use and update... | 0 | 2016-09-26T12:46:07Z | [
"python",
"multithreading",
"caching",
"flask"
] |
deleting (POPing) specific elements from list | 39,702,349 | <p>I am doing book exercise on pop() function in Python (3.5). The instructions are to delete elements from the list using pop(). From the list below, I want to delete n1, n4, n5, n6, n7, n8, n9. Below code works, but very practical) and I don't understand why specific index works only up until [5]. With out using loop... | 0 | 2016-09-26T12:04:41Z | 39,702,423 | <p>The output is: </p>
<pre><code>I can only invite two people to dinner...
('Sorry, but ', 'N1', ' will not be invited todinner')
('Sorry, but ', 'N5', ' will not be invited to dinner')
('Sorry, but ', 'N7', ' will not be invited to dinner')
('Sorry, but ', 'N9', ' will not be invited to dinner')
('Sorry, but ', 'N8... | 2 | 2016-09-26T12:09:03Z | [
"python"
] |
deleting (POPing) specific elements from list | 39,702,349 | <p>I am doing book exercise on pop() function in Python (3.5). The instructions are to delete elements from the list using pop(). From the list below, I want to delete n1, n4, n5, n6, n7, n8, n9. Below code works, but very practical) and I don't understand why specific index works only up until [5]. With out using loop... | 0 | 2016-09-26T12:04:41Z | 39,702,485 | <p>Well, the length of nameList changes dynamically every time you use 'pop'.
So after you pop 4 elements(n1,n4,n5,n6), there are only 5 elements left in nameList.
You can not use pop(5) anymore because the index is out of range at that time.</p>
| 1 | 2016-09-26T12:12:34Z | [
"python"
] |
deleting (POPing) specific elements from list | 39,702,349 | <p>I am doing book exercise on pop() function in Python (3.5). The instructions are to delete elements from the list using pop(). From the list below, I want to delete n1, n4, n5, n6, n7, n8, n9. Below code works, but very practical) and I don't understand why specific index works only up until [5]. With out using loop... | 0 | 2016-09-26T12:04:41Z | 39,702,631 | <p>Specific index works like a charm for all indices <strong>up to the size of your list</strong>. The problem you're running into here is that when you remove an element from a list, you shrink it, the size is reduced by 1 every time you pop.</p>
<p>Say you have a list of 3 elements, <code>l = ["a","b","c"]</code>
Yo... | 0 | 2016-09-26T12:18:56Z | [
"python"
] |
deleting (POPing) specific elements from list | 39,702,349 | <p>I am doing book exercise on pop() function in Python (3.5). The instructions are to delete elements from the list using pop(). From the list below, I want to delete n1, n4, n5, n6, n7, n8, n9. Below code works, but very practical) and I don't understand why specific index works only up until [5]. With out using loop... | 0 | 2016-09-26T12:04:41Z | 39,703,545 | <p>This happens because your list length changes every time you pop an element from the list. So if you want to use <code>pop</code> specifically, to remove the specified elements an easy and tricky way would be the following:</p>
<pre><code>>>> nameList = ['n1', 'n2', 'n3', 'n4', 'n5', 'n6', 'n7', 'n8', 'n9'... | 0 | 2016-09-26T12:58:43Z | [
"python"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.