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 |
|---|---|---|---|---|---|---|---|---|---|
Python Selenium Detection Error? | 39,060,524 | <p>Hi i've been trying to learn selenium.</p>
<p>The problem i am having is that an element isn't being detected. The html code i am working with is highlighted right here <a href="https://gyazo.com/a76608d4c4e9fc3bd29412436604c173" rel="nofollow">https://gyazo.com/a76608d4c4e9fc3bd29412436604c173</a>. That line of co... | 0 | 2016-08-21T03:11:31Z | 39,060,579 | <p>If the problem you're trying to solve is actually conditional assignment, there are two different things you might want to know.</p>
<p>The first is that you <em>can</em> do:</p>
<blockquote>
<p>if(comment!=none)</p>
</blockquote>
<p>you just have to do it like this:</p>
<pre><code>comment = Foo()
if comment i... | 0 | 2016-08-21T03:23:10Z | [
"python",
"selenium"
] |
PySide Application with asynchronous function execution | 39,060,584 | <p>I have a sample pyside demo which I created to see the webkit browser communication with python...
I have two buttons in webkit</p>
<ul>
<li><p>button 1 - when clicked it sleeps for 10 seconds and then prints a message</p></li>
<li><p>button2 - when clicked it prints a message immediately.</p></li>
</ul>
<p>When I... | 6 | 2016-08-21T03:24:10Z | 39,100,133 | <p>Use a <code>QTimer</code> to execute a signal after a certain time period. Like this:</p>
<pre><code>import sys,json
from PySide.QtCore import *
from PySide.QtGui import *
from PySide.QtWebKit import QWebView, QWebSettings
from PySide.QtNetwork import QNetworkRequest
from PySide.QtCore import QObject, Slot, Signal,... | 1 | 2016-08-23T11:38:06Z | [
"python",
"pyside"
] |
PySide Application with asynchronous function execution | 39,060,584 | <p>I have a sample pyside demo which I created to see the webkit browser communication with python...
I have two buttons in webkit</p>
<ul>
<li><p>button 1 - when clicked it sleeps for 10 seconds and then prints a message</p></li>
<li><p>button2 - when clicked it prints a message immediately.</p></li>
</ul>
<p>When I... | 6 | 2016-08-21T03:24:10Z | 39,217,337 | <p>There are a couple of issues here. First, it's worth pointing out why the app freezes when you click on button1: the click causes Qt to call the event handler, <code>reply</code>, and Qt can't handle another event until this handler returns (in my experience, all windowing systems work this way). So if you put any... | 2 | 2016-08-30T01:02:52Z | [
"python",
"pyside"
] |
why does a script run faster as a module? | 39,060,596 | <p>I have a scrip 'xyz.py' that I'm importing as a module for another script (Main.py). Everything in xyz.py is inside of a class that I call in Main.py. Both, xyz.py and Main.py share the same import statements: "xml.etree.ElementTree"; "Tkinter"; "cv2"; "tkFileDialog"; "tkfd"; "from PIL import Image"; "ImageTk"; "os"... | 0 | 2016-08-21T03:26:56Z | 39,060,635 | <p>When a python program runs, the main script is always passed through the interpreter. When a module is imported, however, python checks its cache ( subdirectory named <code>__pycache__</code>) where it stores modules that have previously been compiled to bytecode. If the date of the cached copy matches the date of... | 0 | 2016-08-21T03:36:45Z | [
"python",
"performance",
"import",
"module"
] |
Cannot find reference to Python package (plt.cm.py) | 39,060,599 | <p>I have a small issue with running code from a tutorial that isn't working as it should. It's not a syntax problem for sure. I'm working with scikit-learn and matplotlib, and I'm getting a warning message in my IDE "Cannot find reference 'gray_r' in 'cm.py'..." All my packages are installed properly (via pip) and hav... | 0 | 2016-08-21T03:27:29Z | 39,060,672 | <p>Well for starters your missing a closing parenthesis on your last print statement: <code>print('Prediction:', clf.predict(digits.data[-1]))</code> Other than that, this code runs on my computer with only a deprecation warning. What does the traceback say?</p>
| 0 | 2016-08-21T03:44:45Z | [
"python",
"matplotlib",
"scipy",
"scikit-learn",
"pycharm"
] |
PyQt4 - Running functions that use python 2.7.11's builtin modules in separate threads | 39,060,634 | <p>i'm making an application for my grad paper at the university and i'm stuck with threading.
i'm trying to make an audio player that loads files into a table and plays them while taking specified intervals into account (basically sleeps after each sound played). i can get the list to play in order but it's in the sam... | 0 | 2016-08-21T03:36:02Z | 39,064,373 | <p>i found the issue with the threading module (it was my fault, of course)
For anyone having similar issues here's the correct class code:</p>
<pre><code> class Create_thread(threading.Thread):
def __init__(self,function):
threading.Thread.__init__(self)
self.function=function
... | 1 | 2016-08-21T12:48:19Z | [
"python",
"multithreading",
"user-interface",
"pyqt4",
"qthread"
] |
Subprocess not working with complex Unix command | 39,060,644 | <p>I am trying to run a <code>join</code> command within Python, and I'm being foiled by <code>subprocess</code>. I'm combining thousands of large files iteratively, so a dictionary would require a lot of memory. My rationale is that <code>join</code> only has to deal with two files at a time, so my memory overhead w... | 1 | 2016-08-21T03:38:48Z | 39,060,682 | <p><code><(</code> is a <code>bash</code> extension to standard shell syntax. Notice in the error message that it's running <code>/bin/sh</code>, not <code>/bin/bash</code>; even if <code>/bin/sh</code> is a link to <code>/bin/bash</code>, <code>bash</code> drops many of its extensions when it's run using that link.... | 2 | 2016-08-21T03:47:17Z | [
"python",
"unix",
"subprocess"
] |
Python matplotlib install issue on Windows 7 for freetype, png packages | 39,060,669 | <p>Using Python 2.7 on Windows 7. Here is the command I am using to install and error message. Wondering if anyone have met with similar issues before? Thanks.</p>
<pre><code>C:\Python27\Scripts>pip install matplotlib
Collecting matplotlib
Downloading matplotlib-1.5.2.tar.gz (51.6MB)
100% |###################... | 1 | 2016-08-21T03:44:16Z | 39,060,865 | <p><a href="http://www.lfd.uci.edu/~gohlke/pythonlibs/" rel="nofollow">http://www.lfd.uci.edu/~gohlke/pythonlibs/</a></p>
<p>Get matplotlib from above location. Choose correct package based on python(2.x/3.x) and bit(32/64) version.</p>
<pre><code>32-bit 2.7: matplotlib-1.5.2-cp27-cp27m-win32.whl
64-bit 2.7: matplotl... | 2 | 2016-08-21T04:34:50Z | [
"python",
"windows",
"python-2.7",
"matplotlib",
"windows-7"
] |
Python matplotlib install issue on Windows 7 for freetype, png packages | 39,060,669 | <p>Using Python 2.7 on Windows 7. Here is the command I am using to install and error message. Wondering if anyone have met with similar issues before? Thanks.</p>
<pre><code>C:\Python27\Scripts>pip install matplotlib
Collecting matplotlib
Downloading matplotlib-1.5.2.tar.gz (51.6MB)
100% |###################... | 1 | 2016-08-21T03:44:16Z | 39,060,880 | <p>As you can see it <code>png</code> and <code>freetype</code> modules are missing. You need to install them separately.</p>
<p>Try doing the following :</p>
<pre><code>> pip install freetype-py
> pip install pypng
> pip install matplotlib
</code></pre>
| 2 | 2016-08-21T04:37:21Z | [
"python",
"windows",
"python-2.7",
"matplotlib",
"windows-7"
] |
Python matplotlib install issue on Windows 7 for freetype, png packages | 39,060,669 | <p>Using Python 2.7 on Windows 7. Here is the command I am using to install and error message. Wondering if anyone have met with similar issues before? Thanks.</p>
<pre><code>C:\Python27\Scripts>pip install matplotlib
Collecting matplotlib
Downloading matplotlib-1.5.2.tar.gz (51.6MB)
100% |###################... | 1 | 2016-08-21T03:44:16Z | 39,105,374 | <p>I solved it by taking version 1.5.1</p>
<pre><code>pip install matplotlib==1.5.1
</code></pre>
<p>it seems that version 1.5.2 installer is broken.</p>
| 3 | 2016-08-23T15:35:31Z | [
"python",
"windows",
"python-2.7",
"matplotlib",
"windows-7"
] |
Python 3: Regex doesn't work when read text from file | 39,060,721 | <p>The following is my information:</p>
<p>The input:</p>
<pre><code> \"button\" \"button\" href=\"#\" data-id=\"11111111111\" \"button\" \"button\" href=\"#\" data-id=\"222222222222\"
\"button\" \"button\" href=\"#\"
</code></pre>
<p>The output I'd like:</p>
<pre><code>11111111111
222222222222
</code><... | -1 | 2016-08-21T03:57:49Z | 39,060,748 | <p>You can do:</p>
<pre><code>re.findall(r'"([^\\]+)\\"', s)
</code></pre>
<ul>
<li><code>"([^\\]+)</code> matches a <code>"</code>, then the captured grouo contains the desired portion i.e. substring upto next <code>\</code>, <code>\\"</code> makes sure that the portion is followed by <code>\\"</code></li>
</ul>
<p... | 1 | 2016-08-21T04:04:20Z | [
"python",
"regex",
"file",
"find"
] |
Python 3: Regex doesn't work when read text from file | 39,060,721 | <p>The following is my information:</p>
<p>The input:</p>
<pre><code> \"button\" \"button\" href=\"#\" data-id=\"11111111111\" \"button\" \"button\" href=\"#\" data-id=\"222222222222\"
\"button\" \"button\" href=\"#\"
</code></pre>
<p>The output I'd like:</p>
<pre><code>11111111111
222222222222
</code><... | -1 | 2016-08-21T03:57:49Z | 39,060,952 | <p>Please check this answer. (Added two lines in str_txt.txt file).</p>
<p>Only change I did in your second code is , I have <strong>'r' as prefix in regex</strong>.
For more info on <strong>'r' prefix in regex</strong>, please <a href="http://stackoverflow.com/questions/2241600/python-regex-r-prefix">check here</a> !... | 1 | 2016-08-21T04:56:12Z | [
"python",
"regex",
"file",
"find"
] |
How to hide ttk Treeitem indicators in a Python GUI | 39,060,756 | <p>I'm building a Python GUI application using ttk treeviews. On Linux, when a Treeitem has child items, it displays an arrow to show that the row can be expanded. I want to hide this indicator arrow (I am using other ways to hint that the row can be expanded). How can I do this?</p>
<p>If I run <code>Style().element_... | 6 | 2016-08-21T04:06:15Z | 39,259,113 | <p>Not sure if you ever figured it out.</p>
<p>When you create the new style and configure it, you have to change the name of the template to <code>"."</code>. This changes the root style for the treeview. You also need to specify a theme, even if it is <code>default</code>. So it would look something like:</p>
<pre>... | 3 | 2016-08-31T21:14:43Z | [
"python",
"treeview",
"ttk"
] |
Can a Python script in a (sub)module import from upstream in its directory hierarchy? | 39,060,757 | <p>I realize there are a slew of posts on SO related to Python and imports, but it seems like a fair number of these posts are asking about import rules/procedures with respect to creating an actual Python package (vs just a project with multiple directories and python files). I am very new to Python and just need some... | 1 | 2016-08-21T04:06:31Z | 39,060,829 | <h3>What's Possible</h3>
<p>Anything.</p>
<p>No, really. See <A HREF="https://docs.python.org/2/library/imp.html" rel="nofollow">the <code>imp</code> module</A>, the <A HREF="https://docs.python.org/2/library/imputil.html" rel="nofollow">the <code>imputil</code> module</A> -- take a look at how <A HREF="https://docs.... | 1 | 2016-08-21T04:26:10Z | [
"python",
"python-2.7",
"import",
"sys.path"
] |
str.replace not appearing to function properly when target string is contained in a list | 39,060,773 | <p>In my program I have a section of code that looks in one of my computer's directories for pickle files and puts their names in a list using a list comprehension. After this I am attempting to remove the ".pickle" file extension from each of the file names in the list, for reasons unnecessary to explain here. However... | 1 | 2016-08-21T04:10:43Z | 39,060,799 | <p><code>each = each.replace(".pickle","")</code> creates a new string and binds it to the name <code>each</code>. This has no effect on the original string object in <code>file_names</code>. </p>
<p>If the <code>.replace</code> method mutated its string in-place then </p>
<pre><code>for each in file_names:
each.... | 3 | 2016-08-21T04:18:18Z | [
"python",
"python-3.x"
] |
str.replace not appearing to function properly when target string is contained in a list | 39,060,773 | <p>In my program I have a section of code that looks in one of my computer's directories for pickle files and puts their names in a list using a list comprehension. After this I am attempting to remove the ".pickle" file extension from each of the file names in the list, for reasons unnecessary to explain here. However... | 1 | 2016-08-21T04:10:43Z | 39,061,369 | <p>You can't replace items inline; try using map or a list comprehension to recreate the list:</p>
<pre><code>import glob
import os
original_files = glob.glob(r'C:/foo/blah/*.pickle')
files = [os.path.basename(os.path.splitext(i)[0]) for i in original_files]
</code></pre>
<p>You can also combine it:</p>
<pre><code>... | 0 | 2016-08-21T06:16:04Z | [
"python",
"python-3.x"
] |
pygame.event.get() is not returning any event | 39,060,855 | <pre><code>import pygame
from pygame.locals import *
...
...
while True:
#comment
for event in pygame.event.get():
if event.type == KEYDOWN:
key_pressed = pygame.key.get_pressed()
#do something
</code></pre>
<p>I replaced <code>#comment</code> with a print statement and found that the <... | 0 | 2016-08-21T04:32:26Z | 39,067,100 | <p><code>pygame.event.get()</code> grabs all of the events that have registered in the event queue and keeps them in the order they happened. <code>pygame.key.get_pressed()</code> only has the keys that are pressed in that moment. That means that they have to be pressed when your game tries to access them.</p>
<p>You ... | 2 | 2016-08-21T17:45:19Z | [
"python",
"pygame"
] |
How to get the corresponding json data in different { } and [ ] (using Python)? | 39,060,894 | <p>I am trying to use Python Flask to process JSON data.<br>
Here is what my data looks like:</p>
<pre><code>[
{ 'className': 'BoardGame',
'fields': {
'objectId': {'type': 'String'},
'playerName': {'type': 'String'},
'cheatMode': {'type': 'Boolean'},
's... | -1 | 2016-08-21T04:40:47Z | 39,060,993 | <pre><code>data = [
{ 'className': 'BoardGame',
'fields': {
'objectId': {'type': 'String'},
'playerName': {'type': 'String'},
'cheatMode': {'type': 'Boolean'},
'score': {'type': 'Number'},
'updatedAt': {'type': 'Date'},
'created... | 1 | 2016-08-21T05:07:21Z | [
"python",
"json"
] |
Variable issues in if statements | 39,060,948 | <p>I've just started python and I've decided to start with a simple program to parse a single line, two argument mathematical expression directly into an answer. Examples: 4 + 2, 3/4, 5435 * 3423, ect. To start with I'm trying to interpret the two variables in the equation before I work on having the program mathify th... | 0 | 2016-08-21T04:55:36Z | 39,061,995 | <p>In Python variables that are referenced inside a function are assumed to be local if their value is set within the function. To override this default behavior, and set globals from inside a function, you need to declare them with the <code>global</code> statement (only if you want to <em>write</em> them, you don't ... | 0 | 2016-08-21T07:45:46Z | [
"python",
"variables",
"if-statement"
] |
Determine if line is date, string or int in python | 39,060,991 | <p>My code reads all lines in a textfile and determines if it is a string, int or date.. The problem is reading if it is a datetime.. If I tried to convert it into a datetime object from a string it raises the error:</p>
<pre><code>ValueError: unconverted data remains:
</code></pre>
<p>Here is my code:</p>
<pre><co... | 1 | 2016-08-21T05:07:06Z | 39,061,054 | <p>Looks like You forgot to remove '\n'. You can modify a line as below :- </p>
<pre><code>date_object = datetime.strptime(line.strip(), '%m-%d-%Y')
</code></pre>
<p>I hope it will solve the problem</p>
| 4 | 2016-08-21T05:20:55Z | [
"python"
] |
Could not figure out the use of prefetch_related in django | 39,061,107 | <p>There is a scenario where i want to show total purchase of the user. I did using @property inside models of userprofiles. Fortunately, it is working as i expected. But i want to use prefetch_related for optimizing django queries as total purchase of user is calculated from order_history which has ManyToMany Relation... | 1 | 2016-08-21T05:28:58Z | 39,061,764 | <p>The difference between the two is</p>
<p>In case of </p>
<p><code>userprofile = UserProfile.objects.get(slug=self.slug)</code> #hits database</p>
<p>This query gets the object of userprofile based on condition from database</p>
<p><code>user_order = userprofile.order_history.all()</code> #hits database again</p>... | 1 | 2016-08-21T07:13:41Z | [
"python",
"django",
"django-models",
"query-optimization",
"django-orm"
] |
logistic regression feature value normalization in scikit-learn | 39,061,109 | <p>Using Python 2.7. The question is about fit method. Question is for features (provided by parameter <code>X</code>), if there are non-numeric features (e.g. string type features, like <code>Male</code>, <code>Female</code>), do I need, or it is recommended to convert into numeric features (for performance and other ... | 0 | 2016-08-21T05:29:27Z | 39,061,168 | <p>You must encode categorical features and convert them to numerical values, if you want to use <code>sklearn</code>. This apples to all <code>sklearn</code> estimators (including <code>LogisticRegression</code>) and it does not matter which version of python you are using. </p>
<p>look at <strong>4.3.4. Encoding cat... | 1 | 2016-08-21T05:39:54Z | [
"python",
"python-2.7",
"machine-learning",
"scikit-learn",
"logistic-regression"
] |
logistic regression feature value normalization in scikit-learn | 39,061,109 | <p>Using Python 2.7. The question is about fit method. Question is for features (provided by parameter <code>X</code>), if there are non-numeric features (e.g. string type features, like <code>Male</code>, <code>Female</code>), do I need, or it is recommended to convert into numeric features (for performance and other ... | 0 | 2016-08-21T05:29:27Z | 39,061,289 | <p>Just to add a bit to MhFarahani's answer:
Yes, you need to convert those labels to numerical values (generally 0 or 1). For things like gender, you would want to have a row that has 0 for male and 1 for female, or vice versa. For something like geographical location, it'd be a bit more complicated. If there's a reas... | 1 | 2016-08-21T06:01:18Z | [
"python",
"python-2.7",
"machine-learning",
"scikit-learn",
"logistic-regression"
] |
Use request.user in class Index(TemplateView) | 39,061,190 | <p>i'm trying to implement this:</p>
<pre><code>class Index(TemplateView):
if request.user.role == 'admin':
template_name = 'index/admin/index.html'
elif request.user.role == 'ff':
template_name = 'index/firefighter/index.html'
else:
template_name = 'index/dev/index.html'
@method_d... | 0 | 2016-08-21T05:43:21Z | 39,061,467 | <p>Set your template in the <code>get_template_names()</code> method:</p>
<pre><code>from django.utils.decorator import method_decorator
class Index(TemplateView):
def get_template_names(self, *args, **kwargs):
roles_urls = {'admin': 'index/admin/index.html',
'ff': 'index/firefighter... | 2 | 2016-08-21T06:33:08Z | [
"python",
"django",
"django-templates",
"django-views",
"django-rest-framework"
] |
Variable not being assigned value when returned from subprogram? Python 3? | 39,061,280 | <p>I am trying to return a value from my subprogram, but when trying to use the variable in the main program, it comes up with an error saying it has not been assigned a value.</p>
<pre><code>correct = 0
def subprogram():
correct2 = 0
loop = 0
while loop == 0:
loop2 = 0
memberID = input("Pl... | 0 | 2016-08-21T05:59:18Z | 39,061,375 | <p>In your main <code>while</code> loop you don't define the <code>correct2</code> variable so it throws an error when you try to do:</p>
<pre><code>if correct2 == 0:
</code></pre>
<p>You assign the result of subprogram to <code>correct</code>:</p>
<pre><code>correct = subprogram()
</code></pre>
<p>where you probab... | 0 | 2016-08-21T06:17:00Z | [
"python"
] |
Scraping YouTube playlist video links | 39,061,354 | <p>I wanted to download all videos of <a href="https://www.youtube.com/playlist?list=PL3D7BFF1DDBDAAFE5" rel="nofollow">this</a> Youtube channel. So I tried to write a script with <code>BeautifulSoup</code> to scrape all the links of the videos. </p>
<p>I did some inspection and found out that the "<code>tr class="pl-... | 0 | 2016-08-21T06:13:33Z | 39,061,569 | <p>Try this one:</p>
<pre><code>import urllib2
from bs4 import BeautifulSoup
htmlParser = "lxml"
url='https://www.youtube.com/playlist?list=PL3D7BFF1DDBDAAFE5'
html=urllib2.urlopen(url)
response=html.read()
soup=BeautifulSoup(response, htmlParser)
links = soup.find_all('a', attrs={'class':'pl-video-title-link'})
for ... | 0 | 2016-08-21T06:48:53Z | [
"python",
"web-scraping",
"beautifulsoup"
] |
Scraping YouTube playlist video links | 39,061,354 | <p>I wanted to download all videos of <a href="https://www.youtube.com/playlist?list=PL3D7BFF1DDBDAAFE5" rel="nofollow">this</a> Youtube channel. So I tried to write a script with <code>BeautifulSoup</code> to scrape all the links of the videos. </p>
<p>I did some inspection and found out that the "<code>tr class="pl-... | 0 | 2016-08-21T06:13:33Z | 39,064,649 | <pre><code>from bs4 import BeautifulSoup as bs
import requests
r = requests.get('https://www.youtube.com/playlist?list=PL3D7BFF1DDBDAAFE5')
page = r.text
soup=bs(page,'html.parser')
res=soup.find_all('a',{'class':'pl-video-title-link'})
for l in res:
print l.get("href")
</code></pre>
<p>It is giving me output as ... | -3 | 2016-08-21T13:20:10Z | [
"python",
"web-scraping",
"beautifulsoup"
] |
Create daily rolling current highest Value series | 39,061,643 | <p>I have the following data which has a <code>Value</code>, <code>Time</code> and <code>Date</code> column:</p>
<p><a href="http://i.stack.imgur.com/MFs4F.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/MFs4F.jpg" alt="raw_date_img"></a></p>
<p><strong>Desired output</strong></p>
<p>I would like to create a ... | 1 | 2016-08-21T06:59:17Z | 39,062,775 | <p>IIUC, you need to use <a href="http://pandas.pydata.org/pandas-docs/version/0.17.0/generated/pandas.Series.cummax.html" rel="nofollow"><code>cummax</code></a> to get the cumulative maximum for the <code>Value</code> column followed by dropping off duplicated entries after grouping them w.r.t <code>Date</code> column... | 1 | 2016-08-21T09:29:08Z | [
"python",
"pandas"
] |
Show if restaurant is open or closed based on weekday, opening and closing time | 39,061,718 | <p>I have a model of restaurant and operating time which has foreign key relation.
for example a restaurant ocean view cafe whose operating time in each week day is </p>
<p>Friday - 10am - 6:30pm</p>
<p>Thursday - 10 am - 9:45 pm</p>
<p>Wednesday - 10 am - 9:45 pm</p>
<p>Tuesday - 10 am - 9:45 pm</p>
<p>Monday - 1... | 0 | 2016-08-21T07:09:34Z | 39,074,515 | <p>Not tested but it should work.</p>
<pre><code>class OperatingTimeManager(models.Manager):
# Use a model manager when accesing table data, use model methods only for row operations
def get_open_restaurants(self, date=datetime.datetime.now()):
# get the id's of open restaurants
open_restauran... | 0 | 2016-08-22T08:22:12Z | [
"python",
"django",
"python-3.x",
"django-models"
] |
python, import package from parent dir | 39,061,805 | <p>My project tree is like this:</p>
<pre><code>maindir\
dir1\
MAINSCRIPT.py
dir2\
scriptA.py
</code></pre>
<p>The <code>MAINSCRIPT.py</code> is my main script!</p>
<p>How can I import <code>scriptA.py</code> from <code>MAINSCRIPT.py</code></p>
| 1 | 2016-08-21T07:19:36Z | 39,061,904 | <p>Well this isn't technical a python package in the first place or it would have an <code>__init__.py</code> in each folder. And also I'm confused why you would have your main program in one of your folders. But something that I've used often to import a file that isn't in Python's regularly checked paths is </p>
<pr... | 2 | 2016-08-21T07:33:17Z | [
"python",
"import",
"package"
] |
python, import package from parent dir | 39,061,805 | <p>My project tree is like this:</p>
<pre><code>maindir\
dir1\
MAINSCRIPT.py
dir2\
scriptA.py
</code></pre>
<p>The <code>MAINSCRIPT.py</code> is my main script!</p>
<p>How can I import <code>scriptA.py</code> from <code>MAINSCRIPT.py</code></p>
| 1 | 2016-08-21T07:19:36Z | 39,062,079 | <p>The following nice solution is from <a href="http://www.napuzba.com/story/import-error-relative-no-parent/" rel="nofollow">ImportError: attempted relative import with no known parent package</a></p>
<p>You can use relative imports. First change your directory structure as follows:</p>
<pre><code>maindir\
... | 1 | 2016-08-21T07:57:59Z | [
"python",
"import",
"package"
] |
Function call on individual field save in django | 39,061,819 | <p>Say I have a model:</p>
<pre><code>class Workplace(models.Model):
name = models.CharField(max_length=255)
...
office_mail_id = models.EmailField(null=True, blank=True)
</code></pre>
<p>What I want is whenever the value of email is changed and the object is saved, a function should be run which would sa... | 0 | 2016-08-21T07:21:51Z | 39,061,864 | <p>Just override <code>save</code> in <code>Workplace</code>:</p>
<pre><code>def save(self, *args, **kwargs):
# do whatever you need, save other models etc..
super().save(*args, **kwargs)) # or super(Workplace, self).save(*args, **kwargs)
# if Python 2
</code></pre>
| 1 | 2016-08-21T07:27:52Z | [
"python",
"django",
"django-models"
] |
How can I 'cycle' through list items when using classes in python pygame to change object colors? | 39,061,843 | <p>I have drawn a caterpillar using <code>pygame.draw</code> and it's color is set as <code>self.color_scheme[0]</code> For example.</p>
<pre><code>self.color_scheme = [red,yellow,purple]
...
...
pygame.draw.ellipse(screen, self.color_scheme[0], [x, y, 40, 45])
</code></pre>
<p>What I'm trying to enable is that when ... | 0 | 2016-08-21T07:25:16Z | 39,062,348 | <p>To cycle:</p>
<pre><code>self.color_scheme_idx = -1
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_s:
self.color_scheme_idx += 1
pygame.draw.ellipse(screen, self.color_scheme[self.color_scheme_idx], [x, y, 40, 45])
</code></pre>
<p>To randomize:</p>
<pre><code>import random
if eve... | 1 | 2016-08-21T08:31:52Z | [
"python",
"pygame"
] |
Python-Firebase (401) Unauthorised error | 39,061,866 | <p>Been trying to retrieve data from my firebase however I keep getting <code>HTTPError: 401 Client Error: Unauthorized.</code> Been using <a href="https://pypi.python.org/pypi/python-firebase/1.2" rel="nofollow">https://pypi.python.org/pypi/python-firebase/1.2</a> as a guide. Tried adjusting the authentication code bu... | 0 | 2016-08-21T07:28:05Z | 39,713,101 | <p>Go to in Firebase Console > Database >Rules and change </p>
<pre><code> ".read": "auth != null",
".write": "auth != null"
</code></pre>
<p>to:</p>
<pre><code>".read": "auth == null",
".write": "auth == null"
</code></pre>
| 0 | 2016-09-26T22:01:47Z | [
"python",
"authentication",
"firebase",
"firebase-database"
] |
Why does my variable resets it's value? | 39,061,875 | <p>I am making a small Python console RPG. I have a very basic fighting system in place, but the health values of my <code>player</code> and <code>enemy</code> keep resetting after they've taken damage. Any ideas as to why this is happening? I think it might have something to do with my variables not being <code>global... | 0 | 2016-08-21T07:29:49Z | 39,062,092 | <p>Could you try mark the variables global in <code>attack</code> function, as you d in <code>fight</code> and see?</p>
| 0 | 2016-08-21T07:59:55Z | [
"python",
"python-3.x",
"global-variables"
] |
Why does my variable resets it's value? | 39,061,875 | <p>I am making a small Python console RPG. I have a very basic fighting system in place, but the health values of my <code>player</code> and <code>enemy</code> keep resetting after they've taken damage. Any ideas as to why this is happening? I think it might have something to do with my variables not being <code>global... | 0 | 2016-08-21T07:29:49Z | 39,062,226 | <p>Just found the problem:</p>
<pre><code>class Player:
def __init__(self, name):
self.name = name
self.max_health = 100
self.health = self.max_health
self.attack = 5
self.health_stat = "{}/{}".format(self.health, self.max_health)
</code></pre>
<p><code>self.health_stat</co... | 0 | 2016-08-21T08:16:32Z | [
"python",
"python-3.x",
"global-variables"
] |
Why matplotlib plot a graph have ticks line off-axis ï¼ | 39,061,930 | <p>I use matplotlib plot graph on OS X system,the top left corner ticks line have off-axis distributionï¼but,on windows,there is no this problem.how to deal with this problemï¼</p>
<p><a href="http://i.stack.imgur.com/XhpyZ.png" rel="nofollow"><img src="http://i.stack.imgur.com/XhpyZ.png" alt="enter image descriptio... | 1 | 2016-08-21T07:37:06Z | 39,073,530 | <p>I Have work out this problem,</p>
<p>1.savefig() do not support the jpg,tif ,so if save the graph use this format, the graph tick line will off-axis.if save the graph use png,eps,svg,the graph will have no this problem</p>
<p>2.show graph program have a bug on OS X system, no matter which format of graph you save,... | 0 | 2016-08-22T07:25:21Z | [
"python",
"osx",
"matplotlib"
] |
Looping dict[key] into gui interface, removing, and replacing | 39,061,986 | <p>So I have this code for Python 2.7 which calculates word frequencies (any optimizations are welcome). </p>
<pre><code>import Tkinter as tk
def let_freq():
user_input = e.get()
alphabet = {
'a': 0,'b': 1,'c': 2,'d': 3,
'e': 4,'f': 5,'g': 6,'h': 7,
'i': 8,'j': 9,'k': 10,'l': 11,
... | 0 | 2016-08-21T07:44:45Z | 39,062,165 | <p>When setting up a Label, you can give it a <code>tkinter.StringVar</code> as it's text variable. Then, whenever you update the variable, the Label will update automatically:</p>
<pre><code>from tkinter import *
from time import sleep
root = Tk()
labeltext = StringVar()
labeltext.set('hello')
label = Label(root, t... | 1 | 2016-08-21T08:08:08Z | [
"python",
"python-2.7",
"tkinter"
] |
Looping dict[key] into gui interface, removing, and replacing | 39,061,986 | <p>So I have this code for Python 2.7 which calculates word frequencies (any optimizations are welcome). </p>
<pre><code>import Tkinter as tk
def let_freq():
user_input = e.get()
alphabet = {
'a': 0,'b': 1,'c': 2,'d': 3,
'e': 4,'f': 5,'g': 6,'h': 7,
'i': 8,'j': 9,'k': 10,'l': 11,
... | 0 | 2016-08-21T07:44:45Z | 39,062,237 | <p>A few tweaks on your function before getting to the question at hand. You're doing a bunch of stuff you don't really need to, and can pare this down quite a bit.</p>
<p>First of all, your <code>value_alphabet</code> is just a reimplemented <code>collections.Counter</code>. Use that instead.</p>
<pre><code>from col... | 1 | 2016-08-21T08:18:29Z | [
"python",
"python-2.7",
"tkinter"
] |
How can I enter multiple commands at once in the python console | 39,061,989 | <p>I'm trying to enter several commands in the python console all at once for the purpose of testing. <br>For example:</p>
<pre><code>userInput = None
while userInput != 'end':
userInput = input('$ ')
userInput = userInput.strip()
if userInput == 'one':
print('all')
elif userInput == 'two':
... | 3 | 2016-08-21T07:45:02Z | 39,062,121 | <p>just create a text file named <code>input.txt</code> like this:</p>
<pre><code>one
two
three
end
</code></pre>
<p>and call your script like this:</p>
<pre><code>python myscript.py < file.txt
</code></pre>
| 1 | 2016-08-21T08:04:09Z | [
"python",
"console",
"arguments",
"automated-tests"
] |
How can I enter multiple commands at once in the python console | 39,061,989 | <p>I'm trying to enter several commands in the python console all at once for the purpose of testing. <br>For example:</p>
<pre><code>userInput = None
while userInput != 'end':
userInput = input('$ ')
userInput = userInput.strip()
if userInput == 'one':
print('all')
elif userInput == 'two':
... | 3 | 2016-08-21T07:45:02Z | 39,062,239 | <p>I recommend inputs from @Jean-Francois Fabre and @Abhirath Mahipal. </p>
<p>But this is just another option, if your inputs are limited.</p>
<pre><code>userInput = raw_input('$ ')
userInput = userInput.strip()
for each in userInput.split('\\r'):
if each == 'one':
print('all')
elif each == 'two':
... | 1 | 2016-08-21T08:18:44Z | [
"python",
"console",
"arguments",
"automated-tests"
] |
How can I enter multiple commands at once in the python console | 39,061,989 | <p>I'm trying to enter several commands in the python console all at once for the purpose of testing. <br>For example:</p>
<pre><code>userInput = None
while userInput != 'end':
userInput = input('$ ')
userInput = userInput.strip()
if userInput == 'one':
print('all')
elif userInput == 'two':
... | 3 | 2016-08-21T07:45:02Z | 39,062,396 | <p>Occasionally I like hacking <code>input</code> so I can just test by hitting F5 in IDLE. In your case you could for example add this before your code:</p>
<pre><code>def input(prompt, inputs=iter('one two three end'.split())):
x = next(inputs)
print(prompt + x)
return x
</code></pre>
<p>Then you don't ... | 2 | 2016-08-21T08:38:16Z | [
"python",
"console",
"arguments",
"automated-tests"
] |
Sending email using python through postfix | 39,062,015 | <p>When I send emails through postfix, headers always contain one extra hop that I would like to get rid of. Here are the headers:</p>
<pre><code>From admin@mta.emailcab.com Sat Aug 20 18:40:58 2016
Return-Path: <admin@mta.emailcab.com>
X-Original-To: oneprovider@prosolutionmail.com
Delivered-To: oneprovider@pr... | 0 | 2016-08-21T07:48:33Z | 39,062,990 | <p>It shouldn't be fixed in python, I don't believe it can be anyway. SMTP uses the "addressed envelope"(To:,From:). The <code>Received From</code> value you are referencing isn't a python issue its a Postfix configuration issue., Think of it like TCP, you don't see the encapsulation/de-encapsulation which would be the... | 0 | 2016-08-21T10:00:48Z | [
"python",
"email",
"postfix"
] |
Django Model Form - Not Valid without any errors | 39,062,172 | <p>I am writing a test for a Django Form. I am populating it with initial data. But when i save the form i get the error that it does not have cleaned_data attribute.</p>
<p>This may happen because the form does not validate but it does not show any errors either.</p>
<p>here is the code.</p>
<pre><code>def test_key... | 1 | 2016-08-21T08:09:32Z | 39,062,256 | <p>You haven't passed any data to the form, only initial values. Therefore the form is not bound and cannot be valid.</p>
| 2 | 2016-08-21T08:20:34Z | [
"python",
"django"
] |
Python-Kivy: on_touch_down() defined to specific children affects on all childrens | 39,062,299 | <p>I want to make an android-lock like thing, so I have 2 Images of the button (the button normal, the the button pressed).</p>
<p>I defined a function on_touch_down on every image, so when I press it, it changes the source to the pressed button, and on_touch_up it changes it back to normal. But every time I press on ... | 0 | 2016-08-21T08:27:18Z | 39,062,465 | <p>Instead of defining <code>on_touch_*</code> event handlers, define a clickable image class with help of the <code>ButtonBehavior</code>:</p>
<pre><code>from kivy.uix.behaviors.button import ButtonBehavior
class ClickableImage(ButtonBehavior, Image):
def on_press(self):
pass
def on_release(self):
... | 0 | 2016-08-21T08:48:46Z | [
"python",
"kivy",
"kivy-language"
] |
Google Cloud Datastore API in Python Code | 39,062,334 | <p>I am trying to Implement Google Cloud DataStore in my Python Django Project not running on Google App Engine.</p>
<p>Can it be possible to use Google Datastore without having the project run on Google App Engine ? If yes, Can you please tell how to retrieve the complete entity object or execute the query successful... | 1 | 2016-08-21T08:30:06Z | 39,158,527 | <p>This <a href="https://cloud.google.com/python/getting-started/using-cloud-datastore" rel="nofollow">guide</a> will probably be helpful. You can see an example of it in action <a href="https://github.com/GoogleCloudPlatform/getting-started-python/blob/master/2-structured-data/bookshelf/model_datastore.py" rel="nofoll... | 1 | 2016-08-26T04:57:19Z | [
"python",
"google-app-engine",
"google-cloud-storage",
"google-cloud-platform",
"google-app-engine-python"
] |
Does read(size) have a built in pointer? | 39,062,336 | <p>I found this code here which monitors the progress of downloads. -</p>
<pre><code>import urllib2
url = "http://download.thinkbroadband.com/10MB.zip"
file_name = url.split('/')[-1]
u = urllib2.urlopen(url)
f = open(file_name, 'wb')
meta = u.info()
file_size = int(meta.getheaders("Content-Length")[0])
print "Downlo... | -1 | 2016-08-21T08:30:14Z | 39,062,413 | <p>File objects and network sockets and other forms of I/O communication are <em>data streams</em>. Reading from them always produces the <em>next</em> section of data, calling <code>.read()</code> with a buffer size does not re-start the stream from the beginning.</p>
<p>So yes, there is a virtual 'position' in strea... | 1 | 2016-08-21T08:41:22Z | [
"python",
"io"
] |
Pandas sql equivalent | 39,062,388 | <p>I've got a <code>pd.dataframe</code> with following fields: <code>id, value</code> (multiple values per id).</p>
<p>What is the <code>pandas</code> equivalent of <code>sql query</code>:</p>
<pre><code>SELECT id, Max(value)-Min(value) AS val1
FROM t1
GROUP BY t1.id
</code></pre>
| 1 | 2016-08-21T08:37:11Z | 39,062,416 | <p>you can do it this way:</p>
<pre><code>In [31]: df = pd.DataFrame(np.random.randint(0, 5, (10, 2)), columns=['id','value'])
In [32]: df
Out[32]:
id value
0 2 4
1 4 0
2 3 1
3 4 2
4 4 1
5 2 3
6 1 0
7 3 2
8 2 2
9 1 1
In [33]: df.groupby('id')... | 1 | 2016-08-21T08:41:35Z | [
"python",
"pandas"
] |
Opencv has found image that doesn't exist on screen | 39,062,403 | <p>I try to use opencv for search button location on screen. If button exist on screen opencv work perfect but it return some !=0 x,y even if image doesn't exist. How to fix it?</p>
<pre><code>import cv2
def buttonlocation(image):
im = ImageGrab.grab()
im.save('screenshot.png')
img = cv2.imread(image,0)
... | -1 | 2016-08-21T08:39:18Z | 39,066,916 | <p>The <a href="http://docs.opencv.org/2.4/doc/tutorials/imgproc/histograms/template_matching/template_matching.html" rel="nofollow">documentation of opencv</a> details to two steps of the template matching procedure.</p>
<ol>
<li><code>R=cv2.matchTemplate(I,T,method)</code> computes an image <code>R</code>. Each pixe... | 0 | 2016-08-21T17:26:19Z | [
"python",
"python-2.7",
"python-3.x"
] |
Django: how to send argument in HtpResponseRedirect | 39,062,448 | <p><strong>Views.py</strong></p>
<pre><code>from django.shortcuts import render
from django.template.context_processors import csrf
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
from .models import studentDetails
from .forms import loginForm
# Create your views here.
... | 0 | 2016-08-21T08:46:59Z | 39,062,559 | <p>You should pass parameter in url first: </p>
<pre><code>url(r'^student/(?P<username>\w+)/$', views.userpage, name='userpage)
</code></pre>
<p>But better use <code>pk</code> field or something with <code>name</code> + <code>pk</code>, as url parametr, because username can be duplicate.<br>
Now you can pass t... | 0 | 2016-08-21T09:01:53Z | [
"python",
"django",
"django-templates",
"django-views",
"django-urls"
] |
Python syslog - view syslog messages | 39,062,464 | <p>I'm running the following code:
# create logger
logger = logging.getLogger("myApp")
logger.setLevel(logging.DEBUG)</p>
<pre><code># create console handler and set level to debug
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
# add ch to logger
logger.addHandler(ch)
logger.debug('debug sample ... | 0 | 2016-08-21T08:48:46Z | 39,062,561 | <p>you can read as file :</p>
<pre><code>important = []
keep_phrases = ["test",
"important",
"warning"]
with open("log.log" 'r') as f:
for line in f:
for phrase in keep_phrases:
if phrase in line:
important.append(line)
print line
... | 0 | 2016-08-21T09:01:58Z | [
"python"
] |
Python TIC TAC TOE skipping turns | 39,062,521 | <p>I am working on a tic-tac-toe program in python. Now, the Human's turn work's fine. However, the AI, after playing the first turn, does not play any further turns. I have scanned through the code and cannot seem to find any errors that can cause this. </p>
<p>Please ignore the comments and the part that deals with ... | 1 | 2016-08-21T08:56:32Z | 39,062,840 | <p>In a word, the problem of your AI is that <em>it chose the same position all the times</em>, which seems like "not playing any further turns".</p>
<p>To prove that, simply add a <code>print</code> in the for-loop of your AI:</p>
<pre><code>for i in range(1,10):
make_move(copied_board,i,pla)
if(win(copied_b... | 2 | 2016-08-21T09:39:16Z | [
"python",
"python-3.x",
"tic-tac-toe"
] |
Django select_related join model attributes with a single query | 39,062,538 | <p>I'm trying to find a optimal solution with a single query to retrieve attributes on a join model.</p>
<p>I have the following models relationships:</p>
<pre><code>class Player(models.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)
season_team = models.Fo... | 1 | 2016-08-21T08:58:00Z | 39,069,148 | <p>Your models are a little mind-twisting, but something like that should minimize the number of requests</p>
<pre><code>from django.db.models import Q, F, Prefetch
...
def get_context_data(self, **kwargs)
context = super(FormationUpdateView, self).get_context_data(**kwargs)
team = (Team.objects
.sel... | 1 | 2016-08-21T21:47:45Z | [
"python",
"django",
"orm",
"django-select-related"
] |
Parsing a binary file written in MATLAB from Python and vice versa | 39,062,570 | <p>I am having major troubles with <code>struct.unpack</code> in python. I have a binary file with a pre-determined format, that can either be written in MATLAB or in Python.</p>
<p>I can write binary data to a file in Python and read the data back with no issues. I can also write the same data to a binary file from ... | 0 | 2016-08-21T09:03:06Z | 39,062,772 | <p>You may be intrested in pandas hdf5 store:</p>
<p>In Python:</p>
<blockquote>
<pre><code>In [418]: df_for_r = pd.DataFrame({"first": np.random.rand(100),
.....: "second": np.random.rand(100),
.....: "class": np.random.randint(0, 2, (100,))},
.....: ... | 1 | 2016-08-21T09:28:52Z | [
"python",
"matlab",
"file",
"struct",
"binary"
] |
Parsing a binary file written in MATLAB from Python and vice versa | 39,062,570 | <p>I am having major troubles with <code>struct.unpack</code> in python. I have a binary file with a pre-determined format, that can either be written in MATLAB or in Python.</p>
<p>I can write binary data to a file in Python and read the data back with no issues. I can also write the same data to a binary file from ... | 0 | 2016-08-21T09:03:06Z | 39,065,661 | <p>The issue is with <a href="https://en.wikipedia.org/wiki/Endianness" rel="nofollow">endianness</a>, the order of bits in a number. You must be on an x86 or x86-64 computer (since those are the only ones MATLAB supports), and those are <a href="https://en.wikipedia.org/wiki/Endianness#Current_architectures" rel="nof... | 1 | 2016-08-21T15:07:17Z | [
"python",
"matlab",
"file",
"struct",
"binary"
] |
Python - compare files with header field by field | 39,062,671 | <p>I have been trying for a couple of days now and I am still stuck and puzzled at why the following code isn't working.<br>
The issue seems to be related in the if condition while calling the lineNumber function. The function compares the length of two files and it works fine(tried), but when called within the if sta... | -5 | 2016-08-21T09:16:52Z | 39,062,708 | <p>You may have a typo. Try changing</p>
<pre><code>if lineNumber(file, fileb):
</code></pre>
<p>to</p>
<pre><code>if lineNumber(filea, fileb):
</code></pre>
| 1 | 2016-08-21T09:21:37Z | [
"python",
"dictionary",
"compare"
] |
Python - compare files with header field by field | 39,062,671 | <p>I have been trying for a couple of days now and I am still stuck and puzzled at why the following code isn't working.<br>
The issue seems to be related in the if condition while calling the lineNumber function. The function compares the length of two files and it works fine(tried), but when called within the if sta... | -5 | 2016-08-21T09:16:52Z | 39,069,622 | <p>I found the issue. I have updated the code above. Thanks everyone</p>
| 0 | 2016-08-21T23:10:18Z | [
"python",
"dictionary",
"compare"
] |
How to run a python app repeatedly using Bluemix? | 39,062,891 | <p>The Bluemix python build pack works just fine - very easy to <code>cf push myapp --no-route</code>. So far, so good.</p>
<h3>A question, though:</h3>
<p>I want to run it periodically on Bluemix as I would using <code>cron</code> on my local system.</p>
<h3>Background</h3>
<p>The app is not written as a long-runn... | 2 | 2016-08-21T09:45:22Z | 39,064,511 | <p>There are a couple options:</p>
<p>1) If you want to do it completely in Python, you could try something like I did in <a href="http://blog.4loeser.net/2015/07/bluemix-simple-cron-like-service-for-my.html" rel="nofollow">this example</a>. The basic structure is like this:</p>
<pre><code>import schedule
import t... | 2 | 2016-08-21T13:05:22Z | [
"python",
"ibm-bluemix",
"openwhisk"
] |
How to run a python app repeatedly using Bluemix? | 39,062,891 | <p>The Bluemix python build pack works just fine - very easy to <code>cf push myapp --no-route</code>. So far, so good.</p>
<h3>A question, though:</h3>
<p>I want to run it periodically on Bluemix as I would using <code>cron</code> on my local system.</p>
<h3>Background</h3>
<p>The app is not written as a long-runn... | 2 | 2016-08-21T09:45:22Z | 39,250,213 | <p>This turned out to be incredibly easy after having got my head around <em>Openwhisk</em>'s simple <strong>trigger</strong>; <strong>action</strong>; <strong>rule</strong> model. </p>
<p>So I migrated my Python app to <em>Openwhisk</em> entirely rather than use the Bluemix Python buildpack or Bluemix Docker contai... | 2 | 2016-08-31T12:52:55Z | [
"python",
"ibm-bluemix",
"openwhisk"
] |
How to create dictionary from another dictionary if some condition met | 39,062,987 | <p>From dictionary : </p>
<pre><code>{0: (u'Donald', u'PERSON'), 1: (u'John', u'PERSON'), 2: (u'Trump', u'PERSON'), 14: (u'Barack', u'PERSON'), 15: (u'Obama', u'PERSON'), 17: (u'Michelle', u'PERSON'), 18: (u'Obama', u'PERSON'), 30: (u'Donald', u'PERSON'), 31: (u'Jonh', u'PERSON'), 32: (u'Trump', u'PERSON')}
</code></p... | 1 | 2016-08-21T10:00:43Z | 39,063,130 | <p>I think the main problem you need to solve is to identify persons by grouping keys denoting an increasing int sequence, as you described it.</p>
<p>Fortunately, Python has <a href="https://docs.python.org/2.6/library/itertools.html#examples" rel="nofollow">a recipe</a> for this.</p>
<pre><code>from itertools impor... | 3 | 2016-08-21T10:20:39Z | [
"python",
"dictionary",
"count"
] |
How to create dictionary from another dictionary if some condition met | 39,062,987 | <p>From dictionary : </p>
<pre><code>{0: (u'Donald', u'PERSON'), 1: (u'John', u'PERSON'), 2: (u'Trump', u'PERSON'), 14: (u'Barack', u'PERSON'), 15: (u'Obama', u'PERSON'), 17: (u'Michelle', u'PERSON'), 18: (u'Obama', u'PERSON'), 30: (u'Donald', u'PERSON'), 31: (u'Jonh', u'PERSON'), 32: (u'Trump', u'PERSON')}
</code></p... | 1 | 2016-08-21T10:00:43Z | 39,063,228 | <pre><code>def add_name(d, consecutive_keys, result):
result_key = ' '.join(d[k][0] for k in consecutive_keys)
if result_key in result:
result[result_key] += 1
else:
result[result_key] = 1
d = {0: (u'Donald', u'PERSON'), 1: (u'John', u'PERSON'), 2: (u'Trump', u'PERSON'),
14: (u'Barack'... | 2 | 2016-08-21T10:32:53Z | [
"python",
"dictionary",
"count"
] |
How to copy queryset Django | 39,063,017 | <p>I am trying to access queryset of ManyToManyField before and after saving in def save_related(self, request, form, *args, **kwargs) method.
I want to compare them and get new objects, that were added to ManyToManyField.</p>
<p>So, I am getting old queryset with:</p>
<pre><code>def save_related(self, request, form,... | 0 | 2016-08-21T10:04:42Z | 39,063,122 | <p>You can get lists of IDs before and after save, then compare these lists:</p>
<pre><code>def save_related(self, request, form, *args, **kwargs):
obj = form.instance
list_before = list(obj.translations.all().values_list('pk', flat=True))
super(WordAdmin, self).save_related(request, form, *args, ** kwargs... | 0 | 2016-08-21T10:19:44Z | [
"python",
"django",
"many-to-many",
"django-queryset",
"manytomanyfield"
] |
How to copy queryset Django | 39,063,017 | <p>I am trying to access queryset of ManyToManyField before and after saving in def save_related(self, request, form, *args, **kwargs) method.
I want to compare them and get new objects, that were added to ManyToManyField.</p>
<p>So, I am getting old queryset with:</p>
<pre><code>def save_related(self, request, form,... | 0 | 2016-08-21T10:04:42Z | 39,064,659 | <p>The problem is that printing a queryset will evaluate only a slice of the queryset, and as a result, it won't fill the queryset's internal cache.</p>
<p>You need to completely evaluate the queryset before you make the changes, so that the internal cache is filled. The easiest way to do this is with the <code>bool()... | 0 | 2016-08-21T13:21:13Z | [
"python",
"django",
"many-to-many",
"django-queryset",
"manytomanyfield"
] |
How to filter model_set in django | 39,063,092 | <p>Here is my part of template:</p>
<pre><code>{% for sitting in c.sittings %}
{% if sittings.sit_date == sittings.shiftdate_set.all %}
<p>Firstly it was scheduled on {{sitting.sit_date}}</p>
{% endif %}
{% endfor %}
</code></pre>
<p>But this code return all the sitting dates not particula... | 0 | 2016-08-21T10:14:46Z | 39,063,360 | <p>I don't think you can just compare sitting.sit_date to whatever model the shift date is. You probably need to point it to the field that contains the new sit_date and then do this:</p>
<pre><code>{% for sitting in c.sittings %}
{% for shiftdate in sittings.shiftdate_set.all %}
{% if sittings.sit_date ==... | 0 | 2016-08-21T10:49:15Z | [
"python",
"django"
] |
Passing a Python list to C function using the Python/C API | 39,063,112 | <p>I've recently started using the Python/C API to build modules for Python using C code. I've been trying to pass a Python list of numbers to a C function without success:</p>
<p><strong>asdf_module.c</strong></p>
<pre class="lang-c prettyprint-override"><code>#include <stdio.h>
#include <math.h>
#includ... | 1 | 2016-08-21T10:17:54Z | 39,133,508 | <p>This example will show you how to</p>
<ol>
<li>Get the length of the list</li>
<li>Allocate storage for an array of <code>double</code></li>
<li>Get each element of the list</li>
<li>Convert each element to a <code>double</code></li>
<li>Store each converted element in the array</li>
</ol>
<p>Here is the code:</p>... | 0 | 2016-08-24T21:45:23Z | [
"python",
"c"
] |
IndexError: fail to coerce slice entry of type tensorvariable to integer | 39,063,169 | <p>I run "ipython debugf.py" and it gave me error message as below</p>
<pre><code>IndexError Traceback (most recent call last)
/home/ml/debugf.py in <module>()
8 fff = theano.function(inputs=[index],
9 outputs=cost,
---> 10 ... | 3 | 2016-08-21T10:24:59Z | 39,064,543 | <p>Change train_set_x variable to theano.shared variable, and the code is OK.
I dont know the reason, but it works! Hope this post can help others.
The correct code is as below </p>
<pre><code>import theano.tensor as T
import theano
import numpy
index =T.lscalar()
x=T.dmatrix()
cost=x +index
t... | 0 | 2016-08-21T13:08:09Z | [
"python",
"theano"
] |
IndexError: fail to coerce slice entry of type tensorvariable to integer | 39,063,169 | <p>I run "ipython debugf.py" and it gave me error message as below</p>
<pre><code>IndexError Traceback (most recent call last)
/home/ml/debugf.py in <module>()
8 fff = theano.function(inputs=[index],
9 outputs=cost,
---> 10 ... | 3 | 2016-08-21T10:24:59Z | 39,368,179 | <p>The reason this occurs is because index is a tensor symbolic variable (a long scalar, as you can see on line 4). So when python tries to build the dictionary that theano needs for its 'given' input, it tries to slice the numpy array using the symbolic variable â which it obviously can't do because it doesn't have ... | 0 | 2016-09-07T11:03:58Z | [
"python",
"theano"
] |
Python - Regex findall repeated pattern followed by variable length of chars | 39,063,200 | <p>I have the following pattern:<br>
<code>1MHG161 xxxxxxxxxxxxx 1MHG161 xxx</code> <br>
where <code>xxxx</code> is variable length of chars & spaces.</p>
<p>I am trying to capture each one and have the following expected output: <br>
<code>[ '1MHG161 xxxxxxxxxxxxx ' , '1MHG161 xxx' ]</code></p>
<p>I have tri... | 1 | 2016-08-21T10:30:01Z | 39,063,243 | <p>You can use:</p>
<pre><code>>>> re.findall(r"(1MHG161.+?)(?=1MHG161|$)", content)
['1MHG161 xxxxxxxxxxxxx ', '1MHG161 xxx']
</code></pre>
<p>Lookahead <code>(?=1MHG161|$)</code> will match <code>1MHG161</code> or end of line anchor <code>$</code> after your match.</p>
| 3 | 2016-08-21T10:34:50Z | [
"python",
"regex"
] |
Python path in command prompt | 39,063,247 | <p>I had Python3 installed on my computer after Python2. Then I executed "python" in command prompt, Python3 showed up.
How does the command prompt find Python without specifying the path?
Can I switch it back to Python2 without reinstalling?</p>
| 0 | 2016-08-21T10:35:13Z | 39,063,264 | <p>If you are on windows you need the python27 to be first in your PATH enviroment variable</p>
<pre><code>PATH=c:\python27;otherstuff...;c:\python35;...;
</code></pre>
<p>or just write </p>
<pre><code>py -2
</code></pre>
<p>To start python2</p>
| 2 | 2016-08-21T10:38:07Z | [
"python",
"command-prompt"
] |
Cost function for Convolution neural network | 39,063,302 | <p>I am doing Text Classification by Convolution Neural Network. In the example <a href="https://www.tensorflow.org/versions/r0.10/tutorials/mnist/beginners/index.html" rel="nofollow">MNIST</a> they have 60.000 images examples of hand-written digits, each image has size 28 x 28 and there are 10 labels (from 0 to 9). So... | 0 | 2016-08-21T10:42:43Z | 39,063,705 | <p>Placeholder <code>x</code> is an array of flattened images, where first dimension <code>None</code> corresponds to batch size, i.e. number of images, and <code>256000 = 2000 * 128</code>. So, in order to feed <code>x</code> properly you need to flatten your input. Since you mention that your input is numpy arrays, t... | 1 | 2016-08-21T11:31:46Z | [
"python",
"tensorflow",
"word2vec"
] |
django custom property to return filtered field | 39,063,340 | <p>In a django app, with an existing database, I've used <code>inspectdb</code> to build a model:</p>
<pre><code> class Sensorparser(models.Model):
""" a read-only implemenation to access the MeshliumDB """
id_wasp = models.TextField(blank=True, null=True)
id_secret = models.TextField(blank=True, nu... | 2 | 2016-08-21T10:46:54Z | 39,063,398 | <p>You can create <a href="https://docs.djangoproject.com/en/1.10/topics/db/managers/#custom-managers" rel="nofollow">custom manager</a>:</p>
<pre><code>class BatteryManager(models.Manager):
def get_queryset(self):
return super(BatteryManager, self).get_queryset().filter(sensor='BAT')
class Sensorparser(m... | 3 | 2016-08-21T10:53:59Z | [
"python",
"django",
"django-models"
] |
django custom property to return filtered field | 39,063,340 | <p>In a django app, with an existing database, I've used <code>inspectdb</code> to build a model:</p>
<pre><code> class Sensorparser(models.Model):
""" a read-only implemenation to access the MeshliumDB """
id_wasp = models.TextField(blank=True, null=True)
id_secret = models.TextField(blank=True, nu... | 2 | 2016-08-21T10:46:54Z | 39,063,414 | <p>Something like this maybe:</p>
<pre><code>def _get_battery(self):
return self.sensor.objects.filter(sensor='BAT')
battery = property(_get_battery)
</code></pre>
| 0 | 2016-08-21T10:55:55Z | [
"python",
"django",
"django-models"
] |
Parsing an optional list of ranges | 39,063,371 | <p>My script needs to take an option followed by a list of pages, specified as comma-separated list of ranges, and to process the expanded list of pages. So, for instance,</p>
<pre><code>script.py -a 2,4-6,9,10-13
</code></pre>
<p>should get the list</p>
<pre><code>[2, 4, 5, 6, 9, 10, 11, 12, 13]
</code></pre>
<p>t... | 1 | 2016-08-21T10:50:56Z | 39,066,191 | <p>Here's one solution. It's not necessarily the best. In particular, there is probably a more performant version involving chained iterators rather than nested iterators.</p>
<p>Given:</p>
<pre><code>>>> range='2,4-6,9,10-13'
</code></pre>
<p>You could do something like:</p>
<pre><code>>>> res... | 1 | 2016-08-21T16:07:00Z | [
"python",
"argparse"
] |
How to do a "tree walk" recursively on an Abstract Syntax Tree? | 39,063,413 | <p>Simple example of assignment in my language:</p>
<pre><code>x = 3 ->
</code></pre>
<p>Here's the generated AST after parsing (In Python):</p>
<pre><code>[('statement', ('assignment', 'x', ('assignment_operator', '='), ('expr', ('term', ('factor', '3')))), '->')]
</code></pre>
<p>How can I recursively acces... | 6 | 2016-08-21T10:55:55Z | 39,063,464 | <p>To walk a tree, just use a stack or a queue (depending on wether you want to go depth first or breath first).</p>
<p>For each node encountered, push the children onto the stack or into the queue, then take the next item out of the data structure to process and repeat.</p>
<p>For example, breath first could look li... | 6 | 2016-08-21T11:02:05Z | [
"python",
"recursion"
] |
golang appengine - filename too long | 39,063,494 | <p>I developed an appengine application in GO and now I tried to use the androidpublisher api. For this I need many dependencies like:</p>
<ul>
<li>github.com/google/google-api-go-client</li>
<li>github.com/golang/oauth2</li>
<li>google.golang.org/appengine</li>
<li>google.golang.org/appengine/urlfetch</li>
</ul>
<p>... | 2 | 2016-08-21T11:05:42Z | 39,132,556 | <p>I solved the problem by setting my GOPATH.</p>
<p>It's set now like this:</p>
<pre><code>GOPATH=C:\Users\me\development\appengine\gopath;C:\Users\me\project
</code></pre>
<p>Now everything works find and the uploaded file is much smaller now. 2MB vs. 11MB.</p>
<p>Thanks for the tip.</p>
| 0 | 2016-08-24T20:31:46Z | [
"python",
"google-app-engine",
"go"
] |
Update Cassandra Via python | 39,063,661 | <p>I'm quite new to python and I am trying to Update cassandra table via python. When i run the code following error appears.</p>
<pre><code>type error not all arguments converted during string formatting
</code></pre>
<p>error was in following line, is there anything wrong with the formatting with following code,</p... | 1 | 2016-08-21T11:26:59Z | 39,066,915 | <p>The error is because your string is malformed. In this case, it would be better to split the command in many lines for readability:</p>
<pre><code>command = """
UPDATE "CourseAssignment"
SET "value" = '%s'
WHERE "key" = "SYSTEM"
"""
</code></pre>
<p>Using the triple quotes, don't need escaping the inner quotes.</p... | 0 | 2016-08-21T17:26:16Z | [
"python",
"python-3.x",
"cassandra"
] |
Saving Django model with DateTime fields | 39,063,671 | <p>Model:</p>
<pre><code>class Meal(models.Model):
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
collection_from = models.DateTimeField(blank=False, null=False)
discount_price = models.DecimalField(blank=False, null=False, decimal_places=2, max_di... | 1 | 2016-08-21T11:28:21Z | 39,064,936 | <p>Did you try:</p>
<pre><code>from django.utils import timezone
class Meal(models.Model):
...
collection_from = models.DateTimeField(default=timezone.now)
...
</code></pre>
<p>instead of sending current time?</p>
| -1 | 2016-08-21T13:50:50Z | [
"python",
"django",
"datetime",
"django-rest-framework"
] |
How to boost a Keras based neural network using AdaBoost? | 39,063,676 | <p>Assuming I fit the following neural network for a binary classification problem:</p>
<pre><code>model = Sequential()
model.add(Dense(21, input_dim=19, init='uniform', activation='relu'))
model.add(Dense(80, init='uniform', activation='relu'))
model.add(Dense(80, init='uniform', activation='relu'))
model.add(Dense(1... | 1 | 2016-08-21T11:28:46Z | 39,084,657 | <p>Keras itself does not implement adaboost. However, Keras models are compatible with scikit-learn, so you probably can use <code>AdaBoostClassifier</code> from there: <a href="http://scikit-learn.org/stable/modules/generated/sklearn.ensemble.AdaBoostClassifier.html" rel="nofollow">link</a>. Use your <code>model</code... | 2 | 2016-08-22T16:40:49Z | [
"python",
"neural-network",
"keras",
"adaboost",
"boosting"
] |
Ruby's ERB like feature in python | 39,063,728 | <p>I've configuration files some formatted as <code>json</code> some formatted as <code>yaml</code>. I want to be able to read those configuration files with values which comes as environment variables. for example:</p>
<pre><code>{"username":"Dan", "password":"<%= ENV['DB_PASSWORD']%>"}
</code></pre>
<p>Which ... | 2 | 2016-08-21T11:33:49Z | 39,064,824 | <p>What you are looking for is commonly called <em>templating</em>, and you have basically defined a <em>template language</em>.</p>
<p>Depending on what <em>exactly</em> you want to do, you can use the <a href="https://docs.python.org/3/library/string.html#template-strings" rel="nofollow"><code>string.Template</code>... | 1 | 2016-08-21T13:39:16Z | [
"python",
"ruby",
"python-2.7"
] |
Python 2.7 [Errno 113] No route to host | 39,063,817 | <p>I have 2 computers on the same LAN. The first PC has an ip address 192.168.178.30, the other PC has an ip address 192.168.178.26.
Ping, traceroute, telnet, ssh, everything works between the two PCs. Both PCs run the same OS - CentOS 7 and both PCs have the same python version 2.7.5 (checked with the python -V comman... | 1 | 2016-08-21T11:44:49Z | 39,063,838 | <p>You should <code>bind</code> the server socket to <code>'0.0.0.0'</code>, not <code>'192.168.178.30'</code>.</p>
| 1 | 2016-08-21T11:47:24Z | [
"python",
"python-2.7",
"sockets"
] |
Python 2.7 [Errno 113] No route to host | 39,063,817 | <p>I have 2 computers on the same LAN. The first PC has an ip address 192.168.178.30, the other PC has an ip address 192.168.178.26.
Ping, traceroute, telnet, ssh, everything works between the two PCs. Both PCs run the same OS - CentOS 7 and both PCs have the same python version 2.7.5 (checked with the python -V comman... | 1 | 2016-08-21T11:44:49Z | 39,063,883 | <p>Check the firewall (on the server).</p>
| 1 | 2016-08-21T11:52:38Z | [
"python",
"python-2.7",
"sockets"
] |
Python 2.7 [Errno 113] No route to host | 39,063,817 | <p>I have 2 computers on the same LAN. The first PC has an ip address 192.168.178.30, the other PC has an ip address 192.168.178.26.
Ping, traceroute, telnet, ssh, everything works between the two PCs. Both PCs run the same OS - CentOS 7 and both PCs have the same python version 2.7.5 (checked with the python -V comman... | 1 | 2016-08-21T11:44:49Z | 39,063,973 | <p>I stopped the firewall like Messa suggested and now it works. </p>
<pre><code>service firewalld stop
</code></pre>
<p>I still don't understand what the problem was. I even tried using different distributions. Do all distributions have strict firewalls or something. For example Ubuntu to Ubuntu, Ubuntu to CentOS, C... | 0 | 2016-08-21T12:05:23Z | [
"python",
"python-2.7",
"sockets"
] |
Django - How to restrict foreign key choices in dropdown menu depending on datatime field | 39,063,850 | <p><br>I have form for adding data in database and I want to restrict foreign key choices in my dropdown menu. It have to be restricted on my finishDate field. If finishDate is date before today (eg. today is 21-08-2016 and finishDate is 30-06-2013), then I don't want to show foreign key value of that finishDate. What ... | 0 | 2016-08-21T11:49:11Z | 39,063,978 | <p>You can filter it in the <code>__init__</code></p>
<pre><code>import datetime
def NetForm(forms.ModelForm):
#...fields
def __init__(self, *args, **kwargs):
super(NetForm, self).__init__(*args, **kwargs)
# Now set the queryset...
self.fields['idAccount'].queryset = Account.objects.fi... | 0 | 2016-08-21T12:05:42Z | [
"python",
"django",
"date",
"dropdown"
] |
Python pyttsx, how to use external loop | 39,064,089 | <p>In my program I need class(which can be some thread) to check some list like "say_list" and when other classes add some text to it, pyttsx say that text.
I search in pyttsx <a href="http://pyttsx.readthedocs.io/en/latest/engine.html" rel="nofollow">docs</a> and I find some external loops feature but I can not find e... | 0 | 2016-08-21T12:16:58Z | 39,069,269 | <p>I can get the proper results by using python's built in Queue class:</p>
<pre><code>import pyttsx
from Queue import Queue
from threading import Thread
q = Queue()
def say_loop():
engine = pyttsx.init()
while True:
engine.say(q.get())
engine.runAndWait()
q.task_done()
def another_m... | 1 | 2016-08-21T22:05:23Z | [
"python",
"text-to-speech",
"pyttsx"
] |
Failed to establish a new connection | 39,064,126 | <pre><code>import requests
url = 'http://ES_search_demo.com/document/record/_search?pretty=true'
data = '{"query":{"bool":{"must":[{"text":{"record.document":"SOME_JOURNAL"}},{"text":{"record.articleTitle":"farmers"}}],"must_not":[],"should":[]}},"from":0,"size":50,"sort":[],"facets":{}}'
response = requests.get(url, ... | -1 | 2016-08-21T12:20:59Z | 39,064,181 | <p>Seems like your DNS server can't find an address associated to the URL you are passing</p>
| 0 | 2016-08-21T12:26:39Z | [
"python",
"python-2.7",
"ubuntu-14.04"
] |
Failed to establish a new connection | 39,064,126 | <pre><code>import requests
url = 'http://ES_search_demo.com/document/record/_search?pretty=true'
data = '{"query":{"bool":{"must":[{"text":{"record.document":"SOME_JOURNAL"}},{"text":{"record.articleTitle":"farmers"}}],"must_not":[],"should":[]}},"from":0,"size":50,"sort":[],"facets":{}}'
response = requests.get(url, ... | -1 | 2016-08-21T12:20:59Z | 39,064,195 | <blockquote>
<p>NewConnectionError(': Failed to establish a new connection: [Errno -5] No address associated with hostname',))</p>
</blockquote>
<p>In other words, your DNS does not have an IP address for the given host.
Since there is, however, a valid IP address with the domain name <em>given originally</em>, prob... | 0 | 2016-08-21T12:29:07Z | [
"python",
"python-2.7",
"ubuntu-14.04"
] |
Python PyQt QLineEdit to Search bar | 39,064,247 | <p>am trying to build translator and put a search bar in it .with QLineEdit
and what i want is auto complet the word .
..
i tried this . but this code is not working , i'm talking about SearchBar function . but the rest of the code is working with the rest program just fine . but the SearchBar function not working . an... | 0 | 2016-08-21T12:34:41Z | 39,064,919 | <p>The function setModel() and setCompleter() are void, return no value.</p>
<p>Doc: <a href="http://doc.qt.io/qt-4.8/qcompleter.html#setModel" rel="nofollow">setModel</a> <a href="http://doc.qt.io/qt-4.8/qlineedit.html#setCompleter" rel="nofollow">setCompleter</a></p>
<p>You can write like this:</p>
<pre><code... | 0 | 2016-08-21T13:49:13Z | [
"python",
"pyqt4",
"pyqt5"
] |
Python PyQt QLineEdit to Search bar | 39,064,247 | <p>am trying to build translator and put a search bar in it .with QLineEdit
and what i want is auto complet the word .
..
i tried this . but this code is not working , i'm talking about SearchBar function . but the rest of the code is working with the rest program just fine . but the SearchBar function not working . an... | 0 | 2016-08-21T12:34:41Z | 39,066,331 | <p>i found it .. it must pass a list to SearchBar function not a dict ..
so this works .. </p>
<pre><code> # first make an empty lists
self.AraList = []
self.GerList = []
for raw in cors.fetchall():
self.AraList.append(raw[0]) # put all data in one list
self.GerList.append(raw[1]) # "... | 0 | 2016-08-21T16:21:37Z | [
"python",
"pyqt4",
"pyqt5"
] |
Reconnecting to a websocket using AutoBahn | 39,064,347 | <p>I'm getting data from the <a href="https://poloniex.com/support/api/" rel="nofollow">Poloniex API</a> by consuming their websocket API. I'm using the <a href="https://pypi.python.org/pypi/autobahn" rel="nofollow">AutoBahn Python websocket library</a>. </p>
<p>Currently, I'm using the following code to print ticket ... | 1 | 2016-08-21T12:44:47Z | 39,546,824 | <p><em>Since WebSocket connections are persistent, and no data is sent when there's no need, without actual traffic it's not discovered that the underlying connection has been killed</em> (which is what happens when Poloniex Websocket server restart) - <em>at least not quickly.</em> </p>
<p><em>To enable reacting quic... | 0 | 2016-09-17T12:28:56Z | [
"python",
"python-3.x",
"websocket",
"python-asyncio",
"autobahn"
] |
How to assign a variable in my python script? | 39,064,392 | <p>im new to python and i have have script that need to parse different urls
for now i have been able only to make it like this..
i would like to assign a variable into URLList {0 to 10} instead of my solution
thanks you very much</p>
<pre><code>def ReadUrl():
URLList = ['1', '2', '3', '4', '5', '6', '7', '8', '9... | -3 | 2016-08-21T12:51:05Z | 39,064,405 | <p>Use <a href="https://docs.python.org/2/library/functions.html#xrange" rel="nofollow"><code>xrange</code></a> (or <code>range</code> in Python 3):</p>
<pre><code>for i in xrange(1, 11):
url = "http://www.exemple.com/?&page=" + str(i)
.
.
.
</code></pre>
| 1 | 2016-08-21T12:52:50Z | [
"python"
] |
Parsing data from JSON with python | 39,064,490 | <p>I'm just starting out with Python and here is what I'm trying to do. I want to access Bing's API to get the picture of the day's url. I can import the json file fine but then I can't parse the data to extract the picture's url.</p>
<p>Here is my python script:</p>
<pre><code>import urllib, json
url = "http://www.... | 1 | 2016-08-21T13:03:20Z | 39,064,538 | <pre><code>print data["images"][0]["url"]
</code></pre>
<p>there is only one object in "images" array</p>
| 0 | 2016-08-21T13:07:47Z | [
"python",
"json",
"api",
"parsing",
"bing"
] |
Parsing data from JSON with python | 39,064,490 | <p>I'm just starting out with Python and here is what I'm trying to do. I want to access Bing's API to get the picture of the day's url. I can import the json file fine but then I can't parse the data to extract the picture's url.</p>
<p>Here is my python script:</p>
<pre><code>import urllib, json
url = "http://www.... | 1 | 2016-08-21T13:03:20Z | 39,064,564 | <p>Since there is only one element in the <code>images</code> list, you should have <code>data['images'][0]['url']</code>.</p>
<p>You can also see that under the "Viewer" tab in the "json viewer" that you linked to.</p>
| 0 | 2016-08-21T13:11:10Z | [
"python",
"json",
"api",
"parsing",
"bing"
] |
Failed to run an ansible-play book, | 39,064,528 | <p>I created an ansible-playbook which does some system configuration, but when I run it on my cluster, it raises errors like: </p>
<pre><code> [WARNING]: Host file not found: /etc/ansible/hosts
[WARNING]: provided hosts list is empty, only localhost is available
ERROR! Syntax Error while loading YAML.
The erro... | -1 | 2016-08-21T13:07:12Z | 39,065,130 | <p>You've got a syntax error in the task which Ansible complains about (although it points to a different line).</p>
<p>In <code>/home/ansible/goblin/roles/prepare-sys/tasks/main.yml</code> change:</p>
<pre><code>copy:{
</code></pre>
<p>To:</p>
<pre><code>copy: {
</code></pre>
| 1 | 2016-08-21T14:10:04Z | [
"python",
"ansible",
"ansible-playbook"
] |
Failed to run an ansible-play book, | 39,064,528 | <p>I created an ansible-playbook which does some system configuration, but when I run it on my cluster, it raises errors like: </p>
<pre><code> [WARNING]: Host file not found: /etc/ansible/hosts
[WARNING]: provided hosts list is empty, only localhost is available
ERROR! Syntax Error while loading YAML.
The erro... | -1 | 2016-08-21T13:07:12Z | 39,075,153 | <p>Your playbook syntax is flawed.<br>
This code is a mix of dict and string parameters passing, which will not work even if you fix the typo (space between <code>:</code> and <code>{</code>).</p>
<pre><code># THIS CODE IS WRONG
- name: swap selinux file
copy:{
src="$GOBLIN_HOME/roles/prepare-sys/files/selinux... | 0 | 2016-08-22T08:56:22Z | [
"python",
"ansible",
"ansible-playbook"
] |
How to use SimpleHTTPServer? | 39,064,577 | <p>I'm trying to start a simple http server with the most recent version of Python 2.7. I'm following a tutorial and it instructs me to do the following:</p>
<p>Open the Terminal then navigate to our client directory and enter the following command:</p>
<pre><code>$ python -m SimpleHTTPServer
</code></pre>
<p>But no... | 0 | 2016-08-21T13:12:45Z | 39,064,595 | <p>The dollar sign is not part of the command:</p>
<p><code>python -m SimpleHTTPServer</code></p>
<p>I guess it was simply used as a representation for the command line prompt
in the tutorial you have been following</p>
| 0 | 2016-08-21T13:14:14Z | [
"python",
"terminal",
"server",
"directory",
"simplehttpserver"
] |
How to use SimpleHTTPServer? | 39,064,577 | <p>I'm trying to start a simple http server with the most recent version of Python 2.7. I'm following a tutorial and it instructs me to do the following:</p>
<p>Open the Terminal then navigate to our client directory and enter the following command:</p>
<pre><code>$ python -m SimpleHTTPServer
</code></pre>
<p>But no... | 0 | 2016-08-21T13:12:45Z | 39,065,687 | <p>Firstly, if you're just starting to learn Python, I (and the members of the <a href="http://sopython.com" rel="nofollow">Stack Overflow Python community</a>) <strong>strongly</strong> <a href="http://sopython.com/wiki/What_tutorial_should_I_read%3F" rel="nofollow">recommend</a> using <a href="https://www.python.org/... | 0 | 2016-08-21T15:10:13Z | [
"python",
"terminal",
"server",
"directory",
"simplehttpserver"
] |
why must one use __iter__() method in classes? | 39,064,605 | <p>What exactly is the role of <strong>iter</strong>? Consider the following code block:</p>
<pre><code>class Reverse:
def __init__(self,data):
self.data = data
self.index = len(data)
def __iter__(self):
return self
def next(self):
if self.index == 0:
raise StopI... | 0 | 2016-08-21T13:14:47Z | 39,064,642 | <p>The __iter__ return the <a href="https://docs.python.org/3/library/stdtypes.html#iterator-types" rel="nofollow">iterator object</a> which allows to convert the object to a container which can be iterated via <code>for .. in ..</code>.</p>
<p>The iterator object is any object which define __next__ method which retur... | 0 | 2016-08-21T13:19:26Z | [
"python"
] |
why must one use __iter__() method in classes? | 39,064,605 | <p>What exactly is the role of <strong>iter</strong>? Consider the following code block:</p>
<pre><code>class Reverse:
def __init__(self,data):
self.data = data
self.index = len(data)
def __iter__(self):
return self
def next(self):
if self.index == 0:
raise StopI... | 0 | 2016-08-21T13:14:47Z | 39,064,657 | <p>The <code>__iter__</code> method is always called, when an iterator is needed, e.g. by explicitly calling <code>iter</code> or in <code>for</code>-loops or when creating lists <code>list(xy)</code>.</p>
<p>So you cannot use your second class <code>Reverse2</code> in all these contexts.</p>
<pre><code>>>> ... | 1 | 2016-08-21T13:21:12Z | [
"python"
] |
Numpy: advanced slices | 39,064,607 | <p>I need a fast way to find the smallest element among three neighbor elements in a string, and add it to element under the central element. For border elements only two upper elements are checking.</p>
<p>For example I have a numpy array:</p>
<pre><code> [1, 2, 3, 4, 5],
[0, 0, 0, 0, 0]
</code></pre>
<p>I ... | 1 | 2016-08-21T13:15:11Z | 39,064,754 | <p>Use <code>numpy.minimum.reduce</code>:</p>
<pre><code>matrix[h][1:-1] = numpy.minimum.reduce([matrix[h-1][0:-2], matrix[h-1][1:-1], matrix[h-1][2:]])
</code></pre>
<p>For example:</p>
<pre><code>>>> matrix = numpy.zeros((2,10))
>>> matrix[0, :] = numpy.random.randint(0,100,10)
>>> h = 1... | 2 | 2016-08-21T13:32:42Z | [
"python",
"arrays",
"performance",
"numpy",
"slice"
] |
Numpy: advanced slices | 39,064,607 | <p>I need a fast way to find the smallest element among three neighbor elements in a string, and add it to element under the central element. For border elements only two upper elements are checking.</p>
<p>For example I have a numpy array:</p>
<pre><code> [1, 2, 3, 4, 5],
[0, 0, 0, 0, 0]
</code></pre>
<p>I ... | 1 | 2016-08-21T13:15:11Z | 39,064,969 | <p>I would do it explicitly for somewhat more clarity with explicit slicing</p>
<pre><code>n = 10
x = np.random.randint(0,100,n)
y = np.zeros_like(x,dtype=int)
for ind in range(n):
if ind == 0:
lo , hi = None , ind + 2
elif ind >= n-2:
lo , hi = ind - 1 , None
else:
lo , hi = i... | 1 | 2016-08-21T13:53:30Z | [
"python",
"arrays",
"performance",
"numpy",
"slice"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.