title stringlengths 10 172 | question_id int64 469 40.1M | question_body stringlengths 22 48.2k | question_score int64 -44 5.52k | question_date stringlengths 20 20 | answer_id int64 497 40.1M | answer_body stringlengths 18 33.9k | answer_score int64 -38 8.38k | answer_date stringlengths 20 20 | tags list |
|---|---|---|---|---|---|---|---|---|---|
Python Changing value of XML | 39,170,181 | <p>Hello im using lxml to try and change the value of a specific xml element. Here is my code.</p>
<pre><code>directory = '/Users/eeamesX/work/data/expert/EFTlogs/20160725/IT'
XMLParser = etree.XMLParser(remove_blank_text=True)
for f in os.listdir(directory):
if f.endswith(".xml"):
xmlfile = directory + ... | 0 | 2016-08-26T15:51:29Z | 39,170,343 | <p>looks like you need assignment <code>=</code> not comparison <code>==</code> and the cast to string <code>str()</code> is unnecessary. once you've assigned the value, you'll want to write the result back out to the file:</p>
<pre><code>hardwareRevisionNode.text = "DVT3"
outfile = open(xmlfile, 'w')
oufile.write(e... | 2 | 2016-08-26T16:00:04Z | [
"python",
"xml",
"lxml"
] |
How to make a portion of a Kivy screen scrollable | 39,170,283 | <p>I'm looking to make a page in Python using the Kivy library of the following format</p>
<pre><code> ________________________
| |
| title |
|______________________|
>>| Example 1 |<<
|______________________|
| | |
... | 1 | 2016-08-26T15:57:13Z | 39,176,727 | <p>Yes it is possible, if you get the indentation and size hints right.<br>
<a href="https://kivy.org/docs/api-kivy.uix.scrollview.html" rel="nofollow">ScrollView doc</a> </p>
<p>Try this: </p>
<pre><code><MyLabel@Label>:
size_hint:1,None
<ExampleScreen>:
BoxLayout:
orientation: 'vertic... | 0 | 2016-08-27T01:52:55Z | [
"python",
"kivy",
"kivy-language"
] |
Python Simon Game: I Cannot Make the Command of the Button Work the Way I Need | 39,170,407 | <p>I am working on a Simon Game in Python using Tkinter and I am having problems making work the command of the button.</p>
<p>For the game the activebackground of the button must change from the normal color to another color when clicked and then return to the normal color and I must be able to repeat the action for ... | 1 | 2016-08-26T16:03:43Z | 39,170,502 | <pre><code>import Tkinter
import time
base = Tkinter.Tk()
fr = Tkinter.Frame(base, bg="black", width="238", height="238")
def yellowClick():
yellow.configure(activebackground="yellow")
time.sleep(3)
yellow.configure(activebackground="yellow3")
yellow = Tkinter.Button(base, bd="0", highlightthickness="0",... | 0 | 2016-08-26T16:09:52Z | [
"python",
"tkinter"
] |
Python Simon Game: I Cannot Make the Command of the Button Work the Way I Need | 39,170,407 | <p>I am working on a Simon Game in Python using Tkinter and I am having problems making work the command of the button.</p>
<p>For the game the activebackground of the button must change from the normal color to another color when clicked and then return to the normal color and I must be able to repeat the action for ... | 1 | 2016-08-26T16:03:43Z | 39,170,851 | <blockquote>
<p>but I don't know how to return it after 3 seconds to yellow,</p>
</blockquote>
<p>Tkinter widgets have a method named <code>after</code> for precisely this sort of thing. If you want to change it to a different color in three seconds you can do this:</p>
<pre><code> yellow.configure(activebackground... | 2 | 2016-08-26T16:29:39Z | [
"python",
"tkinter"
] |
Seaborn clustermap within subplot | 39,170,455 | <p>I am trying to plot clustermap and box plots for a dataframe as subplots. I am having trouble plotting the clustermap as subplot as it is a figure level plot. Is there a way to achieve this?</p>
<pre><code>import pandas as pd
import seaborn as sns
# initiliaze a dataframe with index and column names
idf = pd.DataF... | 1 | 2016-08-26T16:06:42Z | 39,170,714 | <p>You should pass the ax as argument of the clustermap function:</p>
<pre><code>cax = sns.clustermap(idf, col_cluster=False, row_cluster=True, ax = ax2)
</code></pre>
<p>As you can see from the documentation of the function clustermap (<a href="https://stanford.edu/~mwaskom/software/seaborn/generated/seaborn.cluster... | -2 | 2016-08-26T16:21:37Z | [
"python",
"matplotlib",
"heatmap",
"seaborn"
] |
Seaborn clustermap within subplot | 39,170,455 | <p>I am trying to plot clustermap and box plots for a dataframe as subplots. I am having trouble plotting the clustermap as subplot as it is a figure level plot. Is there a way to achieve this?</p>
<pre><code>import pandas as pd
import seaborn as sns
# initiliaze a dataframe with index and column names
idf = pd.DataF... | 1 | 2016-08-26T16:06:42Z | 39,173,061 | <p>From @mwaskom 's comment, I read more into the clustermap figure function and realized that I can just replace the column dendrogram image with the boxplot image. However, I would try to find how to add another axis instead of replacing the column dendrogram axis just in case I need to show both row and column dendr... | 0 | 2016-08-26T18:58:10Z | [
"python",
"matplotlib",
"heatmap",
"seaborn"
] |
Use CharField as a string | 39,170,580 | <p>I want to create a model where I just put in two fields and the rest is generated with API requests, the generation I've got but I can't get the CharField in a usable string format.
So on field is:</p>
<pre><code>name = models.CharField(max_length=250, default='default')
</code></pre>
<p>And I want to run it throu... | 1 | 2016-08-26T16:14:14Z | 39,171,582 | <p>I think a custom <code>save</code> will help you accomplish what you are looking to do. Here's an example:</p>
<pre><code>class MyModel(models.Model):
name = models.CharField(max_length=250, default='default')
movieData = models.JSONField(blank=True)
movieYear = models.CharField(max_length=250, blank=Tr... | 0 | 2016-08-26T17:17:31Z | [
"python",
"json",
"django",
"web"
] |
Convert complex roots into standard float form without affecting quality of result | 39,170,624 | <p>I have a transformed stress tensor, its principle values are coming in complex form:</p>
<pre><code>#simple roots calculated by characteristic equation
def princ_cherac(sten):
sxx,syy,szz,sxy,syz,szx = sten
H1 = (sxx+syy+szz)/3.
H2 = (syz**2 + szx**2 + sxy**2 - syy*szz - szz*sxx - sxx-syy)/3.
H3 =... | -1 | 2016-08-26T16:16:09Z | 39,171,366 | <p>There is a mistake in your implementation of <code>H2</code>. You have the last term as <code>sxx-syy</code>, but that should be <code>sxx*syy</code>.</p>
<p>By the way, you'll likely get more accurate results by using <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.linalg.eigvalsh.html" rel="no... | 3 | 2016-08-26T17:03:25Z | [
"python",
"numpy",
"scipy"
] |
how to match two dataFrame in python | 39,170,651 | <p>I have two dataFrame in Python.
The first one is df1:</p>
<pre><code>'ID' 'B'
AA 10
BB 20
CC 30
DD 40
</code></pre>
<p>The second one is df2:</p>
<pre><code> 'ID' 'C' 'D'
BB 30 0
DD 35 0
</code></pre>
<p>What I want to get finally is like df3:</p>
<pre><code>'ID' '... | 1 | 2016-08-26T16:17:31Z | 39,171,009 | <p>Following code will replace zero in df1 with value df2</p>
<pre><code>df1=pd.DataFrame(['A','B',0,4,6],columns=['x'])
df2=pd.DataFrame(['A','X',3,0,5],columns=['x'])
df3=df1[df1!=0].fillna(df2)
</code></pre>
| 0 | 2016-08-26T16:40:47Z | [
"python",
"dataframe"
] |
how to match two dataFrame in python | 39,170,651 | <p>I have two dataFrame in Python.
The first one is df1:</p>
<pre><code>'ID' 'B'
AA 10
BB 20
CC 30
DD 40
</code></pre>
<p>The second one is df2:</p>
<pre><code> 'ID' 'C' 'D'
BB 30 0
DD 35 0
</code></pre>
<p>What I want to get finally is like df3:</p>
<pre><code>'ID' '... | 1 | 2016-08-26T16:17:31Z | 39,171,884 | <p>So first of all, I've interpreted the question differently, since your description is rather ambiguous. Mine boils down to this:</p>
<p>df1 is this data structure:</p>
<pre><code>ID B <- column names
AA 10
BB 20
CC 30
DD 40
</code></pre>
<p>df2 is this data structure:</p>
<pre><code>ID C D... | 0 | 2016-08-26T17:38:11Z | [
"python",
"dataframe"
] |
Finding twin primes in a list and recording the order they appear in | 39,170,731 | <p>I am working on a program right now that has the goal of analyzing twin primes in a certain way(twin primes are primes in the form of(p,p+2)). Right now I have a code that counts the twin primes remainders in % 10 form. </p>
<p>This is that code:</p>
<pre><code>def twin_prime_counter_type10(n):
not_prime = []
... | 2 | 2016-08-26T16:22:34Z | 39,301,617 | <p>assuming that <code>sieve</code> is the <a href="http://stackoverflow.com/questions/3939660/sieve-of-eratosthenes-finding-primes-python">Sieve of Eratosthenes</a>, or <a href="http://stackoverflow.com/questions/2211990/how-to-implement-an-efficient-infinite-generator-of-prime-numbers-in-python">similar</a>, then you... | -1 | 2016-09-02T22:52:23Z | [
"python"
] |
Python ElementTree won't update new file after parsing | 39,170,748 | <p>Using <code>ElementTree</code> to parse attribute's value in an <strong>XML</strong> and writing a new <strong>XML</strong> file. It will console the new updated value and write a new file. But won't update any changes in the new file. Please help me understand what I am doing wrong. Here is <strong>XML</strong> &am... | 1 | 2016-08-26T16:23:31Z | 39,170,960 | <p>When you get the attribute <code>i</code>, and assign it to <code>port_id</code>, you just have a regular Python string. Calling replace on it is just the Python string <code>.replace()</code> method. </p>
<p>You want to use the <a href="https://docs.python.org/2/library/xml.etree.elementtree.html#xml.etree.Element... | 1 | 2016-08-26T16:37:12Z | [
"python",
"xml",
"xml-parsing",
"elementtree"
] |
Transpostion decryption is not working with some keys? | 39,170,837 | <p>Why is this transposition decryption code not working with some keys?</p>
<pre><code>def transencrypt(word,key):
'''Traspositon encryption function. This function is used to encrypt a line
using the transposition encryption method. To know how transpositon encryption
works you can visit here https://en.wikipedi... | 0 | 2016-08-26T16:28:30Z | 39,173,388 | <p>The problem is that the string length (11) doesn't divide evenly into the key (5), so the string <code>"hello world"</code> encodes into the groups <code>h d-ew-lo-lr-ol</code> i.e. <code>"h dewlolrol"</code>. Which is fine, but the decrypt routine chops <code>"h dewlolrol"</code> into <code>h d-ewl-olr-ol</code> a... | 0 | 2016-08-26T19:21:57Z | [
"python",
"python-3.x",
"encryption"
] |
foreign keys for specific primary key django forms | 39,170,841 | <p>I have class Company, Driver and Car</p>
<pre><code>class Company(models.Model):
title = models.CharField(max_length=256)
...
Class Car(models.Model):
...
company = ForeignKey('Company')
class Driver(models.Model):
...
company = ForeignKey('Company')
company_car = OneToOneField('Car')
</code></pre>
<p>Also I... | 1 | 2016-08-26T16:28:46Z | 39,171,612 | <p>On your form field, you can specify a query set for the ModelChoiceField. You haven't given your form, but it could look something like this:</p>
<pre><code>class MyForm(ModelForm):
def __init__(self, *args, **kwargs):
self.fields['car'] = ModelChoiceField(
queryset = Car.objects.filter(compan... | 0 | 2016-08-26T17:19:38Z | [
"python",
"ajax",
"django",
"django-forms"
] |
Print all matching JSON dictionaries in Python | 39,170,917 | <p>I am currently using the AWS Boto3 to try to get a list of all of my current running EC2 instances. I am at the point where I am able to use describe_instances to list all of my instances, but I am trying to figure out how to pull out all of the instance ID's so I can print them AND use them for another part of the ... | 2 | 2016-08-26T16:34:30Z | 39,170,991 | <p>You may achieve is via:</p>
<pre><code>>>> instance_ids = [instance['InstanceId'] for reservations in response['Reservations'] for instance in reservations['Instances']]
>>> instance_ids
['i-6fb4ad61', 'i-afe3faa1']
</code></pre>
<p>where your <code>JSON</code> structure is saved as <code>respons... | 2 | 2016-08-26T16:39:58Z | [
"python",
"json",
"amazon-web-services",
"amazon-ec2",
"boto3"
] |
Print all matching JSON dictionaries in Python | 39,170,917 | <p>I am currently using the AWS Boto3 to try to get a list of all of my current running EC2 instances. I am at the point where I am able to use describe_instances to list all of my instances, but I am trying to figure out how to pull out all of the instance ID's so I can print them AND use them for another part of the ... | 2 | 2016-08-26T16:34:30Z | 39,170,998 | <p>Try this</p>
<pre><code>instance_ids = []
for reservations in response['Reservations']:
for instance in reservations['Instances']:
instance_ids.append(instance['InstanceId'])
</code></pre>
| 2 | 2016-08-26T16:40:15Z | [
"python",
"json",
"amazon-web-services",
"amazon-ec2",
"boto3"
] |
regexp_tokenize and Arabic text | 39,170,944 | <p>I'm using <a href="http://www.nltk.org/_modules/nltk/tokenize/regexp.html" rel="nofollow"><code>regexp_tokenize()</code></a> to return tokens from an Arabic text without any punctuation marks:</p>
<pre><code>import re,string,sys
from nltk.tokenize import regexp_tokenize
def PreProcess_text(Input):
tokens=regexp... | 2 | 2016-08-26T16:35:48Z | 39,234,920 | <p>When you use <code>raw_input</code>, the symbols are coded as bytes.</p>
<p>You need to convert it into a Unicode string with</p>
<pre><code>H.decode('utf8')
</code></pre>
<p>And you may keep your regex:</p>
<pre><code>tokens=regexp_tokenize(Input, r'[ØØ!.Ø]\s*', gaps=True)
</code></pre>
| 1 | 2016-08-30T18:44:38Z | [
"python",
"regex",
"nltk"
] |
Python __init__() how don't override important functionality? | 39,170,964 | <p>I need to add another option in a class, a simple 'edit=False'. Whithout override completely <strong>init</strong>().
I found this piece of code written for kivy:</p>
<pre><code>class TitleBox(BoxLayout):
def __init__(self, **kwargs):
# make sure we aren't overriding any important functionality
... | 1 | 2016-08-26T16:37:27Z | 39,171,358 | <p>Given an <code>__init__</code> signature of:</p>
<pre><code>def __init__(self, edit=False, **kwargs):
</code></pre>
<p>When you do this:</p>
<pre><code>add = Person_Dialog(root, 'Add person')
</code></pre>
<p>Python creates an instance and assigns it to the <code>self</code> argument. Then it assigns <code>root... | 2 | 2016-08-26T17:03:02Z | [
"python",
"tkinter",
"init",
"super"
] |
Match similar item in list | 39,171,087 | <p>I have 2 lists of hostnames</p>
<pre><code>foo=['some-router-1', 'some-switch-1', 'some-switch-2']
bar=['some-router-1-lo','some-switch-1','some-switch-2-mgmt','some-switch-3-mgmt']
</code></pre>
<p>I would expect output to be like...</p>
<pre><code>out=['some-switch-3-mgmt']
</code></pre>
<p>I want to find ent... | 0 | 2016-08-26T16:45:49Z | 39,171,261 | <p>You could do this with a list comprehension and <code>all</code>:</p>
<pre><code>>>> out = [i for i in bar if all(j not in i for j in foo)]
>>> out
['some-switch-3-mgmt']
</code></pre>
<p>Meaning, you select every element <code>i</code> in <code>bar</code> if, for every element <code>j</code>... | 0 | 2016-08-26T16:56:52Z | [
"python",
"list"
] |
Match similar item in list | 39,171,087 | <p>I have 2 lists of hostnames</p>
<pre><code>foo=['some-router-1', 'some-switch-1', 'some-switch-2']
bar=['some-router-1-lo','some-switch-1','some-switch-2-mgmt','some-switch-3-mgmt']
</code></pre>
<p>I would expect output to be like...</p>
<pre><code>out=['some-switch-3-mgmt']
</code></pre>
<p>I want to find ent... | 0 | 2016-08-26T16:45:49Z | 39,171,264 | <p>You may achieve it by using <code>filter</code> as:</p>
<pre><code>>>> filter(lambda x: x if not any(x.startswith(f) for f in foo) else None, bar)
['some-switch-3-mgmt']
</code></pre>
<p>I am using <code>startswith</code> to check whether any element of <code>bar</code> starts with any element of <code>fo... | 0 | 2016-08-26T16:57:03Z | [
"python",
"list"
] |
Match similar item in list | 39,171,087 | <p>I have 2 lists of hostnames</p>
<pre><code>foo=['some-router-1', 'some-switch-1', 'some-switch-2']
bar=['some-router-1-lo','some-switch-1','some-switch-2-mgmt','some-switch-3-mgmt']
</code></pre>
<p>I would expect output to be like...</p>
<pre><code>out=['some-switch-3-mgmt']
</code></pre>
<p>I want to find ent... | 0 | 2016-08-26T16:45:49Z | 39,171,350 | <p>You can use <code>startswith()</code> to see if a string starts with another string. So something like:</p>
<pre><code>out = [bar_string for bar_string in bar if not bar_string.startswith(tuple(foo))]
</code></pre>
| 0 | 2016-08-26T17:02:19Z | [
"python",
"list"
] |
Match similar item in list | 39,171,087 | <p>I have 2 lists of hostnames</p>
<pre><code>foo=['some-router-1', 'some-switch-1', 'some-switch-2']
bar=['some-router-1-lo','some-switch-1','some-switch-2-mgmt','some-switch-3-mgmt']
</code></pre>
<p>I would expect output to be like...</p>
<pre><code>out=['some-switch-3-mgmt']
</code></pre>
<p>I want to find ent... | 0 | 2016-08-26T16:45:49Z | 39,172,151 | <p>There is some problems with the solutions provided by @Jim and @bbkglb when the elements are repeated in <strong><em>bar</em></strong>. Those solutions should be converted to <strong><em>sets</em></strong>. I tested the solutions and their response times:</p>
<pre><code>foo=['some-router-1', 'some-switch-1', 'some-... | 0 | 2016-08-26T17:57:17Z | [
"python",
"list"
] |
Error on Keras SimpleRNN when input_shape is specified to be 3-d | 39,171,170 | <p>I'm doing trying to train from text on a SimpleRNN on Keras.</p>
<p>In Keras, i specified a very simple parameters for SimpleRNN as below:</p>
<pre><code>model = Sequential()
model.add(SimpleRNN(output_dim=1, input_shape=(1,1,1))
</code></pre>
<p>I understand that input_shape should be (nb_samples, timesteps, inp... | 2 | 2016-08-26T16:51:00Z | 39,183,717 | <p>You are not supposed to include <code>n_samples</code> in the input shape of the model. So you have to specify a tuple of size 2 for input shape of a your layer (or set the first element of shape to <code>None</code>). Here Keras automatically adds <code>None</code> to your input shape resulting in <code>ndim=4</cod... | 0 | 2016-08-27T17:11:12Z | [
"python",
"neural-network",
"theano",
"keras",
"recurrent-neural-network"
] |
Appending data with additional information to text in a file | 39,171,182 | <p>I have a text file containing thousands of lines of code and I would like to replace certain elements as follows:</p>
<p>Text from file1:</p>
<pre><code>serverfarm host foobar2:443
failaction reassign
probe tcp111-probe
rserver foobar1 443
rserver foobar2 443
</code></pre>
<p>Text with additional informat... | 0 | 2016-08-26T16:52:23Z | 39,171,964 | <p>The idea is to write a custom parser/translator like the following:</p>
<pre><code>replacements = {}
with open('file2.txt') as f:
for l in f:
l = l.strip()
if l.startswith('rserver'):
server_header = l
server = l.split()
server_name = server[2]
elif 'i... | 1 | 2016-08-26T17:43:45Z | [
"python"
] |
Appending data with additional information to text in a file | 39,171,182 | <p>I have a text file containing thousands of lines of code and I would like to replace certain elements as follows:</p>
<p>Text from file1:</p>
<pre><code>serverfarm host foobar2:443
failaction reassign
probe tcp111-probe
rserver foobar1 443
rserver foobar2 443
</code></pre>
<p>Text with additional informat... | 0 | 2016-08-26T16:52:23Z | 39,172,000 | <p>If you are running a Linux distro, then you can use awk command and pipe it with grep.</p>
<p>If you want a solution with python, then the complexity is going to be O(n.m), where n is the number of lines in first file and m is the number of lines in second file.</p>
<p>Algorithm in python:</p>
<pre><code>open a n... | 0 | 2016-08-26T17:46:01Z | [
"python"
] |
Appending data with additional information to text in a file | 39,171,182 | <p>I have a text file containing thousands of lines of code and I would like to replace certain elements as follows:</p>
<p>Text from file1:</p>
<pre><code>serverfarm host foobar2:443
failaction reassign
probe tcp111-probe
rserver foobar1 443
rserver foobar2 443
</code></pre>
<p>Text with additional informat... | 0 | 2016-08-26T16:52:23Z | 39,172,007 | <p>Yes, you can use a dictionary or <a href="https://docs.python.org/2/library/collections.html#collections.defaultdict" rel="nofollow"><code>defaultdict</code></a> to map server names from the second file and their list of details (ip and service status) and insert these details while writing into a new file:</p>
<pr... | 1 | 2016-08-26T17:46:23Z | [
"python"
] |
FileNotFoundError: [Errno 2] No such file or directory: 'userDetails' | 39,171,257 | <p>My program needs to read an external Notepad (.txt) file which has usernames and passwords. (Both the program and the document are on my desktop.) I used this code to read it.</p>
<pre><code>file = open ("userDetails.txt", "r")
userDetails = file.readlines()
file.close()
</code></pre>
<p>But I keep getting this ... | 0 | 2016-08-26T16:56:39Z | 39,171,293 | <p>Try and specify the full file path to the text file when you open it:</p>
<p>i.e <code>/full/path/to/file.txt</code> such as <code>/Users/Harrison/Desktop/file.txt</code></p>
<p>Right now it's likely that Python is looking for the file in the default Python working directory.</p>
<p>Also, it's a better practice w... | 1 | 2016-08-26T16:58:56Z | [
"python"
] |
FileNotFoundError: [Errno 2] No such file or directory: 'userDetails' | 39,171,257 | <p>My program needs to read an external Notepad (.txt) file which has usernames and passwords. (Both the program and the document are on my desktop.) I used this code to read it.</p>
<pre><code>file = open ("userDetails.txt", "r")
userDetails = file.readlines()
file.close()
</code></pre>
<p>But I keep getting this ... | 0 | 2016-08-26T16:56:39Z | 39,171,605 | <p>I think your userDetails.txt does not reside in the python script working directory. So you have to specify your file names for input and output like e.g.:</p>
<pre><code># ----------------------------------------
# open file and select coordinates
# ----------------------------------------
pathnameIn = "D:/local/p... | 0 | 2016-08-26T17:19:17Z | [
"python"
] |
Issue with Sum of Odd Numbers Code | 39,171,284 | <p>I know that there are other post on this and I have referred to them but I can't seem to figure this one out.</p>
<p>This code gives me the value 2500, just 2500.</p>
<pre><code>sum = 0;
for i in range (1,100):
if i % 2 == 1:
sum = sum + i;
print (sum)
</code></pre>
<p>However I want the range to vary... | 2 | 2016-08-26T16:58:06Z | 39,171,309 | <p>Python considers that the return code is <code>None</code> for functions not returning anything</p>
<p>You actually have to RETURN sum not print it in your function </p>
<pre><code>def odd_sum_n(n):
sum = 0;
for i in range(1,2*n):
if i % 2 != 0:
sum += i;
return (sum)
print(odd_sum... | 5 | 2016-08-26T16:59:57Z | [
"python"
] |
Issue with Sum of Odd Numbers Code | 39,171,284 | <p>I know that there are other post on this and I have referred to them but I can't seem to figure this one out.</p>
<p>This code gives me the value 2500, just 2500.</p>
<pre><code>sum = 0;
for i in range (1,100):
if i % 2 == 1:
sum = sum + i;
print (sum)
</code></pre>
<p>However I want the range to vary... | 2 | 2016-08-26T16:58:06Z | 39,171,360 | <p>You are not returning any value from your odd_sum(n) function that's why it print None.</p>
| 0 | 2016-08-26T17:03:08Z | [
"python"
] |
Issue with Sum of Odd Numbers Code | 39,171,284 | <p>I know that there are other post on this and I have referred to them but I can't seem to figure this one out.</p>
<p>This code gives me the value 2500, just 2500.</p>
<pre><code>sum = 0;
for i in range (1,100):
if i % 2 == 1:
sum = sum + i;
print (sum)
</code></pre>
<p>However I want the range to vary... | 2 | 2016-08-26T16:58:06Z | 39,171,394 | <p>This program illustrates why you get <code>2500</code> printed</p>
<pre><code>def print2500():
print(2500)
print2500()
</code></pre>
<p>And this one why you get <code>None</code> printed</p>
<pre><code>def doNotReturnAnything():
n = 2500
print(doNotReturnAnything())
</code></pre>
<p>Combine both and you ge... | 0 | 2016-08-26T17:05:49Z | [
"python"
] |
Issue with Sum of Odd Numbers Code | 39,171,284 | <p>I know that there are other post on this and I have referred to them but I can't seem to figure this one out.</p>
<p>This code gives me the value 2500, just 2500.</p>
<pre><code>sum = 0;
for i in range (1,100):
if i % 2 == 1:
sum = sum + i;
print (sum)
</code></pre>
<p>However I want the range to vary... | 2 | 2016-08-26T16:58:06Z | 39,172,447 | <p>you want to get the value from your <code>def odd_sum_n(n)</code> for that you need to <code>return(sum)</code> and then just <code>print(odd_sum_n(n))</code> this will only print your answer.
you are getting <code>none</code> because you are trying to print two times one time in <code>def</code> and other time in ... | 1 | 2016-08-26T18:17:16Z | [
"python"
] |
writing pandas series into tab separated file | 39,171,396 | <p>I have a pandas series y which I generated by group by and looks like </p>
<pre><code>Item Attribute Feature
aaaa x1 f1,f2
x2 f3,f4
bbbb x3 f5
x4 f6
</code></pre>
<p>I want to generate a tab delimted output that looks exactly as above. When I try</p>
<pre><code... | 2 | 2016-08-26T17:05:56Z | 39,171,557 | <p>The text you want isn't <code>csv</code>.</p>
<p>Assume <code>df</code> is your dataframe or series:</p>
<pre><code>with open('out.txt', 'w') as f:
f.write(df.__repr__())
</code></pre>
<hr>
<h3><code>to_txt</code> function</h3>
<pre><code>import pandas as pd
def to_txt(df, fn=None):
x, c, r = ['expand_... | 1 | 2016-08-26T17:16:13Z | [
"python",
"pandas"
] |
Apply a split and take second element of result in Pandas column that sometimes contains None and sometimes does not split into more than 1 component | 39,171,399 | <p>I am looking at an email sender data column that looks like this:</p>
<pre><code>from_name
----------
Joe Smith, VP at Corp
Alice Brown
None
Helpdesk, McRay's Store
</code></pre>
<p>From this, I'd like to generate a column like this:</p>
<pre><code>title_if_any
-------------
VP at Corp
None
None
McRay's Store
</c... | 3 | 2016-08-26T17:06:03Z | 39,171,519 | <p>you can do <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.split.html" rel="nofollow">str.split()</a>:</p>
<pre><code>In[53]:df['title_if_any']=df.from_name.str.split(',',expand=True)[1]
In[54]:df
Out[54]:
0 VP at Corp
1 None
2 None
... | 3 | 2016-08-26T17:13:31Z | [
"python",
"pandas"
] |
Python scraping: 403 and 503 Errors | 39,171,510 | <p>I am trying to crawl some public information(apple app's info) on a website. </p>
<p>This website requires log-in in order to perform actions such as "search app/developer". Although there are many website provide similar information, but I consider this particular website provides the most complete and detailed in... | 1 | 2016-08-26T17:13:05Z | 39,171,938 | <p>plain python requests package is enough, you shouldn't need other packages.</p>
<p>I'm sure your problem is just you're not perfectly emulating a browser request.
On Google Chrome and Mozilla Firefox you should be able to see requests headers from a developer panel.</p>
<p>Be sure you always use the <strong>same</... | 0 | 2016-08-26T17:42:24Z | [
"python",
"web-crawler",
"http-error"
] |
Ubuntu , Apache2 , Django ) Fatal Python error: Py_Initialize: Unable to get the locale encoding ImportError: No module named 'encodings' | 39,171,616 | <p>I'm trying to set up my <strong>django(1.8)</strong> application with <strong>AWS EC2</strong> having <strong>Ubuntu 14.04 , Apache2 , python 3.4.</strong></p>
<p>When I run 'sudo service apache2 start' , the page keeps re-loading and the same error message is stacking at '/var/log/apache2/error.log'.</p>
<p>The e... | 0 | 2016-08-26T17:19:59Z | 39,172,342 | <p>It was because of the line 'WSGIPythonHome /usr/bin/pytyon3.4' in /etc/apache2/httpd.conf.</p>
<p>Without this line, it runs without error thank you</p>
| 0 | 2016-08-26T18:09:59Z | [
"python",
"django",
"apache",
"ubuntu",
"mod-wsgi"
] |
Adding docstring to __slots__ descriptor? | 39,171,672 | <p>I'm writing a storage automation module that provisions volumes. Instead of passing the half dozen or more arguments needed to actually create a volume on the storage controller, I created a parameter class using <code>__slots__</code> that is passed into the create method like this:</p>
<pre><code>from mock import... | 2 | 2016-08-26T17:23:46Z | 39,171,830 | <p>No, there is no option to add docstrings to the descriptor objects that are generated for names defined in <code>__slots__</code>. They are like regular non-descriptor attributes in that regard.</p>
<p>On a regular object without slots, you can, at most, add comments and set default values:</p>
<pre><code>class Vo... | 3 | 2016-08-26T17:33:48Z | [
"python"
] |
django: is it possible to keep a model field updated with a model method? | 39,171,685 | <p>So basically I have a model Equipment that has foreign key calibration. I would like to have a field in Equipment as 'latest_calibrated_date' which get the 'cal_date' from the newest created calibration. Here is what I have now:</p>
<pre><code>def latest_calibration_date(self):
return Calibration.objects.fi... | 0 | 2016-08-26T17:24:20Z | 39,172,567 | <p>As <em>Daniel Roseman</em> pointed out, you can override <code>save</code> method on <code>Calibration</code> model. For example:</p>
<pre><code>class Calibration(model.Model):
# your fields
def save(self, *args, **kwargs):
super(Calibration, self).save(*args, **kwargs)
# update latest cal... | 1 | 2016-08-26T18:24:13Z | [
"python",
"django"
] |
How to add each item in a list to the previous one in Python? | 39,171,764 | <p>I have a list and I want to add each element in the list to the previous one. For example if I have the list <code>(1,1,3,3,4)</code>, I want the program to output <code>(1,2,5,8,12)</code>. </p>
| 1 | 2016-08-26T17:29:10Z | 39,171,796 | <pre><code>[sum(a[:i]) for i in range(1,len(a)+1)]
</code></pre>
<p>is probably the easiest way ... I guess ...</p>
<pre><code>numpy.cumsum(a)
</code></pre>
<p>would also work i think</p>
| 2 | 2016-08-26T17:31:54Z | [
"python",
"list"
] |
How to add each item in a list to the previous one in Python? | 39,171,764 | <p>I have a list and I want to add each element in the list to the previous one. For example if I have the list <code>(1,1,3,3,4)</code>, I want the program to output <code>(1,2,5,8,12)</code>. </p>
| 1 | 2016-08-26T17:29:10Z | 39,171,876 | <pre><code>for i in range(1, len(arr)):
arr[i] += arr[i - 1]
</code></pre>
<p>more efficient than Joran Beasley loop</p>
| 1 | 2016-08-26T17:37:00Z | [
"python",
"list"
] |
How to add each item in a list to the previous one in Python? | 39,171,764 | <p>I have a list and I want to add each element in the list to the previous one. For example if I have the list <code>(1,1,3,3,4)</code>, I want the program to output <code>(1,2,5,8,12)</code>. </p>
| 1 | 2016-08-26T17:29:10Z | 39,171,897 | <p>using <a href="https://docs.python.org/3/library/itertools.html#itertools.accumulate" rel="nofollow"><code>itertools.accumulate</code></a></p>
<pre><code>>>> import itertools
>>> list(itertools.accumulate([1,1,3,3,4], lambda total,el: total+el))
[1, 2, 5, 8, 12]
</code></pre>
<p><em>disclaimer</e... | 2 | 2016-08-26T17:38:57Z | [
"python",
"list"
] |
How do I properly avoid the usage of a delimiter in a custom string? | 39,171,765 | <p>I am currently working on a Discord Bot that interacts with my gameserver through rcon and came across a problem.</p>
<p>I have two functions. This is for the bot to recognize a command (e.g. '.say Hello World')</p>
<pre><code>@bot.command(pass_context=True, aliases=[])
@asyncio.coroutine
def say(context, *, msg):... | 0 | 2016-08-26T17:29:15Z | 39,171,841 | <p>you should instead make your delimiter an unprintable character like <code>'\x00'</code> ... that would easily solve the issue ...</p>
| 0 | 2016-08-26T17:34:35Z | [
"python",
"security",
"python-3.5"
] |
Fastest way to convert a URI into a scheme relative URI (in python) | 39,171,815 | <p>In python, whats the <em>fastest</em> way to convert a url of the type <code>scheme://netloc/path;parameters?query#fragment</code> into a "scheme relative" or "protocol relative" URI?</p>
<hr>
<p>Currently, I'm doing a version of <a href="http://stackoverflow.com/a/21687728/4936905">this</a>, but was thinking ther... | 0 | 2016-08-26T17:32:43Z | 39,171,886 | <pre><code>from urlparse import urlparse
o = urlparse('http://www.cwi.nl:80/%7Eguido/Python.html')
print o.scheme
print o.netloc
print o.path
</code></pre>
<p>is how i would probably do it ...</p>
| 0 | 2016-08-26T17:38:12Z | [
"python"
] |
Fastest way to convert a URI into a scheme relative URI (in python) | 39,171,815 | <p>In python, whats the <em>fastest</em> way to convert a url of the type <code>scheme://netloc/path;parameters?query#fragment</code> into a "scheme relative" or "protocol relative" URI?</p>
<hr>
<p>Currently, I'm doing a version of <a href="http://stackoverflow.com/a/21687728/4936905">this</a>, but was thinking ther... | 0 | 2016-08-26T17:32:43Z | 39,172,526 | <p>The fastest way that I could find is with <code>str.partition</code>:</p>
<pre><code>In [1]: url = 'https://netloc/path;parameters?query#fragment'
In [2]: %timeit url.partition('://')[2]
The slowest run took 6.70 times longer than the fastest. This could mean that an intermediate result is being cached.
1000000 lo... | 1 | 2016-08-26T18:21:35Z | [
"python"
] |
In Python, how to get a localized timestamp with only the datetime package? | 39,171,908 | <p>I have a unix timestamp in seconds (such as <code>1294778181</code>) that I can convert to UTC using </p>
<pre><code>from datetime import datetime
datetime.utcfromtimestamp(unix_timestamp)
</code></pre>
<p>Problem is, I would like to get the corresponding time in <code>'US/Eastern'</code> (considering any DST) and... | 1 | 2016-08-26T17:39:28Z | 39,174,019 | <p>Easiest, but not supersmart solution is using timedelta</p>
<pre><code>import datetime
>>> now = datetime.datetime.utcnow()
</code></pre>
<p>US/Eastern is 5 hours behind UTC, so let's just create thouse five hours as a timedelta object and make it negative, so that when reading back our code we can see th... | 1 | 2016-08-26T20:12:12Z | [
"python",
"datetime",
"epoch",
"python-datetime"
] |
Python Script to filter arrays containing a specific value in JSON object | 39,171,919 | <p>I have a json object that consists of one object with key 'data', that has values listed in a set of arrays. I need to return all arrays that contain the value x, but the arrays themselves do not have keys. I'm trying to write a script to enter a source file (inFile) an define an export file (outFile). Here is my da... | 1 | 2016-08-26T17:40:08Z | 39,172,228 | <p>First problem the query string will be true for everything (aka return the whole data set back since you are comparing b (a list) to 'x' a string</p>
<pre><code> b = [b for b in a if b != 'x' ]
</code></pre>
<p>What you wanted to do was:</p>
<pre><code> b = [b for b in a if b[0] != 'x' ]
</code></pre>
<p>The s... | 1 | 2016-08-26T18:02:10Z | [
"python",
"arrays",
"json"
] |
Python Script to filter arrays containing a specific value in JSON object | 39,171,919 | <p>I have a json object that consists of one object with key 'data', that has values listed in a set of arrays. I need to return all arrays that contain the value x, but the arrays themselves do not have keys. I'm trying to write a script to enter a source file (inFile) an define an export file (outFile). Here is my da... | 1 | 2016-08-26T17:40:08Z | 39,172,394 | <p>So, basically you want to filter out your input data containing arrays whose first element is 'x', maybe something like this will do:</p>
<pre><code>import json
def jsonFilter(inFile, outFile):
with open(inFile, 'r') as jsonFile:
d = json.loads(json_data)
out = {
'data': filter(la... | 1 | 2016-08-26T18:14:00Z | [
"python",
"arrays",
"json"
] |
Cannot connect to MySql in Docker. Access Denied Error thrown. Flask-SqlAlchemy | 39,171,970 | <p>Alright so been trying for a while to get this to work. Here is the line of commands I run from start to finish and I get an <code>Access denied...</code> error shown below.</p>
<pre><code>$ docker-compose up --build -d
$ docker exec -it flaskdocker_mysql_1 mysql -u root -p
mysql> CREATE DATABASE flask_docker;
m... | 3 | 2016-08-26T17:44:07Z | 39,172,183 | <p>It seems the problem there:</p>
<p><code>mysql> GRANT ALL PRIVILEGES ON flask_docker.* TO 'flask-docker'@'localhost';</code>
You grant privileges for <strong>localhost</strong> user</p>
<p>But you use mysql as <code>flask-docker'@'flaskdocker_web_1.flaskdocker_default</code> user.</p>
<p>To solve this grant us... | 3 | 2016-08-26T17:59:37Z | [
"python",
"docker",
"flask",
"flask-sqlalchemy",
"docker-compose"
] |
Pandas Python - get value counts by grouped values | 39,172,047 | <p>I have a situation where multiple customer ids can be belong to the same account, and all records are grouped in to one of two groups:</p>
<pre><code>CUSTOMER_ACCOUNT_ID CUSTOMER_ID GROUP
123 555 A
123 556 A
124 557 B
124 ... | 2 | 2016-08-26T17:49:06Z | 39,172,127 | <p>You can use the <code>nunique()</code> method after the grouping:</p>
<pre><code>df.groupby('GROUP')['CUSTOMER_ACCOUNT_ID'].nunique().reset_index()
# GROUP CUSTOMER_ACCOUNT_ID
# 0 A 2
# 1 B 1
</code></pre>
| 3 | 2016-08-26T17:55:07Z | [
"python",
"pandas",
"group-by"
] |
Pandas Python - get value counts by grouped values | 39,172,047 | <p>I have a situation where multiple customer ids can be belong to the same account, and all records are grouped in to one of two groups:</p>
<pre><code>CUSTOMER_ACCOUNT_ID CUSTOMER_ID GROUP
123 555 A
123 556 A
124 557 B
124 ... | 2 | 2016-08-26T17:49:06Z | 39,172,386 | <p>Is this what you want to achieve? </p>
<pre><code>In [103]: df.drop_duplicates(['CUSTOMER_ACCOUNT_ID', 'GROUP']).drop('CUSTOMER_ID', 1)
Out[103]:
CUSTOMER_ACCOUNT_ID GROUP
0 123 A
2 124 B
4 125 A
</code></pre>
| 2 | 2016-08-26T18:13:30Z | [
"python",
"pandas",
"group-by"
] |
Pandas dataframe replace | 39,172,068 | <p>New to Pandas and python and have a question on replacing multiple unicode characters within an entire data frame. Using python 2.7 and importing from an excel sheet. My desire is to replace all non-ascii characters with their ascii equivalent or nothing.</p>
<p>examples:<br>
u'SHOGUN JAPANESE \u2013 GRAND'<br>
u... | 2 | 2016-08-26T17:50:43Z | 39,172,455 | <p>You can do an encode/decode cycle like so:</p>
<pre><code>rawdf["Account_Name"].str..encode('ascii', 'ignore').str.decode('ascii')
</code></pre>
<p>The use of 'ignore' makes characters that cannot be represented in ascii be dropped. The intermediate representation is bytes, so we need to encode it back to strings ... | 1 | 2016-08-26T18:17:47Z | [
"python"
] |
Python writing to an xml file | 39,172,079 | <p>I am trying to write to an xml file. I have changed a specific element in my code, and am able to get it to print successfully. I need to have it written to the file, without changing the structure of the file.<br>
My code:</p>
<p>import os
from lxml import etree</p>
<pre><code>directory = '/Users/eeamesX/work/d... | 1 | 2016-08-26T17:51:24Z | 39,172,181 | <p>To get newlines in the output file, it looks like you need to pass <a href="http://lxml.de/tutorial.html#serialisation" rel="nofollow"><code>pretty_print=True</code></a> to your sterilization (<code>write</code> or <code>tostring</code>) call.</p>
<p>Side note; Normally, when you open files with python you open the... | 1 | 2016-08-26T17:59:35Z | [
"python",
"xml",
"lxml",
"elementtree"
] |
Python writing to an xml file | 39,172,079 | <p>I am trying to write to an xml file. I have changed a specific element in my code, and am able to get it to print successfully. I need to have it written to the file, without changing the structure of the file.<br>
My code:</p>
<p>import os
from lxml import etree</p>
<pre><code>directory = '/Users/eeamesX/work/d... | 1 | 2016-08-26T17:51:24Z | 39,172,361 | <p>If you are wanting to replace a value within an existing XML file then use:</p>
<pre><code>tree.write(xmlfile)
</code></pre>
<p>Currently you are simply overwriting your file entirely and using the incorrect method (<code>open()</code>). <code>tree.write()</code> is normally what you would want to use. It might l... | 1 | 2016-08-26T18:11:46Z | [
"python",
"xml",
"lxml",
"elementtree"
] |
How can I dynamically create ttk widgets depending on the value entered in a ttk.entry box? | 39,172,143 | <p>I am trying to make a GUI where as soon as the user inputs an integer into a <code>ttk.entry</code> field, that many checkbuttons need to appear below it. For example, if they put "5" into the entry widget, 5 check buttons need to appear below the entry field.</p>
<p>Edit:</p>
<p>What I ended up using:</p>
<pre><... | -2 | 2016-08-26T17:56:27Z | 39,230,126 | <p>take a look at the below and let me know what you think...</p>
<p>A very ugly, super basic example:</p>
<pre><code>from Tkinter import *
root = Tk()
root.geometry('200x200')
root.grid_rowconfigure(0, weight = 1)
root.grid_columnconfigure(0, weight = 1)
win1 = Frame(root, bg= 'blue')
win1.grid(row=0, column=0, st... | 1 | 2016-08-30T14:22:33Z | [
"python",
"python-2.7",
"tkinter"
] |
Python: lxml not pretty-printing newly added nodes | 39,172,188 | <p>I'm using a Python script to add nodes (or copy existing nodes) in an XML file. The script uses lxml library. Here is existing snippet:</p>
<pre><code><entitlements>
<bpuiEnabledForSubusers>true</bpuiEnabledForSubusers>
<appCodesAllowedForSubusers>My Accounts,Bill Pay</appCodesAl... | 0 | 2016-08-26T17:59:50Z | 39,172,248 | <p><code>pretty_print=True</code> only has useful effect when your tree doesn't have trailing whitespace on the nodes already. Thus, you want to look at not just how your emit them, but how you're parsing them in the first place.</p>
<p>Use the <code>remove_blank_text=True</code> parser option:</p>
<pre><code>parser ... | 1 | 2016-08-26T18:03:45Z | [
"python",
"xml",
"lxml"
] |
Can a line of Python code know its indentation nesting level? | 39,172,306 | <p>From something like this:</p>
<pre><code>print(get_indentation_level())
print(get_indentation_level())
print(get_indentation_level())
</code></pre>
<p>I would like to get something like this:</p>
<pre><code>1
2
3
</code></pre>
<p>Can the code read itself in this way?</p>
<p>All I want is the outpu... | 139 | 2016-08-26T18:07:24Z | 39,172,459 | <pre><code>>>> import inspect
>>> help(inspect.indentsize)
Help on function indentsize in module inspect:
indentsize(line)
Return the indent size, in spaces, at the start of a line of text.
</code></pre>
| 5 | 2016-08-26T18:18:02Z | [
"python",
"reflection",
"metaprogramming",
"indentation",
"tokenize"
] |
Can a line of Python code know its indentation nesting level? | 39,172,306 | <p>From something like this:</p>
<pre><code>print(get_indentation_level())
print(get_indentation_level())
print(get_indentation_level())
</code></pre>
<p>I would like to get something like this:</p>
<pre><code>1
2
3
</code></pre>
<p>Can the code read itself in this way?</p>
<p>All I want is the outpu... | 139 | 2016-08-26T18:07:24Z | 39,172,520 | <p>You can use <code>sys.current_frame.f_lineno</code> in order to get the line number. Then in order to find the number of indentation level you need to find the previous line with zero indentation then be subtracting the current line number from that line's number you'll get the number of indentation:</p>
<pre><code... | 9 | 2016-08-26T18:21:24Z | [
"python",
"reflection",
"metaprogramming",
"indentation",
"tokenize"
] |
Can a line of Python code know its indentation nesting level? | 39,172,306 | <p>From something like this:</p>
<pre><code>print(get_indentation_level())
print(get_indentation_level())
print(get_indentation_level())
</code></pre>
<p>I would like to get something like this:</p>
<pre><code>1
2
3
</code></pre>
<p>Can the code read itself in this way?</p>
<p>All I want is the outpu... | 139 | 2016-08-26T18:07:24Z | 39,172,552 | <p>Yeah, that's definitely possible, here's a working example:</p>
<pre><code>import inspect
def get_indentation_level():
callerframerecord = inspect.stack()[1]
frame = callerframerecord[0]
info = inspect.getframeinfo(frame)
cc = info.code_context[0]
return len(cc) - len(cc.lstrip())
if 1:
pr... | 22 | 2016-08-26T18:23:18Z | [
"python",
"reflection",
"metaprogramming",
"indentation",
"tokenize"
] |
Can a line of Python code know its indentation nesting level? | 39,172,306 | <p>From something like this:</p>
<pre><code>print(get_indentation_level())
print(get_indentation_level())
print(get_indentation_level())
</code></pre>
<p>I would like to get something like this:</p>
<pre><code>1
2
3
</code></pre>
<p>Can the code read itself in this way?</p>
<p>All I want is the outpu... | 139 | 2016-08-26T18:07:24Z | 39,172,845 | <p>If you want indentation in terms of nesting level rather than spaces and tabs, things get tricky. For example, in the following code:</p>
<pre><code>if True:
print(
get_nesting_level())
</code></pre>
<p>the call to <code>get_nesting_level</code> is actually nested one level deep, despite the fact that there is... | 104 | 2016-08-26T18:41:27Z | [
"python",
"reflection",
"metaprogramming",
"indentation",
"tokenize"
] |
Can a line of Python code know its indentation nesting level? | 39,172,306 | <p>From something like this:</p>
<pre><code>print(get_indentation_level())
print(get_indentation_level())
print(get_indentation_level())
</code></pre>
<p>I would like to get something like this:</p>
<pre><code>1
2
3
</code></pre>
<p>Can the code read itself in this way?</p>
<p>All I want is the outpu... | 139 | 2016-08-26T18:07:24Z | 39,191,937 | <p>To solve the ârealâ problem that lead to your question you could implement a contextmanager which keeps track of the indention level and make the <code>with</code> block structure in the code correspond to the indentation levels of the output. This way the code indentation still reflects the output indentation w... | 6 | 2016-08-28T13:46:19Z | [
"python",
"reflection",
"metaprogramming",
"indentation",
"tokenize"
] |
Script to check a page | 39,172,390 | <p>I have a script that alerts me by mail when a phrase changes on a web page. I tried many things, but I can't fix the <strong>isAvailable()</strong> function: the script says "not available" every time, whether or not I give it an available server. Have you any clues?</p>
<pre><code># CONFIG
TARGET_KIMSUFI_ID = "1... | -1 | 2016-08-26T18:13:46Z | 39,173,556 | <p>Your <code>isAvailable()</code> function returns <code>True</code> if the website is available, <code>False</code> otherwise. You should change the <code>if</code> statement to:</p>
<pre><code>if not isAvailable():
...
</code></pre>
| 1 | 2016-08-26T19:33:32Z | [
"python"
] |
How to save a pandas dataframe such that there is no delimiter? | 39,172,403 | <p>I have the following pandas dataframe:</p>
<pre><code>import pandas as pd
df = pd.DataFrame(np.random.choice([0,1], (6,3)), columns=list('XYZ'))
X Y Z
0 1 0 1
1 1 1 0
2 0 0 0
3 0 1 1
4 0 1 1
5 1 1 1
</code></pre>
<p>Let's say I take the transpose and wish to save it</p>
<pre><code>df = df.... | 2 | 2016-08-26T18:14:39Z | 39,172,436 | <p>Leave original <code>df</code> alone. Don't transpose.</p>
<pre><code>df = pd.DataFrame(np.random.choice([0,1], (6,3)), columns=list('XYZ'))
df.astype(str).apply(''.join)
X 101100
Y 101001
Z 111110
dtype: object
</code></pre>
| 2 | 2016-08-26T18:16:54Z | [
"python",
"csv",
"pandas",
"dataframe"
] |
How to save a pandas dataframe such that there is no delimiter? | 39,172,403 | <p>I have the following pandas dataframe:</p>
<pre><code>import pandas as pd
df = pd.DataFrame(np.random.choice([0,1], (6,3)), columns=list('XYZ'))
X Y Z
0 1 0 1
1 1 1 0
2 0 0 0
3 0 1 1
4 0 1 1
5 1 1 1
</code></pre>
<p>Let's say I take the transpose and wish to save it</p>
<pre><code>df = df.... | 2 | 2016-08-26T18:14:39Z | 39,172,527 | <p>If you do want to transpose, then you can do something like this:</p>
<pre><code>In [126]: df.T.apply(lambda row: ''.join(map(str, row)), axis=1)
Out[126]:
X 001111
Y 000000
Z 010010
dtype: object
</code></pre>
| 1 | 2016-08-26T18:21:36Z | [
"python",
"csv",
"pandas",
"dataframe"
] |
How to include your hostname in the IPython 5 prompt? | 39,172,421 | <p>In previous version of IPython it was easy to include your hostname in the prompt, by including the following in your config:</p>
<pre><code>c.PromptManager.in_template = '(\H) In [\\#]: '
</code></pre>
<p>(the <code>\H</code> would be substituted with your hostname).</p>
<p>However, the <code>PromptManager</code... | 1 | 2016-08-26T18:15:56Z | 39,172,422 | <p>As the warning indicates, you should use the new <code>TerminalInteractiveShell.prompts_class</code>. So to include your hostname in your prompt you can drop the following in your config:</p>
<pre><code>from IPython.terminal.prompts import Prompts, Token
import socket
class MyPrompt(Prompts):
def __init__(sel... | 2 | 2016-08-26T18:15:56Z | [
"python",
"ipython"
] |
Python Update random field choice function from OrderedDict Class | 39,172,467 | <p>I'm trying to do a script that choose a string and update a current field, but for some reason the code doesn't update the last value when calling my <code>changerandom</code> function in the <code>Greeting</code> class.</p>
<pre><code>...[snip]...
class Greeting(Packet):
fields = OrderedDict([
("Morni... | 0 | 2016-08-26T18:18:25Z | 39,172,687 | <p>The problem is that you're <code>return</code>ing a result, without assigning it anywhere.</p>
<p>You also use the <em>value</em> of <code>fields</code>, rather than the <em>key</em>. So, your code should be something like </p>
<pre><code>def changerandom(self, n = 1):
function=[
{"Mo... | 0 | 2016-08-26T18:30:25Z | [
"python",
"string",
"function"
] |
Python: How to interpolate errors using scipy interpolate.interp1d | 39,172,559 | <p>I have a number of data sets, each containing <em>x, y</em>, and <em>y_error</em> values, and I'm simply trying to calculate the average value of <em>y</em> at each <em>x</em> across these data sets. However the data sets are not quite the same length. I thought the best way to get them to an equal length would be t... | 0 | 2016-08-26T18:23:45Z | 39,174,418 | <p>As long as you can assume that your errors represent one-sigma intervals of normal distributions, you can always generate synthetic datasets, resample and interpolate those, and compute the 1-sigma errors of the results.</p>
<p>Or just interpolate values+err and values-err, if all you need is a quick and dirty roug... | 0 | 2016-08-26T20:47:17Z | [
"python",
"scipy",
"interpolation"
] |
Python: When do two variables point at the same object in memory? | 39,172,565 | <p>Here is an example:</p>
<pre><code>l = [1, 5, 9, 3]
h = l
h[0], h[2] = h[2], h[0]
print(h) # [9, 5, 1, 3]
print(l) # [9, 5, 1, 3]
h = h*2
print(h) # [9, 5, 1, 3, 9, 5, 1, 3]
print(l) # [9, 5, 1, 3]
</code></pre>
<p>My understanding was that calling setting <code>h = l</code> would simply point <code>h</code> at... | 6 | 2016-08-26T18:24:03Z | 39,172,629 | <p>That's quite simple to check, run this simple test:</p>
<pre><code>l = [1, 5, 9, 3]
h = l
h[0], h[2] = h[2], h[0]
print(h) # [9, 5, 1, 3]
print(l) # [9, 5, 1, 3]
print id(h), id(l)
h = h * 2
print id(h), id(l)
print(h) # [9, 5, 1, 3, 9, 5, 1, 3]
print(l) # [9, 5, 1, 3]
</code></pre>
<p>As you can see becau... | 6 | 2016-08-26T18:27:01Z | [
"python",
"pointers"
] |
Python: When do two variables point at the same object in memory? | 39,172,565 | <p>Here is an example:</p>
<pre><code>l = [1, 5, 9, 3]
h = l
h[0], h[2] = h[2], h[0]
print(h) # [9, 5, 1, 3]
print(l) # [9, 5, 1, 3]
h = h*2
print(h) # [9, 5, 1, 3, 9, 5, 1, 3]
print(l) # [9, 5, 1, 3]
</code></pre>
<p>My understanding was that calling setting <code>h = l</code> would simply point <code>h</code> at... | 6 | 2016-08-26T18:24:03Z | 39,172,678 | <p>Anytime you assign to a variable, its identity (memory address) generally changes - the only reason why it wouldn't change is that you happened to assign it the value that it already held. So, your statement <code>h = h * 2</code> caused h to become an entirely new object - one whose value happened to be based on t... | 1 | 2016-08-26T18:29:55Z | [
"python",
"pointers"
] |
Python: When do two variables point at the same object in memory? | 39,172,565 | <p>Here is an example:</p>
<pre><code>l = [1, 5, 9, 3]
h = l
h[0], h[2] = h[2], h[0]
print(h) # [9, 5, 1, 3]
print(l) # [9, 5, 1, 3]
h = h*2
print(h) # [9, 5, 1, 3, 9, 5, 1, 3]
print(l) # [9, 5, 1, 3]
</code></pre>
<p>My understanding was that calling setting <code>h = l</code> would simply point <code>h</code> at... | 6 | 2016-08-26T18:24:03Z | 39,172,680 | <p>The assignment does make <strong>h</strong> point to the same item as <strong>l</strong>. However, it does not permanently weld the two. When you change <strong>h</strong> with <strong>h = h * 2</strong>, you tell Python to build a doubled version elsewhere in memory, and then make <strong>h</strong> point to the ... | 2 | 2016-08-26T18:29:56Z | [
"python",
"pointers"
] |
Python: When do two variables point at the same object in memory? | 39,172,565 | <p>Here is an example:</p>
<pre><code>l = [1, 5, 9, 3]
h = l
h[0], h[2] = h[2], h[0]
print(h) # [9, 5, 1, 3]
print(l) # [9, 5, 1, 3]
h = h*2
print(h) # [9, 5, 1, 3, 9, 5, 1, 3]
print(l) # [9, 5, 1, 3]
</code></pre>
<p>My understanding was that calling setting <code>h = l</code> would simply point <code>h</code> at... | 6 | 2016-08-26T18:24:03Z | 39,172,773 | <p><code>h = h * 2</code> assigns <code>h</code> to a new list object.</p>
<p>You probably want to modify <code>h</code> <em>in-place</em>: </p>
<pre><code>h *= 2
print(h) # [9, 5, 1, 3, 9, 5, 1, 3]
print(l) # [9, 5, 1, 3, 9, 5, 1, 3]
</code></pre>
| 4 | 2016-08-26T18:35:55Z | [
"python",
"pointers"
] |
Python: When do two variables point at the same object in memory? | 39,172,565 | <p>Here is an example:</p>
<pre><code>l = [1, 5, 9, 3]
h = l
h[0], h[2] = h[2], h[0]
print(h) # [9, 5, 1, 3]
print(l) # [9, 5, 1, 3]
h = h*2
print(h) # [9, 5, 1, 3, 9, 5, 1, 3]
print(l) # [9, 5, 1, 3]
</code></pre>
<p>My understanding was that calling setting <code>h = l</code> would simply point <code>h</code> at... | 6 | 2016-08-26T18:24:03Z | 39,172,841 | <p>It's tricky, but when you multiply a list, you are creating a new list.</p>
<pre><code>l = [1, 5, 9, 3]
h = l
</code></pre>
<p>'l' and 'h' are now referring to the same list in memory.</p>
<pre><code>h[0], h[2] = h[2], h[0]
print(h) # [9, 5, 1, 3]
print(l) # [9, 5, 1, 3]
</code></pre>
<p>You swapped the value... | 1 | 2016-08-26T18:41:04Z | [
"python",
"pointers"
] |
Pandas concatenation of multiple dataframes returns null values | 39,172,575 | <p>I have a dataframe (<code>df</code>), that I break down into 4 new dfs (<code>media</code>, <code>client</code>, <code>code_type</code>, and <code>date</code>). <code>media</code> has one column of null values, while the other three are only 1-dim dfs, each consisting of nulls. After replacing the nulls in each data... | 1 | 2016-08-26T18:24:40Z | 39,172,992 | <p>Starting with this:</p>
<pre><code> code_name media_type acq. revenue
0 RASH Radio 50.0 34004.0
1 100 NaN 10.0 1035.0
2 NEWS SiriusXM 61.0 3475.0
3 DR SiriusXM 53.0 4307.0
4 SPORTS SiriusXM 45.0 6503.0
5 DOUBL Podcast 13.0 4205.0
</code></pre>
... | 0 | 2016-08-26T18:53:03Z | [
"python",
"pandas",
"concatenation"
] |
Xlxswriter - Change Date format from str to date | 39,172,576 | <p>I am having trouble changing the date format of date column in the dataframe i created using Xlsxwriter. The current format is 3/31/2016 12:00:00 AM, which i thought python is reading a date and adding a time to it. I would like the format to simply be dd/mm/yyyy with know time associate with it for all of column A... | 2 | 2016-08-26T18:24:41Z | 39,173,220 | <h2><code>datetime.strftime</code> is for converting datetimes into strings</h2>
<p>You are not giving it a datetime object to convert.</p>
<pre><code>from datetime import datetime
today = datetime.today() # this returns a datetime object
today.strftime("%m/%d/%Y") # this returns a string
datetime.strftime(today, "... | 1 | 2016-08-26T19:08:57Z | [
"python",
"datetime",
"xlsxwriter"
] |
SQLAlchemy table property takes exactly 2 arguments (1 given) | 39,172,703 | <p>I have the following SQLAlchemy class:</p>
<pre><code>class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
password = db.Column(db.String(100))
@property
def encrypt_password(self, password):
self.password = hash_password(password)
</code></pre>
<p>When I use the property I g... | -1 | 2016-08-26T18:31:27Z | 39,172,788 | <p>You defined the <code>getter</code> for the property as the <code>setter</code>. Either remove the <a href="https://docs.python.org/3/library/functions.html#property" rel="nofollow"><code>property</code></a> because this is a function, or define the property correctly.</p>
<p>If you're going the property route, re... | 0 | 2016-08-26T18:36:58Z | [
"python",
"sqlalchemy"
] |
Need help ignoring button press. Tkinter | 39,172,727 | <p>I am working on making a stopwatch program. I can't get the start button to do nothing if the timer is already running. </p>
<p>When I search, I see the same <a href="http://code.activestate.com/recipes/124894-stopwatch-in-tkinter/" rel="nofollow">14 year old code</a>. I'd find it hard to believe that all these ind... | 3 | 2016-08-26T18:32:55Z | 39,172,894 | <p>Set the state of the button to disabled immediately after it's clicked (make sure to update it), and then set it back to normal when the timer stops running.</p>
<pre><code>start_button.config(state = 'disabled')
start_button.update()
# do whatever you need to do i.e run the stop watch
start_button.update()
start... | 4 | 2016-08-26T18:44:45Z | [
"python"
] |
same binary image - different in python & matlab | 39,172,816 | <p>OK. I'm thoroughly confused. I have a binary image. The values are (allegedly) 0 and 1. I read it in Matlab, to verify:</p>
<pre><code>binaryImage = imread('binary.png');
</code></pre>
<p>I get the max and min values, and the values are 1 and 0, respectively.</p>
<pre><code>maxValue = max(binaryImage(:));
min... | 0 | 2016-08-26T18:39:15Z | 39,172,965 | <p>matlab supports logical arrays and scipy converts the image to grayscale. Depending on what you want to do you can convert the grayscale image to logicals</p>
<pre><code>bit_img = img > 127
</code></pre>
<p>or convert the logical array to int8 in matlab</p>
<pre><code>img = int8(binary_image) * 255
</code></pr... | 0 | 2016-08-26T18:50:54Z | [
"python",
"matlab",
"image-processing"
] |
Django queryset "using()" method for specifying database doesn't work on related_name queries | 39,172,828 | <p>I've noticed something strange in Django that I haven't been able figure out. Let's say I have a Django application (I'm using 1.7) with two models like so:</p>
<pre><code>class Bookstore(models.Model):
name = models.CharField(max_length=50)
class Book(models.Model):
title = models.CharField(max_length=100... | 2 | 2016-08-26T18:39:57Z | 39,173,895 | <p>Look at SQL from first example (without <code>using()</code>):</p>
<pre><code>SELECT "book"."id", "book"."title", "book"."store_id"
FROM "book" JOIN "bookstore" ON "book"."store_id" = "bookstore"."id"
WHERE "bookstore"."id" = 1
ORDER BY "book"."id"
LIMIT 1
</code></pre>
<p>Do You see the problem? You cannot do a <... | 0 | 2016-08-26T20:00:58Z | [
"python",
"django"
] |
Why don't work linkClicked, and works linkHovered PyQt4? | 39,172,849 | <p>Here is some code. I created modal window, set easy html, and then I want to connect some method on click link. Signal "linkClicked" dont works , but link are loaded. And signal <strong>linkHovered</strong> works. Where is mistake? And how to include some method to "linkClicked"?</p>
<pre><code># -*- coding: utf-8... | 0 | 2016-08-26T18:41:33Z | 39,173,826 | <p>From the documentation for <a href="http://doc.qt.io/qt-4.8/qwebview.html#linkClicked" rel="nofollow">linkClicked</a>:</p>
<blockquote>
<p>This signal is emitted whenever the user clicks on a link and the
page's linkDelegationPolicy property is set to delegate the link
handling for the specified url.</p>
</bl... | 1 | 2016-08-26T19:55:06Z | [
"python",
"pyqt4",
"qtwebkit",
"qwebview"
] |
Python Openpyxl, copy and paste cell range | 39,172,937 | <p>I know how to select a cell range in Openpyxl:</p>
<pre><code>cell_range = sheet['A1':'C3']
</code></pre>
<p>How can I paste cell_range above to another range, like <code>sheet['A11':'C13']</code>?</p>
| 0 | 2016-08-26T18:48:32Z | 39,173,627 | <p>I don't think there is a slicing notation exactly as described in your example, mostly because <code>openpyxl</code> uses lists of <code>Cell</code>s rather than lists of plain values.</p>
<p>Here is the basic flow I would use to grab just a part of a sheet.</p>
<pre><code>>>> wb = openpyxl.load_workbook(... | 1 | 2016-08-26T19:38:36Z | [
"python",
"excel",
"openpyxl"
] |
Python Openpyxl, copy and paste cell range | 39,172,937 | <p>I know how to select a cell range in Openpyxl:</p>
<pre><code>cell_range = sheet['A1':'C3']
</code></pre>
<p>How can I paste cell_range above to another range, like <code>sheet['A11':'C13']</code>?</p>
| 0 | 2016-08-26T18:48:32Z | 39,174,143 | <p>You might want to look at <a href="https://bitbucket.org/snippets/openpyxl/qyzKn" rel="nofollow">this snippet</a> for some ideas. Please note it is <strong>entirely</strong> unsupported.</p>
| 0 | 2016-08-26T20:22:12Z | [
"python",
"excel",
"openpyxl"
] |
Absolute path in Python requiring an extra leading forward slash? | 39,172,944 | <p>I am trying to open a resource via an absolute path on my Macbook with <code>open(file[,mode])</code>. The resource I am trying to access is not in the same folder as the script that is running. If I use something like <code>/Users/myname/Dev/project/resource</code> I get an <code>IOError: No such file or directory<... | 0 | 2016-08-26T18:49:00Z | 39,173,233 | <p>The best way to deal with this is to avoid constructing the path yourself altogether. Let os.path.join() do it for you.</p>
| 0 | 2016-08-26T19:10:05Z | [
"python",
"python-2.7",
"file-io",
"path"
] |
Python: Running a for loop with multiple inputs and sorting the results into different lists | 39,172,967 | <p>So I have a bit of code that looks like this:</p>
<pre><code>measure_list=[]
for file in file_list:
with open(file,"r") as read_data:
y=read_data.read()
if "Part: ABCD" in y:
for line in m:
if "Measure X:" in line:
measure_list.append(line)
... | 0 | 2016-08-26T18:50:55Z | 39,173,046 | <p>Make two arrays of outputs and sort the input into each using a for loop with an if statement inside. Then join the two outputs.</p>
| 1 | 2016-08-26T18:57:12Z | [
"python",
"python-3.x"
] |
Python: Running a for loop with multiple inputs and sorting the results into different lists | 39,172,967 | <p>So I have a bit of code that looks like this:</p>
<pre><code>measure_list=[]
for file in file_list:
with open(file,"r") as read_data:
y=read_data.read()
if "Part: ABCD" in y:
for line in m:
if "Measure X:" in line:
measure_list.append(line)
... | 0 | 2016-08-26T18:50:55Z | 39,173,121 | <p>I don't have python up in front of me so there might be a slight syntax edit needed. This should sort the list by the X and Y portion of the "Measure X:..."</p>
<pre><code>sorted(measure_list,key=lambda item: item.split()[1][0])
</code></pre>
| 1 | 2016-08-26T19:02:15Z | [
"python",
"python-3.x"
] |
Python: Running a for loop with multiple inputs and sorting the results into different lists | 39,172,967 | <p>So I have a bit of code that looks like this:</p>
<pre><code>measure_list=[]
for file in file_list:
with open(file,"r") as read_data:
y=read_data.read()
if "Part: ABCD" in y:
for line in m:
if "Measure X:" in line:
measure_list.append(line)
... | 0 | 2016-08-26T18:50:55Z | 39,173,129 | <p>Why not to use two lists?</p>
<pre><code>if "Measure X:" in line:
listx.append(line)
elif "Measure Y:" in line:
listy.append(line)
</code></pre>
<p>Then simply</p>
<pre><code>final = ''.join(listx + listy)
</code></pre>
| 3 | 2016-08-26T19:02:53Z | [
"python",
"python-3.x"
] |
Python: Running a for loop with multiple inputs and sorting the results into different lists | 39,172,967 | <p>So I have a bit of code that looks like this:</p>
<pre><code>measure_list=[]
for file in file_list:
with open(file,"r") as read_data:
y=read_data.read()
if "Part: ABCD" in y:
for line in m:
if "Measure X:" in line:
measure_list.append(line)
... | 0 | 2016-08-26T18:50:55Z | 39,173,152 | <p>Your <code>measure_list</code> seems like this:</p>
<pre><code>['Measure X: 1000', 'Measure Y: 2000', 'Measure X: 100' , 'Measure Y: 900']
</code></pre>
<p>If that's right, you can simply sort this <code>measure_list</code>:</p>
<p><code>measure_list.sort()</code></p>
<p>Then you will have:</p>
<pre><code>['Mea... | 1 | 2016-08-26T19:04:41Z | [
"python",
"python-3.x"
] |
Using Matplotlib to plot over a subset of data | 39,173,034 | <p>I am using matplotlib to plot bar charts of data in my DataFrame. I use this construction to first plot over the whole dataset:</p>
<pre><code>import pandas as pd
from collections import Counter
import matplotlib.pyplot as plt
Temp_Counts = Counter(weatherDFConcat['TEMPBIN_CONS'])
df = pd.DataFrame.from_dict(Temp... | 2 | 2016-08-26T18:56:18Z | 39,174,614 | <p>If I'm understanding your question correctly, you are trying to do two things prior to plotting:</p>
<ol>
<li><p>Filter based on <code>REGION_NAME</code>.</p></li>
<li><p>Within that filtered dataframe, count how many times each value in the <code>TEMPBIN_CONS</code> column appears.</p></li>
</ol>
<p>You can do bo... | 1 | 2016-08-26T21:06:05Z | [
"python",
"pandas",
"numpy",
"matplotlib",
"plot"
] |
Pexpect: Read from the last send | 39,173,069 | <p>I am trying to read the output of pexpect.send(cmd) but here's the problem I am facing.</p>
<p>I am sending many commands in a sequence and I want to read/expect after a certain set of commands. Condition is that only the output of last command is to be considered. But <code>expect</code> matches from the point it ... | 0 | 2016-08-26T18:58:50Z | 39,256,145 | <p>There are three ways in which this problem can be handled but none to flush the buffer</p>
<ol>
<li>In Pexpect every <code>send</code> call should be matched with a call to
<code>expect</code>. This ensures that the file pointer has moved ahead of the
previous send.</li>
<li>If there is a series of <code>send</code... | 0 | 2016-08-31T17:57:57Z | [
"python",
"python-2.7",
"pexpect"
] |
Python equivalent of this Curl command | 39,173,107 | <p>I am trying to download a file using python, imitating the same behavior as this curl command:</p>
<pre><code>curl ftp://username:password@example.com \
--retry 999 \
--retry-max-time 0
-o 'target.txt' -C -
</code></pre>
<p>How would this look in python ?</p>
<p>Things I have looked into:</p>
<ul>
<... | 0 | 2016-08-26T19:01:30Z | 39,173,753 | <p>there is this library for downloading files from ftp server</p>
<p><a href="https://pypi.python.org/pypi/fileDownloader.py/0.2.1" rel="nofollow">fileDownloader.py</a></p>
<p>to download the file</p>
<pre><code>downloader = fileDownloader.DownloadFile(âhttp://example.com/file.zipâ, âC:UsersusernameDownloadsn... | 0 | 2016-08-26T19:50:19Z | [
"python",
"curl"
] |
Python equivalent of this Curl command | 39,173,107 | <p>I am trying to download a file using python, imitating the same behavior as this curl command:</p>
<pre><code>curl ftp://username:password@example.com \
--retry 999 \
--retry-max-time 0
-o 'target.txt' -C -
</code></pre>
<p>How would this look in python ?</p>
<p>Things I have looked into:</p>
<ul>
<... | 0 | 2016-08-26T19:01:30Z | 39,174,507 | <p>you can use python's inbuilt ftplib</p>
<p>Here is the code:</p>
<pre><code>from ftplib import FTP
ftp = FTP('example.com', 'username', 'password') #logs in
ftp.retrlines() # to see the list of files and directories ftp.cwd('to change to any directory')
ftp.retrbinary('RETR filename', open('Desktop\filename', '... | 1 | 2016-08-26T20:55:43Z | [
"python",
"curl"
] |
Hybrid Naive Bayes: How to train Naive Bayes Classifer with numeric and category variable together(sklearn) | 39,173,169 | <p>Basicly, skelarn have naive bayes with Gaussian kernal which can class numeric variables.</p>
<p>However, how to deal with data set containing numeric variables and category variables together.</p>
<p>For an example, give a dataset below, how use sklearn train mixed data type together without discreting numeric va... | 0 | 2016-08-26T19:05:43Z | 39,175,843 | <p>The answer comes directly from the mathematics of Naive Bayes</p>
<ol>
<li><p>Categorical variables provide you with log P(a|cat) ~ SUM_i log P(cat_i|a) + log P(a) (I am omitting division by P(cat), as what NB implementation returns is also ignoring it)</p></li>
<li><p>Continuous variables give you the same thing, ... | 1 | 2016-08-26T23:18:30Z | [
"python",
"statistics",
"scikit-learn",
"naivebayes"
] |
In python does self require any object of its same type? | 39,173,175 | <p>I am reading 9.3.2. Class Objects from the python docs and I was hoping someone can clear up the following:</p>
<p>How come both scenarios return 'hello world'? The first instance I kind of understand (at least I believe I do) because self is referencing the object itself 'MyClass' and I guess passing 'm' to self i... | 1 | 2016-08-26T19:05:54Z | 39,173,276 | <p>Python is "duck-typed", meaning it doesn't matter <em>what</em> type <code>self</code> is, as long as it provides the correct interface. Here, <code>self</code> isn't used in the body of the function, so you could pass absolutely <em>anything</em> to <code>MyClass.f</code> and it would work.</p>
<pre><code>>>... | 3 | 2016-08-26T19:13:19Z | [
"python",
"class"
] |
In python does self require any object of its same type? | 39,173,175 | <p>I am reading 9.3.2. Class Objects from the python docs and I was hoping someone can clear up the following:</p>
<p>How come both scenarios return 'hello world'? The first instance I kind of understand (at least I believe I do) because self is referencing the object itself 'MyClass' and I guess passing 'm' to self i... | 1 | 2016-08-26T19:05:54Z | 39,173,348 | <pre><code>MyClass.f('what the...')
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-2-cca57c03fecc> in <module>()
----> 1 MyClass.f('what the...')
TypeError: unbound method f() must be ... | 0 | 2016-08-26T19:19:23Z | [
"python",
"class"
] |
Python Compile file(.pyc) generated even after errors in code-why? | 39,173,176 | <p>I have the below code in a file <strong>a1.py</strong></p>
<pre><code>fff
def test(arg):
print 'sid'
print arg
print 'sid2'
test()
</code></pre>
<p>The above code contains 2 errors:</p>
<ol>
<li><p>fff does not exist and is still being asked to print</p></li>
<li><p>Arguments are not passe... | 0 | 2016-08-26T19:06:00Z | 39,173,286 | <p>Python automatically compiles your script to compiled code, so called byte code, before running it. When a module is imported for the first time, or when the source is more recent than the current compiled file, a .pyc file containing the compiled code will usually be created in the same directory as the .py file.</... | 0 | 2016-08-26T19:14:07Z | [
"python",
"python-2.7",
"compilation"
] |
Matplotlib/Openpyxl - Pasting multiple images into different worksheets excel | 39,173,182 | <p>I am having a real problem understanding ow python is reading my code and need some help. I have several worksheets within one excel workbook, all containing one dataframe table and one chart. I have organized my code in a way where i run all the different dataframe, write them to each excel worksheet, plot each cha... | 2 | 2016-08-26T19:06:28Z | 39,206,541 | <p>Ah okay yes! Because I am opening and closing the workbook each time, the images are getting deleted from the previous worksheet. If I simply only open the connection once, paste all images to each of the worksheets, and then close it works.</p>
<pre><code>#Write PNG file to existing worksheet
from openpyxl import ... | 2 | 2016-08-29T12:37:20Z | [
"python",
"matplotlib",
"openpyxl"
] |
Python requests decode using a different charset | 39,173,203 | <p>I'm using <code>requests</code> to fetch a webpage but the automatically inferred encoding in <code>response.encoding</code> is incorrect. I need to decode the bytes in unicode, but I didn't find an API for this. <code>response.text</code> is Unicode but not the byte array. Any idea?</p>
| -1 | 2016-08-26T19:07:52Z | 39,173,262 | <p>From <a href="http://docs.python-requests.org/en/master/user/quickstart/#response-content" rel="nofollow">the documentation</a> (emphasis added):</p>
<blockquote>
<p>When you make a request, Requests makes educated guesses about the
encoding of the response based on the HTTP headers. The text encoding
guessed... | 1 | 2016-08-26T19:12:06Z | [
"python",
"python-requests"
] |
Scrapy performance improvements and memory consumtion | 39,173,260 | <p>Server</p>
<ul>
<li>6 GB RAM</li>
<li>4 Cores Intel Xeon 2.60GHz</li>
<li>32 CONCURRENT_REQUESTS</li>
<li>1m URLs in CSV</li>
<li>700 Mbit/s downstream</li>
<li>96% Memory Consumtion</li>
</ul>
<p>With debug mode on, the scrape stops after around 400 000 urls, most likely because the server runs out of memory.
Wi... | 1 | 2016-08-26T19:11:59Z | 39,173,498 | <pre><code>import csv
from collections import namedtuple
import scrapy
def get_urls_from_csv():
with open('data.csv', newline='') as csv_file:
data = csv.reader(csv_file, delimiter=',')
for row in data:
yield row[2]
# if you can use something else than scrapy
rssitem = namedtuple('r... | 0 | 2016-08-26T19:29:21Z | [
"python",
"scrapy",
"scrapy-spider"
] |
Scrapy performance improvements and memory consumtion | 39,173,260 | <p>Server</p>
<ul>
<li>6 GB RAM</li>
<li>4 Cores Intel Xeon 2.60GHz</li>
<li>32 CONCURRENT_REQUESTS</li>
<li>1m URLs in CSV</li>
<li>700 Mbit/s downstream</li>
<li>96% Memory Consumtion</li>
</ul>
<p>With debug mode on, the scrape stops after around 400 000 urls, most likely because the server runs out of memory.
Wi... | 1 | 2016-08-26T19:11:59Z | 39,173,768 | <p>As I commented you should use <a href="https://wiki.python.org/moin/Generators" rel="nofollow"><em>generators</em></a> to avoid creating lists of objects in memory(<a href="http://stackoverflow.com/questions/231767/what-does-the-yield-keyword-do-in-python">what-does-the-yield-keyword-do-in-python</a>), using generat... | 1 | 2016-08-26T19:51:54Z | [
"python",
"scrapy",
"scrapy-spider"
] |
Numpy-like printing for python objects | 39,173,398 | <p>While doing data analysis in Ipython I often have to look at the data by just printing its contents to the shell. Numpy have the facility to show only the <strong>margins</strong> of huge objects when they are too long themselves. I really like this feature of ndarrays but when I print internal python object (eg. di... | 5 | 2016-08-26T19:22:49Z | 39,173,441 | <p>There is a good built-in library <a href="https://docs.python.org/3/library/pprint.html" rel="nofollow"><code>pprint</code></a>. Take a look at it.</p>
<pre><code>>>> from pprint import pprint
>>> pprint({x: list(range(x)) for x in range(10)})
{0: [],
1: [0],
2: [0, 1],
3: [0, 1, 2],
4: [0, 1,... | 1 | 2016-08-26T19:25:18Z | [
"python",
"printing",
"ipython"
] |
Numpy-like printing for python objects | 39,173,398 | <p>While doing data analysis in Ipython I often have to look at the data by just printing its contents to the shell. Numpy have the facility to show only the <strong>margins</strong> of huge objects when they are too long themselves. I really like this feature of ndarrays but when I print internal python object (eg. di... | 5 | 2016-08-26T19:22:49Z | 39,173,528 | <p>If your dictionary is well structured, you could convert it to a Pandas dataframe for viewing.</p>
<pre><code>import numpy as np
import pandas as pd
>>> pd.DataFrame({'random normal': np.random.randn(1000),
'random int': np.random.randint(0, 10, 1000)})
random int random normal
0 ... | 1 | 2016-08-26T19:30:59Z | [
"python",
"printing",
"ipython"
] |
Numpy-like printing for python objects | 39,173,398 | <p>While doing data analysis in Ipython I often have to look at the data by just printing its contents to the shell. Numpy have the facility to show only the <strong>margins</strong> of huge objects when they are too long themselves. I really like this feature of ndarrays but when I print internal python object (eg. di... | 5 | 2016-08-26T19:22:49Z | 39,174,588 | <p>The <code>numpy</code> formatter has an ellipsis functionality; as a default it kicks in with 1000+ items. </p>
<p><code>pprint</code> can make the display nicer, but I don't think it has an ellipsis functionality. But you can study its docs.</p>
<p>With a list I may use a slice</p>
<pre><code>list(range(100))[... | 0 | 2016-08-26T21:03:40Z | [
"python",
"printing",
"ipython"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.