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 listlengths 1 5 |
|---|---|---|---|---|---|---|---|---|---|
Detect pupil in iris recognition python | 38,355,049 | <p>I have the problem when i use the Hough Transform. I want detect the only pupil in iris image of test. The code is the following:</p>
<p><code></p>
<pre><code>import cv2
from cv2 import cv
import numpy as np
import os
directory = os.listdir("/home/joker26/Scrivania/casia/test")
numero_file = len(directory)
for fi... | -3 | 2016-07-13T14:50:57Z | 38,361,340 | <p>What is the point of detecting the pupil instead of the iris? They are both a part of the eye. However your error lies within your testing data. </p>
<p>You are using testing data that, I assume, are thousands of photos of peoples eyes. Now your computer will learn to recognize what is in these photos and if your t... | 0 | 2016-07-13T20:43:06Z | [
"python",
"opencv",
"iris-recognition"
] |
Python GUI and animation | 38,355,090 | <p>I am creating a GUI to plot live graphs from temperature sensors using tkinter, and animation function from matplotlib. I am getting beautiful live graphs. But the problem I am facing is that the live graphs start as soon as I run the application. I have created a button to call a command in <strong>class StartPage<... | 0 | 2016-07-13T14:52:07Z | 38,355,596 | <p>Ok, dirty hack:</p>
<pre><code>global do_animate
do_animate = False
</code></pre>
<p>change your command as follows:</p>
<pre><code>#creating button
#if agree then move to temperature graph
button1 = ttk.Button(self, text="Start Monitoring",
command=lambda: do_animate=True) # with lambda we ... | 0 | 2016-07-13T15:13:32Z | [
"python",
"user-interface",
"animation",
"matplotlib",
"tkinter"
] |
Python GUI and animation | 38,355,090 | <p>I am creating a GUI to plot live graphs from temperature sensors using tkinter, and animation function from matplotlib. I am getting beautiful live graphs. But the problem I am facing is that the live graphs start as soon as I run the application. I have created a button to call a command in <strong>class StartPage<... | 0 | 2016-07-13T14:52:07Z | 38,368,512 | <p>Similar to Jean-François Fabre's solution, this is not gonna stop your animate() from running, but it is gonna stop it from doing anything.</p>
<pre><code>def animate(i):
global draw
if draw:
""" here goes all you want your animate func to do """
draw = False
</code></pre>
<p>So by adding what you ... | 0 | 2016-07-14T07:53:34Z | [
"python",
"user-interface",
"animation",
"matplotlib",
"tkinter"
] |
Python GUI and animation | 38,355,090 | <p>I am creating a GUI to plot live graphs from temperature sensors using tkinter, and animation function from matplotlib. I am getting beautiful live graphs. But the problem I am facing is that the live graphs start as soon as I run the application. I have created a button to call a command in <strong>class StartPage<... | 0 | 2016-07-13T14:52:07Z | 38,374,813 | <p>Just found a way to solve my own problem. I hope it might help someone </p>
<p>before app.mainloop() i created a test function</p>
<pre><code>app.geometry("1280x720")
def test():
ani1 = animation.FuncAnimation(f1,animate1, interval = 1000)
ani2 = animation.FuncAnimation(f2,animate2, interval = 1000)
an... | 0 | 2016-07-14T12:53:51Z | [
"python",
"user-interface",
"animation",
"matplotlib",
"tkinter"
] |
What is the difference between division and exponentiation for a computer? | 38,355,116 | <p>When trying to solve an optimization problem, I was constantly getting:</p>
<pre><code> RuntimeWarning: divide by zero encountered in divide
</code></pre>
<p>Although analitically writing 1/x and x^(-1) are the same thing, re-writing my function by substituting each division as shown solved my problem. </p>
<p>I ... | 0 | 2016-07-13T14:53:11Z | 38,355,369 | <p>In python, ^ operator is XOR operation.
Exponentiation is done using ** operator, which will give ZeroDivision error for 0**-1</p>
| 2 | 2016-07-13T15:03:32Z | [
"python",
"runtime-error",
"division",
"zero",
"exponentiation"
] |
What is the difference between division and exponentiation for a computer? | 38,355,116 | <p>When trying to solve an optimization problem, I was constantly getting:</p>
<pre><code> RuntimeWarning: divide by zero encountered in divide
</code></pre>
<p>Although analitically writing 1/x and x^(-1) are the same thing, re-writing my function by substituting each division as shown solved my problem. </p>
<p>I ... | 0 | 2016-07-13T14:53:11Z | 38,356,325 | <p>This is your problem:</p>
<pre><code>>>> alpha = 1
>>> w = 2
>>> term = alpha/w
>>> term
0
>>> term = alpha * w **(-1)
>>> term
0.5
>>>
>>> term = float(alpha)/w
>>> term
0.5
</code></pre>
<p>In the first example, you are doing inte... | 1 | 2016-07-13T15:48:10Z | [
"python",
"runtime-error",
"division",
"zero",
"exponentiation"
] |
initial centroids for scikit-learn kmeans clustering | 38,355,153 | <p>if I already have a numpy array that can serve as the initial centroids, how can I properly initialize the kmeans algorithm? I am using the scikit-learn Kmeans class</p>
<p>this post (<a href="http://stackoverflow.com/questions/28862334/k-means-with-selected-initial-centers">k-means with selected initial centers</a... | 0 | 2016-07-13T14:54:33Z | 38,355,273 | <p>Yes, setting initial centroids via <code>init</code> should work. Here's a quote from scikit-learn <a href="http://scikit-learn.org/stable/modules/generated/sklearn.cluster.KMeans.html" rel="nofollow">documentation</a>:</p>
<pre><code> init : {âk-means++â, ârandomâ or an ndarray}
Method for initializa... | 1 | 2016-07-13T14:59:32Z | [
"python",
"scikit-learn",
"k-means"
] |
How to overload modules when using python-asyncio? | 38,355,189 | <p>I'm using <code>pyinotify</code> to track file changes and try to overload the module where this modified file.
But unfortunately, not the module probably is not overloaded, the changes that I am not visible.</p>
<pre><code>import sys
import asyncio
import pyinotify
import importlib
from aiohttp import web
from aa.... | 4 | 2016-07-13T14:55:57Z | 38,368,684 | <p>You could try <a href="https://pypi.python.org/pypi/aiohttp_autoreload/0.0.1" rel="nofollow">aiohttp_autoreload</a></p>
<p><a href="https://github.com/sloria/aiohttp_utils" rel="nofollow">aiohttp_utils</a> also provides autoreload facility.</p>
| 2 | 2016-07-14T08:02:56Z | [
"python",
"python-3.x",
"python-asyncio",
"aiohttp",
"pyinotify"
] |
Is it possible to reset a DataFrame index by name, instead of level? | 38,355,261 | <p>Is it possible to remove an index by name? I am removing and adding lots of indexes in multiple places throughout and I can see it getting quite confusing if I have to keep track of each level at all times.</p>
<p>I am creating a MultiIndex like so:</p>
<pre><code>df = cass_df.groupby(['hash', 'campaign_id'])[['ac... | 0 | 2016-07-13T14:58:59Z | 38,355,824 | <p>Yes. You can also add <code>inplace=True</code>. You can also remove double <code>[]</code> in aggaregate <code>groupby</code>:</p>
<pre><code>df = pd.DataFrame({'A':[2,2,3],
'B':[1,1,6],
'C':[7,8,9],
'D':[1,3,5],
'E':[5,3,6],
... | 1 | 2016-07-13T15:24:44Z | [
"python",
"pandas"
] |
TensorFlow: storing distortions in graph definition | 38,355,306 | <p>Below I have some code that I use to deploy trained TensorFlow models. It basically just loads the model from a .pb file, gets the first and last layer of the model and evaluates an image. This works well, but I want to deploy many models with different image dimensions and distortions such as blurring, whitening an... | 0 | 2016-07-13T15:00:42Z | 38,356,869 | <p>The answer depends on how the original <code>graph.pb</code> was generated.</p>
<p>If you have modify the script that produced the original <code>graph.pb</code>, you can simply add your reshaping, distortions etc. operations to that script and regenerate the <code>graph.pb</code>. Note that you have to remove the ... | 0 | 2016-07-13T16:15:26Z | [
"python",
"machine-learning",
"tensorflow"
] |
flask, pymongo, forms - loading pymongo data into a form for editing | 38,355,463 | <p><em>What I am trying to achieve:</em></p>
<p>I am trying to build a very simple admin interface from scratch that stores text fields and images in a mongodb. The user can then login and make small changes to the content of the site. </p>
<p><em>My issue and where I think I am confused:</em></p>
<p>Is it possible ... | 0 | 2016-07-13T15:07:56Z | 38,355,995 | <p>This is actually really simple. If you look at the HTML docs for forms then you'll find you can do something like:</p>
<pre><code> <input type="text" name="firstname" value="Mickey"><br>
</code></pre>
<p>And "Mickey" will show up in the form for you. So, with flask all you need to do is declare vari... | 0 | 2016-07-13T15:32:16Z | [
"python",
"flask",
"pymongo",
"wtforms",
"flask-wtforms"
] |
Limiting execution time of a function call in Python kills my Kernel | 38,355,482 | <p>I need to apply a function several times on different inputs. Sometimes the function takes hours to run. I do not want it to last more than 10 seconds. I found the method on a previous post (<a href="http://stackoverflow.com/questions/366682/how-to-limit-execution-time-of-a-function-call-in-python">How to limit exec... | 0 | 2016-07-13T15:08:21Z | 38,355,592 | <p>You're creating 10 signals with <code>SIGALRM</code> handler, meaning you now have 10 exceptions going on at the same time. You may want to instead try:</p>
<pre><code>signal.signal(signal.SIGALRM, signal_handler)
signal.alarm(10) # Ten seconds
for i in range(10):
try:
time.sleep(0.2) # The function... | 1 | 2016-07-13T15:13:21Z | [
"python",
"signals",
"spyder"
] |
Timeseries as 2 numpy arrays ('Date' and 'Data') and then extracting 'Data' from a specified 'Date' range? | 38,355,517 | <p>I would like to ask what the best 'Date' datatype is to use for the following problem:</p>
<p>I am reading timeseries data from an ASCII file and creating two numpy arrays; 1) <code>date</code>, 2) <code>data</code>. Once created, I would like to extract <code>data</code> from a date range specified from a differen... | 1 | 2016-07-13T15:09:49Z | 38,356,006 | <p>I would use pandas for this. there is really good support for time series stuff, <a href="http://pandas.pydata.org/pandas-docs/stable/timeseries.html" rel="nofollow">see the docs</a>. You would probably want to use a time series index for more detailed work, here I am using it as a normal column.</p>
<p>Note, your ... | 1 | 2016-07-13T15:32:41Z | [
"python",
"arrays",
"datetime",
"numpy",
"time-series"
] |
passing each element of a list as an argument to a function | 38,355,636 | <p>I have a list </p>
<pre><code>try_list = ["[('aaaa', 34), ('bbbb', 1), ('cccc', 1)]", "[('dddd', 4), ('eeee', 1)]"]
</code></pre>
<p>Each entry within "" is an element of a list.</p>
<p>When I say </p>
<pre><code>for i in try_list:
print i
</code></pre>
<p>I get the individual elements,</p>
<pre><code>[('... | -3 | 2016-07-13T15:15:15Z | 38,355,757 | <p>Quite (un)fortunately, the return value of <code>__repr__</code> for the list <code>[('aaaa', 34)]</code> is the same as the string <code>"[('aaaa', 34)]"</code>. </p>
<p>That's why you have <code>print</code> outputting something that looks like a list. But what you have is not a list of lists but a list of string... | 2 | 2016-07-13T15:21:11Z | [
"python"
] |
segmentation fault when saving pandas dataframe to disk with to_hdf | 38,355,647 | <p>I am trying to save a dataframe to disk using hdf5 format.
Even this simple piece of code gives me "Segmentation fault (core dumped)"</p>
<pre><code>import pandas as pd
import tables
df=pd.DataFrame([0,1,2,3],index=['a','b','c','d'])
df.to_hdf('test.h5','test',mode='w',format='table')
</code></pre>
<p>The probl... | 2 | 2016-07-13T15:15:38Z | 38,374,657 | <p>Use a newer version of PyTables. Version 3.2.3.1 does the job perfectly.</p>
| 3 | 2016-07-14T12:47:43Z | [
"python",
"pandas"
] |
Batch replace strings in files with Python | 38,355,701 | <p>So I'm trying to create a Python script that will look through <code>*.styles</code> and <code>*.layout</code> files and replace specific strings in those files. I've tried a number of things, but I can't figure out what I should be doing, and even looking at other code samples online just makes it even more confusi... | 0 | 2016-07-13T15:17:52Z | 38,355,815 | <p><code>open</code> opens a single file; you seem to be trying to use it to open a collection of files that match a pattern. Perhaps you want to look at <code>os.walk</code> to traverse a directory of files, so you can individually process each.</p>
| 1 | 2016-07-13T15:24:12Z | [
"python",
"file",
"file-io",
"helpers"
] |
Batch replace strings in files with Python | 38,355,701 | <p>So I'm trying to create a Python script that will look through <code>*.styles</code> and <code>*.layout</code> files and replace specific strings in those files. I've tried a number of things, but I can't figure out what I should be doing, and even looking at other code samples online just makes it even more confusi... | 0 | 2016-07-13T15:17:52Z | 38,355,971 | <p>As Scott Hunter wrote, <code>open</code> opens a single file. You need to get a list of matching files, and call <code>open</code> separately for each of them, in a loop. Here is how to do it.</p>
<p>Create a function which processes a single file:</p>
<pre><code>def process_file(filename):
print(filename)
# .... | 2 | 2016-07-13T15:31:10Z | [
"python",
"file",
"file-io",
"helpers"
] |
Batch replace strings in files with Python | 38,355,701 | <p>So I'm trying to create a Python script that will look through <code>*.styles</code> and <code>*.layout</code> files and replace specific strings in those files. I've tried a number of things, but I can't figure out what I should be doing, and even looking at other code samples online just makes it even more confusi... | 0 | 2016-07-13T15:17:52Z | 38,356,096 | <p>I'm sorry I can't comment yet, but I had to do something like that.
I managed with <code>fileinput.input</code> something like :
First i would iterate on the files and then modify them :</p>
<pre><code>for current_path, dirs, files in os.walk(Your_Path_With_Files)):
for file in files:
i... | 0 | 2016-07-13T15:37:05Z | [
"python",
"file",
"file-io",
"helpers"
] |
Bash: How to give executable permission to all the python scripts in unix? | 38,355,791 | <p>Suppose I have a python script called <strong>a.py</strong> like this:</p>
<pre><code>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Author : Bhishan Poudel
# Date : Jul 13, 2016
# Imports
# Script
print("hello")
</code></pre>
<p>I can run this scripts in two ways:<br>
<strong>Using python interprete... | 1 | 2016-07-13T15:23:28Z | 38,355,855 | <p><strong>The hard way</strong></p>
<p>Run below with root privilege:</p>
<pre><code>find /your/path/ -type f -name "*.py" -exec chmod u+x {} \;
</code></pre>
<p><strong>Note:</strong></p>
<p><code>chmod</code> need not be run as root if you're the owner of <code>.py</code> file.</p>
<p><strong>The smart way</str... | 3 | 2016-07-13T15:25:39Z | [
"python",
"bash",
"path",
"executable",
"chmod"
] |
Bash: How to give executable permission to all the python scripts in unix? | 38,355,791 | <p>Suppose I have a python script called <strong>a.py</strong> like this:</p>
<pre><code>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Author : Bhishan Poudel
# Date : Jul 13, 2016
# Imports
# Script
print("hello")
</code></pre>
<p>I can run this scripts in two ways:<br>
<strong>Using python interprete... | 1 | 2016-07-13T15:23:28Z | 38,356,135 | <p>Using the idea of @sjsam,
I did following:</p>
<p>Suppose I have a file hello.py in any location. </p>
<pre><code>cd to that location
find $PWD -type f -name "*.py" -exec chmod u+x {} \;
./hello.py
# Now, i can create any number of .py files in that folder and run ./filename
# Note: if we are running as user per... | 1 | 2016-07-13T15:39:17Z | [
"python",
"bash",
"path",
"executable",
"chmod"
] |
Pandas : how to get the unique number of values in cells when cells contain lists? | 38,355,931 | <p>For some mysterious reason I have a dataframe that looks like</p>
<pre><code>index col_weird col_normal
2012-01-01 14:30 ['A','B'] 2
2012-01-01 14:32 ['A','C','D'] 4
2012-01-01 14:36 ['C','D'] 2
2012-01-01 14:39 ['E','B'] 4
2012-01-01 14:40 ['G','H'] 2
</code></pre>
<p>I ... | 1 | 2016-07-13T15:29:19Z | 38,356,221 | <p>I think you can expand <code>list</code> to <code>Series</code> first:</p>
<pre><code>df = df['col'].apply(pd.Series).stack().reset_index(drop=True, level=1)
print (df)
2012-01-01 14:30 A
2012-01-01 14:30 B
2012-01-01 14:32 A
2012-01-01 14:32 C
2012-01-01 14:32 D
2012-01-01 14:36 C
2012-01-01 14:3... | 2 | 2016-07-13T15:42:50Z | [
"python",
"pandas"
] |
Pandas : how to get the unique number of values in cells when cells contain lists? | 38,355,931 | <p>For some mysterious reason I have a dataframe that looks like</p>
<pre><code>index col_weird col_normal
2012-01-01 14:30 ['A','B'] 2
2012-01-01 14:32 ['A','C','D'] 4
2012-01-01 14:36 ['C','D'] 2
2012-01-01 14:39 ['E','B'] 4
2012-01-01 14:40 ['G','H'] 2
</code></pre>
<p>I ... | 1 | 2016-07-13T15:29:19Z | 38,356,304 | <p>Group by <code>pd.TimeGrouper('5Min')</code> then apply an obnoxious function.</p>
<pre><code>df.groupby(pd.TimeGrouper('5Min')).col.apply(lambda x: x.apply(pd.Series).stack().unique().shape[0])
index
2012-01-01 14:30:00 4
2012-01-01 14:35:00 4
2012-01-01 14:40:00 2
Freq: 5T, Name: col, dtype: int64
</cod... | 1 | 2016-07-13T15:47:05Z | [
"python",
"pandas"
] |
Should I use polymorphism when overloading all the parent class's methods? | 38,356,021 | <p>I am creating a basic OOP program for one of my modules at college. I am making a simple CLI RPG game using python. For a few classes I will be overloading all of the parent class's functions and I'm not sure whether I should be using polymorphism in these cases.</p>
<p>Example:</p>
<pre><code>class character():
... | 0 | 2016-07-13T15:33:26Z | 38,357,524 | <p>Yeah, I don't see why not. Here's an example of the benefits, where I've refactored your code to re-use (look up 'Python DRY') some common code between Player and Character, just for attacked. It looks as if it's a lot more code, but what it allows you to do is to focus on differences and commonalities between Pla... | 0 | 2016-07-13T16:51:41Z | [
"python",
"python-2.7",
"oop",
"polymorphism"
] |
Django model is not iterable in template | 38,356,031 | <p>I am trying to iterate through a model to get first image in the list and it is giving me error that model is not iterable. Following is my code for the model and template. I just need to get the first image in list associated with single product. </p>
<p>models.py:</p>
<pre><code>class Product(models.Model):
... | 3 | 2016-07-13T15:34:11Z | 38,356,059 | <p>You use <code>all</code> to get <em>all</em> the related product images and iterate through them:</p>
<pre><code>{% for img in object.productimage_set.all %}
</code></pre>
<p>But if you get a single object, like when you get the first related product image then you can't iterate:</p>
<pre><code>{{ object.producti... | 3 | 2016-07-13T15:35:25Z | [
"python",
"django",
"django-templates"
] |
Django model is not iterable in template | 38,356,031 | <p>I am trying to iterate through a model to get first image in the list and it is giving me error that model is not iterable. Following is my code for the model and template. I just need to get the first image in list associated with single product. </p>
<p>models.py:</p>
<pre><code>class Product(models.Model):
... | 3 | 2016-07-13T15:34:11Z | 38,356,383 | <p>You can use <code>with</code> tag instead of <code>for</code> to avoid error:</p>
<p>Change this:</p>
<pre><code>{% for img in object.productimage_set.first %}
...
{% endfor %}
</code></pre>
<p>to</p>
<pre><code>{% with img=object.productimage_set.first %}
...
{% endwith %}
</code></pre>
| 2 | 2016-07-13T15:51:03Z | [
"python",
"django",
"django-templates"
] |
Tkinter change data | 38,356,048 | <p>i wanna change the data, just switch some pixels to white or black, but i dont get it working that i can change the data ? When i use the line np.roll() it rolls the image and updates it very fast, but when i use any other method of simply changing the values of the data-array, i fail ?</p>
<p>what should i do, wha... | -1 | 2016-07-13T15:34:46Z | 38,356,705 | <p>The thing was to not init the data var randomly at init. This code works with 95 Frames per second</p>
<pre><code>import Tkinter
from PIL import Image, ImageTk
import numpy
import time
times=1
timestart=time.clock()
data = None
photo = None
sw = 1
def image_loop():
global data
global times
... | 2 | 2016-07-13T16:06:56Z | [
"python",
"tkinter"
] |
get the length from last 2 columns in python | 38,356,086 | <p>I am trying to get the inside values only from the given table, I am supposed to write a for loop but I am very new in python and I am stuck. It is not printing the length of th</p>
<pre><code>gi|564120226|gb|AHB72725.1| TMHMM2.0 inside 1 6
gi|564120226|gb|AHB72725.1| TMHMM2.0 TMheli... | -2 | 2016-07-13T15:36:42Z | 38,358,339 | <p>You can use csv:</p>
<pre><code>import csv
with open (fn) as csv_txt:
for row in csv.reader(csv_txt, delimiter='|', skipinitialspace=True):
print row
</code></pre>
<p>Prints:</p>
<pre><code>['gi', '564120226', 'gb', 'AHB72725.1', 'TMHMM2.0 inside 1 6']
['gi', '564120226', 'gb', 'AHB72725.1', 'TMHMM2.0... | 0 | 2016-07-13T17:37:28Z | [
"python",
"python-2.7",
"bioinformatics"
] |
get the length from last 2 columns in python | 38,356,086 | <p>I am trying to get the inside values only from the given table, I am supposed to write a for loop but I am very new in python and I am stuck. It is not printing the length of th</p>
<pre><code>gi|564120226|gb|AHB72725.1| TMHMM2.0 inside 1 6
gi|564120226|gb|AHB72725.1| TMHMM2.0 TMheli... | -2 | 2016-07-13T15:36:42Z | 38,405,761 | <p>difference = 0
for line in lin:</p>
<pre><code>if line.startswith('gi|564120226|gb|AHB72725.1| TMHMM2.0 inside'):
elements = line.split('\t')
last_second, last_one = elements[-2], elements[-1]
last_one= last_one.split()
diff=int(last_one[1])-int(last_one[0])
print "diff", diff
... | -1 | 2016-07-15T22:21:13Z | [
"python",
"python-2.7",
"bioinformatics"
] |
DataFrame: add column whose values are the quantile number/rank of an existing column? | 38,356,156 | <p>I have a DataFrame with some columns. I'd like to add a new column where each row value is the quantile rank of one existing column. </p>
<p>I can use DataFrame.rank to rank a column, but then I don't know how to get the quantile number of this ranked value and to add this quantile number as a new colunm.</p>
<p>E... | 0 | 2016-07-13T15:40:28Z | 38,356,617 | <p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.quantile.html" rel="nofollow">DataFrame.quantile</a> with q=[0.25, 0.5, 0.75] on the existing column to produce a quartile column.</p>
<p>Then, you can <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Da... | 1 | 2016-07-13T16:02:29Z | [
"python",
"pandas"
] |
DataFrame: add column whose values are the quantile number/rank of an existing column? | 38,356,156 | <p>I have a DataFrame with some columns. I'd like to add a new column where each row value is the quantile rank of one existing column. </p>
<p>I can use DataFrame.rank to rank a column, but then I don't know how to get the quantile number of this ranked value and to add this quantile number as a new colunm.</p>
<p>E... | 0 | 2016-07-13T15:40:28Z | 38,977,090 | <p>I <a href="http://stackoverflow.com/questions/28442991/python-pandas-create-new-bin-bucket-variable-with-pd-qcut">discovered</a> it is quite easy:</p>
<pre><code>df['quantile'] = pd.qcut(df['b'], 2, labels=False)
a b quantile
0 1 1 0
1 2 10 0
2 3 100 1
3 4 100 1
</... | 0 | 2016-08-16T14:04:53Z | [
"python",
"pandas"
] |
Why does SciPy return `nan` for a t-test with samples with 0 variance? | 38,356,250 | <p>I am using <a href="http://en.wikipedia.org/wiki/SciPy" rel="nofollow">SciPy</a> in Python and the following return a <code>nan</code> value for whatever reason:</p>
<pre><code>>>>stats.ttest_ind([1, 1], [1, 1])
Ttest_indResult(statistic=nan, pvalue=nan)
>>>stats.ttest_ind([1, 1], [1, 1, 1])
Ttes... | 0 | 2016-07-13T15:44:26Z | 38,357,668 | <p>Division by zero will raise the NaN (= not a number) exception, or return a floating-point representation that, by convention, matches NaN. Be particularly careful of divide-by-N versus divide-by-N-plus-one standard deviation formulae.</p>
| 2 | 2016-07-13T16:59:19Z | [
"python",
"scipy",
null,
"hypothesis-test"
] |
how can I use remove for this code? | 38,356,276 | <pre><code>class student(object):
def student(self):
self.name=input("enter name:")
self.stno=int(input("enter stno:"))
self.score=int(input("enter score:"))
def dis(self):
print("name:",self.name,"stno:",self.stno,"score:",self.score)
def stno(self):
return self.stn... | 0 | 2016-07-13T15:45:28Z | 38,356,363 | <p>just call</p>
<p><code>y.remove(c)</code></p>
<p>when you do <code>c.stno</code> it won't exist in the list because what is actually in the list is the object itself not it's attributes</p>
| 2 | 2016-07-13T15:49:47Z | [
"python",
"python-2.7",
"python-3.x"
] |
how can I use remove for this code? | 38,356,276 | <pre><code>class student(object):
def student(self):
self.name=input("enter name:")
self.stno=int(input("enter stno:"))
self.score=int(input("enter score:"))
def dis(self):
print("name:",self.name,"stno:",self.stno,"score:",self.score)
def stno(self):
return self.stn... | 0 | 2016-07-13T15:45:28Z | 38,356,393 | <p>It's not good to change the array you are iterating. You can try this:</p>
<pre><code>for item in [c for c in y if s.stdno==n]:
y.remove(item)
</code></pre>
| 1 | 2016-07-13T15:51:27Z | [
"python",
"python-2.7",
"python-3.x"
] |
Recursion in dict | 38,356,396 | <p>I have a nested <code>dict</code> which looks like this:</p>
<p><a href="http://i.stack.imgur.com/VnElN.png" rel="nofollow"><img src="http://i.stack.imgur.com/VnElN.png" alt="enter image description here"></a></p>
<p>There are multiple nestings within the key <code>children</code>. I would like to capture the key ... | 2 | 2016-07-13T15:51:35Z | 38,356,704 | <p>You have some unnecessary redundancies. If I understand you correctly, you need to add the handles to the list separately from the recursion, because you want to test <code>branch</code> in the parent.</p>
<pre><code>def GatherConcepts(header):
if 'children' in header and 'branch' in header:
for child i... | 1 | 2016-07-13T16:06:53Z | [
"python",
"dictionary",
"recursion"
] |
Recursion in dict | 38,356,396 | <p>I have a nested <code>dict</code> which looks like this:</p>
<p><a href="http://i.stack.imgur.com/VnElN.png" rel="nofollow"><img src="http://i.stack.imgur.com/VnElN.png" alt="enter image description here"></a></p>
<p>There are multiple nestings within the key <code>children</code>. I would like to capture the key ... | 2 | 2016-07-13T15:51:35Z | 38,356,735 | <p>In order to get recursion correctly, you can use this simple template for it:</p>
<pre><code>def recursive(variable):
if something:
# base step
return somethingelse
else:
# recursive step
return recursive(somethingelse)
</code></pre>
<p>In your case, you can try something li... | 0 | 2016-07-13T16:08:15Z | [
"python",
"dictionary",
"recursion"
] |
Python While-loop Not Working Properly | 38,356,432 | <p>Here is my code:</p>
<pre><code>def pressC():
""" Wait for "c" to be entered from the keyboard in the Python shell """
entry = " "
while(entry != "c"):
entry = raw_input("Press c to continue. ")
print("Thank you. ")
print
def unstuck():
""" This gets the robot unstuck if it becomes ... | -1 | 2016-07-13T15:53:04Z | 38,356,581 | <p>You have your <code>return</code> statement in the wrong place. Try this:</p>
<pre><code># This gets the robot unstuck if it is stalled
def unstuck():
""" This gets the robot unstuck if it becomes stalled by hitting a wall """
stalls = 0
while timeRemaining(120):
stallStatus = getStall()
... | 1 | 2016-07-13T16:00:50Z | [
"python",
"while-loop"
] |
Python for loop output outside of for loop and format | 38,356,526 | <p>I'm a Python newbie and I have a few questions. In the below example I want to use the output of x in the for loop outside of the for loop with while maintaining its format. I tried to append it to a list outside the loop but when I print the appended variable it does not show in the same format.</p>
<p>Question 1... | 0 | 2016-07-13T15:57:37Z | 38,356,615 | <p>You're actually creating two lists when you call <code>.split()</code>. If you want to store them in the list, you need a second loop.</p>
<pre><code>my_list = []
for i in split_file:
x = (str(i).split())
for split in x:
my_list.append(split)
print(my_list)
</code></pre>
<p>With respect to your thi... | 1 | 2016-07-13T16:02:25Z | [
"python",
"loops"
] |
Python for loop output outside of for loop and format | 38,356,526 | <p>I'm a Python newbie and I have a few questions. In the below example I want to use the output of x in the for loop outside of the for loop with while maintaining its format. I tried to append it to a list outside the loop but when I print the appended variable it does not show in the same format.</p>
<p>Question 1... | 0 | 2016-07-13T15:57:37Z | 38,356,669 | <p>The first output you have is the x's printed line by line. The second output has all of the x's in an array, so that's why they show comma-separated. If you want to print them in the same format, you'll have to run a for loop on my_list, and call print on each line instead of printing the entire array.</p>
<p>So,</... | 0 | 2016-07-13T16:05:10Z | [
"python",
"loops"
] |
Using pandas, write a custom function applied to DataFrame group to calculate average step | 38,356,534 | <p>Assume I have the following data:</p>
<pre><code>df = pd.DataFrame({'c1': ['a','a','a','b','b','b'],
'c2': [3,3,3,4,4,4],
'code': [1,2,3,1,2,3],
'd1': [100,101,102,103,104,105],
'd2': [200,201,202,203,204,205],})
</code></pre>
<p>It looks like this:</p>
... | -1 | 2016-07-13T15:58:17Z | 38,356,768 | <p>Try:</p>
<pre><code>step_size = df.set_index(['c1', 'c2']).groupby(level=[0, 1]).diff(2).dropna()
step_rate = step_size[['d1', 'd2']].div(step_size.code, axis=0)
step_rate
</code></pre>
<p><a href="http://i.stack.imgur.com/mHyji.png" rel="nofollow"><img src="http://i.stack.imgur.com/mHyji.png" alt="enter image des... | 0 | 2016-07-13T16:09:45Z | [
"python",
"pandas"
] |
Using pandas, write a custom function applied to DataFrame group to calculate average step | 38,356,534 | <p>Assume I have the following data:</p>
<pre><code>df = pd.DataFrame({'c1': ['a','a','a','b','b','b'],
'c2': [3,3,3,4,4,4],
'code': [1,2,3,1,2,3],
'd1': [100,101,102,103,104,105],
'd2': [200,201,202,203,204,205],})
</code></pre>
<p>It looks like this:</p>
... | -1 | 2016-07-13T15:58:17Z | 38,356,999 | <pre><code>import pandas as pd
df = pd.DataFrame({'c1': ['a','a','a','b','b','b'],
'c2': [3,3,3,4,4,4],
'code': [1,2,3,1,2,3],
'd1': [100,101,102,103,104,105],
'd2': [200,201,202,203,204,205],})
def avg_step(g):
print('g = ')
print(g,... | 0 | 2016-07-13T16:22:11Z | [
"python",
"pandas"
] |
Can't access dropdown select using Selenium in Python | 38,356,550 | <p>I'm new to using Selenium in Python and I'm trying to access index data on Barclays Live's website. Once I login and the page loads, I'm trying to select 'Custom1' from a dropdown in the page. The select object in the HTML code associated with the list looks like this:</p>
<pre><code><select name="customViewId"... | 3 | 2016-07-13T15:59:20Z | 38,356,663 | <p>One method to alter select elements by sending keys to it.</p>
<p>First locate the select element, then send keys to it. You usually only need the first 1-3 letters to get the proper (unique) result out of element.</p>
<pre><code>select_elem = browser.find_element_by_name("customViewId")
select_elem.send_keys("cu"... | 0 | 2016-07-13T16:05:02Z | [
"javascript",
"python",
"html",
"selenium",
"xpath"
] |
Can't access dropdown select using Selenium in Python | 38,356,550 | <p>I'm new to using Selenium in Python and I'm trying to access index data on Barclays Live's website. Once I login and the page loads, I'm trying to select 'Custom1' from a dropdown in the page. The select object in the HTML code associated with the list looks like this:</p>
<pre><code><select name="customViewId"... | 3 | 2016-07-13T15:59:20Z | 38,357,476 | <blockquote>
<p>The select element is indeed located in an iframe.</p>
</blockquote>
<p>This means that you should <em><a href="http://selenium-python.readthedocs.io/api.html#selenium.webdriver.remote.webdriver.WebDriver.switch_to_frame" rel="nofollow">switch</a> into the context of the frame</em> and only then find... | 1 | 2016-07-13T16:49:04Z | [
"javascript",
"python",
"html",
"selenium",
"xpath"
] |
Pandas: converting .xlsx file to .csv results in a zip file | 38,356,555 | <p>I am using pandas to covert .xlsx file to .csv. The problem is anytime I run the program the resulting file becomes a zip file instead of csv file.
This is my code:</p>
<pre><code> def exl2csv(x,y):
exlfilename = str(x)
exlsheetname = str(y)
workbook = xlrd.open_workbook(exlfilename)
worksheet = wor... | 0 | 2016-07-13T15:59:31Z | 38,356,674 | <p>You could use pandas to do the whole thing if you'd like.</p>
<p><code>pandas.read_excel()</code> will allow you to specify the sheet you want to read so you could do:</p>
<pre><code>def exl2csv(x,y):
exlfilename = str(x)
exlsheetname = str(y)
df = pandas.read_excel(exlfilename, exlsheetname)
csvfi... | 0 | 2016-07-13T16:05:36Z | [
"python",
"excel",
"csv",
"pandas"
] |
python multiprocessing/threading code exits early | 38,356,584 | <p>I'm trying to create multiple processes which each call multiple threads.
I'm running the following code with python3.5</p>
<p>A simplified example of the problem looks like this: </p>
<pre><code>import multiprocessing
import time
import threading
class dumb(threading.Thread):
def __init__(self):
... | 2 | 2016-07-13T16:01:14Z | 38,360,900 | <p>Resolution: the new bug was closed as a duplicate of <a href="http://bugs.python.org/issue18966" rel="nofollow">http://bugs.python.org/issue18966</a></p>
<p>Alas, there's no simple, satisfying explanation "for why". The cause is that <code>multiprocessing</code> arranges for worker processes to leave Python via c... | 1 | 2016-07-13T20:12:37Z | [
"python",
"multithreading",
"python-3.x",
"python-multiprocessing"
] |
Use of zip() throws "Shape of passed values is (x,y), indices imply (w,z)" on DataFrames with mixed types | 38,356,588 | <p><strong>* EDITED EDITED EDITED *</strong></p>
<p>I am wrestling with this issue for quite some time and <strong>while the plain vanilla case works fine, I keep getting this error on a DataFrame with mixed types</strong>.</p>
<p>My objective is to add two new, calculated columns.</p>
<pre><code>import pandas as pd... | 2 | 2016-07-13T16:01:26Z | 38,424,681 | <p>Apparently <code>df.apply</code> needs to return something for the third column too and your <code>lambda</code> is returning two values for each row.
So just select your first two columns like this to get a 4x2 DataFrame for your <code>apply</code>:</p>
<p><code>df['sum'], df['prod'] = zip(*df[['one', 'two']].appl... | 1 | 2016-07-17T18:40:25Z | [
"python",
"pandas"
] |
Use of zip() throws "Shape of passed values is (x,y), indices imply (w,z)" on DataFrames with mixed types | 38,356,588 | <p><strong>* EDITED EDITED EDITED *</strong></p>
<p>I am wrestling with this issue for quite some time and <strong>while the plain vanilla case works fine, I keep getting this error on a DataFrame with mixed types</strong>.</p>
<p>My objective is to add two new, calculated columns.</p>
<pre><code>import pandas as pd... | 2 | 2016-07-13T16:01:26Z | 38,425,497 | <p>I was intrigued by your issue with mixed types and did some digging in <code>DataFrame</code>'s source code. Apparently when your <code>DataFrame</code> is mixed type (i.e. <code>df._is_mixed_type</code> is <code>True</code>), a different function is applied than when it is homogeneous.</p>
<p>When you call <code>a... | 2 | 2016-07-17T20:09:31Z | [
"python",
"pandas"
] |
Can sockets in python be used without internet access | 38,356,627 | <p>I'm trying to send data from one software to another running on the same pc. The coding in the former s/w is done in python. I'm doing this:</p>
<pre><code>sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.sendto("msg,Hi!", ("127.0.0.1", 12345))
</code></pre>
<p>This works fine when I have internet acce... | 0 | 2016-07-13T16:03:25Z | 38,356,710 | <p>AF_INET has nothing to do with the INTERNET. It just means use IP based communication. You can do it on the same computer or across computers. 127.0.0.1 refers to local-host IP i.e. my own IP. Each unix/linux machine has the same local IP.</p>
<p>So yes this code will work without internet access.</p>
| 4 | 2016-07-13T16:07:05Z | [
"python",
"sockets"
] |
Can sockets in python be used without internet access | 38,356,627 | <p>I'm trying to send data from one software to another running on the same pc. The coding in the former s/w is done in python. I'm doing this:</p>
<pre><code>sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.sendto("msg,Hi!", ("127.0.0.1", 12345))
</code></pre>
<p>This works fine when I have internet acce... | 0 | 2016-07-13T16:03:25Z | 38,356,839 | <p>Of course, You do not need any Internet concepts while using Sockets. You can use an ad-hoc network to create a relaxed network and run a simple <strong>TCP</strong> or <strong>UDP</strong> socket script to transfer things you like. </p>
<p>You can infact use <strong>Multicasting</strong> or <strong>Broadcasting</s... | 0 | 2016-07-13T16:13:39Z | [
"python",
"sockets"
] |
Once I use multiple classes it expects an indented block | 38,356,629 | <p>I have multiple classes inside a single file. Once I try to run the code it says it expects an indented block. The error always occurs with the second class in reading order, even if I switch the order of the classes. I am sure that my indents are correct.</p>
<p>So I expect that you can't have multiple separate cl... | -4 | 2016-07-13T16:03:33Z | 38,356,662 | <p>You need to implement the <em>method</em> or leave it empty by specifying <code>pass</code></p>
<pre><code>class FirstClass:
def __init__(self):
pass
class SecondClass:
pass
</code></pre>
| 4 | 2016-07-13T16:05:00Z | [
"python"
] |
How to initialize and train an SVM with rootSIFT features in python | 38,356,689 | <p>I have a CBIR system set up in python utilizing OpenCV. I have successfully extracted the keypoints and descriptors, clustered them using k-means to create a codebook, and have generated histograms describing images based on this codebook. I would like to know how I can use these histograms generated on the last lin... | 0 | 2016-07-13T16:06:18Z | 38,360,612 | <p>Take a look at <a href="http://scikit-learn.org/stable/modules/generated/sklearn.svm.SVC.html" rel="nofollow">sklearn.svm</a> and how SVM classification works <a href="http://scikit-learn.org/stable/modules/svm.html#svm-classification" rel="nofollow">here</a>.
Maybe you can just follow the <a href="https://en.wikip... | 0 | 2016-07-13T19:56:19Z | [
"python",
"opencv",
"computer-vision",
"scikit-learn"
] |
Pandas value_counts Into New Columns | 38,356,690 | <p>I have a timeseries dataset which looks a bit like</p>
<pre><code>ts userid v1 v2
2016-04-23 10:50:12 100001 10 ac
2016-04-23 11:23:29 100002 11 ad
2016-04-23 11:56:57 100002 11 ad
2016-04-23 12:33:38 100001 12 ae
2016-04-23 13:06:43 100001 13 aa
2016-04-23 14:16:34 100001 14 a... | 1 | 2016-07-13T16:06:19Z | 38,356,887 | <p>You can do it with crosstab:</p>
<pre><code>pd.crosstab(df['userid'], df['v1'])
Out[30]:
v1 10 11 12 13 14 15 23
userid
100001 1 0 1 1 1 0 0
100002 0 2 0 0 0 1 0
100003 0 0 0 0 0 0 1
</code></pre>
<p>For other alternatives, take a lo... | 5 | 2016-07-13T16:16:24Z | [
"python",
"pandas"
] |
Pandas value_counts Into New Columns | 38,356,690 | <p>I have a timeseries dataset which looks a bit like</p>
<pre><code>ts userid v1 v2
2016-04-23 10:50:12 100001 10 ac
2016-04-23 11:23:29 100002 11 ad
2016-04-23 11:56:57 100002 11 ad
2016-04-23 12:33:38 100001 12 ae
2016-04-23 13:06:43 100001 13 aa
2016-04-23 14:16:34 100001 14 a... | 1 | 2016-07-13T16:06:19Z | 38,356,983 | <p>This will do:</p>
<pre><code>df.groupby('userid').v1.value_counts().unstack(0).reindex(range(24)).fillna(0).astype(int).T
</code></pre>
<p><a href="http://i.stack.imgur.com/QUeLJ.png" rel="nofollow"><img src="http://i.stack.imgur.com/QUeLJ.png" alt="enter image description here"></a></p>
| 2 | 2016-07-13T16:21:30Z | [
"python",
"pandas"
] |
How to pass enum as argument in ctypes python? | 38,356,698 | <p>I have a <code>dll</code> and a <code>c</code> header file <code>.h</code>. There are some functions which accepts <code>c</code> <code>enum</code>, for example;</p>
<pre><code>enum Type
{
typeA,
typeB
};
</code></pre>
<p>and a function </p>
<pre><code>bool printType(Type type );
</code></pre>
<p>Now I w... | -1 | 2016-07-13T16:06:41Z | 38,358,368 | <p>If you read <a href="https://pypi.python.org/pypi/enum/0.4.6" rel="nofollow">the enum docs on pip</a> you'll see:</p>
<blockquote>
<p>Python 3 now has in its standard library an enum implementation (also available for older Python versions as the third-party flufl.enum distribution) that supersedes this library.<... | 1 | 2016-07-13T17:39:20Z | [
"python",
"enums",
"ctypes"
] |
How to do a group by operation on a list of json objects in python? | 38,356,755 | <p>I am working on a Python script where I need to group by a key in a list of JSON objects.</p>
<p>Iâve a list of a large number of JSON objects in python in the following format:</p>
<p>[{'name': xyz,
'territory': abc,
'parameter_a': 1,
'parameter_b': 2,
'parameter_c': 3},
â¦] </p>
<p>Now I w... | -1 | 2016-07-13T16:08:54Z | 38,357,006 | <pre><code>from json import loads, dumps
from collections import defaultdict
json_string = """
[
{"name": "xyz", "territory": "abc", "parameter_a": 1, "parameter_b": 2, "parameter_c": 3},
{"name": "qrs", "territory": "def", "parameter_a": 1, "parameter_b": 2, "parameter_c": 3},
{"name": "tuv", "territory":... | 0 | 2016-07-13T16:22:27Z | [
"python",
"json",
"list"
] |
How to do a group by operation on a list of json objects in python? | 38,356,755 | <p>I am working on a Python script where I need to group by a key in a list of JSON objects.</p>
<p>Iâve a list of a large number of JSON objects in python in the following format:</p>
<p>[{'name': xyz,
'territory': abc,
'parameter_a': 1,
'parameter_b': 2,
'parameter_c': 3},
â¦] </p>
<p>Now I w... | -1 | 2016-07-13T16:08:54Z | 38,358,800 | <p>Using this part of Rob's answer for the setup:</p>
<pre><code>from json import loads, dumps
from collectins import defaultdict
json_string = """
[
{"name": "xyz", "territory": "abc", "parameter_a": 1, "parameter_b": 2, "parameter_c": 3},
{"name": "qrs", "territory": "def", "parameter_a": 1, "parameter_b": ... | 0 | 2016-07-13T18:03:10Z | [
"python",
"json",
"list"
] |
Pyside Installation "Failed to find the MSVC compiler version 10.0 on your system" | 38,356,766 | <p>I'm currently in the process of developing a gui for my python script and want to do that by using PySide.</p>
<p>Right now I just can't get it up and running. PIP alwyas exits with this error: </p>
<pre><code>nmake not found. Trying to initialize the MSVC env...
Searching MSVC compiler version 10.0 error: Failed... | 0 | 2016-07-13T16:09:35Z | 38,357,171 | <blockquote>
<p>PySide requires Python 2.6 or later and Qt 4.6 or better.</p>
<p>Qt 5.x is currently not supported.</p>
</blockquote>
<p>From: <a href="https://pypi.python.org/pypi/PySide/1.2.4#installing-pyside-on-a-windows-system" rel="nofollow">https://pypi.python.org/pypi/PySide/1.2.4#installing-pyside-on-a... | 0 | 2016-07-13T16:32:27Z | [
"python",
"qt",
"user-interface",
"frameworks",
"pyside"
] |
Numpy Minimize COBYLA Constraints | 38,356,781 | <p>I am using scipy.minimize with the COBYLA method, but I seem to be unable to write the constraints properly because when I check the values of the objective function, they do not respect those constraints.</p>
<p>Basically, the objective function accepts an array as argument, that must follow two constraints:</p>
... | -1 | 2016-07-13T16:10:38Z | 38,421,654 | <p>You are not checking that the solver converged (output.success == True) --- and in your case it does not converge. If there is no convergence, nothing is guaranteed about the constraints.</p>
| 0 | 2016-07-17T13:18:02Z | [
"python",
"numpy",
"scipy",
"constraints",
"minimize"
] |
Numpy Minimize COBYLA Constraints | 38,356,781 | <p>I am using scipy.minimize with the COBYLA method, but I seem to be unable to write the constraints properly because when I check the values of the objective function, they do not respect those constraints.</p>
<p>Basically, the objective function accepts an array as argument, that must follow two constraints:</p>
... | -1 | 2016-07-13T16:10:38Z | 38,421,948 | <p>Apparently a version problem, the issue has been fixed since. I was using Python 2.7 and Scipy 0.13...</p>
| 0 | 2016-07-17T13:51:26Z | [
"python",
"numpy",
"scipy",
"constraints",
"minimize"
] |
can not find nbconvert.py after git clone and pip install nbconvert | 38,356,845 | <p>I am following the instruction here <a href="http://www.slideviper.oquanta.info/tutorial/slideshow_tutorial_slides.html#/10" rel="nofollow">http://www.slideviper.oquanta.info/tutorial/slideshow_tutorial_slides.html#/10</a> to convert my ipynb file to a html slideshow.</p>
<p>As I didn't have nbconvert, I <code>$git... | 0 | 2016-07-13T16:13:59Z | 39,291,768 | <p>You should add c:\python27\Script\jupyter.exe (or wherever this file is) to the windows path, then you should <em>cd</em> to where your .ipynb file is and type in a windows cmd console :</p>
<p>jupyter nbconvert youfile.ipynb format</p>
<p>"format" can be : html, slides, pdf, etc...</p>
<p>Good luck</p>
| 0 | 2016-09-02T11:52:04Z | [
"python",
"jupyter",
"nbconvert"
] |
Installing and using virtualenvwrapper | 38,357,035 | <p>I am trying to learn how to program using Django, but I am stuck dealing with some problems related to the use of <code>virtualenv</code> and <code>virtualenvwrapper</code>.</p>
<p>I am using a Mac with the following OSX <code>OS X El Capitan 10.11.3</code> with <code>Python 2.7.10</code> as default.</p>
<p>I have... | 1 | 2016-07-13T16:23:52Z | 38,357,322 | <p><code>virtualenvwrapper.sh</code> should be in your path somewhere. The simplest solution is tp change the <code>source</code> statement to read</p>
<pre><code>source `which virtualenvwrapper.sh`
</code></pre>
<p>Note the back-ticks around the <code>which virtualenvwrapper.sh</code> part of the command.</p>
<p>Th... | 0 | 2016-07-13T16:40:04Z | [
"python",
"virtualenv",
"virtualenvwrapper"
] |
Merge Sort on Python: Unusual pattern of result obtained | 38,357,060 | <p>I have a unsorted array of 10,000 integers from 0 to 9,999. I wanted to apply merge sort on this unsorted array and I wrote the following code-</p>
<pre><code>import sys
def merge_sort(data):
result = []
if len(data) <= 1:
return data
else:
mid = int(len(data)/2)
left = data[:... | 1 | 2016-07-13T16:25:44Z | 38,357,121 | <p>You are ordering strings: <code>'9989' < '999' < '9990'</code>. If you want to order integers, you'll have to convert your input list to integers.</p>
| 1 | 2016-07-13T16:29:22Z | [
"python",
"python-2.7",
"mergesort"
] |
Merge Sort on Python: Unusual pattern of result obtained | 38,357,060 | <p>I have a unsorted array of 10,000 integers from 0 to 9,999. I wanted to apply merge sort on this unsorted array and I wrote the following code-</p>
<pre><code>import sys
def merge_sort(data):
result = []
if len(data) <= 1:
return data
else:
mid = int(len(data)/2)
left = data[:... | 1 | 2016-07-13T16:25:44Z | 38,357,125 | <p>Is your data coming in as strings or integers? Based on your sample output, they are strings.</p>
<p>In such a case, '1' comes just before '10'. If you're expecting integers, then you could convert to int to do the sort.</p>
| 0 | 2016-07-13T16:29:37Z | [
"python",
"python-2.7",
"mergesort"
] |
Merge Sort on Python: Unusual pattern of result obtained | 38,357,060 | <p>I have a unsorted array of 10,000 integers from 0 to 9,999. I wanted to apply merge sort on this unsorted array and I wrote the following code-</p>
<pre><code>import sys
def merge_sort(data):
result = []
if len(data) <= 1:
return data
else:
mid = int(len(data)/2)
left = data[:... | 1 | 2016-07-13T16:25:44Z | 38,357,521 | <p>Your <code>data</code> is in strings, not numbers. To convert to integers, use:</p>
<pre><code>data = [int(x) for x in data]
</code></pre>
<p>Python will "compare" a wide variety of objects. For example:</p>
<pre><code>>>> "a" < "ab"
True
>>> None < "a"
True
>>> 1 < "a"
True
... | 0 | 2016-07-13T16:51:39Z | [
"python",
"python-2.7",
"mergesort"
] |
Split pandas dataframe column based on number of digits | 38,357,130 | <p>I have a pandas dataframe which has two columns key and value, and the value always consists of a 8 digit number something like</p>
<pre><code>>df1
key value
10 10000100
20 10000000
30 10100000
40 11110000
</code></pre>
<p>Now I need to take the value column and split it on the digits present, such that my ... | 5 | 2016-07-13T16:30:06Z | 38,357,424 | <p>Assuming your input is stored as strings and all have the same length (8, as posed), then the following works:</p>
<pre><code>df1 = pd.concat([df1,pd.DataFrame(columns=range(8))])
df1[list(range(8))] = df1['Value'].apply(lambda x: pd.Series(list(str(x)),index=range(8)))
</code></pre>
| 3 | 2016-07-13T16:45:37Z | [
"python",
"pandas",
"dataframe",
"data-manipulation"
] |
Split pandas dataframe column based on number of digits | 38,357,130 | <p>I have a pandas dataframe which has two columns key and value, and the value always consists of a 8 digit number something like</p>
<pre><code>>df1
key value
10 10000100
20 10000000
30 10100000
40 11110000
</code></pre>
<p>Now I need to take the value column and split it on the digits present, such that my ... | 5 | 2016-07-13T16:30:06Z | 38,357,443 | <p>This should work:</p>
<pre><code>df.value.astype(str).apply(list).apply(pd.Series).astype(int)
</code></pre>
<p><a href="http://i.stack.imgur.com/ZTDqX.png"><img src="http://i.stack.imgur.com/ZTDqX.png" alt="enter image description here"></a></p>
| 8 | 2016-07-13T16:46:37Z | [
"python",
"pandas",
"dataframe",
"data-manipulation"
] |
Split pandas dataframe column based on number of digits | 38,357,130 | <p>I have a pandas dataframe which has two columns key and value, and the value always consists of a 8 digit number something like</p>
<pre><code>>df1
key value
10 10000100
20 10000000
30 10100000
40 11110000
</code></pre>
<p>Now I need to take the value column and split it on the digits present, such that my ... | 5 | 2016-07-13T16:30:06Z | 38,357,565 | <p>One approach could be -</p>
<pre><code>arr = df.value.values.astype('S8')
df = pd.DataFrame(np.fromstring(arr, dtype=np.uint8).reshape(-1,8)-48)
</code></pre>
<p>Sample run -</p>
<pre><code>In [58]: df
Out[58]:
key value
0 10 10000100
1 20 10000000
2 30 10100000
3 40 11110000
In [59]: arr = d... | 3 | 2016-07-13T16:53:21Z | [
"python",
"pandas",
"dataframe",
"data-manipulation"
] |
Split pandas dataframe column based on number of digits | 38,357,130 | <p>I have a pandas dataframe which has two columns key and value, and the value always consists of a 8 digit number something like</p>
<pre><code>>df1
key value
10 10000100
20 10000000
30 10100000
40 11110000
</code></pre>
<p>Now I need to take the value column and split it on the digits present, such that my ... | 5 | 2016-07-13T16:30:06Z | 38,357,571 | <p>A vectorized version would be:</p>
<pre><code>df['value'].astype(str).str.join(' ').str.split(' ', expand=True)
</code></pre>
<p>This first introduces spaces between characters and then splits. It's just a workaround to be able to use str.split (maybe not necessary, not sure). But it is quite faster:</p>
<pre><co... | 2 | 2016-07-13T16:53:42Z | [
"python",
"pandas",
"dataframe",
"data-manipulation"
] |
What is wrong with my python script and cron job? | 38,357,132 | <p>I have this python script to check services like MySQL and Apache and if some of them are down then it starts again:</p>
<pre><code>import subprocess
import smtplib
_process = ['mysql', 'apache2']
for _proc in _process:
p = subprocess.Popen(["service", _proc, "status"], stdout=subprocess.PIPE)
output, err ... | 1 | 2016-07-13T16:30:18Z | 38,360,425 | <p>The problem is that <code>service</code> isn't in any of the directories listed in the $PATH of the cron process.</p>
<p>There are many solutions. One solution is to specify the complete path to <code>service</code> in your <code>.Popen()</code> call. On my computer, that is <code>/usr/sbin/service</code>.</p>
<p>... | 3 | 2016-07-13T19:46:13Z | [
"python",
"cron-task"
] |
Have Pycharm run inspections only on the code that changed since a commit | 38,357,236 | <p>I've been using Pycharm for a few years now, but it has always been a bit laggy and a bit of a resource hog. I was wondering if anyone knows a way to have Pycharm run inspections only on the code that would come up in a git-diff. I am working in a large code-base with large files, and I don't need all that inspectio... | 1 | 2016-07-13T16:36:04Z | 38,357,615 | <p>From the jetbrains documentation: <a href="https://www.jetbrains.com/help/pycharm/2016.1/running-inspections.html" rel="nofollow">https://www.jetbrains.com/help/pycharm/2016.1/running-inspections.html</a></p>
<p>What you seem to want to do is change the scope of the inspections that are run. In the settings menu if... | 0 | 2016-07-13T16:56:07Z | [
"python",
"pycharm"
] |
Accessing python parent class variables from child class | 38,357,253 | <p>Why doesn't this work?</p>
<pre><code>class Parent:
__var = "Whatever"
class Child(Parent):
def printVar(self):
print(self.__var)
Timmy = Child()
Timmy.printVar()
</code></pre>
<p>I get the following exception:</p>
<pre><code>Traceback (most recent call last):
File "<stdin>", line 1, in... | 3 | 2016-07-13T16:36:58Z | 38,357,389 | <p>Double underscore is used for private attributes, you should use single underscore.</p>
<pre><code>class Parent:
_var = "Whatever"
class Child(Parent):
def printVar(self):
print(self._var)
Timmy = Child()
Timmy.printVar()
</code></pre>
| 0 | 2016-07-13T16:44:10Z | [
"python"
] |
Accessing python parent class variables from child class | 38,357,253 | <p>Why doesn't this work?</p>
<pre><code>class Parent:
__var = "Whatever"
class Child(Parent):
def printVar(self):
print(self.__var)
Timmy = Child()
Timmy.printVar()
</code></pre>
<p>I get the following exception:</p>
<pre><code>Traceback (most recent call last):
File "<stdin>", line 1, in... | 3 | 2016-07-13T16:36:58Z | 38,357,420 | <p>This is because you chose to name the attribute with a double leading underscore. This triggers some name-mangling</p>
<p>You can access it as <code>self._Parent__var</code></p>
<pre><code>In [8]: class Parent:
__var = "Whatever"
...:
In [9]: class Child(Parent):
def foo(self): print self._Parent__... | 2 | 2016-07-13T16:45:25Z | [
"python"
] |
Accessing python parent class variables from child class | 38,357,253 | <p>Why doesn't this work?</p>
<pre><code>class Parent:
__var = "Whatever"
class Child(Parent):
def printVar(self):
print(self.__var)
Timmy = Child()
Timmy.printVar()
</code></pre>
<p>I get the following exception:</p>
<pre><code>Traceback (most recent call last):
File "<stdin>", line 1, in... | 3 | 2016-07-13T16:36:58Z | 38,357,467 | <p>You have provided <code>__var</code> as a <em>class variable</em> which is name-mangled due to the double-leading underscore. Hence, you cannot access it nicely with <code>__var</code>, but rather would need to use <code>self._Parent__var</code>. It can only be accessed by instances of <code>Parent</code> with <code... | 1 | 2016-07-13T16:48:23Z | [
"python"
] |
Dealing with Irregular Embedded ArrayFields in Django | 38,357,279 | <p>I am currently using Django with PostgreSQL. I use <code>django-extensions</code> to run custom scripts, inserting data to database. I have a model as below:</p>
<pre><code>class Route(models.Model):
"""
Bus routes of İzmir.
"""
code = models.PositiveSmallIntegerField(
unique=True,
... | 0 | 2016-07-13T16:37:59Z | 38,362,458 | <p>So, there seems to be no participant to this question. Thus, I wanted to share my own solution. In short, I modified the script in a way of question (1) above, which means, I extended each list with filler <code>None</code> values to <em>equalize</em> the length of every list.</p>
<p>Assuming I have data as below:<... | 0 | 2016-07-13T22:02:49Z | [
"python",
"arrays",
"django",
"postgresql",
"python-3.x"
] |
How do I install OpenCV 3 on Centos 6.8? | 38,357,319 | <p>I'm working on a CentOS cluster right now and have Python2.7 installed. I've managed to get OpenCV 2.4 installed (using <a href="https://superuser.com/questions/678568/install-opencv-in-centos">these</a> helpful instructions) but it does not have all of the functionality of 3 (I need the connectedComponents function... | 0 | 2016-07-13T16:39:44Z | 38,358,885 | <blockquote>
<p>I've managed to get OpenCV 2.4 installed (using these helpful instructions) but it does not have all of the functionality of 3 (I need the connectedComponents function and a couple others not available).</p>
</blockquote>
<p>Why don't you just download OpenCV 3 then? </p>
<blockquote>
<p>Something... | 1 | 2016-07-13T18:07:53Z | [
"python",
"linux",
"opencv",
"cmake",
"centos"
] |
How do I install OpenCV 3 on Centos 6.8? | 38,357,319 | <p>I'm working on a CentOS cluster right now and have Python2.7 installed. I've managed to get OpenCV 2.4 installed (using <a href="https://superuser.com/questions/678568/install-opencv-in-centos">these</a> helpful instructions) but it does not have all of the functionality of 3 (I need the connectedComponents function... | 0 | 2016-07-13T16:39:44Z | 38,360,421 | <p>It seems like OpenCV 3 would be better suited for what you are doing, you even said yourself that you are needing features that aren't available in 2.7. </p>
<p>The OpenCV 3.0 documentation actually has a full guide on installing the latest version of the library using the Yum feature in your terminal. It walks you... | 0 | 2016-07-13T19:46:03Z | [
"python",
"linux",
"opencv",
"cmake",
"centos"
] |
Convert datetime to unix timestamp in SQLAlchemy model before executing query? | 38,357,352 | <p>I am using SQLAlchemy to work with a remote database that uses a strange timestamp format--it stores timestamps as double-precision milliseconds since epoch. I'd like to work with python datetime objects, so I wrote getter/setter methods in my model, following <a href="https://gist.github.com/luhn/4170996" rel="nofo... | 2 | 2016-07-13T16:41:44Z | 38,360,432 | <p>You have to use a custom type, which isn't as scary as it sounds.</p>
<pre><code>from sqlalchemy.types import TypeDecorator
class DoubleTimestamp(TypeDecorator):
impl = DOUBLE
def __init__(self):
TypeDecorator.__init__(self, as_decimal=False)
def process_bind_param(self, value, dialect):
... | 2 | 2016-07-13T19:46:37Z | [
"python",
"sqlalchemy"
] |
Getting Access Denied after receiving valid session id | 38,357,376 | <p>I have a working python/tk program that runs a cgi script based on user selection. I'm working to cut this down to a small script that just focuses on one particular cgi script. It appears to be getting the session id correctly but when I launch the browser I keep getting "access denied". As the other program wor... | 1 | 2016-07-13T16:43:05Z | 38,729,555 | <p>Resolved. The script was ending therefore closing the socket before the browser had a chance to respond to the request </p>
| 0 | 2016-08-02T20:08:00Z | [
"python",
"session",
"websocket",
"tornado"
] |
Removing entries from arrays in a parallel manner | 38,357,403 | <p>I have a list/array of x and y coordinates, for example:</p>
<pre><code>x = [x1, x2, x3,...]
y = [y1, y2, y3,...]
</code></pre>
<p>Now, I want to remove certain entries based on conditions, for example, the following: </p>
<pre><code>for i in x:
if i <= 40 and i >= -40:
print "True"
else:
... | 3 | 2016-07-13T16:44:46Z | 38,357,560 | <p>This should do it. </p>
<pre><code>for i in x1:
if i <= 40 and i >= -40:
print "True"
for i in y1:
if i <=20 and i >=-20:
print "True"
else:
x1.remove(i)
y1.remove(i)
else:
x1.remove(i)
y1.re... | 1 | 2016-07-13T16:53:07Z | [
"python",
"arrays",
"list",
"numpy"
] |
Removing entries from arrays in a parallel manner | 38,357,403 | <p>I have a list/array of x and y coordinates, for example:</p>
<pre><code>x = [x1, x2, x3,...]
y = [y1, y2, y3,...]
</code></pre>
<p>Now, I want to remove certain entries based on conditions, for example, the following: </p>
<pre><code>for i in x:
if i <= 40 and i >= -40:
print "True"
else:
... | 3 | 2016-07-13T16:44:46Z | 38,357,626 | <p>Another option is to work with <code>list-comprehension</code>:</p>
<p><em>Input</em>:</p>
<pre><code>x = [50, 10, -50, 30, 5, 6]
y = [2, 40, 10, 5, 3, 5]
</code></pre>
<p><em>Code</em>:</p>
<pre><code>x, y = list(zip(*[(x, y) for x, y in zip(x, y) if x <= 40 and x > -40 and y <= 20 and y > -20]))
</... | 3 | 2016-07-13T16:57:04Z | [
"python",
"arrays",
"list",
"numpy"
] |
Removing entries from arrays in a parallel manner | 38,357,403 | <p>I have a list/array of x and y coordinates, for example:</p>
<pre><code>x = [x1, x2, x3,...]
y = [y1, y2, y3,...]
</code></pre>
<p>Now, I want to remove certain entries based on conditions, for example, the following: </p>
<pre><code>for i in x:
if i <= 40 and i >= -40:
print "True"
else:
... | 3 | 2016-07-13T16:44:46Z | 38,357,673 | <p>Try this:</p>
<pre><code>mask = ((x <= 40) & (x >= -40) & (y <= 20) & (y >= -20))
x, y = x[mask], y[mask]
</code></pre>
<p>NumPy will vectorize these operations, so it should be very efficient.</p>
<p><a href="https://python-astro.blogspot.com/2012/05/playing-with-arrays-slicing-sorting.ht... | 3 | 2016-07-13T16:59:35Z | [
"python",
"arrays",
"list",
"numpy"
] |
Removing entries from arrays in a parallel manner | 38,357,403 | <p>I have a list/array of x and y coordinates, for example:</p>
<pre><code>x = [x1, x2, x3,...]
y = [y1, y2, y3,...]
</code></pre>
<p>Now, I want to remove certain entries based on conditions, for example, the following: </p>
<pre><code>for i in x:
if i <= 40 and i >= -40:
print "True"
else:
... | 3 | 2016-07-13T16:44:46Z | 38,358,005 | <p>Form a boolean selection mask:</p>
<pre><code>mask = ~((x > 40) | (x < -40) | (y > 20) | (y < -20))
</code></pre>
<p>then, to select values from <code>x</code> and <code>y</code> where <code>mask</code> is True:</p>
<pre><code>x, y = x[mask], y[mask]
</code></pre>
<hr>
<p>When <code>x</code> is a Nu... | 4 | 2016-07-13T17:19:26Z | [
"python",
"arrays",
"list",
"numpy"
] |
Removing entries from arrays in a parallel manner | 38,357,403 | <p>I have a list/array of x and y coordinates, for example:</p>
<pre><code>x = [x1, x2, x3,...]
y = [y1, y2, y3,...]
</code></pre>
<p>Now, I want to remove certain entries based on conditions, for example, the following: </p>
<pre><code>for i in x:
if i <= 40 and i >= -40:
print "True"
else:
... | 3 | 2016-07-13T16:44:46Z | 38,363,845 | <p>For completeness, here is a solution based on <strong>itertools</strong>.</p>
<p>Consider the following lists of coordinates:</p>
<pre><code>x = [-50, -50, -10, 0, 10, 50, 50, -10, -10, 0, 10, 40]
y = [-50, -20, -50, 50, -50, 20, 50, -20, -10, 0, 20, 10]
</code></pre>
<p>Our goal is to set-up a boolean mask w... | 0 | 2016-07-14T00:43:40Z | [
"python",
"arrays",
"list",
"numpy"
] |
Reading csv files with python gets me to the last line | 38,357,417 | <p>This might be a really dumb question but I've been stuck there for more than an hour.</p>
<p>I am doing some csv-file reading with python using the following code:</p>
<pre><code>with open(filename, 'rb') as csvfile:
for line in csvfile.readlines():
print("Line = "+str(line))
array = line.split... | 1 | 2016-07-13T16:45:17Z | 38,357,662 | <p>As I open your question for editing and "walk" my cursor through your code, I see that your indentations use a combination of spaces and tabs. This is bad in Python code: the interpreter does have rules on understanding this but those rules are basically un-followable for humans.</p>
<p>Replace all your tabs with s... | 2 | 2016-07-13T16:59:08Z | [
"python",
"csv"
] |
Most common value from multiple colums in Pandas | 38,357,461 | <p>I have a series of data in an irregular number of columns and I need to determine the most common value from split sections across multiple columns using pandas. An example of what I mean is if I had information of what kind of cheese my coworkers had with their lunches each day:</p>
<pre><code>Idx Name Cheese1 ... | 3 | 2016-07-13T16:47:59Z | 38,357,773 | <pre><code>import io
import pandas as pd
data = io.StringIO("""\
Idx Name Cheese1 Cheese2 Cheese3
0 Evan Gouda NaN NaN
1 John Cheddar Havarti Blue
2 Evan Cheddar Gouda NaN
3 John Havarti Swiss NaN
4 Rick NaN NaN NaN
""")
df = pd.read_csv(data, delim_white... | 4 | 2016-07-13T17:05:07Z | [
"python",
"pandas",
"statistics"
] |
Most common value from multiple colums in Pandas | 38,357,461 | <p>I have a series of data in an irregular number of columns and I need to determine the most common value from split sections across multiple columns using pandas. An example of what I mean is if I had information of what kind of cheese my coworkers had with their lunches each day:</p>
<pre><code>Idx Name Cheese1 ... | 3 | 2016-07-13T16:47:59Z | 38,361,723 | <p>Recently, I've been using <code>R</code> quite a bit and there I would solve this like:</p>
<pre class="lang-R prettyprint-override"><code>library(data.table)
library(dplyr)
library(tidyr)
x <- fread('
Idx Name Cheese1 Cheese2 Cheese3
0 Evan Gouda NaN NaN
1 John Cheddar Havarti Blue
... | 0 | 2016-07-13T21:07:17Z | [
"python",
"pandas",
"statistics"
] |
How to match an exact word inside a string? | 38,357,533 | <pre><code>op = ['TRAIL_RATE_ID 8 TRAIL_RATE_NAME VC-4 TRAIL_ORDER High Order ', 'TRAIL_RATE_ID 9 TRAIL_RATE_NAME VC4-4 TRAIL_ORDER High Order ' , 'TRAIL_RATE_ID 10 TRAIL_RATE_NAME VC-8 TRAIL_ORDER High Order ']
word = "8"
for op1 in op:
pp=re.search('(\\b'+word +'\\b)', op1, flags=re.IGNORECASE|re.DOTALL)
p... | 1 | 2016-07-13T16:52:16Z | 38,357,587 | <p>Word boundaries won't help because <code>-</code> is not considered a word character.</p>
<p>You can use lookarounds:</p>
<pre><code>p = re.compile(r'(?:(?<=^)|(?<=\s))' + word + r'(?=\s|$)', flags=re.IGNORECASE|re.M)
re.search(p, op1)
</code></pre>
<p><a href="http://ideone.com/euVKrD" rel="nofollow">Code ... | 4 | 2016-07-13T16:54:41Z | [
"python",
"regex",
"python-2.7"
] |
How to match an exact word inside a string? | 38,357,533 | <pre><code>op = ['TRAIL_RATE_ID 8 TRAIL_RATE_NAME VC-4 TRAIL_ORDER High Order ', 'TRAIL_RATE_ID 9 TRAIL_RATE_NAME VC4-4 TRAIL_ORDER High Order ' , 'TRAIL_RATE_ID 10 TRAIL_RATE_NAME VC-8 TRAIL_ORDER High Order ']
word = "8"
for op1 in op:
pp=re.search('(\\b'+word +'\\b)', op1, flags=re.IGNORECASE|re.DOTALL)
p... | 1 | 2016-07-13T16:52:16Z | 38,357,592 | <p>You can require that there should not be a non-whitespace symbol on both sides of the word:</p>
<pre><code>r'(?<!\S){0}(?!\S)'.format(re.escape(word))
</code></pre>
<p>See the <a href="https://regex101.com/r/aY8zM7/1" rel="nofollow">regex demo</a></p>
<p>I added <code>re.escape(word)</code> in case your keywor... | 3 | 2016-07-13T16:54:56Z | [
"python",
"regex",
"python-2.7"
] |
Binning by days of the week. Pandas Python Matplotlib | 38,357,632 | <p>I have a DF series days of the week.</p>
<pre><code>dayname
MONDAY
MONDAY
WEDNESDAY
SATURDAY
SUNDAY
</code></pre>
<p>What I want to do is plot their counts which I can get using a groupby count function like this <code>df = df.groupby('dayname').count()</code> .</p>
<pre><code> count
dayname
MO... | 1 | 2016-07-13T16:57:27Z | 38,358,333 | <p>Create a list of days and use it to <code>reindex</code></p>
<pre><code>DAYS = ['MONDAY', 'TUESDAY', 'WEDNESDAY', 'THURSDAY', 'FRIDAY', 'SATURDAY', 'SUNDAY']
df.dayname.value_counts().reindex(DAYS, fill_value=0).plot.bar()
</code></pre>
<p><a href="http://i.stack.imgur.com/kiSVF.png" rel="nofollow"><img src="http... | 2 | 2016-07-13T17:37:09Z | [
"python",
"pandas",
"matplotlib"
] |
How to handle upload File in Plone using plone.api create and NamedBlobFile | 38,357,649 | <p>Dears,</p>
<p>I have been create a script to read a txt and do a upload in Plone site (Plone 4.3.10).
The script is here:
<a href="http://stackoverflow.com/questions/38351633/script-python-using-plone-api-to-create-file-appear-error-wrongtype-when-set-a-f">Script Python using plone.api to create File appear error W... | 1 | 2016-07-13T16:58:33Z | 38,370,615 | <p>PDF is a binary format so you might want to read on how to open files in Python. Something like <code>data=open(pdf_path, 'rb')</code> should help.</p>
<p>Also I recommend you learn about pdb and insert a breakpoint just before this line so you can inspect if everything works as expected.</p>
| 2 | 2016-07-14T09:33:16Z | [
"python",
"blob",
"plone",
"zope"
] |
How to handle upload File in Plone using plone.api create and NamedBlobFile | 38,357,649 | <p>Dears,</p>
<p>I have been create a script to read a txt and do a upload in Plone site (Plone 4.3.10).
The script is here:
<a href="http://stackoverflow.com/questions/38351633/script-python-using-plone-api-to-create-file-appear-error-wrongtype-when-set-a-f">Script Python using plone.api to create File appear error W... | 1 | 2016-07-13T16:58:33Z | 38,393,769 | <p>The following worked on a Plone 4.3.10 + plone.app.contenttypes (default DX types)</p>
<pre><code>>>> plone = app.Plonedemo
>>> plone
<PloneSite at /Plonedemo>
>>> from zope.component.hooks import setSite
>>> setSite(plone)
>>> from plone import api
>>> pd... | 3 | 2016-07-15T10:25:23Z | [
"python",
"blob",
"plone",
"zope"
] |
numpy difference between flat and ravel() | 38,357,811 | <p>What is the difference between the following?</p>
<pre><code>>>> import numpy as np
>>> arr = np.array([[[ 0, 1, 2],
... [ 10, 12, 13]],
... [[100, 101, 102],
... [110, 112, 113]]])
>>> arr
array([[[ 0, 1, 2],
[ 10, 12... | 3 | 2016-07-13T17:07:26Z | 38,357,947 | <p><code>flat</code> is an iterator. It is a separate object that just happens to give access to the array elements via indexing. It's main purpose is to be used in loops and comprehension expressions. The order it gives is the same as the one you would generally get from <code>ravel</code>.</p>
<p>Unlike the result o... | 3 | 2016-07-13T17:15:52Z | [
"python",
"numpy"
] |
How can I in Blender acces a polygon, which is given by indices, for an operator? | 38,357,820 | <p>In <code>Blender 2.77</code> I have a polygon, referenced as:</p>
<pre><code> bpy.data.objects['Cube.001'].data.polygons[0]
</code></pre>
<p>and an operator:</p>
<pre><code>bpy.ops.transform.resize(value=(0, 0, 1), constraint_axis=(False, False, False), constraint_orientation='GLOBAL', mirror=False, proportional... | 0 | 2016-07-13T17:07:57Z | 38,361,895 | <p>Looks like you need to toggle back to OBJECT mode to do the ...polygons[0].select</p>
<pre><code># assume in EDIT... mode now
bpy.data.objects['Cube.001'].data.polygons[0]
bpy.ops.object.editmode_toggle()
bpy.data.objects['Cube.001'].data.polygons[0].select = True
bpy.ops.object.editmode_toggle()
bpy.ops.transform.... | 0 | 2016-07-13T21:21:16Z | [
"python",
"reference",
"blender"
] |
How can I in Blender acces a polygon, which is given by indices, for an operator? | 38,357,820 | <p>In <code>Blender 2.77</code> I have a polygon, referenced as:</p>
<pre><code> bpy.data.objects['Cube.001'].data.polygons[0]
</code></pre>
<p>and an operator:</p>
<pre><code>bpy.ops.transform.resize(value=(0, 0, 1), constraint_axis=(False, False, False), constraint_orientation='GLOBAL', mirror=False, proportional... | 0 | 2016-07-13T17:07:57Z | 38,381,523 | <p>While blender stores the mesh data within <code>object.data</code>, this data is only valid in object mode, when you switch to edit mode a bmesh copy of the mesh data is created, which replaces the <code>object.data</code> contents when you leave edit mode. As you are using a duplicate mesh while editing any selecti... | 0 | 2016-07-14T18:23:02Z | [
"python",
"reference",
"blender"
] |
Create sites in runtime with different domains | 38,358,052 | <p>I would like to create django sites in runtime, using the same settings.py</p>
<p>For example, I have in my django_site table the following rows,</p>
<pre><code>1 | 127.0.0.1:8001 | sitea
2 | 127.0.0.1:8002 | siteb
3 | 127.0.0.1:8003 | sitec
</code></pre>
<p>My django goes to my settings.py, fetchs the site_id an... | 0 | 2016-07-13T17:21:46Z | 38,359,064 | <p>I suggest you to look at <a href="https://github.com/tkaemming/django-subdomains" rel="nofollow">django-subdomains</a>.</p>
<p>While it manages different sites as sitea.127.0.0.1:8001, siteb.127.0.0.1:8001 etc unlike you want but you really can check their <code>SubdomainURLRoutingMiddleware</code> to inspirate you... | 0 | 2016-07-13T18:18:32Z | [
"python",
"django",
"django-settings",
"url-pattern"
] |
Im trying to create an image while using a list full of RGB values | 38,358,184 | <p>I am trying to create an image using a list full of RGB values where every one of them is a pixel ,I am also using numpy so i can edit the list by transforming it to a multidimensional array ;However, when i transform the list to an array , the tuples that contain the RGB values becomes a list that contains RGB valu... | -1 | 2016-07-13T17:28:24Z | 38,358,367 | <p>You can use a <a href="https://docs.python.org/2.7/tutorial/datastructures.html?list-comprehensions#list-comprehensions" rel="nofollow">list comprehension</a> to convert a list of lists into a list of tuples, like:</p>
<pre><code>>>> l = [[1,2,3], [2,3,4], [3,4,5]]
>>> l = [tuple(i) for i in l]
&g... | 0 | 2016-07-13T17:39:07Z | [
"python",
"arrays",
"list",
"numpy",
"colors"
] |
Im trying to create an image while using a list full of RGB values | 38,358,184 | <p>I am trying to create an image using a list full of RGB values where every one of them is a pixel ,I am also using numpy so i can edit the list by transforming it to a multidimensional array ;However, when i transform the list to an array , the tuples that contain the RGB values becomes a list that contains RGB valu... | -1 | 2016-07-13T17:28:24Z | 38,359,358 | <p>Faster with <code>map</code></p>
<pre><code>from time import clock
spin = 200000
t0 = clock()
for c in range(spin):
li = [[134, 234, 200], [234, 0, 255], [122,12,45], [210,50,87], [3,150,250],
[100,200,0], [230,44,78], [35,78,40], [122,124,231], [251,98,13]]
li = [tuple(e) for e in li]
t1 = cloc... | 0 | 2016-07-13T18:36:36Z | [
"python",
"arrays",
"list",
"numpy",
"colors"
] |
Biopython parse from variable instead of file | 38,358,191 | <pre><code>import gzip
import io
from Bio import SeqIO
infile = "myinfile.fastq.gz"
fileout = open("myoutfile.fastq", "w+")
with io.TextIOWrapper(gzip.open(infile, "r")) as f:
line = f.read()
fileout.write(line)
fileout.seek(0)
count = 0
for rec in SeqIO.parse(fileout, "fastq"): #parsing from file
count += 1
... | 1 | 2016-07-13T17:28:52Z | 38,360,389 | <p>It's because <code>SeqIO.parse</code> only accepts a file handler or a filename as the first parameter.</p>
<p>If you want to read a gzipped file directly into <code>SeqIO.parse</code> just pass a handler to it:</p>
<pre><code>import gzip
from Bio import SeqIO
count = 0
with gzip.open("myinfile.fastq.gz") as f:
... | 4 | 2016-07-13T19:43:36Z | [
"python",
"biopython"
] |
Biopython parse from variable instead of file | 38,358,191 | <pre><code>import gzip
import io
from Bio import SeqIO
infile = "myinfile.fastq.gz"
fileout = open("myoutfile.fastq", "w+")
with io.TextIOWrapper(gzip.open(infile, "r")) as f:
line = f.read()
fileout.write(line)
fileout.seek(0)
count = 0
for rec in SeqIO.parse(fileout, "fastq"): #parsing from file
count += 1
... | 1 | 2016-07-13T17:28:52Z | 38,374,360 | <p>Just to add to the other answer, if your input sequence is being read from something other than a file (i.e. a web query), then you can use <code>io.StringIO</code> to simulate a file-like object. A StringIO object behaves like a file-handle, but reads/writes from a memory buffer. The input to <code>StringIO()</code... | 1 | 2016-07-14T12:34:42Z | [
"python",
"biopython"
] |
File size increasing after extraction? | 38,358,222 | <p>This is a pretty general question, and I don't even know whether this is the correct community for the question, if not just tell me.</p>
<p>I have recently had an html file from which I was extracting ~90 lines of HTML code (total lines were ~8000). I did this with a simple Python script. I stored my output (the s... | 0 | 2016-07-13T17:30:21Z | 38,359,836 | <p>This code does not write to the original HTML file. Something else must be causing the increased file size .</p>
| 0 | 2016-07-13T19:08:46Z | [
"python",
"html",
"text-files",
"filesize"
] |
Only part of unicode is replacing in python.Don't understand why | 38,358,300 | <pre><code>subject = page.select('div.container h1')
subject = [x.text.replace('2015', '')for x in subject]
print subject
[u'\u20132016 Art Courses']# This is the code after.
[u'2015\u20132016 Art Courses']#This is the code before.
subject = [x.text.replace('20132016', '')for x in subject]
</code></pre>
<p>When I ... | 1 | 2016-07-13T17:35:18Z | 38,358,364 | <p>You don't have the characters "2013" in your string. You have a single character, unicode 2013, ie "â", an en dash. You need to replace that character.</p>
<pre><code>x.text.replace(/u'u20132016', '') for x in subject]
</code></pre>
| 2 | 2016-07-13T17:39:05Z | [
"python",
"string",
"unicode",
"replace"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.