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 |
|---|---|---|---|---|---|---|---|---|---|
fastest way in python to enumerate all combinations and return the index | 38,040,946 | <p>It is hard to describe my problem in the title. I think the title of this problem is not very good. My problem is the following</p>
<p>Say I have a list [0,0,0,0,0], I want to put 3 ones into these 5 slots in the list. I want to enumerate all the possible combinations. In this case, it will be 5 choose 3, which is ... | 1 | 2016-06-26T17:00:44Z | 38,041,040 | <p>Using <a href="https://docs.python.org/3/library/itertools.html#itertools.combinations" rel="nofollow">itertools.combinations</a></p>
<p>To get all the possible binary lists of length 5 with 3 ones</p>
<pre><code>N = 5
zeros = [0]*N
for comb in itertools.combinations(range(N), r = 3):
l = zeros.copy()
for ... | 1 | 2016-06-26T17:08:35Z | [
"python",
"combinations"
] |
fastest way in python to enumerate all combinations and return the index | 38,040,946 | <p>It is hard to describe my problem in the title. I think the title of this problem is not very good. My problem is the following</p>
<p>Say I have a list [0,0,0,0,0], I want to put 3 ones into these 5 slots in the list. I want to enumerate all the possible combinations. In this case, it will be 5 choose 3, which is ... | 1 | 2016-06-26T17:00:44Z | 38,041,093 | <p>Is this what you are looking for?</p>
<pre><code>from itertools import combinations
num_ones = 3
slots = 5
comb_indices = list(combinations(range(5),3))
print comb_indices
</code></pre>
<p><code>
[(0, 1, 2), (0, 1, 3), (0, 1, 4), (0, 2, 3), (0, 2, 4), (0, 3, 4), (1, 2, 3), (1, 2, 4), (1, 3, 4), (2, 3, 4)]</cod... | 1 | 2016-06-26T17:15:03Z | [
"python",
"combinations"
] |
How to use imdbpy using python? | 38,040,982 | <p>I am using imdbpy to get the ratings of movies.I have succesfully installed the imdbpy but running into problem while running this small code.
here is the code:</p>
<pre><code>from imdb import IMDb
ia = IMDb()
the_matrix = ia.get_movie('0133093')
print the_matrix['director']
</code></pre>
<p>error: </p>
<pre><cod... | 0 | 2016-06-26T17:03:16Z | 38,041,158 | <p>Can you give the full error trace?<br>
One of the reasons could be that you might have saved this code in the file <code>imdb.py</code> which would be shadowing the original <code>imdb</code> module and that's why python can no longer import <code>IMDb</code>.</p>
| 1 | 2016-06-26T17:23:16Z | [
"python",
"python-2.7",
"imdb",
"imdbpy"
] |
Spark Random Forest Cross-Validation error | 38,040,991 | <p>I am trying to run cross-validation on a Random Forest in Spark.</p>
<pre><code>from pyspark.ml import Pipeline
from pyspark.ml.classification import RandomForestClassifier
from pyspark.ml.tuning import CrossValidator, ParamGridBuilder
from pyspark.ml.evaluation import MulticlassClassificationEvaluator
data = nds.... | 1 | 2016-06-26T17:04:16Z | 38,041,089 | <p>You pass incorrect values to <code>rf.featureSubsetStrategy</code>. It should be a string describing a strategy and it supports following values: auto, all, onethird, sqrt, log2. See: <code>RandomForestClassifier.featureSubsetStrategy.doc</code>.</p>
<p>Also don't use <code>data.toDF(['label','features'])</code>. I... | 2 | 2016-06-26T17:14:32Z | [
"python",
"apache-spark",
"pyspark",
"apache-spark-mllib"
] |
Tweepy use multiple API keys with cursor to search Twitter | 38,041,037 | <p>I've been using the example in this <a href="http://stackoverflow.com/questions/20427674/get-twitter-followers-using-tweepy-and-multiple-api-keys">post</a></p>
<p>to create a system that searches and gets a large number of Tweets in a short time period. However, each time I switch to a new API key (make a new curso... | 1 | 2016-06-26T17:08:24Z | 38,077,455 | <p>I found a workaround that I think works, although I still encounter some issues. The idea is to add into</p>
<pre><code>currentCursor = tweepy.Cursor(apis[currentAPI].search, q = '%40deltaKshatriya', cursor = currentCursor, max_id = max_id)
</code></pre>
<p>Where max_id is the id of the last tweet fetched before t... | 0 | 2016-06-28T13:21:40Z | [
"python",
"twitter",
"tweepy"
] |
Using Groups, drop duplicated NaNs only | 38,041,043 | <p>With my data grouped by Assay, Image and Roi, for each group I wish to delete all but the first rows which have a NaN value in the 'Intensity' column. </p>
<p>My attempt is able to delete duplicates, but this isn't specific to NaN values.</p>
<pre><code>from pandas import Series, DataFrame
import pandas as pd
impo... | 0 | 2016-06-26T17:08:42Z | 38,041,176 | <p>Instead of using <code>drop_duplicates</code> you can pass the <code>duplicated & is.null</code> checker into the lambda function as:</p>
<pre><code>df.groupby(['assay','image','roi']).apply(lambda x: x.loc[~(x.duplicated(['intensity']) & x.intensity.isnull())])
</code></pre>
| 2 | 2016-06-26T17:24:53Z | [
"python",
"pandas"
] |
request csv format data from url using python | 38,041,083 | <p>i wana simply send a request to the following url and recive data in csv format and save on the following location,but doest not work!any help will be appreciated </p>
<pre><code>from urllib import request
my_url='http://real-chart.finance.yahoo.com/table.csv?s=CSV&a=07&b=9& c=1996&d=05&e=26&... | 0 | 2016-06-26T17:14:07Z | 38,041,146 | <p>The correct way to receive a file from <code>url</code> and save a file at <code>save_dest</code> is:</p>
<pre><code>import urllib
file = urllib.URLopener()
file.retrieve(url, save_dest)
</code></pre>
| 1 | 2016-06-26T17:22:08Z | [
"python"
] |
How to change the color of a line with different pattern classifications in python | 38,041,126 | <p>I have a time series dataset that I used a machine learning algorithm to identify distinct patterns. I have that classified but I want to check it visually to see how it did. </p>
<p>How do I make a time series graph with different colors for each pattern classification OR what is the best way to visualize or check... | 0 | 2016-06-26T17:19:10Z | 38,042,058 | <p>Here's what I've tried:</p>
<p>1.Convert your (assuming str) data to int</p>
<pre><code>x = '0000000000000000011111111111111111110000000000000000000000000022222222222222222'
x = [int(x[i]) for i in range(len(x))]
</code></pre>
<p>2.Create a color label array. I use here gray scale but you can use any RGB array.<... | 0 | 2016-06-26T18:53:56Z | [
"python",
"matplotlib",
"machine-learning",
"time-series",
"classification"
] |
Drastic reduction in speed when list formation transferred to function | 38,041,175 | <p>I wrote a code that is supposed to do some operation on a sentence of a file and elements of two lists - <code>keywords</code> and <code>keywords2</code>. It is as follows - </p>
<pre><code>import os
keywords=['a','b']
keywords2=['c','d mvb']
def foo(sentence,k2):
gs_list=[] #####
fo... | 1 | 2016-06-26T17:24:50Z | 38,041,208 | <p>You're not passing <code>gs_list</code> to <code>foo</code>. It's possible that working with global variables is slowing your script down.</p>
<p>Also, consider making BETA a list comprehension. This should be what you need:</p>
<p><code>gs_list = [k for k in keywords if k in sentence]</code></p>
| 1 | 2016-06-26T17:28:44Z | [
"python",
"performance"
] |
I'm trying to create a python gui for twitter that will submit my textbox as a tweet | 38,041,177 | <p>Here is the code i'm using:</p>
<pre><code>from Tkinter import *
import tweepy
from secrets import *
auth = tweepy.OAuthHandler(C_KEY, C_SECRET)
auth.set_access_token(A_TOKEN, A_TOKEN_SECRET)
api = tweepy.API(auth)
class MyFirstGUI(Frame):
def __init__(self, master):
Frame.__init__(self, master)
... | 0 | 2016-06-26T17:24:58Z | 38,042,670 | <p><code>content</code> should be the content of your <code>Entry</code>:</p>
<pre><code>def post(self):
api.update_status(self.tweet.get())
</code></pre>
| 0 | 2016-06-26T20:01:19Z | [
"python",
"twitter",
"tkinter"
] |
How to install and run rodeo-python in another devices/disks? | 38,041,264 | <p>I want to install <a href="https://github.com/yhat/rodeo" rel="nofollow">rodeo software</a> in my ubuntu 14.04. Because of the lack of space in my Ubuntu system drive I want to install rodeo in another device/disk. I have python 2.7.6,numpy,matplotlib installed in my system without IPython / Jupyter library.</p>
<... | 0 | 2016-06-26T17:35:21Z | 38,042,407 | <h2>Challenges of Installing Packages on Ubuntu onto a Separate Drive</h2>
<p>On Ubuntu, packages aren't installed in just one directory, such as <code>Program Files</code> in Windows OS. The reason for this is that packages installed on Ubuntu, unlike Windows, follow the <a href="https://help.ubuntu.com/community/Lin... | 1 | 2016-06-26T19:32:19Z | [
"python",
"linux",
"install",
"ubuntu-14.04",
"rodeo"
] |
Python for..else loop always triggers else | 38,041,284 | <p>I am trying to read a tab-separated file and collect all characters except control characters. If a control character is hit, the remainder of line should be ignored too.
I've tried the following code in Python 3.5, using a <a href="https://docs.python.org/3.5/tutorial/controlflow.html#break-and-continue-statements-... | 0 | 2016-06-26T17:36:49Z | 38,041,568 | <p>The <code>else</code> block of a <code>for</code> loop is <em>only</em> executed if the <code>for</code> loop never was interrupted. You'll only see the <code>continue</code> statement in the <code>else</code> block executed if there were <em>no control characters in the line</em>. From the <a href="https://docs.pyt... | 1 | 2016-06-26T18:07:44Z | [
"python",
"python-3.x",
"if-statement",
"for-loop"
] |
binary outputs are different in hash SHA256 | 38,041,402 | <p>SHA256 hashing output is different in two codes, input is same so outputs should be identical, the code seems to be fine, I can't understand why it produces different results. What is wrong with it?</p>
<p><strong>VB.NET CODE</strong></p>
<pre><code>Private Sub Button1_Click(sender As Object, e As EventArgs) Handl... | -1 | 2016-06-26T17:48:41Z | 38,042,552 | <p>It is not clear to me why you are going via a Base64 string in the VB version. You don't do that in the Python version, so you should expect the results to be different.</p>
<p>Here is similar code <em>without</em> using Base64:</p>
<pre><code>Function SHA256BytesAsBinary(s As String) As String
Dim pt As New S... | 0 | 2016-06-26T19:49:47Z | [
"python",
"vb.net"
] |
print one time uniqe variable in if or while statement python | 38,041,435 | <p>Is there a way to see / print looping variables which have unique values?</p>
<p>for an example:</p>
<pre><code>while random.randint(0,15) != 7:
</code></pre>
<p>If I do:</p>
<pre><code>while random.randint(0,15) != 7:
print (random.randint(0,15))
</code></pre>
<p>I won't get the same result as it was prod... | 2 | 2016-06-26T17:51:59Z | 38,041,454 | <p>You can do something like</p>
<pre><code>x = random.randint(0,15)
while x != 7:
x = random.randint(0,15)
print (x)
</code></pre>
| 2 | 2016-06-26T17:54:04Z | [
"python",
"python-3.x",
"printing"
] |
print one time uniqe variable in if or while statement python | 38,041,435 | <p>Is there a way to see / print looping variables which have unique values?</p>
<p>for an example:</p>
<pre><code>while random.randint(0,15) != 7:
</code></pre>
<p>If I do:</p>
<pre><code>while random.randint(0,15) != 7:
print (random.randint(0,15))
</code></pre>
<p>I won't get the same result as it was prod... | 2 | 2016-06-26T17:51:59Z | 38,041,456 | <p>Redesign your flow control and store the value of the current random variable:</p>
<pre><code>while True:
rand_ = random.randint(0,15)
if rand_ != 7:
continue
print (rand_)
</code></pre>
| 0 | 2016-06-26T17:54:15Z | [
"python",
"python-3.x",
"printing"
] |
print one time uniqe variable in if or while statement python | 38,041,435 | <p>Is there a way to see / print looping variables which have unique values?</p>
<p>for an example:</p>
<pre><code>while random.randint(0,15) != 7:
</code></pre>
<p>If I do:</p>
<pre><code>while random.randint(0,15) != 7:
print (random.randint(0,15))
</code></pre>
<p>I won't get the same result as it was prod... | 2 | 2016-06-26T17:51:59Z | 38,041,517 | <p>You can make function which will print it.</p>
<p>It would be something like this:</p>
<pre><code>def rprint(x):
print(x)
return x
while rprint(random.randint(0,15)) != 7:
</code></pre>
| 2 | 2016-06-26T18:01:43Z | [
"python",
"python-3.x",
"printing"
] |
How to read and plot arrays from pandas df fast | 38,041,544 | <p>I have following data frame in pandas that contains array reading it directly from a sqlite db using pd.read_sql():</p>
<pre><code> ArrayID Value
0 0 0
1 0 1
2 0 2
3 0 3
4 0 4
5 0 5
6 1 0
7 1 1
8 1 ... | 1 | 2016-06-26T18:04:55Z | 38,041,600 | <p>Use <code>groupby</code> to obtain the groups in one call, (instead of many calls to <code>df.loc</code> and <code>df['ArrayID'] == id</code>):</p>
<pre><code>for aid, grp in df.groupby(['ArrayID']):
plt.plot(grp['Value'].values)
</code></pre>
<hr>
<p>Note also that <code>plt.plot</code> is not very fast. Ca... | 1 | 2016-06-26T18:10:33Z | [
"python",
"sql",
"arrays",
"pandas",
"matplotlib"
] |
using layouts in QT/PYQT | 38,041,590 | <p>So i wrote this program, everything works fine but i want to add a "layout" to clean it up a bit. But when i do and then go to run it it tells me that there is already a layout or format in place and all the widgets appear on top of each other in the top right hand corner. what am i missing. </p>
<pre><code>import ... | 0 | 2016-06-26T18:09:34Z | 38,043,632 | <p>The layout should be part of the ui file, so you should use Qt Designer to add it.</p>
<p>For a basic overview, see: <a href="http://doc.qt.io/qt-4.8/designer-layouts.html" rel="nofollow">Using Layouts in Qt Designer</a>.</p>
| 0 | 2016-06-26T22:03:57Z | [
"python",
"qt",
"pyqt"
] |
Saving an image into user model | 38,041,605 | <p>I'm trying to make an "avatar" field in my user model (tried using all libraries out there, didnt quite like them)</p>
<pre><code>class UserProfile(models.Model):
user = models.OneToOneField(User, related_name='profile')
...
pic = models.ImageField(upload_to="photos", default='pic')
</code></pre>
<p>in setting.py<... | 1 | 2016-06-26T18:11:08Z | 38,041,687 | <p>I dont know how your MEDIA_URL looks like but the media settings should look like something like this: </p>
<pre><code>BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
MEDIA_URL = "/media/"
MEDIA_ROOT = os.path.join(BASE_DIR, "media")
</code></pre>
<p>and no, you do not save media files unde... | 1 | 2016-06-26T18:20:40Z | [
"python",
"django",
"imagefield"
] |
Saving an image into user model | 38,041,605 | <p>I'm trying to make an "avatar" field in my user model (tried using all libraries out there, didnt quite like them)</p>
<pre><code>class UserProfile(models.Model):
user = models.OneToOneField(User, related_name='profile')
...
pic = models.ImageField(upload_to="photos", default='pic')
</code></pre>
<p>in setting.py<... | 1 | 2016-06-26T18:11:08Z | 38,042,319 | <p>You need to configure your settings to serve static media properly when using a local environment.</p>
<p><strong>Add this to your settings.py</strong></p>
<pre><code>DEBUG = True
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
STATICF... | 1 | 2016-06-26T19:20:15Z | [
"python",
"django",
"imagefield"
] |
loop though excel files do something and save them to new folder python pandas | 38,041,607 | <p>I have am having trouble with a for loop.
I dont know what happened, this used to work, but now it tells me "No objects to concatenate".</p>
<p>I want to accomplish two things.
I want to loop through all excel files in a folder. For each excel file I want to remove 2 lines of header data (which the code below alrea... | 1 | 2016-06-26T18:11:24Z | 38,042,746 | <p>IIUC you can do it this way:</p>
<pre><code>import os
import glob
import pandas as pd
fmask = '/path/to/excel_files_dir/*.xls*'
target_dir = '/path/to/'
target_fname = '/path/to/result.xlsx'
dfs = []
for f in glob.glob(fmask):
df = pd.read_excel(f, header=None, skiprows=2)
df.to_excel(os.path.join(target_... | 1 | 2016-06-26T20:10:11Z | [
"python",
"for-loop",
"pandas",
"append",
"export-to-excel"
] |
loop though excel files do something and save them to new folder python pandas | 38,041,607 | <p>I have am having trouble with a for loop.
I dont know what happened, this used to work, but now it tells me "No objects to concatenate".</p>
<p>I want to accomplish two things.
I want to loop through all excel files in a folder. For each excel file I want to remove 2 lines of header data (which the code below alrea... | 1 | 2016-06-26T18:11:24Z | 38,042,904 | <p>Most likely the reason script worked before and not now is you moved its location from the folder of Excel files as this code uses relative paths. Try using absolute paths where you concatenate the folder path name to file name. Consider using <code>os.path.join()</code> which even helps in saving to new folder:</p>... | 1 | 2016-06-26T20:31:37Z | [
"python",
"for-loop",
"pandas",
"append",
"export-to-excel"
] |
How to return JSON in Flask server built with Haxe | 38,041,638 | <p>I'm trying to build a Flask server using Haxe, and I'm stumped on how to return a JSON. I got an example up and running using <a href="https://gist.github.com/nadako/62ecfba4b6faf14a6c67" rel="nofollow">this gist</a> that has <code>Main.index()</code> return a String, but when I try to return a String from <code>hax... | 2 | 2016-06-26T18:15:02Z | 38,195,890 | <p>It doesn't seem to be well documented but Haxe's python target only supports Python 3. See <a href="https://github.com/HaxeFoundation/haxe/issues/4195" rel="nofollow">https://github.com/HaxeFoundation/haxe/issues/4195</a></p>
<p>In this case, "print" was a keyword in Python 2, and the Haxe generated code is trying ... | 2 | 2016-07-05T05:40:38Z | [
"python",
"flask",
"haxe"
] |
Manipulating Text with tkinter | 38,041,715 | <p>My plan was to show strings and then highlist specific letters, depending on the index of the letter.
To give you an idea, this is extly how it should look in the end:
<a href="http://i.stack.imgur.com/PlQoo.jpg" rel="nofollow">click me</a></p>
<p>I wanted to use tkinter and it's canvas, but now I know, that it can... | 1 | 2016-06-26T18:24:13Z | 38,041,894 | <p>so if i understand it correctly u want to just add some text, and then highlight it? id suggest u go to tutorials point, their pretty clear ob how to do it, heres the link: <a href="http://www.tutorialspoint.com/python/tk_text.htm" rel="nofollow">http://www.tutorialspoint.com/python/tk_text.htm</a></p>
<p>heres som... | 1 | 2016-06-26T18:40:55Z | [
"python",
"string",
"tkinter",
"highlight"
] |
UnboundLocalError - Python Error | 38,041,722 | <p>I am getting the following error with my code:</p>
<pre><code>UnboundLocalError: local variable 'row' referenced before assignment
</code></pre>
<p>I have tried many things, but nothing has worked. I suspect it is something to do around the 'quantityQuestion' subprogram. According to the scripter, the problem is a... | 0 | 2016-06-26T18:24:50Z | 38,041,762 | <p>The problem is in <code>restockAction()</code>:</p>
<pre><code>for row in csvList:
# some code
else:
if float(row[3]) >= float(row[4]):
# ^
</code></pre>
<p>If there are no rows in <code>csvList</code>, <code>row</code> will not have any value, since the <code>for</code> will not be execute... | 1 | 2016-06-26T18:28:39Z | [
"python",
"csv",
"variables",
"local"
] |
UnboundLocalError - Python Error | 38,041,722 | <p>I am getting the following error with my code:</p>
<pre><code>UnboundLocalError: local variable 'row' referenced before assignment
</code></pre>
<p>I have tried many things, but nothing has worked. I suspect it is something to do around the 'quantityQuestion' subprogram. According to the scripter, the problem is a... | 0 | 2016-06-26T18:24:50Z | 38,041,954 | <p>You have to verify you have that you have any rows before checking whether row[index] has a value:</p>
<pre><code>else:
if row and float(row[3]) >= float(row[4]):
restockTxt.write("No (other) stock needs to be replenished.")
restockTxt.close()
restockRead = open("restock.txt", "r")
... | 0 | 2016-06-26T18:46:06Z | [
"python",
"csv",
"variables",
"local"
] |
Executing a Python file with Ajax | 38,041,806 | <p>I am trying to run a python script on page load. The python script will save a log.text file with some log information. After doing some research I came up with:</p>
<pre><code> <script>
window.onload = function () {
$.ajax({
type: 'POST',
url: "img/test.py",
... | 1 | 2016-06-26T18:32:06Z | 38,043,351 | <p>Did you set the execution flag on that file? </p>
<pre><code> chmod +x test.py
</code></pre>
<p>should doâ¦</p>
| 0 | 2016-06-26T21:26:50Z | [
"python",
"html",
"ajax"
] |
checking if key's already in dictionary with try except | 38,041,857 | <p>I'm using a dictionary to count how many times different items appear in a dataset. In the <strong>init</strong> of the class, I create the property as a dictionary like this</p>
<pre><code>self.number_found = {}
</code></pre>
<p>The first time I find any particular item, I would get a KeyError if I try to do this... | -1 | 2016-06-26T18:37:47Z | 38,041,889 | <p>You can use a <code>defaultdict</code>:</p>
<pre><code>from collections import defaultdict
self.number_found = defaultdict(int)
</code></pre>
<p>The first time an item is accessed, its value will take a default of <code>0</code></p>
<p>A <code>None</code> is returned because you're not <em>returning</em> anythin... | 4 | 2016-06-26T18:40:29Z | [
"python"
] |
checking if key's already in dictionary with try except | 38,041,857 | <p>I'm using a dictionary to count how many times different items appear in a dataset. In the <strong>init</strong> of the class, I create the property as a dictionary like this</p>
<pre><code>self.number_found = {}
</code></pre>
<p>The first time I find any particular item, I would get a KeyError if I try to do this... | -1 | 2016-06-26T18:37:47Z | 38,042,180 | <p>The return at the end of the except block must be moved out. That way, x is returned for both cases</p>
<pre><code>class C(object):
def __init__(self):
self.number_found = {}
def _count_occurrences(self, item):
try:
#this checks to see if the item's already in the dict
... | 2 | 2016-06-26T19:06:23Z | [
"python"
] |
AngularJS request.POST return QueryDict: {} | 38,041,879 | <p>I am making a POST request in AngularJS as follows:</p>
<pre><code>'use strict';
angular.module('app').controller('RegisterController', function($scope, $http) {
$scope.login = []
$scope.registrar = function() {
$http({
method : 'POST',
url : '/register/',
... | 0 | 2016-06-26T18:39:43Z | 38,041,993 | <p>It's accessible via <code>request.body</code> so you need to do <code>json.loads(request.body)</code> to retrieve the posted data.</p>
<p>Also consider using <a href="http://www.django-rest-framework.org/" rel="nofollow">DRF</a> instead. It will handle retrieving json payload automatically.</p>
| 0 | 2016-06-26T18:49:33Z | [
"python",
"angularjs",
"django"
] |
Get the row and column labels for selected values in a Pandas dataframe | 38,041,936 | <p>I'd like to get the row and column labels for values matching some condition in a dataframe. Just to keep it interesting, I need it to work with a hierarchical (multi-)index. For example:</p>
<pre><code>df = pd.DataFrame(np.arange(16).reshape(4, 4), columns=pd.MultiIndex.from_product((('a', 'b'), ('x', 'y'))))
... | 1 | 2016-06-26T18:44:52Z | 38,041,988 | <p>Use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html" rel="nofollow"><code>np.where</code></a> to obtain the ordinal indices of the True values:</p>
<pre><code>import numpy as np
import pandas as pd
df = pd.DataFrame(np.arange(16).reshape(4, 4),
columns=pd.MultiIndex.... | 2 | 2016-06-26T18:48:53Z | [
"python",
"pandas",
"indexing"
] |
Making for loop more idiomatic | 38,041,939 | <p>I want to make the first for loop more pythonic, so how can I use only one variable instead of 2?:</p>
<pre><code> #Split input file into lines using LF as separator
program_lines1 = input_file.split("\n", "")
#Delete CR at end of lines if present
program_lines2 = ""
for line in program_lines1:
... | 0 | 2016-06-26T18:45:16Z | 38,042,163 | <p>If i understand you code:</p>
<pre><code>for line in range(len(program_lines2)):
program_lines2.remove("p2")
</code></pre>
<p>can be replaced with</p>
<pre><code>program_lines2 = [line for line in program_lines2 if line != 'p2']
</code></pre>
<p>Same situation with first variable - code</p>
<pre><code>f... | 3 | 2016-06-26T19:04:27Z | [
"python"
] |
Making for loop more idiomatic | 38,041,939 | <p>I want to make the first for loop more pythonic, so how can I use only one variable instead of 2?:</p>
<pre><code> #Split input file into lines using LF as separator
program_lines1 = input_file.split("\n", "")
#Delete CR at end of lines if present
program_lines2 = ""
for line in program_lines1:
... | 0 | 2016-06-26T18:45:16Z | 38,042,256 | <p>Something along these lines? Took the liberty of not using "for" loops whatsoever.</p>
<pre><code>with open('filename.txt') as f:
lines = f.readlines() # Split file into lines
lines = list(map(lambda x: x.strip(), lines)) # Clear LF's
lines = list(filter(lambda x: x != "p2", lines)) # Remove all 'p2'... | 0 | 2016-06-26T19:13:08Z | [
"python"
] |
Selenium Scroll inside of popup div | 38,041,974 | <p>I am using selenium and trying to scroll inside the popup div on instagram.</p>
<p>I get to a page like '<a href="https://www.instagram.com/kimkardashian/" rel="nofollow">https://www.instagram.com/kimkardashian/</a>', click followers, and then I can't get the followers list to scroll down.</p>
<p>I tried using hov... | 1 | 2016-06-26T18:47:56Z | 38,045,098 | <p>You would need to use jQuery to execute a function on the div. Here's the way I figured to do it. It was easier to solve it with jQuery and execute a script than handle it with the api.</p>
<pre><code>height = 2000
query = 'jQuery("div").filter((i, div) => jQuery(div).css("overflow-y") == "scroll")[0].scrollTo... | 0 | 2016-06-27T02:28:38Z | [
"python",
"selenium",
"screen-scraping"
] |
Run shell script/commands when starting flask development server | 38,042,079 | <p>I have a web app written in reactjs with a flask backend. As I currently have the project set up, the reactjs app is nested within the flask app and I use symlinks to place the compiled <code>bundle.js</code> file in its proper place (the file containing my js). So my project looks something like this:</p>
<pre><co... | 0 | 2016-06-26T18:55:51Z | 38,042,299 | <p>I am certainly no React.js dev, but for such cases I usually just write a quick bash wrapper script like:</p>
<pre><code>#!/bin/bash
npm run build && flask run
</code></pre>
<p>That way Flask will only run if the NPM build completed successfully.
Hope this helps, somehow.</p>
| 1 | 2016-06-26T19:18:12Z | [
"python",
"shell",
"reactjs",
"flask"
] |
Angular JS routing makes infinite loop | 38,042,135 | <p>i got Django server with </p>
<p>urls.py </p>
<pre><code>urlpatterns = [
url('^', IndexView.as_view(), name='index')
]
</code></pre>
<p>landing/urls.py</p>
<pre><code>urlpatterns = [
url(r'^admin/', admin.site.urls),
url('^.*', include("landing.urls"))
]
</code></pre>
<p>views.py </p>
<pre><code>class In... | 0 | 2016-06-26T19:02:09Z | 38,325,959 | <p>This is your issue, I believe:</p>
<h1>urls.py</h1>
<pre><code>urlpatterns = [
url('^', IndexView.as_view(), name='index')
]
</code></pre>
<h1>landing/urls.py</h1>
<pre><code>urlpatterns = [
url(r'^admin/', admin.site.urls),
url('^.*', include("landing.urls")) # Circular reference
]
</code></pre>
<p>You'... | 1 | 2016-07-12T10:14:50Z | [
"javascript",
"python",
"angularjs",
"django"
] |
request.user.is_authenticated returning false even though logged in | 38,042,296 | <p>In the HTML template, request.user.is_authenticated keeps returning nothing, and it keeps acting like I have never logged in. I have logged in... </p>
<p>This is Home Views.py, after it logged in, it returns to home.html</p>
<pre><code>@login_required
def home(request):
print("USER?: " + str(request.user))
... | 0 | 2016-06-26T19:17:49Z | 38,042,847 | <p>You are not using a RequestContext to render the template, so context processors are not run and <code>user</code> is not added to the context.</p>
<p>You can see from the example of the <code>log_in</code> view that you should be using <code>render(request, ...)</code> rather than <code>render_to_response(...)</co... | 1 | 2016-06-26T20:24:29Z | [
"python",
"django"
] |
GAE Python - OperationalError: (2013, 'Lost connection to MySQL server during query') | 38,042,300 | <p>I've been trying to connect to ClouSQL using Flexible Environments (vm:true)</p>
<p>but when I upload my app using:</p>
<pre><code>gcloud preview app deploy --version MYVERSION
</code></pre>
<p>An error is thrown:</p>
<pre><code>OperationalError: (2013, 'Lost connection to MySQL server during query')
</code></p... | 3 | 2016-06-26T19:18:20Z | 38,042,402 | <p>take a look in you my.cnf in the /etc/mysql/ directory and change the parameter <strong>max_allowed_packet</strong> and set the value higher. then you must restart the Database</p>
<p>you can also change this value via SQL like this:</p>
<pre><code>MariaDB [yourSchema]> show GLOBAL variables like 'max_allowed_p... | 1 | 2016-06-26T19:31:19Z | [
"python",
"mysql",
"google-app-engine",
"pymysql"
] |
Filter inner keys from 2 level nested dictionaries | 38,042,324 | <p>I looking the most elegant way to get this:</p>
<pre><code>{'i_1': {'a': 33, 't': 4}, 'i_2': {'a': 9, 't': 0}}
</code></pre>
<p>From this:</p>
<pre><code>{'i_1': {'a': 33, 'b': 55, 't': 4}, 'i_2': {'a': 9, 'b': 11, 't': 0}}
</code></pre>
<p>Each inner dict can have a lot of a, b, ..., z keys.</p>
<p>for now I h... | 3 | 2016-06-26T19:20:57Z | 38,042,387 | <pre><code>import copy
def foo(d):
d_copy = copy.deepcopy(d)
for key in d_copy:
print(key, d[key])
if isinstance(d[key], dict):
foo(d[key])
if key == 'b':
d.pop(key)
</code></pre>
| 0 | 2016-06-26T19:29:24Z | [
"python"
] |
Filter inner keys from 2 level nested dictionaries | 38,042,324 | <p>I looking the most elegant way to get this:</p>
<pre><code>{'i_1': {'a': 33, 't': 4}, 'i_2': {'a': 9, 't': 0}}
</code></pre>
<p>From this:</p>
<pre><code>{'i_1': {'a': 33, 'b': 55, 't': 4}, 'i_2': {'a': 9, 'b': 11, 't': 0}}
</code></pre>
<p>Each inner dict can have a lot of a, b, ..., z keys.</p>
<p>for now I h... | 3 | 2016-06-26T19:20:57Z | 38,042,409 | <p>Here you go. This functions takes a dict in a format you specified and a list of keys that have to be removed from inner dictionaries:</p>
<pre><code>def remove_inner_keys(data: dict, inner_keys_to_remove: list) -> dict:
result = dict()
for outer_key in data.keys():
partial_result = dict()
... | 0 | 2016-06-26T19:32:25Z | [
"python"
] |
Filter inner keys from 2 level nested dictionaries | 38,042,324 | <p>I looking the most elegant way to get this:</p>
<pre><code>{'i_1': {'a': 33, 't': 4}, 'i_2': {'a': 9, 't': 0}}
</code></pre>
<p>From this:</p>
<pre><code>{'i_1': {'a': 33, 'b': 55, 't': 4}, 'i_2': {'a': 9, 'b': 11, 't': 0}}
</code></pre>
<p>Each inner dict can have a lot of a, b, ..., z keys.</p>
<p>for now I h... | 3 | 2016-06-26T19:20:57Z | 38,042,447 | <p>You can make your code a little bit more readable by using <code>items</code> instead of <code>keys</code>:</p>
<pre><code>{k: dict(a=v['a'], t=v['t']) for k, v in d.items())
</code></pre>
| 2 | 2016-06-26T19:37:10Z | [
"python"
] |
Python / Kivy App running only once | 38,042,329 | <p>I'm running a very simple python (3.5) script using Spyder IDE from Anaconda platform.</p>
<pre><code>from kivy.app import App
from kivy.uix.label import Label
from kivy.uix.gridlayout import GridLayout
from kivy.uix.textinput import TextInput
class LoginScreen(GridLayout):
def __init__(self, **kwargs):
... | 1 | 2016-06-26T19:21:17Z | 38,057,823 | <p>Not that much Kivy-related problem. The "Spyder" probably keeps old stuff in memory? Try in a simple interpreter type your code line by line. Then close the app and try again typing <code>TestApp().run()</code> - the same three lines.</p>
<p>This way you'll see that if the old stuff(variables, classes, whatever is ... | 1 | 2016-06-27T15:27:49Z | [
"python",
"kivy",
"spyder"
] |
Huge memory consumption while trying to run this code | 38,042,361 | <p>While trying to run this code:</p>
<pre><code>l = 1000000
w = [1, 1]
for i in range(2, l):
w.append(w[-1] + w[-2])
</code></pre>
<p>computer hangs on and Blue screen of death appears. The only info which I get is about MEMORY MANAGEMENT. Problem occurs in version 2.7 of Python and 3.4 as well.</p>
<p>Code wor... | 2 | 2016-06-26T19:25:25Z | 38,042,573 | <p>The numbers you're producing are huger than you might realize. For example, here's the size in memory of the last one:</p>
<pre><code>>>> a, b = 1, 1
>>> for i in xrange(2, 1000000):
... a, b = b, a+b
...
>>> sys.getsizeof(b)
92592
</code></pre>
<p>That's 92 kilobytes for one integer... | 6 | 2016-06-26T19:52:14Z | [
"python"
] |
Huge memory consumption while trying to run this code | 38,042,361 | <p>While trying to run this code:</p>
<pre><code>l = 1000000
w = [1, 1]
for i in range(2, l):
w.append(w[-1] + w[-2])
</code></pre>
<p>computer hangs on and Blue screen of death appears. The only info which I get is about MEMORY MANAGEMENT. Problem occurs in version 2.7 of Python and 3.4 as well.</p>
<p>Code wor... | 2 | 2016-06-26T19:25:25Z | 38,042,594 | <p>The fibonacci numbers are HUGE. In R and other languages, integers overflow, so not that much memory is required. But in Python, integers simply don't overflow. The 1000000th fibonacci number would require terabytes of space. Once your OS uses up all the physical RAM, it'll switch over to hard disk swap. When it run... | 2 | 2016-06-26T19:55:00Z | [
"python"
] |
Huge memory consumption while trying to run this code | 38,042,361 | <p>While trying to run this code:</p>
<pre><code>l = 1000000
w = [1, 1]
for i in range(2, l):
w.append(w[-1] + w[-2])
</code></pre>
<p>computer hangs on and Blue screen of death appears. The only info which I get is about MEMORY MANAGEMENT. Problem occurs in version 2.7 of Python and 3.4 as well.</p>
<p>Code wor... | 2 | 2016-06-26T19:25:25Z | 38,042,754 | <p>In python list take too much space in memory. try to use tuple</p>
<p>Example code:</p>
<pre><code>l = 1000000
w = (1,1)
for i in xrange(2,l):
w = w + (w[-1] + w[-2],)
</code></pre>
<p>execution of program take time, that depend on your number of cpu's and main memory.</p>
| 0 | 2016-06-26T20:11:35Z | [
"python"
] |
Pip error when trying to install module | 38,042,446 | <p>I'm trying to install PyDrive [a wrapper library of the google drive api for python] and pip is giving me this error. It did the same thing when trying to install things like matplotlib or mega.py [a mega.nz api for python].</p>
<p>Here's the error:
<a href="http://i.stack.imgur.com/QhkWM.png" rel="nofollow"><img s... | 0 | 2016-06-26T19:37:02Z | 38,043,892 | <p>You could try renaming that <code>pip.py</code> to something else.</p>
<p>There is a library called pip somewhere on your system (and it may also be bundled within pip.exe). That is different from the "entry point" script that actually runs pip from the command line. When you run pip, it will try to import the libr... | 1 | 2016-06-26T22:47:33Z | [
"python",
"python-3.x",
"pip"
] |
Flip the entries in a list without looping | 38,042,513 | <p>In Python, I have a list of zeros and ones (could be very long), e.g., </p>
<pre><code>L = [0,1,0,1,1,0,1,0,0,1]
</code></pre>
<p>I want to flip every entry in the list without use loop, e.g., make 0 to 1 and make 1 to 0.</p>
<p>My idea is the following: this L can be viewed as a binary representation of a real n... | 2 | 2016-06-26T19:45:48Z | 38,042,648 | <p>You can achieve this using a list comprehension, and bitwise XOR operator (^) for flipping each bit:</p>
<pre><code>def flip(L):
return [ x ^ 1 for x in L ]
L = [0,1,0,1,1,0,1,0,0,1]
print flip(L)
</code></pre>
| 0 | 2016-06-26T19:59:19Z | [
"python",
"bit-manipulation"
] |
Flip the entries in a list without looping | 38,042,513 | <p>In Python, I have a list of zeros and ones (could be very long), e.g., </p>
<pre><code>L = [0,1,0,1,1,0,1,0,0,1]
</code></pre>
<p>I want to flip every entry in the list without use loop, e.g., make 0 to 1 and make 1 to 0.</p>
<p>My idea is the following: this L can be viewed as a binary representation of a real n... | 2 | 2016-06-26T19:45:48Z | 38,042,651 | <p>You can do it using lambda and map:</p>
<pre><code>l = [0,1,0,1]
f = map(lambda x: int(not x),l)
print f # prints [1,0,1,0]
</code></pre>
| 2 | 2016-06-26T19:59:29Z | [
"python",
"bit-manipulation"
] |
Flip the entries in a list without looping | 38,042,513 | <p>In Python, I have a list of zeros and ones (could be very long), e.g., </p>
<pre><code>L = [0,1,0,1,1,0,1,0,0,1]
</code></pre>
<p>I want to flip every entry in the list without use loop, e.g., make 0 to 1 and make 1 to 0.</p>
<p>My idea is the following: this L can be viewed as a binary representation of a real n... | 2 | 2016-06-26T19:45:48Z | 38,042,937 | <p>Turn the list to a string, use <code>str.translate</code> to do the substitution, turn it back into a list.</p>
<pre><code>import string
d = [0,1,0,1,1,0,1,0,0,1]
e = ''.join(map(str,d))
table = string.maketrans('01','10')
f = e.translate(table)
g = map(int,f)
</code></pre>
<hr>
<pre><code>>>> d
[0, 1, 0... | 1 | 2016-06-26T20:35:36Z | [
"python",
"bit-manipulation"
] |
Flip the entries in a list without looping | 38,042,513 | <p>In Python, I have a list of zeros and ones (could be very long), e.g., </p>
<pre><code>L = [0,1,0,1,1,0,1,0,0,1]
</code></pre>
<p>I want to flip every entry in the list without use loop, e.g., make 0 to 1 and make 1 to 0.</p>
<p>My idea is the following: this L can be viewed as a binary representation of a real n... | 2 | 2016-06-26T19:45:48Z | 38,043,141 | <p>You can do this by: </p>
<ol>
<li><p>Creating an iterator from your list, </p></li>
<li><p>Freezing the <code>next</code> items of the iterator in a string literal, </p></li>
<li><p>Performing the flip operation in the string, and </p></li>
<li><p>Calling <code>eval</code> on an expanded version of the string liter... | 0 | 2016-06-26T21:01:15Z | [
"python",
"bit-manipulation"
] |
How to compress a text file? | 38,042,517 | <p>I have a text file created and I want to compress it.</p>
<p>How would I accomplish this?</p>
<p>I have done some research, around the forum ; found a question, similar to this but when I tried it out, it did not work as it was text typed in, not a file, for example</p>
<pre><code>import zlib, base64
text = 'STA... | -2 | 2016-06-26T19:46:05Z | 38,043,936 | <p>there is a section entitled "Example of how to GZIP compress an existing file" at the bottom of <a href="https://docs.python.org/2/library/gzip.html" rel="nofollow">https://docs.python.org/2/library/gzip.html</a></p>
| 0 | 2016-06-26T22:54:37Z | [
"python",
"python-2.7"
] |
How to compress a text file? | 38,042,517 | <p>I have a text file created and I want to compress it.</p>
<p>How would I accomplish this?</p>
<p>I have done some research, around the forum ; found a question, similar to this but when I tried it out, it did not work as it was text typed in, not a file, for example</p>
<pre><code>import zlib, base64
text = 'STA... | -2 | 2016-06-26T19:46:05Z | 38,059,643 | <p>you should use this code to do what you tried:</p>
<pre><code>import zlib, base64
file = open('Suitable.txt','r')
text = file.read()
file.close()
code = base64.b64encode(zlib.compress(text.encode('utf-8'),9))
code = code.decode('utf-8')
print(code)
</code></pre>
<p>but it actually want be compressed because <code... | 0 | 2016-06-27T17:15:07Z | [
"python",
"python-2.7"
] |
MVC the simplest example | 38,042,632 | <p>I'm struggling to understand the MVC pattern. I've been working with MVC frameworks like ASP.NET MVC and Django, but project structure there is pretty much forced, so it really didn't help to understand how to build my own apps based on this pattern. To clear things up i decided to write the simplest example of my u... | 3 | 2016-06-26T19:57:42Z | 38,042,759 | <p>The MVC architecture is very broad and can change depending on the programming language and type of application you are doing, so in this case, yes your approach can be accepted as correct. </p>
<p>What I have learned from static typed languages is that you define the model and views as complete separate entities, ... | 2 | 2016-06-26T20:12:27Z | [
"python",
"model-view-controller"
] |
Dataframe conditional logic | 38,042,698 | <p>I have a dataframe ('dayData') with the columns 'Power1' and 'Power2'</p>
<pre><code> Power1 Power2
1.049246442 -0.231991505
-0.950753558 0.276990531
-0.950753558 0.531481549
0 -0.231991505
-0.464648091 -0.231991505
1.049246442 -1.204952258
0.455388896 -0.4... | -1 | 2016-06-26T20:05:05Z | 38,042,860 | <p>When you want element-wise logical operations on pandas objects, you need to use <code>&</code> for <code>and</code> and <code>|</code> for <code>or</code>. So, this is what you are looking for:</p>
<pre><code>In [15]: dayData
Out[15]:
Power1 Power2
0 1.049246 -0.231992
1 -0.950754 0.276991
2 -0.9507... | 0 | 2016-06-26T20:25:59Z | [
"python",
"pandas"
] |
Dataframe conditional logic | 38,042,698 | <p>I have a dataframe ('dayData') with the columns 'Power1' and 'Power2'</p>
<pre><code> Power1 Power2
1.049246442 -0.231991505
-0.950753558 0.276990531
-0.950753558 0.531481549
0 -0.231991505
-0.464648091 -0.231991505
1.049246442 -1.204952258
0.455388896 -0.4... | -1 | 2016-06-26T20:05:05Z | 38,043,298 | <pre><code>df['ResultPower'] = df['Power1']
cond1 = (df.Power1 >= 0) & (df.Power2 <= 0)
cond2 = (df.Power1 <= 0) & (df.Power2 >= 0)
df.loc[cond1 | cond2, 'ResultPower'] = 0
</code></pre>
<p>Using timeit: 100 loops, best of 3: 1.87 ms per loop</p>
| 1 | 2016-06-26T21:21:39Z | [
"python",
"pandas"
] |
Why quizfile.write(" ") is not working from the Second for loop | 38,042,704 | <p>I got this question Automate the boring Stuff book. The Code is also given there but When I was Practising this on my own the problem I am getting is this code is not writing in the files after the first for loop.</p>
<pre><code>import random
import os
capitals = {'Alabama': 'Montgomery', 'Alaska': 'Juneau', 'Arizo... | -1 | 2016-06-26T20:05:37Z | 38,042,988 | <p>You've got some for loops that need to be nested within others. You're attempting to access out of scope variables as it is now.</p>
<p>Your code, cleaned up:</p>
<pre><code>import random
import os
capitals = {'Alabama': 'Montgomery', 'Alaska': 'Juneau', 'Arizona': 'Phoenix',
'Arkansas': 'Little Rock', 'Califor... | 0 | 2016-06-26T20:41:54Z | [
"python",
"python-3.x"
] |
An integer is required | 38,042,706 | <p>I'm new in Python 3. I use aiohttp module for Python 3.5.
When I run my project, I have a following error</p>
<pre><code>TypeError: an integer is required (got type str)
</code></pre>
<p>The stack-trace is:</p>
<pre><code>Traceback (most recent call last):
File "/home/santi/tesis/tanner/server.py", line 82, i... | 0 | 2016-06-26T20:05:57Z | 38,042,740 | <p>The port number should be an Integer:</p>
<pre><code>f = loop.create_server(
lambda: HttpRequestHandler(debug=False, keep_alive=75), '0.0.0.0', 8090)
</code></pre>
| 2 | 2016-06-26T20:09:38Z | [
"python",
"python-3.5",
"aiohttp"
] |
specific Regular expression search python | 38,042,750 | <p>This is my first post.
I always come to this forum looking for an answer when it comes to code. </p>
<p>I have been fighting with understanding regular expressions in Python, but it is kind of hard. </p>
<p>I have text that looks like this:</p>
<pre class="lang-none prettyprint-override"><code>Name: Clash1
Dis... | 2 | 2016-06-26T20:11:02Z | 38,042,953 | <pre><code>import re
lines = s.split('\n')
names = []
points = []
for line in lines:
result = re.search('^Name:\s*(\w+)', line)
if result:
names.append(result.group(1))
result = re.search('^Clash Point:\s*([-0-9m., ]+)',line)
if result:
points.append(result.group(1))
print(name... | 0 | 2016-06-26T20:38:17Z | [
"python",
"regex"
] |
specific Regular expression search python | 38,042,750 | <p>This is my first post.
I always come to this forum looking for an answer when it comes to code. </p>
<p>I have been fighting with understanding regular expressions in Python, but it is kind of hard. </p>
<p>I have text that looks like this:</p>
<pre class="lang-none prettyprint-override"><code>Name: Clash1
Dis... | 2 | 2016-06-26T20:11:02Z | 38,043,270 | <p>If you're looking for a regex solution, you could come up with:</p>
<pre><code>^Name:\s* # look for Name:, followed by whitespaces
# at the beginning of a line
(?P<name>.+) # capture the rest of the line
# in a group called "name"
[\s\S]+? # anything a... | 1 | 2016-06-26T21:17:56Z | [
"python",
"regex"
] |
Pandas - count if multiple conditions | 38,042,768 | <p>Having a dataframe in python:</p>
<pre><code>CASE TYPE
1 A
1 A
1 A
2 A
2 B
3 B
3 B
3 B
</code></pre>
<p>how can I create a result dataframe which would yield all cases and either an "A" if the case had only "A's" assigned, "B" if it was onl... | 2 | 2016-06-26T20:13:56Z | 38,043,128 | <p>Here is an option, where we firstly collect the TYPE as list by group of <code>CASE</code> and then check the <code>length</code> of unique TYPE, if it is larger than <code>1</code>, return <code>MIXED</code> otherwise the TYPE by itself:</p>
<pre><code>import pandas as pd
import numpy as np
groups = df.groupby('CA... | 2 | 2016-06-26T20:59:49Z | [
"python",
"pandas",
"dataframe",
"group-by"
] |
Pandas - count if multiple conditions | 38,042,768 | <p>Having a dataframe in python:</p>
<pre><code>CASE TYPE
1 A
1 A
1 A
2 A
2 B
3 B
3 B
3 B
</code></pre>
<p>how can I create a result dataframe which would yield all cases and either an "A" if the case had only "A's" assigned, "B" if it was onl... | 2 | 2016-06-26T20:13:56Z | 38,043,136 | <p>here is one bit ugly, but not that slow solution:</p>
<pre><code>In [154]: df
Out[154]:
CASE TYPE
0 1 A
1 1 A
2 1 A
3 2 A
4 2 B
5 3 B
6 3 B
7 3 B
8 4 C
9 4 C
10 4 B
In [155]: %paste
(df.groupby('CASE')['TYPE']
.apply(lamb... | 1 | 2016-06-26T21:00:50Z | [
"python",
"pandas",
"dataframe",
"group-by"
] |
Pandas - count if multiple conditions | 38,042,768 | <p>Having a dataframe in python:</p>
<pre><code>CASE TYPE
1 A
1 A
1 A
2 A
2 B
3 B
3 B
3 B
</code></pre>
<p>how can I create a result dataframe which would yield all cases and either an "A" if the case had only "A's" assigned, "B" if it was onl... | 2 | 2016-06-26T20:13:56Z | 38,043,561 | <pre><code>df['NTYPES'] = df.groupby('CASE').transform(lambda x: x.nunique())
df.loc[df.NTYPES > 1, 'TYPE'] = 'MIXED'
df.groupby('TYPE', as_index=False).first().drop('NTYPES', 1)
TYPE CASE
0 A 1
1 B 3
2 MIXED 2
</code></pre>
| 2 | 2016-06-26T21:55:42Z | [
"python",
"pandas",
"dataframe",
"group-by"
] |
Pandas - count if multiple conditions | 38,042,768 | <p>Having a dataframe in python:</p>
<pre><code>CASE TYPE
1 A
1 A
1 A
2 A
2 B
3 B
3 B
3 B
</code></pre>
<p>how can I create a result dataframe which would yield all cases and either an "A" if the case had only "A's" assigned, "B" if it was onl... | 2 | 2016-06-26T20:13:56Z | 38,043,772 | <p>Here is a (admittedly over-engineered) solution that avoids looping over groups and <code>DataFrame.apply</code> (these are slow, so avoiding them may become important if your dataset gets sufficiently large).</p>
<pre><code>import pandas as pd
df = pd.DataFrame({'CASE': [1]*3 + [2]*2 + [3]*3,
'T... | 1 | 2016-06-26T22:24:54Z | [
"python",
"pandas",
"dataframe",
"group-by"
] |
TypeError: not all arguments converted during string formatting in python script output | 38,042,800 | <p>I am attempting to learn python following using "Learn Python the Hard Way" 3rd edition and getting an error on exercise 8.</p>
<p>I have python v 2.7.11 and using the following code</p>
<pre><code>formatter = "%r %r %r $r"
print formatter % (1, 2, 3, 4)
print formatter % ("one", "two", "three", "four")
print for... | 0 | 2016-06-26T20:18:36Z | 38,042,827 | <p>what's the <code>$r</code> doing?</p>
<pre><code>formatter = "%r %r %r %r"
</code></pre>
<p>should work!</p>
| 1 | 2016-06-26T20:21:51Z | [
"python",
"python-2.7"
] |
Matplotlib: different stacked bars? | 38,042,838 | <p>I want to create a stacked bar plot with different amount of stacks for each bar. The <a href="http://matplotlib.org/examples/pylab_examples/bar_stacked.html" rel="nofollow">general example</a> for stacked bars works fine if my data are all homogenous, but I want something that rather looks like the shown example.</... | 0 | 2016-06-26T20:22:43Z | 38,044,391 | <p>I guess you are working directly in matplotlib, but these days plotting data, especially for quick a view can be easily done with pandas, following your example we get:</p>
<pre><code>import matplotlib.pyplot as plt
import matplotlib
matplotlib.style.use("ggplot")
import pandas as pd
import numpy as np
df = pd.Da... | 1 | 2016-06-27T00:25:17Z | [
"python",
"matplotlib"
] |
python2.7 on Raspberry Pi 3 - Pyaudio Input overflowed | 38,042,875 | <p>I'm calling for help for an issue I havn't been able to tackle so far...
I'm using a Raspberry Pi 3 Model B on which I've plugged a Focusrite Scarlett 2i2 USB Sound Card on which is plugged a XLR microphone. The whole thing is working fine on Audacity for example. It can record and/or play a sound.
Now I'd like to u... | 1 | 2016-06-26T20:27:37Z | 38,057,990 | <p>Not sure if your question can be explicitly answered the way you have phrased it. Hopefully I can point you in a couple of directions. I've been doing some audio streaming work with my Model 3, so I'm very interested in your example.</p>
<p>The biggest difference between the Pi and a computer is the CPU speed and ... | 0 | 2016-06-27T15:35:08Z | [
"python",
"python-2.7",
"raspbian",
"raspberry-pi3"
] |
Strange values calculating Fibonacci in numpy | 38,042,877 | <p>I've got this small (maybe inefficient, but still reasonable) code:</p>
<pre><code>fib = np.array([0,1])
for i in range(2,100):
fib = np.append(fib, fib[-2] + fib[-1])
</code></pre>
<p>Reviewing the result at first all looks good:</p>
<pre><code>In [17]: fib[:20]
Out[17]: array([ 0, 1, 1, 2, 3, ... | 2 | 2016-06-26T20:27:51Z | 38,043,055 | <blockquote>
<p>I figure this is a data type accuracy issue, but a clear explanation will be appreciated.</p>
</blockquote>
<p>It seems that <code>numpy</code> arrays, by default, use signed 32-bit integers, which are only capable of storing values between -2,147,483,648 and 2,147,483,647. Once you exceed the maximu... | 4 | 2016-06-26T20:49:08Z | [
"python",
"numpy"
] |
Saving list values when terminating | 38,042,915 | <p>I am doing some tests: running time functions and appending values to a list.</p>
<p>I am not really sure what to receive. I am thinking about cancelling the shell after a period of time. However, I would like to see what values were appended to the list. Is there any pythonic way to do this, or is the best way to ... | 1 | 2016-06-26T20:32:51Z | 38,043,046 | <p>If you really need the output to be robust to random shutdowns and/or crashes, you should write each entry to file as they are generated instead of appending to a list (assuming you don't need them in the program). And if you do it using <code>with open(...) as f:</code> then it will handle closing the file appropri... | 1 | 2016-06-26T20:48:29Z | [
"python",
"python-3.x",
"save"
] |
whats wrong with this statement(count from 0-9) | 38,042,936 | <p>I am trying to get this code to calculate 5 and print numbers by 5's with a while statement of 7, so I want it to loop through, generating a different number 7 times; however, when it gets to a number over 10, I want it to start back over at 0 and ignore the 10.</p>
<p>This is my code:</p>
<pre><code>while z < ... | -4 | 2016-06-26T20:35:32Z | 38,042,950 | <p>Your code is not in the loop. Python's code blocks are created with indents:</p>
<pre><code>while z < 7:
firstpickplusfive = int(firstpickplusfive) + 1
counts = counts + 1
if counts == 1:
if firstpickplusfive > 9:
firstpickplusfive = 0
if counts == 5:
print firstpickp... | 1 | 2016-06-26T20:37:26Z | [
"python",
"python-2.7"
] |
whats wrong with this statement(count from 0-9) | 38,042,936 | <p>I am trying to get this code to calculate 5 and print numbers by 5's with a while statement of 7, so I want it to loop through, generating a different number 7 times; however, when it gets to a number over 10, I want it to start back over at 0 and ignore the 10.</p>
<p>This is my code:</p>
<pre><code>while z < ... | -4 | 2016-06-26T20:35:32Z | 38,043,402 | <p>Is this the result you were trying to achieve:</p>
<pre><code>import random
x = random.randint(1,9)
for i in range(1,8):
print x
x += 5
if x >= 10:
x -= 9
</code></pre>
<p>This generates a random number, and adds 5 until it passes 10, then subtracts 9, and it does this seven times. If I und... | 0 | 2016-06-26T21:33:49Z | [
"python",
"python-2.7"
] |
whats wrong with this statement(count from 0-9) | 38,042,936 | <p>I am trying to get this code to calculate 5 and print numbers by 5's with a while statement of 7, so I want it to loop through, generating a different number 7 times; however, when it gets to a number over 10, I want it to start back over at 0 and ignore the 10.</p>
<p>This is my code:</p>
<pre><code>while z < ... | -4 | 2016-06-26T20:35:32Z | 38,059,057 | <p>no this is not what I was trying to do here is what I am trying to do.</p>
<pre><code>counts = 0
r = 0
firstpickplusfive = 7
p = firstpickplusfive + 5
while r < 3:
firstpickplusfive = p + counts
if firstpickplusfive > 6:
firstpickplusfive = firstpickplusfive + counts - 10
if p > 9:
... | 0 | 2016-06-27T16:37:16Z | [
"python",
"python-2.7"
] |
whats wrong with this statement(count from 0-9) | 38,042,936 | <p>I am trying to get this code to calculate 5 and print numbers by 5's with a while statement of 7, so I want it to loop through, generating a different number 7 times; however, when it gets to a number over 10, I want it to start back over at 0 and ignore the 10.</p>
<p>This is my code:</p>
<pre><code>while z < ... | -4 | 2016-06-26T20:35:32Z | 38,089,243 | <p>Here is an easier method:</p>
<pre><code>for i in range(1,4):
num = 7
num += 5
num +=(i-1)
if num >=10:
num -= 10
print num
i+=1
</code></pre>
<p>Try this in your script, does it work?</p>
| 0 | 2016-06-29T02:15:36Z | [
"python",
"python-2.7"
] |
How to pass a default value for argument from one function definition to a higher one | 38,042,985 | <p>I'm searching for a good way to pass default values for arguments to a calling function. Let me explain this by example:</p>
<pre><code>def greet(name, greeting='Hello', punctuation='!'):
return greeting+' '+name+punctuation
def greet_with_hi(name, punctuation='!'):
return greet(name, 'Hi', punctuation)
</c... | 1 | 2016-06-26T20:41:38Z | 38,043,009 | <p>Let's simplify your question a little bit. We have two functions, <code>a</code> and <code>b</code> that is using it.</p>
<pre><code>def a(arg = 0):
return arg
def b(arg = 0):
return a(arg)
</code></pre>
<p>And you want them to share the default argument value.</p>
<p>You could simply create a global var... | 1 | 2016-06-26T20:44:26Z | [
"python"
] |
How to pass a default value for argument from one function definition to a higher one | 38,042,985 | <p>I'm searching for a good way to pass default values for arguments to a calling function. Let me explain this by example:</p>
<pre><code>def greet(name, greeting='Hello', punctuation='!'):
return greeting+' '+name+punctuation
def greet_with_hi(name, punctuation='!'):
return greet(name, 'Hi', punctuation)
</c... | 1 | 2016-06-26T20:41:38Z | 38,043,049 | <p>Without modifying your <code>greet</code> function, you can simply remove the argument from the <code>greet_with_hi</code> function and pass nothing for the parameter. That way, the default defined on <code>greet</code> will be used:</p>
<pre><code>def greet_with_hi(name):
return greet(name, 'Hi')
</code></pre>... | 2 | 2016-06-26T20:48:44Z | [
"python"
] |
How to pass a default value for argument from one function definition to a higher one | 38,042,985 | <p>I'm searching for a good way to pass default values for arguments to a calling function. Let me explain this by example:</p>
<pre><code>def greet(name, greeting='Hello', punctuation='!'):
return greeting+' '+name+punctuation
def greet_with_hi(name, punctuation='!'):
return greet(name, 'Hi', punctuation)
</c... | 1 | 2016-06-26T20:41:38Z | 38,043,072 | <p>Why not use <code>None</code>?</p>
<pre><code>def greet(name, greeting='Hello', punctuation='!'):
return greeting+' '+name+punctuation
def greet_with_hi(name, punctuation=None):
if punctuation:
return greet(name, 'Hi', punctuation)
else:
return greet(name, 'Hi')
</code></pre>
<p>Really... | 3 | 2016-06-26T20:52:50Z | [
"python"
] |
matplotlib: How to assign the dpi of your figure to meet some set maximum file size? | 38,042,987 | <p>Just wondering if there is a tried and tested method for setting the dpi output of your figure in matplotlib to be governed by some maximum file size, e.g., 15MB. </p>
| 0 | 2016-06-26T20:41:43Z | 38,043,037 | <p>There can not be such a mechanism, because the file size can only be determined by actually rendering the finished drawing to a file, and that must happen after setting up the figure (where you set the DPI). </p>
<p>How, for example, should anyone know, before rendering your curve, how well it's compressible as PNG... | 0 | 2016-06-26T20:47:31Z | [
"python",
"image",
"matplotlib",
"save"
] |
Verify signature on X509 certificate in Python | 38,043,056 | <p>I have an RSA public key and a signed X509 certificate. How can I check that the key signed the certificate? (My example happens to be a self-signed certificate.)</p>
<p>Here's what I'm doing now:</p>
<p>Generate self-signed cert and convert to DER encoding with openssl cli:</p>
<p>(I'm expecting DER in my real a... | 1 | 2016-06-26T20:49:09Z | 38,043,541 | <p>I guess one way to accomplish this is to create an <code>X509StoreContext</code> containing only one certificate corresponding to the public key I want to check for.</p>
<pre><code>>>> from OpenSSL import crypto
>>> x509_self_signed # already loaded
<OpenSSL.crypto.X509 object at 0x7fcc4049c9b0... | 0 | 2016-06-26T21:52:35Z | [
"python",
"ssl",
"x509",
"pycrypto",
"pyopenssl"
] |
Python webdriver connect to already webpage (selenium) | 38,043,076 | <p>I need to open multiple links in separate tabs or sessions...
I already know how to do it, so what i would like to know is if it's possible to connect to an already open webpage instead of open every links every time i run the script.
What i used now in Python is:</p>
<pre><code>from selenium import webdriver
driv... | 0 | 2016-06-26T20:53:29Z | 38,043,267 | <p>Connecting to the previously opened window is easy:</p>
<pre><code>driver = webdriver.Firefox()
url = driver.command_executor._url
session_id = driver.session_id
driver2 = webdriver.Remote(command_executor=url,desired_capabilities={})
driver2.session_id = session_id
#You're all set to do whatever with the previ... | 0 | 2016-06-26T21:17:24Z | [
"python",
"selenium",
"web",
"selenium-webdriver"
] |
Replace a column in a numpy matrix | 38,043,140 | <p>I'm trying to inter-change columns from 2 matrices, but my assignment seems to not be doing it.</p>
<pre><code>crom1 = crossover_list[0][0][:,j]
print('c1', crom1)
crom2 = crossover_list[1][0][:,j]
print('c2', crom2)
crossover_list[0][0][:,j] = crom2
print(crossover_list[1][0][:,j])
crossover_list[1][0][:,j] = cr... | 1 | 2016-06-26T21:01:04Z | 38,044,298 | <pre><code>aux = numpy.copy(crossover_list[0][0][:,j])
crossover_list[0][0][:,j] = crossover_list[1][0][:,j]
crossover_list[1][0][:,j] = aux
</code></pre>
<p>Seems to work like this (based on <a href="http://stackoverflow.com/questions/4857927/swapping-columns-in-a-numpy-array">Swapping columns in a numpy array?</a> )... | 1 | 2016-06-27T00:04:36Z | [
"python",
"numpy",
"matrix",
"variable-assignment"
] |
How to correctly use kivy graphics context instruction | 38,043,155 | <p>Hi I recently tried my hands on kivy graphics, context instructions(rotate, ranslate etc). So i tried to implement an animated spinning wheel(used for example to show loading screen). I used garden.iconfonts package for this purpose following closely the example implemented in the package. Heres my code</p>
<pre><c... | 0 | 2016-06-26T21:02:50Z | 38,043,872 | <pre><code>canvas:
PushMatrix
Rotate:
angle: -self.p
origin: self.center
axis: 0,0,1
PopMatrix
</code></pre>
<p>Everything between <code>Rotate</code> and <code>PopMatrix</code> will be rotated - that's the point of PushMatrix and PopMatrix, they bound the region where any matrix trans... | 1 | 2016-06-26T22:43:48Z | [
"python",
"kivy"
] |
Vertices coordinates in graph-tool | 38,043,209 | <p>I'd like to specify the coordinates of the vertices of a graph in graph-tool in an efficient way.</p>
<p>Given a csv which looks like:</p>
<pre><code>Node,X,Y
1,2.5,3.8
2,3.4,2.9
</code></pre>
<p>...</p>
<p>I'd like graph-tool to plot vertex 1 at position (2.5,3.8) etc...</p>
<p>A non efficient solution is gi... | 1 | 2016-06-26T21:08:58Z | 38,043,500 | <p>I would try this:</p>
<pre><code>pos = coordinates[['X','Y']].values
</code></pre>
<p>if <code>graph-tool</code> accepts numpy arrays, otherwise:</p>
<pre><code>pos = [tuple(t) for t in coordinates[['X','Y']].values]
</code></pre>
| 0 | 2016-06-26T21:47:23Z | [
"python",
"performance",
"pandas",
"graph",
"graph-tool"
] |
Vertices coordinates in graph-tool | 38,043,209 | <p>I'd like to specify the coordinates of the vertices of a graph in graph-tool in an efficient way.</p>
<p>Given a csv which looks like:</p>
<pre><code>Node,X,Y
1,2.5,3.8
2,3.4,2.9
</code></pre>
<p>...</p>
<p>I'd like graph-tool to plot vertex 1 at position (2.5,3.8) etc...</p>
<p>A non efficient solution is gi... | 1 | 2016-06-26T21:08:58Z | 38,066,290 | <p>I found an answer to my question, an efficient way to do this is to use the .set_2d_array() function;</p>
<pre><code>pos.set_2d_array(coordinates[['X','Y']].values.T)
</code></pre>
<p>does the trick.
Here ".T" is the transposition function, part of the numpy library.</p>
| 0 | 2016-06-28T02:51:45Z | [
"python",
"performance",
"pandas",
"graph",
"graph-tool"
] |
Issue with buildozer packaging a kivy app | 38,043,274 | <p>I'm trying to package my kivy app and I'm having problems with buildozer. Some weeks ago it worked in a right way but today I got this error: </p>
<pre><code>Traceback (most recent call last):
File "build.py", line 517, in <module>
make_package(args)
File "build.py", line 365, in make_package
subp... | 0 | 2016-06-26T21:18:32Z | 38,069,464 | <p>Well, after looking for the answer in some forums I have achieved the correct way to fix the issue. In the <code>buildozer.spec</code>file I changed the sdk version to the last version avaible:</p>
<p><code># (int) Android SDK version to use
android.sdk = 24</code></p>
<p>After that I executed buildozer and tried... | 0 | 2016-06-28T07:15:35Z | [
"android",
"python",
"android-ndk",
"kivy",
"buildozer"
] |
Python2.7 Read a file and use it for if in | 38,043,326 | <p>So what I'm trying to do is use the below code to read a .txt file, and then use that in a if in statement. window is event.WindowName from pyHook.</p>
<pre><code>try:
with open("log.txt") as f:
data = f.read().split()
except:
print "Failed.1"
try:
if data in window:
#do stuff
</code></p... | -1 | 2016-06-26T21:24:42Z | 38,043,427 | <p>Firstly, when you do</p>
<pre><code> data = f.read().split()
</code></pre>
<p>you get list of lines. So if you need list - use <code>split()</code>. But If you try to just read file content use</p>
<pre><code>with open('log.txt') as f:
for line in f:
print(line)
</code></pre>
<p>Secondly, don't us... | 0 | 2016-06-26T21:37:16Z | [
"python",
"if-statement",
"membership"
] |
Key bindings for interrupt execution in Python Sublime REPL | 38,043,336 | <p>I'm using REPL extension for Sublime text 3 for my python projects. Currently when I want to interrupt a running script I have to close to close the REPL window to stop execution and all computations are so far are lost.
I was wondering if anybody knows how to interrupt an execution and have a short cut or key bind... | 1 | 2016-06-26T21:25:34Z | 38,045,139 | <p>On OS X and Linux, the key binding <kbd>Ctrl</kbd><kbd>Shift</kbd><kbd>C</kbd> executes the <code>subprocess_repl_send_signal</code> command with signal 2 (SIGINT), the equivalent of <code>KeyboardInterrupt</code> in Python.</p>
<p>For some reason, though, SublimeREPL's Windows keymap doesn't include this command, ... | 0 | 2016-06-27T02:36:34Z | [
"python",
"sublimetext3",
"sublimerepl"
] |
Python : Add url to menu in appindicator | 38,043,371 | <p>I'm trying to make a little application with appindicator and Gtk. My goal is to display a list of server with link to url of them.</p>
<p>Here is what I try :</p>
<pre><code>from gi.repository import Gtk as gtk
from gi.repository import AppIndicator3 as appindicator
def main():
indicator = appindicator.Indic... | 0 | 2016-06-26T21:29:21Z | 38,053,644 | <p>I've found a way to do that. I'm not sure it's the best way, but it works.</p>
<p>Instead of create a LinkItem, I've made a function for open url:</p>
<pre><code>def open_url(source):
webbrowser.open("http://url/host/id")
</code></pre>
<p>And I call it after, with <code>connect</code> :</p>
<pre><code>item.c... | 0 | 2016-06-27T12:10:24Z | [
"python",
"gtk",
"appindicator"
] |
Python appending not working as expected | 38,043,400 | <pre><code>x_list = [0, 0]
y_list = [0, 1]
def coordinates(condition_x, condition_y):
zipped = zip(x_list, y_list)
condition_coord = condition_x,condition_y
for a,b in zipped:
print a,b
coord = a,b
if condition_coord != coord:
x_list.append(condition_x)
y_list... | 1 | 2016-06-26T21:33:35Z | 38,043,454 | <p>You're code can't work, since you do the check-and-add <em>for every couple</em>. So if you have N coordinates, you'll add the new coordinate N times, or N-1 if it's already present. You have to do something like this:</p>
<pre><code>def coordinates(condition_x, condition_y):
zipped = zip(x_list, y_list)
co... | 1 | 2016-06-26T21:41:36Z | [
"python",
"python-2.7"
] |
Python appending not working as expected | 38,043,400 | <pre><code>x_list = [0, 0]
y_list = [0, 1]
def coordinates(condition_x, condition_y):
zipped = zip(x_list, y_list)
condition_coord = condition_x,condition_y
for a,b in zipped:
print a,b
coord = a,b
if condition_coord != coord:
x_list.append(condition_x)
y_list... | 1 | 2016-06-26T21:33:35Z | 38,043,456 | <p>Your code shall be modified to update coordinates after performing <code>for</code> loop over zipped <code>x_list, y_list</code>, below is modified for loop with comments:</p>
<pre><code>match = False
for a,b in zipped:
print a,b
coord = a,b
if condition_coord == coord: # coord matched
... | 0 | 2016-06-26T21:41:55Z | [
"python",
"python-2.7"
] |
Python appending not working as expected | 38,043,400 | <pre><code>x_list = [0, 0]
y_list = [0, 1]
def coordinates(condition_x, condition_y):
zipped = zip(x_list, y_list)
condition_coord = condition_x,condition_y
for a,b in zipped:
print a,b
coord = a,b
if condition_coord != coord:
x_list.append(condition_x)
y_list... | 1 | 2016-06-26T21:33:35Z | 38,043,485 | <p>You should use a better test condition. As is, your condition adds a new coordinate when at least one test passes, instead, it should add when all the coordinates pass the test. You should use <code>all</code>:</p>
<pre><code>x_list = [0, 0]
y_list = [0, 1]
def coordinates(condition_x, condition_y):
zipped = z... | 0 | 2016-06-26T21:45:11Z | [
"python",
"python-2.7"
] |
Python appending not working as expected | 38,043,400 | <pre><code>x_list = [0, 0]
y_list = [0, 1]
def coordinates(condition_x, condition_y):
zipped = zip(x_list, y_list)
condition_coord = condition_x,condition_y
for a,b in zipped:
print a,b
coord = a,b
if condition_coord != coord:
x_list.append(condition_x)
y_list... | 1 | 2016-06-26T21:33:35Z | 38,043,490 | <p>The problem is that you are just checking if <em>one</em> coordinate does not match your <code>condition coord</code>. You could still search through but a better way is to harness Python's <code>in</code>:</p>
<pre><code>x_list = [0, 0]
y_list = [0, 1]
def coordinates(condition_x, condition_y):
if (condition_... | 1 | 2016-06-26T21:45:47Z | [
"python",
"python-2.7"
] |
Time complexity of python string index access? | 38,043,461 | <p>If I'm not mistaken, a Python string is stored in unicode scalars. However, unicode scalars can combine to form other grapheme clusters. Therefore, using memory displacement <code>start + scalarSize * n</code> for <code>string[n]</code> isn't the answer you're looking for.</p>
<p>Does this mean that Python iterates... | 2 | 2016-06-26T21:42:28Z | 38,043,477 | <p>Python string indexing does not consider grapheme clusters. It works by Unicode code points. I don't think Python actually has anything built-in for working with grapheme clusters.</p>
<p>String indexing takes constant time, but if you want to retrieve the nth grapheme cluster, string indexing won't do that for you... | 2 | 2016-06-26T21:44:10Z | [
"python",
"string",
"python-3.x"
] |
Generate pivot data in Python | 38,043,535 | <p>Suppose I have 100 files, and loop through all of them. In each file, there are records of several attributes: (the total number of attributes are not known before reading all the files)</p>
<p>Assume a simple case that after reading all the files, we obtain 20 different attributes and the following information:</p... | 1 | 2016-06-26T21:51:51Z | 38,043,605 | <p>While reading files; for each attribute you read, check a map to see whether keys includes the attribute. If not, add it, then add the file name that you have read that attribute from to values of that key and if the attribute is already a key of the map, then just add the filename as a value. </p>
| 0 | 2016-06-26T22:01:09Z | [
"python",
"pandas",
"dataframe",
"pivot-table"
] |
Generate pivot data in Python | 38,043,535 | <p>Suppose I have 100 files, and loop through all of them. In each file, there are records of several attributes: (the total number of attributes are not known before reading all the files)</p>
<p>Assume a simple case that after reading all the files, we obtain 20 different attributes and the following information:</p... | 1 | 2016-06-26T21:51:51Z | 38,043,669 | <p><strong>UPDATE2:</strong> <em>How can I generate the "reverse" statistics table</em></p>
<pre><code>In [9]: df
Out[9]:
file attr
0 File_001 a1
1 File_001 a3
2 File_001 a5
3 File_001 a2
4 File_002 a1
5 File_002 a3
6 File_003 a4
7 File_004 a4
8 File_004 a2
9 File_004 a6... | 4 | 2016-06-26T22:10:37Z | [
"python",
"pandas",
"dataframe",
"pivot-table"
] |
How to install pyzipcode? | 38,043,593 | <p>(1) I need to install pyzipcode. But whenever I execute command
<code>conda install pyzipcode</code> it gives </p>
<blockquote>
<p>Syntax Error: Missing parenthesis in call to 'print'.</p>
</blockquote>
<p>I am using Python3. I downloaded file from <a href="http://pypi.python.org/pypi/pyzipcod" rel="nofollow">h... | 0 | 2016-06-26T18:53:58Z | 38,043,594 | <p>The error <code>Missing parenthesis in call to 'print'.</code> indicates you are using a python 2.x installation in python 3. Try uninstalling the current Sphinx and re-installing from
<a href="http://www.sphinx-doc.org/en/stable/install.html" rel="nofollow">http://www.sphinx-doc.org/en/stable/install.html</a></p>
... | 0 | 2016-06-26T19:10:06Z | [
"python",
"anaconda",
"sqlite"
] |
Assign date to Dataframe column | 38,043,629 | <p>Trying to assign a date to a column in a DataFrame.</p>
<p>Assigning in the following way gives an error</p>
<pre><code>for date in sorted(list(set(dates))):
df.loc[:, 'DATE'] = date
Error Cannot set a frame with no defined index and a scalar
</code></pre>
<p>Okay, fine:</p>
<pre><code>for date in sorted(li... | 0 | 2016-06-26T22:03:34Z | 38,043,786 | <p>if you are sure that <code>len(sorted(list(set(dates)))) == len(df)</code> then you can simply do:</p>
<pre><code>df['DATE'] = sorted(list(set(dates)))
</code></pre>
| 0 | 2016-06-26T22:26:53Z | [
"python",
"pandas",
"dataframe",
"warnings"
] |
Arduino to PC Bluetooth Communication | 38,043,634 | <p>I am using PIR motion sensor with Arduino Bluno (with Bluetooth module). I want to send the the values of motion detected by the sensor from arduino to PC via Bluetooth.</p>
<p>How may i get that on my PC? It can be of C++,C# or even Python.
Shall be thankfull if anyone can help.</p>
<p>Here's my arduino code:</p>... | 0 | 2016-06-26T22:04:15Z | 38,062,443 | <p>Unless you specifically want the pc to directly receive, you could use another arduino to receive an print to the serial monitor. You could then have a program collect and save what came into the serial monitor. Just a suggestion. It may be easier in the end. Good luck whatever you choose to do.</p>
| 0 | 2016-06-27T20:12:28Z | [
"c#",
"android",
"python",
"c++",
"bluetooth"
] |
python string encoding unicode | 38,043,658 | <p>I'm using python 2.7 and I have some problems converting chars like "ä" to "ae".</p>
<p>I'm retrieving the content of a webpage using:</p>
<pre><code>req = urllib2.Request(url + str(questionID))
response = urllib2.urlopen(req)
data = response.read()
</code></pre>
<p>After that I'm doing some extraction stuff and... | 0 | 2016-06-26T22:08:24Z | 38,044,026 | <p>Use <code>.decode("latin-1")</code> instead. That is what you are trying to decode.</p>
| -1 | 2016-06-26T23:11:17Z | [
"python",
"unicode",
"encoding"
] |
Use regex or something else to capture website data | 38,043,667 | <p>I'm trying to use python and regex to pull the price in the example website below but am not getting any results. </p>
<p>How can I best capture the price (I don't care about the cents, just the dollar amount)?</p>
<p><a href="http://www.walmart.com/store/2516/search?dept=4044&dept_name=Home&query=43888060... | 0 | 2016-06-26T22:10:22Z | 38,043,716 | <p>With regexp it can be a bit tricky on how accurate your pattern should be.
I quickly typed something togehter here: <a href="https://regex101.com/r/lF5vF2/1" rel="nofollow">https://regex101.com/r/lF5vF2/1</a></p>
<p>You should get the idea and modify this one to fit your actual needs.</p>
<p>Kind regards</p>
| 0 | 2016-06-26T22:17:06Z | [
"python",
"html",
"regex",
"web-scraping"
] |
Use regex or something else to capture website data | 38,043,667 | <p>I'm trying to use python and regex to pull the price in the example website below but am not getting any results. </p>
<p>How can I best capture the price (I don't care about the cents, just the dollar amount)?</p>
<p><a href="http://www.walmart.com/store/2516/search?dept=4044&dept_name=Home&query=43888060... | 0 | 2016-06-26T22:10:22Z | 38,043,759 | <p>Don't use regex use a html parser like <a href="https://www.crummy.com/software/BeautifulSoup/bs4/doc/" rel="nofollow">bs4</a>:</p>
<pre><code>from bs4 import BeautifulSoup
h = """<div class="price-display csTile-price">
<span class="sup">$</span>
299
<span class="currency-... | 0 | 2016-06-26T22:23:24Z | [
"python",
"html",
"regex",
"web-scraping"
] |
Use regex or something else to capture website data | 38,043,667 | <p>I'm trying to use python and regex to pull the price in the example website below but am not getting any results. </p>
<p>How can I best capture the price (I don't care about the cents, just the dollar amount)?</p>
<p><a href="http://www.walmart.com/store/2516/search?dept=4044&dept_name=Home&query=43888060... | 0 | 2016-06-26T22:10:22Z | 38,043,828 | <p>Ok, just search for numerics (I added $ and .) and concat the results into a string (I used "".join()).</p>
<pre><code>>>> txt = """
<div class="price-display csTile-price">
<span class="sup">$</span>
299
<span class="currency-delimiter">.</s... | -1 | 2016-06-26T22:36:43Z | [
"python",
"html",
"regex",
"web-scraping"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.