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 |
|---|---|---|---|---|---|---|---|---|---|
Python3 "If" not catching what it is checking | 37,683,357 | <p>I've reviewed other questions such as ( <a href="http://stackoverflow.com/questions/15771888/python-if-x-is-none-not-catching-nonetype">Python 'if x is None' not catching NoneType</a> ) and I didn't find that the information was usable for my scenario.</p>
<pre><code> import pyautogui
##################... | 0 | 2016-06-07T15:22:30Z | 37,683,570 | <p>I think what's happening is that when you say you're re-running the function, you're doing so recursively. There's no <code>return</code> after the new call to <code>finder</code>:</p>
<pre><code>if currentImage == None: # if that initial search goes "none" ...
print ("Looking") #Let us know we are looking
... | 1 | 2016-06-07T15:31:36Z | [
"python",
"typeerror",
"nonetype",
"pyautogui"
] |
How to combine two for loops | 37,683,439 | <p>Lets say i'm trying to print 0 to 25 and 75 to 100.
Right now I have:</p>
<pre><code>for x in range(0, 26):
print(x)
for x in range(75, 101):
print(x)
</code></pre>
<p>Is there any way to combine these into a single for loop that lead to:</p>
<pre><code>print(x)
</code></pre>
<p>?</p>
<p>Something along... | 3 | 2016-06-07T15:25:50Z | 37,683,485 | <p>You need the <a href="https://docs.python.org/2/library/itertools.html#itertools.chain"><code>itertools.chain()</code></a>:</p>
<blockquote>
<p>Make an iterator that returns elements from the first iterable until it is exhausted, then proceeds to the next iterable, until all of the iterables are exhausted. </p>
<... | 6 | 2016-06-07T15:27:41Z | [
"python",
"for-loop"
] |
How to combine two for loops | 37,683,439 | <p>Lets say i'm trying to print 0 to 25 and 75 to 100.
Right now I have:</p>
<pre><code>for x in range(0, 26):
print(x)
for x in range(75, 101):
print(x)
</code></pre>
<p>Is there any way to combine these into a single for loop that lead to:</p>
<pre><code>print(x)
</code></pre>
<p>?</p>
<p>Something along... | 3 | 2016-06-07T15:25:50Z | 37,683,507 | <pre><code>for x in list(range(0, 26)) + list(range(75, 101)):
print(x)
</code></pre>
<p>You can concatenate two lists by adding them.</p>
| 0 | 2016-06-07T15:29:04Z | [
"python",
"for-loop"
] |
How to combine two for loops | 37,683,439 | <p>Lets say i'm trying to print 0 to 25 and 75 to 100.
Right now I have:</p>
<pre><code>for x in range(0, 26):
print(x)
for x in range(75, 101):
print(x)
</code></pre>
<p>Is there any way to combine these into a single for loop that lead to:</p>
<pre><code>print(x)
</code></pre>
<p>?</p>
<p>Something along... | 3 | 2016-06-07T15:25:50Z | 37,683,744 | <p>Here's a way to do it with list comprehension and a single line, if you don't want to import anything. You basically add all the numbers to a list, then print the list as a long string with newline characters after each number.</p>
<pre><code>print("\n".join([str(x) for x in range(0,101) if x < 26 or x > 74])... | 0 | 2016-06-07T15:39:45Z | [
"python",
"for-loop"
] |
How to combine two for loops | 37,683,439 | <p>Lets say i'm trying to print 0 to 25 and 75 to 100.
Right now I have:</p>
<pre><code>for x in range(0, 26):
print(x)
for x in range(75, 101):
print(x)
</code></pre>
<p>Is there any way to combine these into a single for loop that lead to:</p>
<pre><code>print(x)
</code></pre>
<p>?</p>
<p>Something along... | 3 | 2016-06-07T15:25:50Z | 37,684,033 | <p>Using List Comprehension:</p>
<pre><code>[i for j in (range(0, 26), range(75, 101)) for i in j]
</code></pre>
| 1 | 2016-06-07T15:54:29Z | [
"python",
"for-loop"
] |
Python alternative to linux bluetooth command "rfcomm connect" | 37,683,473 | <p>Requirement:
I need to connect to a remote bluetooth device & port and send data using a device file.
1. First scan the nearest bluetooth devices
2. connect to a remote BT addr & channel and communicate using a device file (/dev/rfcomm0)</p>
<p>I'm stuck at the second step. I'm able to do it through linux s... | 0 | 2016-06-07T15:27:16Z | 37,684,063 | <p>You can you the os module to run Shell commands. You can store the return value like this:</p>
<pre><code>from os import system
Returnedstring = system("Shell command")
</code></pre>
| 0 | 2016-06-07T15:56:38Z | [
"python",
"linux",
"bluetooth",
"rfcomm",
"pybluez"
] |
Receiving image from python child process to node, base64 encoding | 37,683,499 | <p>I'm having trouble sending an image encoded in base64 from a python child process to node. </p>
<p>I am trying to:</p>
<ul>
<li>Spawn a child process in node to run a python file</li>
<li>Open an image from python</li>
<li>Rotate the image</li>
<li>Encode the image</li>
<li>Return the encoded string to node via st... | 0 | 2016-06-07T15:28:38Z | 38,518,642 | <p>Why do you want to chunk += data.toString()?</p>
<p>The data you are receiving are string already and according to your python code, you are printing the image as a whole, so you don't need to chunk += anything.</p>
<p>Just simply write the stdout into a file at your nodejs side.</p>
<p>Also, you can try to use c... | 0 | 2016-07-22T05:12:57Z | [
"python",
"node.js",
"image",
"encoding"
] |
Error installing the mongo-edu on mac | 37,683,519 | <p>I'm trying to install <a href="https://github.com/przemyslawpluta/mongo-edu" rel="nofollow">mongo-edu</a> on my mac without success.
Does anyone have some solution for it?</p>
<pre class="lang-none prettyprint-override"><code>$ sudo npm install mongo-edu -g
</code></pre>
<p>Error log file:</p>
<pre class="lang-... | 0 | 2016-06-07T15:29:40Z | 37,683,889 | <p>there is a issue with youtube downloader</p>
<p><a href="https://github.com/przemyslawpluta/mongo-edu/issues/77" rel="nofollow">see this</a> </p>
<p>that menas youtube downloader package makes a noise :(</p>
| 0 | 2016-06-07T15:47:43Z | [
"python",
"osx",
"mongodb",
"npm",
"nodes"
] |
Pandas Extract Number from String | 37,683,558 | <p>Given the following data frame:</p>
<pre><code>import pandas as pd
import numpy as np
df = pd.DataFrame({'A':['1a',np.nan,'10a','100b','0b'],
})
df
A
0 1a
1 NaN
2 10a
3 100b
4 0b
</code></pre>
<p>I'd like to extract the numbers from each cell (where they exist).
The desired result... | 0 | 2016-06-07T15:31:02Z | 37,683,738 | <p>Give it a regex capture group:</p>
<pre><code>df.A.str.extract('(\d+)')
</code></pre>
<p>Gives you:</p>
<pre><code>0 1
1 NaN
2 10
3 100
4 0
Name: A, dtype: object
</code></pre>
| 2 | 2016-06-07T15:39:21Z | [
"python",
"string",
"python-3.x",
"pandas"
] |
What is the type of a JSON object in python? | 37,683,572 | <p>I'm new to JSON. I have a dictionary, I convert it to a JSON object using </p>
<pre><code> myJsonObject = json.dumps(myDictionary)
</code></pre>
<p>But then If I check the type, I get <code><type 'str'></code></p>
<p><strong><em>Is string is the expected output for a JSON object?</em></strong></... | 1 | 2016-06-07T15:31:39Z | 37,683,591 | <p>Of course, this is called <a href="https://en.wikipedia.org/wiki/Serialization" rel="nofollow">"Serialization"</a> - you are <a href="https://docs.python.org/2/library/json.html#json.dumps" rel="nofollow">dumping a Python data structure into a JSON formatted string</a>:</p>
<blockquote>
<p><code>json.dumps()</cod... | 4 | 2016-06-07T15:32:28Z | [
"python",
"json",
"python-2.7",
"dictionary",
"types"
] |
What is the type of a JSON object in python? | 37,683,572 | <p>I'm new to JSON. I have a dictionary, I convert it to a JSON object using </p>
<pre><code> myJsonObject = json.dumps(myDictionary)
</code></pre>
<p>But then If I check the type, I get <code><type 'str'></code></p>
<p><strong><em>Is string is the expected output for a JSON object?</em></strong></... | 1 | 2016-06-07T15:31:39Z | 37,683,804 | <p>The N of JSON is for Notation ; it is, indeed, a data format specification. A JSON object is usually intended to be used as a storage or inter-process communication format. That's why it is in Python the universal flat format accepted by write() : a string object.</p>
<p>You can print it to screen, save it to a fil... | 1 | 2016-06-07T15:43:31Z | [
"python",
"json",
"python-2.7",
"dictionary",
"types"
] |
Python - Pandas - How to mark elements in 1 dataframe with elements from a second dataframe? | 37,683,577 | <p>I have 1 dataframe - lets call it dataframe 1:</p>
<pre><code> datetime event name
0 31/10/1996 08:30 US-US Personal Outlays SA
1 31/10/1996 08:30 US-Personal Income
2 01/11/1996 10:00 US-ISM Manufacturing
3 01/11/1996 10:00 US-Factory Orders
4 04/11/1996 10:00 US-Constructio... | 1 | 2016-06-07T15:31:51Z | 37,683,688 | <p>you can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.map.html" rel="nofollow">.map()</a> function for that:</p>
<pre><code>In [336]: d1['Category'] = d1['event name'].map(d2.set_index('Event name')['Category'])
In [337]: d1
Out[337]:
datetime event nam... | 1 | 2016-06-07T15:36:51Z | [
"python",
"pandas"
] |
handling unicode in python2 | 37,683,741 | <pre><code>#!/usr/bin/env python
# -*- coding: utf-8 -*-
import tweepy
import json
import re
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
class listener(StreamListener):
def on_data(self, data):
try:
print data
tweet = data.split(',"text":"')[1].split('","source')[0]
print tw... | 0 | 2016-06-07T15:39:39Z | 37,684,371 | <p>Despite the setdefaultencoding method you can't change default encoding in python 2.7. You should use python 3, (default encoding is UTF-8 and you can change it)</p>
| 1 | 2016-06-07T16:13:33Z | [
"python",
"excel",
"unicode"
] |
Django - how to import from a .csv file in memory | 37,683,749 | <p>I'm writing a page to upload a .csv file and import its content into my models. My current view:</p>
<pre><code>class ContentImport(LoginRequiredMixin, PermissionRequiredMixin,View):
permission_required = 'delivery.change_delivery'
def get(self, request, *args, **kwargs):
form = Uploa... | 0 | 2016-06-07T15:40:19Z | 37,683,861 | <p>This is your problem.</p>
<pre><code>self.import_contents(request.FILES['file'].read())
</code></pre>
<p><code>csv.reader()</code> expects a file like object, not its content.</p>
<p><a href="http://stackoverflow.com/questions/1396126/unexpected-results-feeding-django-file-upload-object-to-python-csv-module?rq=1"... | 3 | 2016-06-07T15:46:19Z | [
"python",
"django",
"csv"
] |
PySide : How to get a QTabWidget to resize with the window? | 37,683,786 | <p>I'm quite new to Python, and I'm developing an app with the PySide library.</p>
<p>I have a <code>QTabWidget</code> in which I will later define buttons/labels/... with some layouts. The question is simple : <strong>I'd like to have my active tab filling the window horizontally and vertically, even when I resize th... | 0 | 2016-06-07T15:42:34Z | 37,689,517 | <p>If your main window is QMainWindow then it is enough to insert QTabWidget with <code>mainwindow->setCentralWidget()</code> - by default it will use all available space.</p>
<p>In other case, to have QTabWidget to follow the resizing/geometry change of parent widget, it is enough to make some layout on the parent... | 1 | 2016-06-07T21:17:17Z | [
"python",
"qt",
"user-interface",
"pyside"
] |
How can I improve this heavily nested for-loop? | 37,683,800 | <p>I have a function which I'd like to optimize, if possible. But I cannot easily tell if there's a better way to refactor (and optimize) this...</p>
<p>Suppose, </p>
<pre><code>keys_in_order = ['A', 'B', 'C', 'D', 'E']
key_table = { 'A': {'A1': 'one', 'A2': 'two', 'A3': 'three', 'A4': 'four'},
'B': {'B1': 'one-one',... | 1 | 2016-06-07T15:43:13Z | 37,684,070 | <p>Some optimizations:</p>
<ul>
<li>The various <code>key_table[?].items()</code> could be computed before the nested loop</li>
<li>You could compute partials of <code>demo_gp</code> when they are available: <code>demo_gp12 = k1 + k2</code>, <code>demo_gp123 = demo_gp12 + k3</code>, etc. Similar thing could be done w... | 1 | 2016-06-07T15:56:48Z | [
"python",
"optimization"
] |
How can I improve this heavily nested for-loop? | 37,683,800 | <p>I have a function which I'd like to optimize, if possible. But I cannot easily tell if there's a better way to refactor (and optimize) this...</p>
<p>Suppose, </p>
<pre><code>keys_in_order = ['A', 'B', 'C', 'D', 'E']
key_table = { 'A': {'A1': 'one', 'A2': 'two', 'A3': 'three', 'A4': 'four'},
'B': {'B1': 'one-one',... | 1 | 2016-06-07T15:43:13Z | 37,684,137 | <p>I have implemented with an alternative method. Consider as <code>key_table</code> as your main dictionary. </p>
<p>My logic is </p>
<ol>
<li><p>From this i will get all the possible sub keys from the main dict.</p>
<pre><code>In [1]: [i.keys() for i in key_table.values()]
Out[1]:
[['A1', 'A3', 'A2', 'A4'],
['C3'... | 2 | 2016-06-07T16:00:28Z | [
"python",
"optimization"
] |
RobotFramework never release global class libraries in python | 37,683,935 | <p>I'm using robot framework with python. I'm implementing a global library to be shared with all the tests. For this, I'm using <code>ROBOT_LIBRARY_SCOPE = 'GLOBAL'</code>. My problem is this library is never released even at the end of the program...</p>
<pre><code>from robot.api import logger
class TestLibrary:
... | 0 | 2016-06-07T15:49:22Z | 37,685,435 | <p>It seems to be that your real problem isn't with <code>__del__</code>, but that you need to run some code when the suite is finished running. While it may seem like <code>__del__</code> is the right solution, it isn't necessarily so.
Python doesn't guarantee that <code>__del__</code> will be run in all cases so it ... | 1 | 2016-06-07T17:16:29Z | [
"python",
"robotframework"
] |
Creating a new column based on condition with values from another column in python | 37,683,997 | <p>I have a Dataframe and would like to create a new column based on condition, in this new column if a certain condition is met then the value will be from another column otherwise it needs to be zero.
The Orginal DataFrame is;</p>
<pre><code>df2 = pd.read_csv('C:\Users\ABC.csv')
df2['Date'] = pd.to_datetime(df2['Dat... | 1 | 2016-06-07T15:52:42Z | 37,684,048 | <p>use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.where.html" rel="nofollow"><code>where</code></a> with your boolean condition, this will set all row values rather than iterating row-wise:</p>
<pre><code>In [120]:
df2['Occupied'] = df2['Value'].where(df2['Hour'] >= 9, 0)
df2
Out[... | 2 | 2016-06-07T15:55:21Z | [
"python",
"if-statement",
"pandas",
"dataframe"
] |
Python xml - how to loop through <tbody> to get data | 37,684,023 | <p>I have added an snippet of the html i wish to scrape.</p>
<p>I would like to go through each row (tbody) and scrape the relevant data using xml.</p>
<p>the xss for each row can be found by the following:</p>
<pre><code>//*[@id="re_"]/table/tbody
</code></pre>
<p>but im unsure how to set it up in python to loop t... | 0 | 2016-06-07T15:54:05Z | 37,684,264 | <p>I'm thinking you'd be interested in <a href="https://www.crummy.com/software/BeautifulSoup/" rel="nofollow">BeautifulSoup</a>.</p>
<p>With your data, if you wanted to print all comment texts, it would be as simple as:</p>
<pre><code>from bs4 import BeautifulSoup
soup = BeautifulSoup(html_doc, 'html.parser')
for t... | -1 | 2016-06-07T16:07:48Z | [
"python",
"xml",
"lxml"
] |
Python xml - how to loop through <tbody> to get data | 37,684,023 | <p>I have added an snippet of the html i wish to scrape.</p>
<p>I would like to go through each row (tbody) and scrape the relevant data using xml.</p>
<p>the xss for each row can be found by the following:</p>
<pre><code>//*[@id="re_"]/table/tbody
</code></pre>
<p>but im unsure how to set it up in python to loop t... | 0 | 2016-06-07T15:54:05Z | 37,689,546 | <p>Using <em>lxml</em>, you can pull the table directly using the class name and extract all the tbody tags with the xpath <code>//table[@class="grid resultRaceGrid"]/tbody</code></p>
<pre><code>from lxml import html
x = html.parse("http://www.racingpost.com/horses/result_home.sd?race_id=651402&r_date=2016-06-07&... | 1 | 2016-06-07T21:19:31Z | [
"python",
"xml",
"lxml"
] |
Extract emails from a data dump using Python | 37,684,058 | <p>I have a data dump from which I am trying to extract all emails. </p>
<p>This is the code I have written using BeautifulSoup</p>
<pre><code>import urllib2
import re
from bs4 import BeautifulSoup
url = urllib2.urlopen("file:///users/home/Desktop/emails.html").read()
soup = BeautifulSoup(url)
email = raw_input(soup)... | 0 | 2016-06-07T15:56:23Z | 37,684,905 | <p>You can parse to the tag you are looking for using <code>find_all</code> method of <code>BeautifulSoup</code>. Here is the code. (I have stored the sample file as <code>a.html</code>)</p>
<pre><code>from bs4 import BeautifulSoup
url = open("a.html",'r').read()
soup = BeautifulSoup(url)
rows = soup.find_all('tr') # ... | -1 | 2016-06-07T16:44:37Z | [
"python",
"parsing",
"web-scraping",
"beautifulsoup"
] |
Extract emails from a data dump using Python | 37,684,058 | <p>I have a data dump from which I am trying to extract all emails. </p>
<p>This is the code I have written using BeautifulSoup</p>
<pre><code>import urllib2
import re
from bs4 import BeautifulSoup
url = urllib2.urlopen("file:///users/home/Desktop/emails.html").read()
soup = BeautifulSoup(url)
email = raw_input(soup)... | 0 | 2016-06-07T15:56:23Z | 37,697,370 | <p>Your example actually works </p>
<pre><code>re.findall(r'\&lt;(.*?)\&gt;',your_data_bump)=
['sampleemail@gmail.com', 'someemail@gmail.com', '123random@gmail.com']
</code></pre>
| 1 | 2016-06-08T08:39:08Z | [
"python",
"parsing",
"web-scraping",
"beautifulsoup"
] |
Python-performance-print large numpy array as strings to tab file | 37,684,059 | <p>I recently had <a href="http://stackoverflow.com/questions/37618611/compare-two-different-size-matrices-to-make-one-large-matrix-speed-improvement/37621374#37621374">this</a> post, where I was assisted in making a big matrix from two smaller matrices. The resulting matrix is correct and creating the multplied numpy... | 0 | 2016-06-07T15:56:25Z | 37,689,265 | <p>For text output there's also the Numpy array <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.tofile.html" rel="nofollow"><code>tofile</code></a> method. Here's a quick benchmark:</p>
<pre><code>import numpy as np
data = np.random.randint(49, size=(55000))
f = open('test.txt', 'w')
print... | 0 | 2016-06-07T20:59:38Z | [
"python",
"arrays",
"numpy",
"matrix"
] |
Python-performance-print large numpy array as strings to tab file | 37,684,059 | <p>I recently had <a href="http://stackoverflow.com/questions/37618611/compare-two-different-size-matrices-to-make-one-large-matrix-speed-improvement/37621374#37621374">this</a> post, where I was assisted in making a big matrix from two smaller matrices. The resulting matrix is correct and creating the multplied numpy... | 0 | 2016-06-07T15:56:25Z | 37,691,549 | <p>As I commented, <code>savetxt</code> iterates over the 'rows' of your array, and writes each, having passed it through a <code>fmt%tuple(row)</code> expression. This still a line by line write; it's just another way of formatting the string.</p>
<p>To write both a string label and numbers you have to create a stru... | 0 | 2016-06-08T00:33:52Z | [
"python",
"arrays",
"numpy",
"matrix"
] |
How do I structure my PyQt GUI right and call a function while passing the ui? | 37,684,087 | <p>I'm pretty new to python and especially to pyqt4 but I would like to learn it right.</p>
<p>Therefore I want to build my new learning project in three different files.
One main.py file in which I call everything. One by the QDesigner generated UI file (Main_Ui.py) and one Main_Functions.py file in which I would lik... | 1 | 2016-06-07T15:58:15Z | 37,689,645 | <p>The problem is your connection</p>
<pre><code>self.ui.btn1.clicked.connect(f.download(self.ui))
</code></pre>
<p>You need to pass a callback to the connect function. Here, you're actually calling the download function (which returns <code>None</code>) and passing the results to <code>connect</code>.</p>
<p>You ne... | 1 | 2016-06-07T21:24:53Z | [
"python",
"function",
"python-3.x",
"pyqt4"
] |
Appending level of column labels to MultiIndex | 37,684,151 | <p>I am trying to change a single level of column labels within a MultiIndex.</p>
<p>For example, </p>
<pre><code>test = pd.DataFrame(np.random.random((4,4)))
test.columns = pd.MultiIndex.from_product([['Level1'],['A','B','C','D'],['Level3']])
Out:
Level1
A B ... | 4 | 2016-06-07T16:01:26Z | 37,684,439 | <p>IIUC you need to set the level values and then the labels in 2 steps:</p>
<pre><code>In [153]:
test.columns = test.columns.set_levels(['0','1','2','3'],level=2)
test.columns = test.columns.set_labels([0,1,2,3],level=2)
test
Out[153]:
Level1
A B C ... | 1 | 2016-06-07T16:16:42Z | [
"python",
"pandas"
] |
Appending level of column labels to MultiIndex | 37,684,151 | <p>I am trying to change a single level of column labels within a MultiIndex.</p>
<p>For example, </p>
<pre><code>test = pd.DataFrame(np.random.random((4,4)))
test.columns = pd.MultiIndex.from_product([['Level1'],['A','B','C','D'],['Level3']])
Out:
Level1
A B ... | 4 | 2016-06-07T16:01:26Z | 37,685,208 | <p>Alternatively, you could use <code>pd.MultiIndex.from_tuples</code></p>
<pre><code>test = pd.DataFrame(np.random.random((4,4)))
index_tuples = [('Level1',letter,number) for letter,number in zip(['A','B','C','D'],range(1,4+1))]
test.columns = pd.MultiIndex.from_tuples(index_tuples)
</code></pre>
| 0 | 2016-06-07T17:02:10Z | [
"python",
"pandas"
] |
Convert exception error to string | 37,684,153 | <p>I want to work with the error message from an exception but can't seem to convert it to a string. I've read the os library man page but something is not clicking for me.</p>
<p>Printing the error works:</p>
<pre><code>try:
os.open("test.txt", os.O_RDONLY)
except OSError as err:
print ("I got this error: "... | 6 | 2016-06-07T16:01:35Z | 37,684,209 | <p>From <a href="https://docs.python.org/3/library/functions.html#print" rel="nofollow">the docs for <code>print()</code></a></p>
<blockquote>
<p>All non-keyword arguments are converted to strings like str() does and written to the stream</p>
</blockquote>
<p>So in the first case, your error is converted to a strin... | 5 | 2016-06-07T16:04:35Z | [
"python"
] |
Python cannot run module from command line; IPython can | 37,684,228 | <p>This is the directory structure for my modules:
<a href="http://i.stack.imgur.com/v8cPW.png" rel="nofollow">Directory Structure</a></p>
<p>As can be seen, <code>DataProcessor</code> is a module inside which <code>DataLoader</code> has certain functions.</p>
<p>Inside the <code>lda</code> module, the file <code>HFT... | 2 | 2016-06-07T16:05:36Z | 37,689,828 | <p>The path calculation for your python scripts is being affected by initializers or cd directory, or your ipython is actually launching a different python binary. Given that your ipython is pointing into your virtualenv directory I am guessing its the former.</p>
<p>Normally the directory you're running from is added... | 0 | 2016-06-07T21:38:41Z | [
"python",
"python-2.7"
] |
Why does glob not work on a DFS share with command line administrator mode? | 37,684,574 | <p>I have a DFS network share that contains a couple of xml files, and I have written a python script that will grab my xml files using <code>glob</code></p>
<p>The following is my DFS structure</p>
<pre><code>ââ O
âââââ my_path
| âââ test1.xml
| âââ test1.xml
| âââ test... | 1 | 2016-06-07T16:24:36Z | 37,703,419 | <p>Try this:</p>
<pre><code>import glob
import os
path = os.path.join('O:', 'my_path', '*.xml')
print(path)
files = glob.glob(path)
print 'Files found: {}'.format(len(files))
</code></pre>
| 0 | 2016-06-08T13:08:04Z | [
"python",
"glob"
] |
Emacs/Python - function expected an indented block | 37,684,669 | <p>I made the switch to Emacs. I am using Elpy within Emacs as an IDE. My setup is side-by-side windows, on the left is a buffer(script) where I write/edit the code which then gets sent to the IPython shell on the right with <code>Ctrl-Enter</code>. When I type the function:</p>
<pre><code> import numpy as np
import ... | 0 | 2016-06-07T16:30:41Z | 37,686,377 | <p>To send the whole buffer you can press <kbd> C-c C-c </kbd>. You can send the whole region with <kbd> C-c C-r </kbd> and you can send the current line that you are by binding the following function. The following function is essentially a copy of <code>python-shell-send-buffer</code></p>
<pre><code>(defun python-sh... | 1 | 2016-06-07T18:08:38Z | [
"python",
"function",
"shell",
"emacs",
"elpy"
] |
Different import variable has different id in Python2.7? | 37,684,687 | <p>Consider the following source structure:</p>
<pre><code>module/data/__init__.py
module/data/repo.py
module/__init__.py
module/test.py
</code></pre>
<p>And the following code:</p>
<p><strong>repo.py</strong></p>
<pre><code>goods = {}
</code></pre>
<p><strong>test.py</strong></p>
<pre><code>from data import repo... | 1 | 2016-06-07T16:31:59Z | 37,694,151 | <p>You can see that <code>repo1</code> and <code>repo2</code> are different modules, so they are in different namespaces.</p>
<pre><code>print globals()
#Produces the below output (formatted for readability)
{'__builtins__': <module '__builtin__' (built-in)>,
'__file__': '/home/zhou/PycharmProjects/test_impor... | 0 | 2016-06-08T05:45:32Z | [
"python",
"python-2.7"
] |
reordering fixed legth array in python | 37,684,710 | <p>I'm looking for the best way to perform this task in Python 2.x</p>
<p>I have an array of given size, with some element that have to stay at given position identified by attribute. </p>
<p>I have to remove an element from the array, and move all the non fixed elements to the top, and fill the missing bottom entry ... | 1 | 2016-06-07T16:33:05Z | 37,685,294 | <p>I'm assuming you are using python lists</p>
<p>The first three lines just create a list with 3 items. Use your lists instead.</p>
<p>Pop removes the item at the index provided and returns its value
a.append(a[0]) takes the first item, and appends it to the end of the list</p>
<pre><code>>>> a.append(0)
... | 1 | 2016-06-07T17:07:22Z | [
"python",
"arrays",
"sorting",
"python-2.x"
] |
reordering fixed legth array in python | 37,684,710 | <p>I'm looking for the best way to perform this task in Python 2.x</p>
<p>I have an array of given size, with some element that have to stay at given position identified by attribute. </p>
<p>I have to remove an element from the array, and move all the non fixed elements to the top, and fill the missing bottom entry ... | 1 | 2016-06-07T16:33:05Z | 37,685,680 | <p>The answer from joel goldstick is probably your best bet. In some fashion you will need to move the rest of the list up to fill the gap. Here is an example the does the same thing programmatically:</p>
<pre><code>removeIndex = 6 //index to remove
for i in range(removeIndex+1, len(ary)-1... | 0 | 2016-06-07T17:29:31Z | [
"python",
"arrays",
"sorting",
"python-2.x"
] |
subprocess.Popen sets size and location of the external executed programme? | 37,684,715 | <p>I would like to execute an external programme from python via subprocess.Popen. I am wondering whether it is possible to set size and location of the window for the external programme that is executed via the command?</p>
| 0 | 2016-06-07T16:33:24Z | 37,684,832 | <p>I assume Windows for such a question?</p>
<p>You may specify the window to be minimized or maximized, using the <a href="https://docs.python.org/3/library/subprocess.html#subprocess.STARTUPINFO" rel="nofollow"><code>startupinfo</code></a> parameter of popen.</p>
<pre><code>si = subprocess.STARTUPINFO()
si.dwFlags ... | 3 | 2016-06-07T16:40:53Z | [
"python",
"subprocess",
"popen"
] |
groupby and normalize over two arrays | 37,684,836 | <p>I have a<code>DataFrame</code> where the columns are a <code>MultiIndex</code>. The first <code>level</code> specifies <code>'labels'</code>, the second specifies <code>'values'</code>. A <code>'label'</code> in the <code>(i, j)</code> position of <code>df.labels</code> corresponds to the <code>'value'</code> in th... | 3 | 2016-06-07T16:41:09Z | 37,684,837 | <pre><code>df.loc[:, pd.IndexSlice['values', :]] = df.stack().groupby('labels')['values'].apply(lambda x: x / x.sum()).unstack().values
</code></pre>
| 1 | 2016-06-07T16:41:09Z | [
"python",
"numpy",
"pandas",
"group-by",
"multi-index"
] |
groupby and normalize over two arrays | 37,684,836 | <p>I have a<code>DataFrame</code> where the columns are a <code>MultiIndex</code>. The first <code>level</code> specifies <code>'labels'</code>, the second specifies <code>'values'</code>. A <code>'label'</code> in the <code>(i, j)</code> position of <code>df.labels</code> corresponds to the <code>'value'</code> in th... | 3 | 2016-06-07T16:41:09Z | 37,685,625 | <p>To get the normalized values, you could:</p>
<pre><code>new_values = pd.DataFrame(data=np.zeros(df['values'].shape))
for v in np.unique(df['labels']):
mask = df['values'].where(df['labels'].isin([v]))
new_values += mask.div(mask.sum().sum()).fillna(0)
df.loc[:, 'values'] = new_values.values
</code></pre>
<... | 2 | 2016-06-07T17:26:39Z | [
"python",
"numpy",
"pandas",
"group-by",
"multi-index"
] |
How to redirect to a page in python | 37,684,978 | <p><div class="snippet" data-lang="js" data-hide="false" data-console="true">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>def do_GET(self):
if self.path == "/":
self.path = "/index.html"
elif self.path == "/train":
self.path = "/train.html"
... | 0 | 2016-06-07T16:48:27Z | 37,685,087 | <p>I am using Flask and here is what I do: <code>return redirect(url_for('method_name'))</code>. I would definitely recommend using it as well since it makes web development much cleaner. </p>
<p>It has nice wrappers that can help you do authentication, define what actions work for what routes( say for your index pag... | 0 | 2016-06-07T16:55:14Z | [
"python",
"redirect"
] |
'int' object has no attribute 'flatten' | 37,685,084 | <p>I am working on a code this gives me a error saying <code>'int' object has no attribute 'flatten'</code>. I am using kmean algorithm for k=2 to cluster my data (passed as a list of data points). </p>
<pre><code>import csv
import numpy as np
k=2
data=[23,43,67,89,1,10,101,243,34]
clusters = [[] for i in range(k)]
de... | 0 | 2016-06-07T16:55:13Z | 37,685,488 | <p>As mentioned in comments, you tried apply <code>flatten</code> to one <code>int</code> element (not to numpy array). Try </p>
<pre><code>centroids.append([data[np.random.randint(0, len(data), size=1)]])
</code></pre>
<p>instead of </p>
<pre><code>centroids.append(data[np.random.randint(0, len(data), size=1)].flat... | 0 | 2016-06-07T17:19:25Z | [
"python",
"python-3.x"
] |
Download CSV file generated players export - OneSignal | 37,685,145 | <p>How do I download the csv generated by this route: <a href="https://onesignal.com/api/v1/players/csv_export?app_id=" rel="nofollow">https://onesignal.com/api/v1/players/csv_export?app_id=</a></p>
<p>-I am able to get the s3 link of the file.</p>
<p>-I do a Get Request on the CSV file. I have tried using the same ... | 1 | 2016-06-07T16:58:38Z | 37,686,364 | <p>The export file may take a few minutes to generate depending on its size. You should keep trying until you no longer get an error. No authorization is required to download the file.</p>
<p>If it has been longer than 15 minutes and the file is still not available, you should get in touch with OneSignal's support tea... | 0 | 2016-06-07T18:07:52Z | [
"python",
"amazon-s3",
"get",
"amazon",
"onesignal"
] |
Download CSV file generated players export - OneSignal | 37,685,145 | <p>How do I download the csv generated by this route: <a href="https://onesignal.com/api/v1/players/csv_export?app_id=" rel="nofollow">https://onesignal.com/api/v1/players/csv_export?app_id=</a></p>
<p>-I am able to get the s3 link of the file.</p>
<p>-I do a Get Request on the CSV file. I have tried using the same ... | 1 | 2016-06-07T16:58:38Z | 37,702,604 | <p>From OneSignal Support, the link returned with that initial route returns the proper url now:</p>
<p>|Hi there. We found a bug in our system that returned the wrong CSV url in some cases. Sorry for the inconvenience.
This issue is now resolved so you should get a valid URL. You can then download the CSV export with... | 0 | 2016-06-08T12:32:12Z | [
"python",
"amazon-s3",
"get",
"amazon",
"onesignal"
] |
What is the random code set in the middle of a URL? | 37,685,334 | <p>I have a URL: <a href="http://www.cbonline.co.uk/resources/b63662d3-b27b-4239-821d-844d74ee51f8/something.xls" rel="nofollow">http://www.cbonline.co.uk/resources/b63662d3-b27b-4239-821d-844d74ee51f8/something.xls</a>, and I need to download the file from it automatically by Python 2.7. That means I need to reconstru... | -2 | 2016-06-07T17:10:07Z | 37,685,423 | <p>It is an UUID - a random unique ID for the file in question. Basically: you either have that number from some other source (usually an API endpoint, or an HTML page witha listing and links) or you can't have the URL.</p>
| 2 | 2016-06-07T17:15:33Z | [
"python",
"url"
] |
How to call from Python Perl scripts with arguments that return values? | 37,685,383 | <p>I would like to call a Perl script with arguments from my Python program.
so far I have been able to do it using subprocess and piping</p>
<pre><code>#!/usr/bin/python
import subprocess
var = "world"
pipe = subprocess.Popen(["./x.pl", var], stdout=subprocess.PIPE)
result = pipe.stdout.read()
print result
#!/usr/bi... | 0 | 2016-06-07T17:13:31Z | 37,685,708 | <p>Personally, I wouldn't change the Perl script at all. It's already designed to handle a request from its parent process and return its response via stdout. Just provide an appropriate CGI environment for it.</p>
<p>If you want to return transmit a more complex structure, you'll need to serialize it. JSON is usually... | 3 | 2016-06-07T17:31:29Z | [
"python",
"perl"
] |
shutil samefile error on Linux | 37,685,401 | <p>I have a python script that is giving me a hard time on Ubuntu 12.02 with Python 2.7.3.</p>
<p>PS: it runs without problems on Windows.</p>
<pre class="lang-none prettyprint-override"><code>>>> import os
>>> import shutil
>>> shutil.copy("/mnt/my_network_dive/somewhere/sample.xml", "/mn... | 3 | 2016-06-07T17:14:31Z | 37,685,521 | <p>It looks like the two files are both hard links to the same file. You can tell because they share the same inode number</p>
<pre><code>st_ino=4913809333
</code></pre>
<p>Windows users generally don't create hard links. They are more common in linux environments, which is why you may have not encountered the prob... | 2 | 2016-06-07T17:21:10Z | [
"python",
"python-2.7",
"shutil"
] |
shutil samefile error on Linux | 37,685,401 | <p>I have a python script that is giving me a hard time on Ubuntu 12.02 with Python 2.7.3.</p>
<p>PS: it runs without problems on Windows.</p>
<pre class="lang-none prettyprint-override"><code>>>> import os
>>> import shutil
>>> shutil.copy("/mnt/my_network_dive/somewhere/sample.xml", "/mn... | 3 | 2016-06-07T17:14:31Z | 37,685,755 | <p>In <strong>python 3</strong> in shutil.copy there's additional argument follow_symlinks=True
Look at this <a href="https://docs.python.org/3/library/shutil.html" rel="nofollow">https://docs.python.org/3/library/shutil.html</a></p>
<blockquote>
<p>If follow_symlinks is false, and src is a symbolic link, dst will b... | 0 | 2016-06-07T17:33:50Z | [
"python",
"python-2.7",
"shutil"
] |
Avoid scaling binary columns in sci-kit learn StandsardScaler | 37,685,412 | <p>I'm building a linear regression model in sci-kit learn, and am scaling the inputs as a preprocessing step in a sci-kit learn Pipeline. Is there any way I can avoid scaling binary columns? What's happening is that these columns are being scaled with every other column, causing the values to be centered around 0, rat... | 1 | 2016-06-07T17:14:58Z | 37,685,846 | <p>You should create a custom scaler which ignores the last two columns while scaling.</p>
<pre><code>from sklearn.base import TransformerMixin
import numpy as np
class CustomScaler(TransformerMixin):
def __init__(self):
self.scaler = StandardScaler()
def fit(self, X, y):
self.scaler.fit(X[:... | 1 | 2016-06-07T17:38:51Z | [
"python",
"scikit-learn",
"multi-dimensional-scaling"
] |
Python - ValueError: could not convert string to float: | 37,685,468 | <p>I am trying to make a simple decision tree , but I keep on getting the same ValueError and none of the similar threats was of any help. None of my variables are string but still I am getting an error in conversion. </p>
<pre><code>from pandas import Series, DataFrame
import pandas as pd
import numpy as np
import os... | 1 | 2016-06-07T17:18:06Z | 37,686,039 | <p>It is most likely a problem with the data. Since you don't have any point in the code where you attempt to convert to float, it must be that the data you have is in a form that prevents it from being read as a number by your parsing commands.</p>
| 0 | 2016-06-07T17:49:04Z | [
"python",
"decision-tree"
] |
How to plot data read continuously at 15000 points per second in real time with Python? | 37,685,497 | <p>Iâve written a Python script that reads and stores 15000 data points (voltage readings) per second as they are streamed from a LabJack U3-HV connected to a function generator. I am using Pythonâs multiprocessing to read the voltage data from the LabJack at 15000 Hz in one process, passing the data through a pipe... | 2 | 2016-06-07T17:19:48Z | 38,094,404 | <p>I think i can give you two advises:</p>
<p>-if it's possible, reduce the number of points to display (it surely reduce the requirements of the problems) by using for example a point every three (in my application i used to display 6000 points at the second).</p>
<p>-use the animation library, it's quite user-frien... | 0 | 2016-06-29T08:38:54Z | [
"python",
"matplotlib",
"plot"
] |
Pandas: merging two dataframes and retaining only common column names | 37,685,517 | <p>I have two data frames and some column names are same and some are different. I want to make a merged dataframe which has only the common column names. </p>
<p>For instance</p>
<pre><code>d1 = {'group' : ('A', 'B', 'C') , 'names' : ('alpha', 'beta', 'gamma') ,'num1': (1,2,3)}
df1 = pd.DataFrame(d1)
d2 = {'group'... | 0 | 2016-06-07T17:20:52Z | 37,685,738 | <p>I think you want to do a <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.concat.html" rel="nofollow"><code>concat</code></a> instead of a <code>merge</code>:</p>
<pre><code>df = pd.concat([df1, df2], join='inner', ignore_index=True)
</code></pre>
<p>The resulting output:</p>
<pre><code> gro... | 1 | 2016-06-07T17:32:47Z | [
"python",
"pandas",
"dataframe",
"merge"
] |
How to create an object using another model with same attributes in Django | 37,685,538 | <p>is it possible to create an object using another object which model has the same attributes?</p>
<p>In my case, I have two models - <code>TemporaryJob</code> and <code>Job</code>. The <code>TemporaryJob</code> is created when user fills the form. Next thing is to confirm. If he confirms <code>TemporaryJob</code>, t... | 0 | 2016-06-07T17:22:21Z | 37,686,136 | <p>First of all, Klaus D. comment is correct: I also don't think that your design is correct. Instead of having <code>Job</code> and <code>TemporaryJob</code> models with similar fields you should only have a <code>Job</code> model that has a boolean <code>is_temporary</code> field that would be <code>True</code> of th... | 2 | 2016-06-07T17:54:20Z | [
"python",
"django",
"inheritance",
"django-models"
] |
Scrapy: Using FormRequests to handle javascript doPostBack functions | 37,685,550 | <p>I have a clickable link on a dynamically created page, that looks like:</p>
<pre><code><td align="left"><a id="ucResultsGrid_X77" href="javascript:WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions(&quot;ucResultsGrid$X77&quot;, &quot;&quot;, false, &quot;&quot;, &quot;we... | 0 | 2016-06-07T17:22:47Z | 37,685,822 | <p>the final idea is to replicate a Request, not really replicate a "click", which could involve several requests or just internal javascript processing with the actual response.</p>
<p><code>formdata</code> is just another argument you can fill in that FormRequest, the final idea behind <code>from_response</code> is ... | 1 | 2016-06-07T17:37:37Z | [
"python",
"asp.net",
"scrapy"
] |
python re.sub replacement function scope issue | 37,685,561 | <p>I have a method that as part of its work, calls re.sub with the replacement value supplied as a function. This function is defined within this greater function. </p>
<p>The problem is the this inner function that is passed as a parameter to re.sub is not able to access variables defined in the outer function. How c... | 0 | 2016-06-07T17:23:11Z | 37,686,415 | <p>I think <a href="http://stackoverflow.com/questions/5218895/python-nested-functions-variable-scoping">this answer</a> hits on what you're looking for.</p>
<p>I think the simple solution is to make <code>unsub_link</code> a global variable, which seems hackish but would let your callback function have access to it. ... | -1 | 2016-06-07T18:10:16Z | [
"python",
"scope",
"callback"
] |
Python 3 - Replacing part of a string with imformation from the string | 37,685,599 | <p>I have a python project where I am essentially coding a custom language, and for it I need a function that can replace user entered strings with different data, for example random numbers (It's hard to explain what I want to do c:)</p>
<p>An example of this would be that the user types into the command line:</p>
<... | -1 | 2016-06-07T17:25:20Z | 37,685,882 | <p>You can try to use <code>str.find</code> functionality from Python. <a href="https://docs.python.org/3/library/stdtypes.html#str.find" rel="nofollow">Documentation</a></p>
<p>Example:</p>
<pre><code>def parseFunction(input):
index = input.find('{') # or look for more i.e. find('{RANDOM_INT')
return input... | 0 | 2016-06-07T17:40:28Z | [
"python",
"function",
"python-3.x",
"parsing"
] |
Python 3 - Replacing part of a string with imformation from the string | 37,685,599 | <p>I have a python project where I am essentially coding a custom language, and for it I need a function that can replace user entered strings with different data, for example random numbers (It's hard to explain what I want to do c:)</p>
<p>An example of this would be that the user types into the command line:</p>
<... | -1 | 2016-06-07T17:25:20Z | 37,686,145 | <p>Is this what you needed?</p>
<pre><code>import re
import random
def parseFunction(string):
matches = re.match('.*\{r\[(\d+),(\d+)\]\}.*',string)
rand = random.randint(int(matches.groups()[0]), int(matches.groups()[1]))
result = re.sub('\{r\[(\d+),(\d+)\]\}',str(rand),string)
return result
</code></p... | 0 | 2016-06-07T17:54:31Z | [
"python",
"function",
"python-3.x",
"parsing"
] |
Python 3 - Replacing part of a string with imformation from the string | 37,685,599 | <p>I have a python project where I am essentially coding a custom language, and for it I need a function that can replace user entered strings with different data, for example random numbers (It's hard to explain what I want to do c:)</p>
<p>An example of this would be that the user types into the command line:</p>
<... | -1 | 2016-06-07T17:25:20Z | 37,686,622 | <p>Well, instead of using the Python template string (which are powerful but limited) I suggest you using <a href="http://jinja.pocoo.org/" rel="nofollow">Jinja2</a> templates.</p>
<p>This template engine is well-known for developing web applications.</p>
<p>To implement your custom language, you can use <strong>filt... | 0 | 2016-06-07T18:23:07Z | [
"python",
"function",
"python-3.x",
"parsing"
] |
Python error Inconsistent intendation detected | 37,685,619 | <p>I'm fiddeling with a python script for replacing some characters in a specific column of a tab seperated text file.</p>
<p>If I run the script I get the Error: Inconsistent intendation detected.</p>
<pre><code>import csv
# File names: to read in from and read out to
input_file = "test.txt"
output_file = input_file... | -1 | 2016-06-07T17:26:25Z | 37,685,646 | <p>Instead of </p>
<pre><code>with open(input_file) as to_read:
with open(output_file, "wb") as tmp_file:
</code></pre>
<p>you need to use</p>
<pre><code>with open(input_file) as to_read:
with open(output_file, "wb") as tmp_file:
</code></pre>
| 2 | 2016-06-07T17:27:59Z | [
"python",
"csv",
"replace"
] |
How to call a large python script in C++? | 37,685,626 | <p>I am trying to take aspects of two different scripts and use them in a single C++ program (using Ubuntu). The problem I have is that one of the scripts is written in C++ and the other is written in python. I have been trying to accomplish this using the Python.h library, but (being fairly new to programming), I cann... | -2 | 2016-06-07T17:26:55Z | 37,686,563 | <p>You should use popen, it pipes stdin/stdout of child process to returned file handle. Now what you can do is </p>
<pre><code>File* in = popen("python script_name.py", "r");
</code></pre>
<p>Now you can use this <code>FILE*</code> to read the output of your python script.</p>
<p>Than you can use <code>fscanf(in, b... | 1 | 2016-06-07T18:19:40Z | [
"python",
"c++",
"python-2.7",
"unix",
"ubuntu"
] |
python module and imports | 37,685,664 | <p>If this is my directory tree</p>
<pre><code>temp
âââ __init__.py
âââ __main__.py
0 directories, 2 files
</code></pre>
<p>And I have the following code in <code>__init__.py</code> and in <code>__main__.py</code></p>
<h2>__init__.py</h2>
<pre><code>"""Initializes the module"""
CONSTANT = 1
sys.exit("... | 2 | 2016-06-07T17:28:52Z | 37,685,799 | <p>You should be running it from out of the <code>temp</code> directory. If <code>someDir</code> contains your <code>temp</code> directory, then:</p>
<pre><code>someDir $ python -m temp #someDir/temp/__init__.py is your file.
</code></pre>
<hr>
<blockquote>
<p>On running python . in the temp directory I get the ... | 1 | 2016-06-07T17:35:55Z | [
"python",
"python-2.7",
"module",
"python-import"
] |
python module and imports | 37,685,664 | <p>If this is my directory tree</p>
<pre><code>temp
âââ __init__.py
âââ __main__.py
0 directories, 2 files
</code></pre>
<p>And I have the following code in <code>__init__.py</code> and in <code>__main__.py</code></p>
<h2>__init__.py</h2>
<pre><code>"""Initializes the module"""
CONSTANT = 1
sys.exit("... | 2 | 2016-06-07T17:28:52Z | 37,685,805 | <p>You are running <em>inside</em> <code>temp</code>; this is not considered a package and <code>__init__.py</code> is not loaded. Only if the <em>parent</em> of the current directory is on the module loading path and you explicitly load <code>temp</code> as a module, is <code>__init__.py</code> loaded.</p>
<p>Because... | 1 | 2016-06-07T17:36:12Z | [
"python",
"python-2.7",
"module",
"python-import"
] |
python module and imports | 37,685,664 | <p>If this is my directory tree</p>
<pre><code>temp
âââ __init__.py
âââ __main__.py
0 directories, 2 files
</code></pre>
<p>And I have the following code in <code>__init__.py</code> and in <code>__main__.py</code></p>
<h2>__init__.py</h2>
<pre><code>"""Initializes the module"""
CONSTANT = 1
sys.exit("... | 2 | 2016-06-07T17:28:52Z | 37,685,860 | <p>When you tell Python to run a directory, <strong>Python does not treat the directory as a package</strong>. Instead, Python <a href="https://docs.python.org/2/using/cmdline.html#interface-options" rel="nofollow">adds that directory to <code>sys.path</code> and runs its <code>__main__.py</code></a>. <code>__init__.py... | 1 | 2016-06-07T17:39:25Z | [
"python",
"python-2.7",
"module",
"python-import"
] |
socket.error: [Errno 54] Connection reset by peer Selenium-python | 37,685,675 | <p>I am new to selenium and trying an exampler http://www.marinamele.com/selenium-tutorial-web-scraping-with-selenium-and-python">here</p>
<pre><code>import time
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.su... | 2 | 2016-06-07T17:29:21Z | 37,686,171 | <p>Downgrade your firefox and try again.Looks like all versions of firefox not compatible with selenium.</p>
<p>Reference:<a href="http://stackoverflow.com/questions/36063908/selenium-2-50-not-working-on-firefox-45">Selenium 2.50 not working on firefox 45</a></p>
| 2 | 2016-06-07T17:56:15Z | [
"python",
"sockets",
"selenium"
] |
Finding specific links with Beautiful Soup | 37,685,718 | <p>I'm using Beautiful Soup for Python to parse a webpage in order to download data from certain files and aggregate them into one file. The webpages I'm parsing contain tons of different download links, and I'm having trouble getting the specific links that I want.</p>
<p>The HTML is essentially set up like this:</p>... | 1 | 2016-06-07T17:31:51Z | 37,686,045 | <p>The <code>text</code> argument (which is now called <code>string</code>) would not search inside the children elements texts of an element (why? - see the last note inside this <a href="https://www.crummy.com/software/BeautifulSoup/bs4/doc/#string" rel="nofollow">documentation paragraph</a>, <code>.string</code> wou... | 1 | 2016-06-07T17:49:34Z | [
"python",
"beautifulsoup"
] |
search for specific character in string | 37,685,735 | <p>I want to search for the plus sign in <code>message_in_ascii</code> but I kept getting this error:</p>
<blockquote>
<p>UnicodeDecodeError: 'utf-8' codec can't decode byte 0xbc in position 8: invalid start byte</p>
</blockquote>
<p>I'm using this code:</p>
<pre><code>import binascii
message_in_ascii= binascii.... | 0 | 2016-06-07T17:32:41Z | 37,687,252 | <p>Can you post a message you passing ? also try to unicode instead of str in if statement.</p>
| 0 | 2016-06-07T18:58:46Z | [
"python",
"python-3.x"
] |
Looping the function | 37,685,739 | <p>I have this function below, which I have done something wrong in somewhere.</p>
<pre><code>def quantityFunction(product):
valid = False
while True:
if product is not None:
quantity = input("Please enter the amount of this item you would like to purchase: ")
for i in quantity:... | 2 | 2016-06-07T17:32:49Z | 37,685,859 | <p>You said:</p>
<blockquote>
<p>the code should loop back to the start of the function if it hits the Value Error.</p>
</blockquote>
<p>Then you should not use <code>return</code> statements, otherwise the function will terminate, returning <code>True</code> or <code>False</code>.</p>
| 3 | 2016-06-07T17:39:21Z | [
"python",
"function",
"loops"
] |
Looping the function | 37,685,739 | <p>I have this function below, which I have done something wrong in somewhere.</p>
<pre><code>def quantityFunction(product):
valid = False
while True:
if product is not None:
quantity = input("Please enter the amount of this item you would like to purchase: ")
for i in quantity:... | 2 | 2016-06-07T17:32:49Z | 37,686,146 | <p>You should try this..</p>
<pre><code>def quantityFunction(product):
valid = False
while True:
if product is not None:
quantity = raw_input("Please enter the amount of this item you would like to purchase: ")
if quantity.isdigit():
return int(quantity)
va... | 1 | 2016-06-07T17:54:32Z | [
"python",
"function",
"loops"
] |
Looping the function | 37,685,739 | <p>I have this function below, which I have done something wrong in somewhere.</p>
<pre><code>def quantityFunction(product):
valid = False
while True:
if product is not None:
quantity = input("Please enter the amount of this item you would like to purchase: ")
for i in quantity:... | 2 | 2016-06-07T17:32:49Z | 37,686,162 | <p>Few issue:</p>
<p>1) <code>return</code> statement returns control to the calling function. </p>
<p>2) You are looping over the input, which is wrong.</p>
<p>3) <code>valid=True</code> isn't executed at all. </p>
<pre><code>def quantityFunction(product):
valid = False
while True:
if product is no... | 3 | 2016-06-07T17:55:42Z | [
"python",
"function",
"loops"
] |
Looping the function | 37,685,739 | <p>I have this function below, which I have done something wrong in somewhere.</p>
<pre><code>def quantityFunction(product):
valid = False
while True:
if product is not None:
quantity = input("Please enter the amount of this item you would like to purchase: ")
for i in quantity:... | 2 | 2016-06-07T17:32:49Z | 37,686,189 | <p>First, let's address the code. Simply stated, you want a function that will loop until the user enters a legal quantity. </p>
<p><strong>product</strong> doesn't do much for the function; check it in the calling program, not here. Let the function have a single purpose: fetch a valid quantity.</p>
<p>Let's work... | 1 | 2016-06-07T17:57:21Z | [
"python",
"function",
"loops"
] |
Looping the function | 37,685,739 | <p>I have this function below, which I have done something wrong in somewhere.</p>
<pre><code>def quantityFunction(product):
valid = False
while True:
if product is not None:
quantity = input("Please enter the amount of this item you would like to purchase: ")
for i in quantity:... | 2 | 2016-06-07T17:32:49Z | 37,686,207 | <p>Try this (some formatting included too, but the functionality should be the same):</p>
<pre><code>def determine_quantity(product): # descriptive function name
if not product: # avoiding nesting
return False
while True:
quantity = input("Please enter the amount of this item you would like ... | 1 | 2016-06-07T17:58:14Z | [
"python",
"function",
"loops"
] |
Convert rows of pandas Dataframe into an iterable list of strings | 37,685,743 | <p>Imagine I have a dataframe, df, that has 2 columns, a USER_ID and a PRODUCT they bought. </p>
<pre><code>df
USER_ID | PRODUCT
1 a
1 b
1 c
2 d
2 a
2 k
</code></pre>
<p>I want to convert this DataFrame into a new... | 1 | 2016-06-07T17:33:12Z | 37,686,312 | <p>is that what you want?</p>
<pre><code>In [7]: pd.Series(np.intersect1d(df.loc[df.USER_ID == 1, 'PRODUCT'], df.loc[df.USER_ID == 2, 'PRODUCT']))
Out[7]:
0 a
dtype: object
</code></pre>
<p>or using <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Index.intersection.html" rel="nofollow">index.... | 0 | 2016-06-07T18:04:47Z | [
"python",
"list",
"pandas",
"intersection",
"iterable"
] |
Convert rows of pandas Dataframe into an iterable list of strings | 37,685,743 | <p>Imagine I have a dataframe, df, that has 2 columns, a USER_ID and a PRODUCT they bought. </p>
<pre><code>df
USER_ID | PRODUCT
1 a
1 b
1 c
2 d
2 a
2 k
</code></pre>
<p>I want to convert this DataFrame into a new... | 1 | 2016-06-07T17:33:12Z | 37,686,724 | <p>You can perform <code>groupby</code> followed by finding intersection between the two lists as shown: </p>
<pre><code>df2= df.groupby('USER_ID')['PRODUCT'].apply(list)
df2 = df2.reset_index()
print df2
USER_ID PRODUCT
0 1 [a, b, c]
1 2 [d, a, k]
print list(set(df2['PRODUCT'].loc[0]).intersec... | 1 | 2016-06-07T18:29:35Z | [
"python",
"list",
"pandas",
"intersection",
"iterable"
] |
Convert rows of pandas Dataframe into an iterable list of strings | 37,685,743 | <p>Imagine I have a dataframe, df, that has 2 columns, a USER_ID and a PRODUCT they bought. </p>
<pre><code>df
USER_ID | PRODUCT
1 a
1 b
1 c
2 d
2 a
2 k
</code></pre>
<p>I want to convert this DataFrame into a new... | 1 | 2016-06-07T17:33:12Z | 37,686,945 | <p>This will give you a generalizable solution to find the intersection of any two users product list without the sloppy second dataframe</p>
<pre><code>from collections import defaultdict
user1 = 1
user2 = 2
products = defaultdict(set)
for record in df.to_dict('records'):
products[record['USER_ID']].add(record[... | 0 | 2016-06-07T18:42:02Z | [
"python",
"list",
"pandas",
"intersection",
"iterable"
] |
Convert rows of pandas Dataframe into an iterable list of strings | 37,685,743 | <p>Imagine I have a dataframe, df, that has 2 columns, a USER_ID and a PRODUCT they bought. </p>
<pre><code>df
USER_ID | PRODUCT
1 a
1 b
1 c
2 d
2 a
2 k
</code></pre>
<p>I want to convert this DataFrame into a new... | 1 | 2016-06-07T17:33:12Z | 37,687,537 | <p>Try this: </p>
<pre><code>df3 = pd.crosstab(df2.PRODUCT,df2.USER_ID, margins= True)
print df3[df3['All']>1]
# USER_ID 1 2 All
# PRODUCT
# a 1 1 2
# All 3 3 6
</code></pre>
<p>My solution very simliar to @Nikil so using his. </p>
<pre><code>df2 = df.groupby('USER_ID... | 1 | 2016-06-07T19:14:50Z | [
"python",
"list",
"pandas",
"intersection",
"iterable"
] |
What is the most efficient and readable way to pass/format lots of variables to a large string? | 37,685,796 | <p>I have a couple "lengthy" lines like this one:</p>
<pre><code>content = "<!DOCTYPE html>\n<html>\n<head>\n <meta http-equiv=\"content-type\" content=\"text/html; charset=UTF-8\">\n <title>{0} - {1}</title>\n <link rel=\"stylesheet\" type=\"text/css\" href=\"{3}/{2}.{4}\" /&... | 0 | 2016-06-07T17:35:45Z | 37,685,834 | <p>by having the strings in a list and then doing a join as in <code>' '.join(list)</code>. This will be a lot faster than simple concatenation. </p>
<p><code>list = ["The quick brown", "fox"]
result = " ".join(list)
</code>
Here is a <a href="http://stackoverflow.com/questions/3055477/how-slow-is-pythons-string-conc... | 1 | 2016-06-07T17:38:16Z | [
"python",
"python-3.x",
"concat",
"readability",
"code-readability"
] |
What is the most efficient and readable way to pass/format lots of variables to a large string? | 37,685,796 | <p>I have a couple "lengthy" lines like this one:</p>
<pre><code>content = "<!DOCTYPE html>\n<html>\n<head>\n <meta http-equiv=\"content-type\" content=\"text/html; charset=UTF-8\">\n <title>{0} - {1}</title>\n <link rel=\"stylesheet\" type=\"text/css\" href=\"{3}/{2}.{4}\" /&... | 0 | 2016-06-07T17:35:45Z | 37,685,855 | <p>You could use a <a href="https://docs.python.org/3/tutorial/introduction.html#strings" rel="nofollow">multiline string</a>:</p>
<pre><code>args = (settings["app.name"], ncc, name, settings["dir"]["static.style"],
settings["lang.style"], settings["dir"]["static.script"],
settings["lang.script"])
c... | 1 | 2016-06-07T17:39:11Z | [
"python",
"python-3.x",
"concat",
"readability",
"code-readability"
] |
What is the most efficient and readable way to pass/format lots of variables to a large string? | 37,685,796 | <p>I have a couple "lengthy" lines like this one:</p>
<pre><code>content = "<!DOCTYPE html>\n<html>\n<head>\n <meta http-equiv=\"content-type\" content=\"text/html; charset=UTF-8\">\n <title>{0} - {1}</title>\n <link rel=\"stylesheet\" type=\"text/css\" href=\"{3}/{2}.{4}\" /&... | 0 | 2016-06-07T17:35:45Z | 37,685,939 | <p>Another option would be to do:</p>
<pre><code>content = (
"<!DOCTYPE html>\n<html>\n<head>\n "
"<meta http-equiv=\"content-type\" content=\"text/html; charset=UTF-8\">\n"
" <title>{0} - {1}</title>\n "
"<link rel=\"stylesheet\" type=\"text/css\" href=\"{3}/{... | 2 | 2016-06-07T17:43:17Z | [
"python",
"python-3.x",
"concat",
"readability",
"code-readability"
] |
Irregular binning of python pandas dataframe | 37,685,917 | <p>I am getting to grips with python pandas.</p>
<p>The toy problem below, illustrates an issue I am having in a related exercise.</p>
<p>I have sorted a data-frame so that it presents a column's values (in this case students' test scores) in ascending order:</p>
<pre><code>df_sorted =
variable test_score
... | 0 | 2016-06-07T17:42:20Z | 37,686,017 | <p>Just <code>groupby</code> a dummy variable that goes 0, 0, 0, 1, 1, 1, etc. This can be obtained with floor division:</p>
<pre><code>>>> d.groupby(np.arange(len(d))//3).mean()
variable test_score
0 2 53
1 6 64
2 10 73
3 4 77
</code></p... | 1 | 2016-06-07T17:47:42Z | [
"python",
"pandas",
"dataframe",
"binning"
] |
Python threading.Timer object not functioning when compiled to .exe | 37,685,928 | <p>This is a follow up to <a href="http://stackoverflow.com/questions/37684111/ironpython-exe-file-closing-immediately-no-exception-thrown">IronPython exe file closing immediately, no exception thrown</a></p>
<p>I figured out that my program is not working once compiled due to an issue with the Timer object in the thr... | 7 | 2016-06-07T17:42:55Z | 38,251,402 | <p>The problem is that you are relying on the underlying Python interpreter to gracefully handle the case where the main thread of your executable has terminated, but there should be some others still running.</p>
<p>Running the code directly with CPython or IronPython works as expected. The Timer objects that you cr... | 5 | 2016-07-07T17:06:30Z | [
"python",
"timer",
"compilation",
"ironpython",
"pyc"
] |
How to avoid yield command in python throws exceptions every time? | 37,685,956 | <p>I am developing a async web service with Twisted Klein. Part of the code are as follows:</p>
<pre><code>@inlineCallbacks
def test(input1):
try:
result = yield function(input1)
print result
returnValue(result)
except:
returnValue("None")
pass
</code></pre>
<p>I have ... | 0 | 2016-06-07T17:44:28Z | 37,686,169 | <p>First of all you should never have a bare <code>except</code> clause. (there are exceptions, but generally speaking it's better to catch specific errors.) </p>
<p>Second, from the twisted docs on returnValue:</p>
<blockquote>
<p>Note: this is currently implemented by raising an exception derived from BaseExcepti... | 2 | 2016-06-07T17:56:06Z | [
"python",
"twisted",
"klein-mvc"
] |
Create a menu home screen for piTFT using pygame | 37,685,994 | <p>I would like to create a home screen(menu) for my project using pygame(?).
I have a piTFT 2.8" Capactive display from adafruit.</p>
<p>I have design the whole display menu. Take a look on this demo screen for example:
<a href="http://i.stack.imgur.com/Nzytf.png" rel="nofollow"><img src="http://i.stack.imgur.com/Nzy... | 1 | 2016-06-07T17:46:19Z | 37,687,531 | <p>This answer may be a bit general, but what I do to find each position is go to paint or some paint program and then I add markers where positions are, then I can select rectangles and find there positions. It would be hard to find the positions by itself just from that image. Do you have a mac, windows, linux?'</p>
... | 0 | 2016-06-07T19:14:46Z | [
"python",
"raspberry-pi",
"pygame"
] |
Timing Modular Exponentiation in Python: syntax vs function | 37,686,000 | <p>In Python, if the builtin <code>pow()</code> function is used with 3 arguments, the last one is used as the modulus of the exponentiation, resulting in a <a href="https://en.wikipedia.org/wiki/Modular_exponentiation" rel="nofollow">Modular exponentiation</a> operation.</p>
<p>In other words, <code>pow(x, y, z)</cod... | 4 | 2016-06-07T17:47:00Z | 37,686,188 | <p>You're not actually timing the computation with <code>**</code> and <code>%</code>, because the result gets constant-folded by the bytecode compiler. Avoid that:</p>
<pre><code>timeit.timeit('(a**b) % c', setup='a=65537; b=767587; c=14971787')
</code></pre>
<p>and the <code>pow</code> version will win hands down.<... | 7 | 2016-06-07T17:57:11Z | [
"python",
"python-2.7",
"python-3.x"
] |
Timing Modular Exponentiation in Python: syntax vs function | 37,686,000 | <p>In Python, if the builtin <code>pow()</code> function is used with 3 arguments, the last one is used as the modulus of the exponentiation, resulting in a <a href="https://en.wikipedia.org/wiki/Modular_exponentiation" rel="nofollow">Modular exponentiation</a> operation.</p>
<p>In other words, <code>pow(x, y, z)</cod... | 4 | 2016-06-07T17:47:00Z | 37,686,271 | <p>Some glosses on @user2357112's correct answer:</p>
<p>First, if you call <code>eval()</code> on your two strings by hand, it's obvious that <code>st_expmod</code> is enormously slower.</p>
<p>Second, it sometimes (like in this case) pays to look at the generated code. Like so:</p>
<pre><code>>>> def f()... | 4 | 2016-06-07T18:01:57Z | [
"python",
"python-2.7",
"python-3.x"
] |
URLs and linking abruptly broken in Angular / Django app | 37,686,040 | <p>Recently, something changed on my Django / Angular app that broke all of my front-end URLs and links.</p>
<p>For example, our root domain has stayed the same, but our location URLs changed from <code>/<campus.slug>/#campus_info</code> to <code>/<campus.slug>/#/campus_info</code> and it's breaking every ... | 0 | 2016-06-07T17:49:11Z | 37,689,226 | <p>As per <a href="https://github.com/angular/angular.js/issues/4608" rel="nofollow"><strong>this</strong></a> article, <code>$location</code> interferes with some versions of UI-Bootstrap and can have adverse effects on your URLs. </p>
<p>After removing a <code>$location</code> dependency from my controller that was ... | 0 | 2016-06-07T20:57:07Z | [
"javascript",
"python",
"angularjs",
"django"
] |
Mapping values from one DataFrame to another | 37,686,052 | <p>I am trying to figure out some fast and clean way to map values from one <code>DataFrame</code> <code>A</code> to another. Let say I have <code>DataFrame</code> like this one:</p>
<pre><code> C1 C2 C3 C4 C5
1 a b c a
2 d a e b a
3 a c
4 b e e
</code></pre>
<p>And now I want to ch... | 0 | 2016-06-07T17:49:53Z | 37,686,120 | <p>You could use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.replace.html" rel="nofollow"><code>replace</code></a>:</p>
<pre><code>A.replace(B.set_index('Code')['Value'])
</code></pre>
<hr>
<pre><code>import pandas as pd
A = pd.DataFrame(
{'C1': ['a', 'd', 'a', 'b'],
'C2'... | 2 | 2016-06-07T17:53:40Z | [
"python",
"pandas"
] |
Mapping values from one DataFrame to another | 37,686,052 | <p>I am trying to figure out some fast and clean way to map values from one <code>DataFrame</code> <code>A</code> to another. Let say I have <code>DataFrame</code> like this one:</p>
<pre><code> C1 C2 C3 C4 C5
1 a b c a
2 d a e b a
3 a c
4 b e e
</code></pre>
<p>And now I want to ch... | 0 | 2016-06-07T17:49:53Z | 37,686,548 | <p>Another alternative is <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.map.html" rel="nofollow">map</a>. Although it requires looping over columns, if I didn't mess up the tests, it is still faster than replace:</p>
<pre><code>A = pd.DataFrame(np.random.choice(list("abcdef"), (1000, 100... | 2 | 2016-06-07T18:18:37Z | [
"python",
"pandas"
] |
What is using swap. Python version | 37,686,095 | <p>I already have a shell script that can determine which process is using swap and how much, but I would rather do this in python. </p>
<p>Shell one-liner (I found this script on the web but can't remember it's origin): </p>
<pre><code>for file in /proc/*/status ; do awk '/VmSwap|Name/{printf $2 " " $3}END{ print "... | 1 | 2016-06-07T17:52:16Z | 37,688,847 | <p><code>memory_maps()</code> in psutil is only a function to memory map the specified process (not for every process).</p>
<p>Let's start from the beginning - psutil provides a <code>pids()</code> method that lists all the processes currently running, and you then have to create a <code>Process</code> object that let... | 0 | 2016-06-07T20:35:13Z | [
"python",
"linux",
"memory",
"swap"
] |
Send Apple Push Notification via AWS Lambda/Python as JSON with custom variable Message | 37,686,101 | <p>Hello i'm trying to send push notifications like this</p>
<pre><code>message3 = {"APNS_SANDBOX":"{\"aps\": {\"alert\": \"some alert\",\"sound\": \"default\",\"badge\": 1},\"message\": \"additional information\",\"id\": 1234}"}
response = client.publish(
#TopicArn='string',
TargetArn = someEndpoint,
Mes... | 1 | 2016-06-07T17:52:27Z | 37,696,901 | <p>It seems to work like this.</p>
<pre><code>test = "test"
message = {'aps': {'alert': test, 'sound': 'default','badge': 1},'message': 'additional information','id': 1234}
dumped = json.dumps(message)
message3 = {"APNS_SANDBOX":dumped}
response = client.publish(
#TopicArn='string',
TargetArn = someEndpoint,... | 2 | 2016-06-08T08:16:56Z | [
"python",
"json",
"amazon-web-services",
"amazon-sns",
"boto3"
] |
Python - splitting data as columns in csv file | 37,686,105 | <p>I have data in a csv file that looks like that is imported as this.</p>
<pre><code>import csv
with open('Half-life.csv', 'r') as f:
data = list(csv.reader(f))
</code></pre>
<p>the data will come out as this to where it prints out the rows like <code>data[0] = ['10', '2', '2']</code> and so on. </p>
<p>What i... | 2 | 2016-06-07T17:52:48Z | 37,686,390 | <p>You can create three separate lists, and then append to each using <a href="https://docs.python.org/2/library/csv.html#module-contents" rel="nofollow"><code>csv.reader</code></a>.</p>
<pre><code>import csv
c1 = []
c2 = []
c3 = []
with open('Half-life.csv', 'r') as f:
reader = csv.reader(f, delimiter=',')
f... | 2 | 2016-06-07T18:09:10Z | [
"python",
"csv",
"matplotlib"
] |
Python - splitting data as columns in csv file | 37,686,105 | <p>I have data in a csv file that looks like that is imported as this.</p>
<pre><code>import csv
with open('Half-life.csv', 'r') as f:
data = list(csv.reader(f))
</code></pre>
<p>the data will come out as this to where it prints out the rows like <code>data[0] = ['10', '2', '2']</code> and so on. </p>
<p>What i... | 2 | 2016-06-07T17:52:48Z | 37,687,744 | <p>A little more automatic and flexible version of <a href="http://stackoverflow.com/a/37686390/1394393">Alexander's answer</a>:</p>
<pre><code>import csv
from collections import defaultdict
columns = defaultdict(list)
with open('Half-life.csv', 'r') as f:
reader = csv.reader(f, delimiter=',')
for row in read... | 2 | 2016-06-07T19:28:03Z | [
"python",
"csv",
"matplotlib"
] |
Python - splitting data as columns in csv file | 37,686,105 | <p>I have data in a csv file that looks like that is imported as this.</p>
<pre><code>import csv
with open('Half-life.csv', 'r') as f:
data = list(csv.reader(f))
</code></pre>
<p>the data will come out as this to where it prints out the rows like <code>data[0] = ['10', '2', '2']</code> and so on. </p>
<p>What i... | 2 | 2016-06-07T17:52:48Z | 37,692,373 | <p>Another option, if you have <code>numpy</code> installed, you can use <code>loadtxt</code> to read a csv file into a numpy array. You can then transpose the array if you want more columns than rows (I wasn't quite clear on how you wanted the data to look). For example:</p>
<pre><code>import numpy as np
# Load data
... | 2 | 2016-06-08T02:40:45Z | [
"python",
"csv",
"matplotlib"
] |
ImportError libqhull.so.5 when importing pyplot | 37,686,113 | <p>I'm getting an ImportError whenever I try to import pyplot from matplotlib. Matplotlib is installed via pip in a virtual environment. This is the error I'm getting:</p>
<pre><code>>>> import matplotlib.pyplot
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home... | 0 | 2016-06-07T17:53:08Z | 38,862,616 | <p>This can occur after a system upgrade. In my specific case, I upgraded Ubuntu 14.04 to 16.04. Matplotlib links to specific versions of <code>\*.so</code>, and these go out of date. I presume this is because the different versions are not (always) backward compatible.
(For me, I went from <code>libqhull.so.6</code> t... | 1 | 2016-08-10T00:53:44Z | [
"python",
"linux",
"matplotlib",
"importerror"
] |
How to pass directory path from a template to a view? | 37,686,118 | <p>I'm pretty new to Python\Django.</p>
<p>I'm trying to make a <strong>local</strong> Netflix-like Library for my Movie\TV shows collection.</p>
<p>The general idea is that the user chooses a media folder, the server side runs on the files in the folder adds them to the database and then the user can search for the ... | 0 | 2016-06-07T17:53:31Z | 37,687,021 | <p>For security reasons, browsers do not allow to get folder path (<a href="http://stackoverflow.com/questions/15201071/how-to-get-full-path-of-selected-file-on-change-of-input-type-file-using-jav">Stack Overflow</a>). Since you do not want the user to upload files, the possible solution would be to explicitly mention ... | 1 | 2016-06-07T18:45:47Z | [
"python",
"html",
"django",
"file",
"filelist"
] |
TFLearn pip installation bug | 37,686,139 | <p>I've tried installing tflearn through pip as follows </p>
<p><code>pip install tflearn</code></p>
<p>and now when I open python, the following happens:</p>
<p><code>>>> import tflearn
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "//anaconda/lib/python2.7/sit... | 1 | 2016-06-07T17:54:24Z | 37,690,958 | <p>The <code>variance_scaling_initializer()</code> function was <a href="https://github.com/tensorflow/tensorflow/commit/eca3854bc5e4e7d8fa4db9f487c78ccac37b6c23" rel="nofollow">added on April 19th</a>, which means that it wasn't included in version 0.8.0rc0, and you need to upgrade to a newer version of TensorFlow. If... | 2 | 2016-06-07T23:18:12Z | [
"python",
"tensorflow"
] |
TFLearn pip installation bug | 37,686,139 | <p>I've tried installing tflearn through pip as follows </p>
<p><code>pip install tflearn</code></p>
<p>and now when I open python, the following happens:</p>
<p><code>>>> import tflearn
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "//anaconda/lib/python2.7/sit... | 1 | 2016-06-07T17:54:24Z | 37,693,149 | <p>Last tflearn update had a compatibility issue with old TensorFlow versions (like mrry said, caused by 'variance_scaling_initializer()' that was only compatible with TensorFlow 0.9).
That error had already been fix, so you can just update TFLearn and it should works fine with any TensorFlow version over 0.7.</p>
| 0 | 2016-06-08T04:16:33Z | [
"python",
"tensorflow"
] |
Remove a Python array element by name | 37,686,204 | <p>In a Python array, I need to know (<strong>if possible</strong>) how to delete an array element by its name, without knowing the index of the element in the array.</p>
<p>So, if I had this array defined</p>
<pre><code>usernames = ["Billy", "Bob", "Apple"]
</code></pre>
<p>Then we would have three array elements.
... | 2 | 2016-06-07T17:58:06Z | 37,686,241 | <pre><code>if to_delete in usernames:
usernames.pop(usernames.index(to_delete))
</code></pre>
<p>That's it basically.</p>
| 0 | 2016-06-07T18:00:11Z | [
"python",
"arrays",
"sorting"
] |
Remove a Python array element by name | 37,686,204 | <p>In a Python array, I need to know (<strong>if possible</strong>) how to delete an array element by its name, without knowing the index of the element in the array.</p>
<p>So, if I had this array defined</p>
<pre><code>usernames = ["Billy", "Bob", "Apple"]
</code></pre>
<p>Then we would have three array elements.
... | 2 | 2016-06-07T17:58:06Z | 37,686,265 | <p>You can also use <code>remove</code></p>
<pre><code>usernames = ["Billy", "Bob", "Apple"]
if "Billy" in usernames:
usernames.remove("Billy")
# usernames = ["Bob", "Apple"]
</code></pre>
| 5 | 2016-06-07T18:01:45Z | [
"python",
"arrays",
"sorting"
] |
Remove a Python array element by name | 37,686,204 | <p>In a Python array, I need to know (<strong>if possible</strong>) how to delete an array element by its name, without knowing the index of the element in the array.</p>
<p>So, if I had this array defined</p>
<pre><code>usernames = ["Billy", "Bob", "Apple"]
</code></pre>
<p>Then we would have three array elements.
... | 2 | 2016-06-07T17:58:06Z | 37,686,273 | <p>You can use <code>remove()</code> method to remove the element. Check if the required element is present in the list before trying to delete it since a <code>ValueError</code> is raised if the element is not present in the list. </p>
<pre><code>if to_delete in usernames:
usernames.remove(to_delete)
</code></pre>
| 4 | 2016-06-07T18:01:59Z | [
"python",
"arrays",
"sorting"
] |
Remove a Python array element by name | 37,686,204 | <p>In a Python array, I need to know (<strong>if possible</strong>) how to delete an array element by its name, without knowing the index of the element in the array.</p>
<p>So, if I had this array defined</p>
<pre><code>usernames = ["Billy", "Bob", "Apple"]
</code></pre>
<p>Then we would have three array elements.
... | 2 | 2016-06-07T17:58:06Z | 37,686,430 | <pre><code>def remove_by_name(name):
if name in usernames:
usernames.remove(name)
</code></pre>
<p>Remove only first occurrence, if you want all elements, modify the sample above.</p>
| 0 | 2016-06-07T18:11:10Z | [
"python",
"arrays",
"sorting"
] |
Remove a Python array element by name | 37,686,204 | <p>In a Python array, I need to know (<strong>if possible</strong>) how to delete an array element by its name, without knowing the index of the element in the array.</p>
<p>So, if I had this array defined</p>
<pre><code>usernames = ["Billy", "Bob", "Apple"]
</code></pre>
<p>Then we would have three array elements.
... | 2 | 2016-06-07T17:58:06Z | 37,686,905 | <p>@Greg 's answer is right but in the case of multi-occurrences :</p>
<pre><code>while True:
try:
usernames.remove(name)
except ValueError:
break
</code></pre>
| 0 | 2016-06-07T18:39:16Z | [
"python",
"arrays",
"sorting"
] |
How to update stock_quantity in python using woocommerce api | 37,686,239 | <p>Trying to follow the api sample from <a href="http://woothemes.github.io/woocommerce-rest-api-docs/?python#update-a-product-attribute" rel="nofollow">http://woothemes.github.io/woocommerce-rest-api-docs/?python#update-a-product-attribute</a>, but it's not updating the stock_quantity. I've confirmed that I have read... | 1 | 2016-06-07T18:00:03Z | 37,688,460 | <p>Ok figured it out. I was using the wrong version of the api documentation. I should have been using v3. The correct code is:</p>
<pre><code>import sys
import json
from woocommerce import API
wcapi = API(
url="http://(myurl)",
consumer_key="ck_<mykey>",
consumer_secret="cs_<mysecret>",
... | 1 | 2016-06-07T20:13:39Z | [
"python",
"woocommerce"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.