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
Next Biggest Number Same Digits
39,962,076
<p>I don't see anything wrong with my code but I can't seem to return -1 when the input cannot produce a next bigger number, i.e. input of <code>531</code> which is descending. </p> <pre><code>import itertools as it def next_bigger(n): if sorted("531", reverse = True) == list("531"): return -1 s = tupl...
-6
2016-10-10T15:52:07Z
39,962,254
<p>You can simply use an <code>if</code> statement at the beginning of your function to test whether the number is already in reverse sorted order. If it is sorted <code>return -1</code> straight away:</p> <pre><code>&gt;&gt;&gt; sorted("531", reverse = True) == list("531") True </code></pre>
2
2016-10-10T16:02:01Z
[ "python", "integer" ]
Grouping values in Pandas value_counts()
39,962,217
<p>I want to create histogram from my pandas dataframe. I have 1 column, where I save percentage values. I used value_counts() but I have too much percentage values. Example:</p> <pre><code>0.752 1 0.769 2 0.800 1 0.823 1 ... 80.365 1 84.000 1 84.615 1 85.000 ...
1
2016-10-10T15:59:59Z
39,962,397
<p>you can group your data by the result of <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.cut.html" rel="nofollow">pd.cut()</a> method:</p> <pre><code>In [38]: df Out[38]: value count 0 0.752 1 1 11.769 3 2 22.800 4 3 33.823 5 4 55.365 1 5 84.000 1 6 8...
1
2016-10-10T16:09:44Z
[ "python", "pandas", "count", "value" ]
Fully understand for loop python
39,962,277
<p>I start out with a small code example right away:</p> <pre><code>def foo(): return 0 a = [1, 2, 3] for el in a: el = foo() print(a) # [1, 2, 3] </code></pre> <p>I would like to know what <strong><em>el</em></strong> is in this case. As <strong><em>a</em></strong> remains the same, I intuite that <strong...
-1
2016-10-10T16:03:25Z
39,962,348
<p>Yes, you understood this correctly. <code>for</code> sets the target variable <code>el</code> to point to each of the elements in <code>a</code>. <code>el = foo()</code> indeed then updates that name to point to a different, unrelated integer.</p> <p>Using <code>enumerate()</code> is a good way to replace the refer...
1
2016-10-10T16:06:53Z
[ "python", "python-3.x", "for-loop", "reference" ]
Assign a class to itself in python
39,962,292
<p>I just want to ask if I can assign an instance of a class to itself in a method.</p> <p>For example, is the following valid python code?</p> <pre><code>class O(object): def __init__(self,value): self.value = value def do_something(self): self = O(1) </code></pre> <p>Does this lead to any unexpected be...
0
2016-10-10T16:03:48Z
39,962,320
<p><code>self</code> is a local variable. So, it will make your code confusing in that method, and will prevent modifications on (or calls to) the original self object. </p>
0
2016-10-10T16:05:25Z
[ "python", "class", "oop" ]
Assign a class to itself in python
39,962,292
<p>I just want to ask if I can assign an instance of a class to itself in a method.</p> <p>For example, is the following valid python code?</p> <pre><code>class O(object): def __init__(self,value): self.value = value def do_something(self): self = O(1) </code></pre> <p>Does this lead to any unexpected be...
0
2016-10-10T16:03:48Z
39,962,451
<p><code>self</code> is <em>just another local variable</em>. You can assign something else to it just like you can assign something to any variable. To begin with, <code>self</code> points to the same object <code>A</code> points to in your example.</p> <p>When you then execute <code>self = O(1)</code>, that statemen...
3
2016-10-10T16:12:32Z
[ "python", "class", "oop" ]
Assign a class to itself in python
39,962,292
<p>I just want to ask if I can assign an instance of a class to itself in a method.</p> <p>For example, is the following valid python code?</p> <pre><code>class O(object): def __init__(self,value): self.value = value def do_something(self): self = O(1) </code></pre> <p>Does this lead to any unexpected be...
0
2016-10-10T16:03:48Z
39,962,492
<p>As Marcin answered, it is feasible, but it is not an advisable pattern.</p> <p>Why would you like to do something like that? If you'd like instances of your class to have a settable property after instantiation, you shouldn't do it with a constructor. A simple solution for your proposal:</p> <pre><code>class O(obj...
0
2016-10-10T16:15:25Z
[ "python", "class", "oop" ]
i want to create a matrix of multiplication tables
39,962,323
<p>i want to create a matrix of first 12 multiplication tables .</p> <p>my code so far is:</p> <pre><code>x = range(1,13,1) n = range(1,13,1) list_to_append = [] list_for_matrix = [] for i in x: for j in n: list_to_append.append(i*j) list_for_matrix.append(list_to_append[0:12]) list_for_matrix.appen...
0
2016-10-10T16:05:42Z
39,962,394
<p>You can use the following <em>list comprehension</em>:</p> <pre><code>x = range(1,13) # default step value is 1, no need to specify n = range(1,13) mult_table = [[i*j for j in x] for i in n] </code></pre> <hr> <p>Output:</p> <pre><code>print(mult_table) # [[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12], # [2, 4, 6, 8...
4
2016-10-10T16:09:35Z
[ "python", "python-2.7", "python-3.x", "ipython" ]
i want to create a matrix of multiplication tables
39,962,323
<p>i want to create a matrix of first 12 multiplication tables .</p> <p>my code so far is:</p> <pre><code>x = range(1,13,1) n = range(1,13,1) list_to_append = [] list_for_matrix = [] for i in x: for j in n: list_to_append.append(i*j) list_for_matrix.append(list_to_append[0:12]) list_for_matrix.appen...
0
2016-10-10T16:05:42Z
39,962,625
<p>You can create an empty list and append lists to it. Like:</p> <pre><code>#!/usr/bin/python table = [] for y in range(1, 13): # Create the inner lists with a temporary variable. # You must do this every time before the inner loop is entered, # otherwise row = [] # Fill the inner list. for x ...
1
2016-10-10T16:22:32Z
[ "python", "python-2.7", "python-3.x", "ipython" ]
How are the values from c variable in scatter (from matplotlib) converted?
39,962,372
<p>I am creating a PCA plot using matplotlib Python library, I choose the color of each point according to a class value (which is 0, 1 or 2). To do so I am using the parameter called c:</p> <pre><code>plt.scatter(pca_data[:, 0], pca_data[:, 1], c=[0,1,1,0,2]) </code></pre> <p>What I would like to do is add a legend...
1
2016-10-10T16:07:54Z
39,962,691
<p>Here is an example where there are 3 labels (but the method is scalable to any number):</p> <pre><code>import numpy as np import matplotlib.pyplot as plt import matplotlib.cm as cm import matplotlib.colors as colors pca_data = np.random.randn(100,2) #some fake data labels = np.random.randint(low=0,high=3,size=100...
0
2016-10-10T16:26:02Z
[ "python", "matplotlib" ]
Why is BeautifulSoup not extracting all of HTML from a webpage?
39,962,420
<p>I am trying to extract text from this website: <a href="https://www.searchgurbani.com/guru_granth_sahib/ang_by_ang" rel="nofollow">searchgurbani</a>. This website has some old scripture translated in English and Punjabi (an Indian Language) line-by-line. It makes a very good parallel corpus. I have successfully extr...
2
2016-10-10T16:10:50Z
39,962,713
<p>Remember you've suggested to do the following:</p> <blockquote> <p>Please do the following on that web page: Go to preferences -> Tick "ranslation of Sri Guru Granth Sahib ji (by S. Manmohan Singh) - Punjabi" under Additional Translations available on Guru Granth Shahib: -> scroll down - submit changes</p> ...
1
2016-10-10T16:27:28Z
[ "python", "html", "python-3.x", "web-scraping", "beautifulsoup" ]
pandas python using head() generic function
39,962,476
<p>I am a beginner to python,in our college they assigned a project i.e. to display timetables of our department using pandas python.Iam presenting my program as menu driven program.But the problem is Iam not able to display my timetables in a grid pattern using head() in if else loop..can u let me know where I am i wr...
-1
2016-10-10T16:14:24Z
39,962,578
<h1>use this code. it will work. before using this code go to command prompt and write execute this command <code>pip install xlrd</code> I am sure it will work.</h1> <pre><code>import pandas as pd import numpy as np loop=1 while loop==1: print('WELCOME TO CBIT') print('1.IT 2') print('2.EXIT') choice...
0
2016-10-10T16:20:20Z
[ "python", "pandas", "head" ]
pandas python using head() generic function
39,962,476
<p>I am a beginner to python,in our college they assigned a project i.e. to display timetables of our department using pandas python.Iam presenting my program as menu driven program.But the problem is Iam not able to display my timetables in a grid pattern using head() in if else loop..can u let me know where I am i wr...
-1
2016-10-10T16:14:24Z
39,963,537
<p>Add a print statement: <code>print(df.head())</code> . If you are looking for a nicer display you can have a look at <a href="https://docs.python.org/2/library/pprint.html" rel="nofollow"><code>pprint</code></a>.</p>
0
2016-10-10T17:20:40Z
[ "python", "pandas", "head" ]
How to understand/use the Python difflib output?
39,962,499
<p>I am trying to make comprehensive diff that compares command line output of two programs. I used <code>difflib</code> and came up with this code:</p> <pre><code>from difflib import Differ from pprint import pprint import sys def readable_whitespace(line): return line.replace("\n", "\\n") # Two strings are exp...
3
2016-10-10T16:15:53Z
39,963,449
<p>The main problem with your example is how you are handling endline characters. If you completely replace them in the input, the output will no longer line up correctly, and so won't make any sense. To fix that, the <code>readable_whitespace</code> function should look something like this:</p> <pre><code>def readabl...
2
2016-10-10T17:14:38Z
[ "python", "python-2.7", "difflib" ]
Passing variables between functions in Python
39,962,564
<p>Ok so I am having a tough time getting my head around passing variables between functions:</p> <p>I can't seem to find a clear example. </p> <p>I do not want to run funa() in funb(). </p> <pre><code>def funa(): name=input("what is your name?") age=input("how old are you?") return name, age funa() de...
-3
2016-10-10T16:19:35Z
39,962,605
<p>Since <code>funa</code> is <em>returning</em> the values for name and age, you need to assign those to local variables and then pass them into funb:</p> <pre><code>name, age = funa() funb(name, age) </code></pre> <p>Note that the names within the function and outside are not linked; this would work just as well:</...
5
2016-10-10T16:21:48Z
[ "python" ]
Passing variables between functions in Python
39,962,564
<p>Ok so I am having a tough time getting my head around passing variables between functions:</p> <p>I can't seem to find a clear example. </p> <p>I do not want to run funa() in funb(). </p> <pre><code>def funa(): name=input("what is your name?") age=input("how old are you?") return name, age funa() de...
-3
2016-10-10T16:19:35Z
39,962,692
<p>Think of it as passing objects around by using variables and function parameters as references to those objects. When I updated your example, I also changed the names of the variables so that it is clear that the objects live in different variables in different namespaces.</p> <pre><code>def funa(): name=input(...
0
2016-10-10T16:26:03Z
[ "python" ]
Passing variables between functions in Python
39,962,564
<p>Ok so I am having a tough time getting my head around passing variables between functions:</p> <p>I can't seem to find a clear example. </p> <p>I do not want to run funa() in funb(). </p> <pre><code>def funa(): name=input("what is your name?") age=input("how old are you?") return name, age funa() de...
-3
2016-10-10T16:19:35Z
39,962,738
<p>As it is returning a tuple, you can simply unpack it with <code>*</code>:</p> <pre><code>funb(*funa()) </code></pre> <p>It should look something like this:</p> <pre><code>def funa(): # funa stuff return name, age def funb(name, age): # funb stuff print () funb(*funa()) </code></pre>
0
2016-10-10T16:29:42Z
[ "python" ]
ValueError when running keras in python
39,962,723
<p>When I train the CNN:</p> <pre><code>model = Sequential() model.add(Convolution2D(4, 5, 5, border_mode='valid', input_shape=(1,28,28))) model.add(Activation('tanh')) model.add(Convolution2D(8, 3, 3, border_mode='valid')) model.add(Activation('tanh')) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(C...
0
2016-10-10T16:28:41Z
40,013,512
<p>You need to add <code>dim_ordering='th'</code> in <code>Convolution2D</code> and <code>MaxPooling2D</code> sine your <code>input_shape</code> is <code>(1, 28, 28)</code>. Or else if you don't want to add an <code>dim_ordering</code> , then you can change input shape to <code>(28, 28, 1)</code>.</p> <pre><code>#!/us...
0
2016-10-13T06:09:21Z
[ "python", "numpy", "keras" ]
Pandas- how to do merge on multiple columns including index
39,962,731
<p>I want to perform a merge in pandas on more than one column, where one of the columns is an index column.</p> <p>Here are example dataframes:</p> <pre><code> df1 = pd.DataFrame(np.random.rand(4,4), columns=list('ABCD')) df2 = pd.DataFrame(np.random.rand(4,4), columns=list('EFGH'), index= [5,2,4,1]) df1[...
1
2016-10-10T16:29:16Z
39,962,925
<p>what about this?</p> <pre><code>In [82]: pd.merge(df1.reset_index(), df2.reset_index(), on=['index','E']).set_index('index') Out[82]: A B C D E F G H index 1 0.516878 0.56163 0.082839 0.420587 hello 0.62601 0.787371 0.121979 </code></pre>
1
2016-10-10T16:40:56Z
[ "python", "pandas", "merge" ]
Can't reference Lib/site-packages virtualenv flask
39,962,794
<p>I am trying to tinker with Flask and Python using virtualenv. I have made my current working directory C:/Users/dylan/Desktop/TestPython/FlaskTest and activated a virtualenv here. Now when I'm in here and activated, I ran the command pip install flask and the package was copied to Lib/site-packages. I've look at oth...
0
2016-10-10T16:33:21Z
39,963,134
<p>So I figured out that Sublime Text does not use the same command line instance that you have open. It doesn't actually build using the virtual environment. I think I need to modify my build system. If I run python routes.py while activated it does work as expected. I was trying to run it from sublime text and that w...
0
2016-10-10T16:53:14Z
[ "python", "python-3.x", "pip", "virtualenv" ]
error copying folder with python
39,962,808
<p>i made a program that copy automatically a usb device. when it copy the usb it create one folder in correct destination, and one folder in the same path of python program. i want that itcreate only one folder in correct destination! thanks</p> <p>this is the code:</p> <pre><code>import shutil from array import * i...
0
2016-10-10T16:34:10Z
39,963,042
<p>Your problem is the following lines:</p> <pre><code>if not os.path.exists(new_dir): os.makedirs(new_dir) </code></pre> <p>Since <code>new_dir</code> is a relative path (a date string), it will be created in the working folder of your script.</p>
0
2016-10-10T16:47:58Z
[ "python", "python-3.x", "subprocess", "folder", "copy-paste" ]
How to use a train.csv , test.csv and ground_truth.csv in a machine learning model? (cross validation/ python)
39,962,836
<p>Up to now I had only one dataset (df.csv). So far I used a validation size of 20% and <code>.train_test_split</code> for a normal regression model. </p> <pre><code>array = df.values X = array[:,0:26] Y = array[:,26] validation_size = 0.20 seed = 7 X_train, X_validation, Y_train, Y_validation = cross_validation.t...
0
2016-10-10T16:35:46Z
39,973,288
<p>When you perform cross-validation, train and test data are essentially the same dataset which is split in different ways in order to prevent overfitting. The number of folds indicates the different ways the set is split. </p> <p>For example, 5-fold cross validation splits the training set in 5 pieces and each time ...
1
2016-10-11T08:32:07Z
[ "python", "numpy", "machine-learning", "scipy", "cross-validation" ]
Set default logging level in python
39,962,926
<p>I am having trouble with a module (specifically pymel.core in maya) which seems to change the default logging level. When I import pymel, all the different loggers in the modules I'm using suddenly get set to debug and start spewing out loads of things that I don't want to see. It looks to me like pymel is changing ...
0
2016-10-10T16:40:59Z
39,963,223
<p>I don't know <code>pymel</code> specifically but it doesn't look like it's well-behaved with respect to logging. You could try:</p> <pre><code>if __name__ == '__main__': import logging, pymel.core logging.getLogger().setLevel(logging.WARNING) # or whatever logging.getLogger('pymel').setLevel(logging.WA...
0
2016-10-10T16:59:10Z
[ "python", "python-2.7", "logging", "maya", "pymel" ]
Set default logging level in python
39,962,926
<p>I am having trouble with a module (specifically pymel.core in maya) which seems to change the default logging level. When I import pymel, all the different loggers in the modules I'm using suddenly get set to debug and start spewing out loads of things that I don't want to see. It looks to me like pymel is changing ...
0
2016-10-10T16:40:59Z
39,968,463
<p>There's a file called <code>pymel.conf</code> in the Maya install in the pymel subfolder of the <code>site-packages</code> directory. It controls the log settings for different parts of pymel using the same config file system in the default logging module.</p>
0
2016-10-10T23:52:33Z
[ "python", "python-2.7", "logging", "maya", "pymel" ]
Reading multiple CSV files with headers in python with numpy?
39,962,949
<p>Currently I am using this code to read one complete csv file to my code:</p> <pre><code>data = np.loadtxt('csv_Complete.csv', delimiter=',', skiprows=1) </code></pre> <p>However, Now I have multiple csv files that are in this format.</p> <p>Log1.csv</p> <pre><code>x1,x2,x3,x4.... 1.5,3,5,7,8 2,5,1.2,5,2 1,3,3,5....
1
2016-10-10T16:42:25Z
39,963,524
<p>It must be a <code>missing value</code> in file <code>log40a.csv</code>.</p> <p>I have the same error for file like:</p> <pre><code>x1,x2,x3,x4.... 1,3.3,5,7,8 2,5.1,,5.5,2 1,3,3,5,6 </code></pre> <p>Base on <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.loadtxt.html" rel="nofollow">documenta...
1
2016-10-10T17:19:47Z
[ "python" ]
Converting Nodejs signature hashing function to Python
39,962,967
<p>I'm trying to connect to an API that only has Nodejs doc, but I need to use Python.</p> <p>The official doc states the hhtp request need to be signed like this and only gives this code:</p> <pre><code>var pk = ".... your private key ...."; var data = JSON.strigify( {some JSON object} ); var signature = crypto.crea...
1
2016-10-10T16:43:27Z
39,963,293
<p>You should be able to use the python standard library to generate the hashed signature. This will encode the data with the signed key. Depending on the server you may have to manually set header values in your request as well.</p> <pre><code>import hmac import hashlib import base64 import json private_key = '123...
2
2016-10-10T17:04:20Z
[ "python", "node.js", "hash", "rsa", "http-signature" ]
How to import CSV file to django models
39,962,977
<p>I have Django models like this</p> <pre><code>class Revo(models.Model): SuiteName = models.CharField(max_length=255) Test_Case = models.CharField(max_length=255) FileName = models.CharField(max_length=255) Total_Action = models.CharField(max_length=255) Pass = models.CharField(max_len...
1
2016-10-10T16:43:54Z
39,967,865
<p>You can use the built in <a href="https://docs.python.org/3/library/csv.html" rel="nofollow">csv module</a> to turn your csv file into a <a href="https://docs.python.org/3/library/csv.html#csv.DictReader" rel="nofollow">dict like object</a>:</p> <pre><code>import csv with open('import.csv') as csvfile: reader ...
0
2016-10-10T22:44:59Z
[ "python", "django", "csv", "graph" ]
How to import CSV file to django models
39,962,977
<p>I have Django models like this</p> <pre><code>class Revo(models.Model): SuiteName = models.CharField(max_length=255) Test_Case = models.CharField(max_length=255) FileName = models.CharField(max_length=255) Total_Action = models.CharField(max_length=255) Pass = models.CharField(max_len...
1
2016-10-10T16:43:54Z
39,988,049
<p><strong>Before you start</strong></p> <p>The first thing to do is to normalize your database. The data in the CSV file isn't normalized - it need not be. However there is no reason for your table to reflect the structure of your CSV file.</p> <p>For exaple <code>DEMO_TEST_SUITE</code> is repeated and there's no re...
0
2016-10-11T22:59:18Z
[ "python", "django", "csv", "graph" ]
django-orm : How can I insert element to a table of a particular database
39,963,068
<p>I have 2 different database in setting.py. To do select operation I use following statement and is working fine:</p> <pre><code>all_data = Bugs.objects.using('database_one').filter(reporter=user_id, bug_status='resolved', resolution__in=all_resolutions)[:2] </code></pre> <p>But how can I pass the database value t...
0
2016-10-10T16:49:10Z
39,971,303
<p>From <a href="https://docs.djangoproject.com/en/1.10/topics/db/multi-db/#selecting-a-database-for-save" rel="nofollow">docs</a>:</p> <pre><code>row_to_be_added = TableName(pr=pr, case=case, comments=comments).save(using='bugzilla') </code></pre>
0
2016-10-11T06:07:26Z
[ "python", "mysql", "django", "django-orm" ]
Why jpeg image becomes 2D array after being loaded
39,963,151
<p>I have a jpeg image as follows:</p> <p><a href="http://i.stack.imgur.com/b0Dma.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/b0Dma.jpg" alt="enter image description here"></a> <br>Now I want to load this image to do image processing. I use the following code:</p> <pre><code>from scipy import misc import n...
1
2016-10-10T16:54:25Z
39,963,287
<p>From the docs here: <a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.misc.imread.html" rel="nofollow">http://docs.scipy.org/doc/scipy/reference/generated/scipy.misc.imread.html</a>, specify <code>mode='RGB'</code> to get the red, green, blue values. The output appears to default to conversion to a ...
-1
2016-10-10T17:03:47Z
[ "python", "image", "image-processing" ]
Approximating a sine function with tflearn
39,963,178
<p>I am attempting a ridiculously simplistic approximation of a sine function using tflearn, inspired by <a href="http://mourafiq.com/2016/05/15/predicting-sequences-using-rnn-in-tensorflow.html" rel="nofollow">this</a> paper. </p> <pre><code>import tflearn import tensorflow as tf import numpy as np import matplotlib...
0
2016-10-10T16:56:40Z
39,977,259
<p><strong>UPDATE</strong>: I was not assigning a shape to the <code>x = np.linspace(-np.pi,np.pi,10000)</code> tensor:</p> <p>Solved (@lejlot) by changing the line to <code>np.linspace(-np.pi,np.pi,10000).reshape(-1, 1)</code></p> <p>In the line <code>input_data(shape=[10,10000])</code> the shape of each input tenso...
0
2016-10-11T12:28:27Z
[ "python", "machine-learning", "neural-network", "tensorflow" ]
h2o.exceptions.H2OResponseError: Server error water.exceptions.H2OKeyNotFoundArgumentException
39,963,181
<p>I get this error when I run the code below.</p> <pre><code>import h2o from h2o.estimators.gbm import H2OGradientBoostingEstimator as GBM from sklearn import datasets import numpy as np import pandas as pd h2o.init(ip='192.168.0.4',port=54321) # writing data to CSV so that h2o can read it digits = datasets.load_di...
1
2016-10-10T16:56:45Z
39,967,391
<p>Change <code>model.start</code> into <code>model.train</code> (3rd line from the bottom), and it should work.</p> <p>The documentation for <code>model.start()</code> method says "Train the model asynchronously". This means that the model is being trained in the background and is not available right away for the pre...
1
2016-10-10T21:59:06Z
[ "python", "h2o" ]
LFSR code is giving wrong result
39,963,222
<p>I have the code for LFSR and getting wrong results, the first 8 bits should be 01110010 but i'm getting 0101111001.</p> <p>I'm talking about Galois LSFR: en.wikipedia.org/wiki/Linear-feedback_shift_register </p> <p>Can anyone see what the problem is with this code?</p> <pre><code>def lfsr(seed, taps): for i in ...
-1
2016-10-10T16:59:06Z
39,965,500
<p>My answer to the question posted, "Can anyone see what the problem is with this code?", is no. The code is operational, implementing an LFSR (of the type frequently used to do pseudorandom signals in hardware, and the basis for popular CRC functions). I'm left to guess at why you think it isn't. </p> <p>An LFSR of ...
1
2016-10-10T19:35:55Z
[ "python", "lfsr" ]
Discord API, get_member(user_id) errors
39,963,246
<p>I have this code and i am really curious about why it is not working. The problem is in <code>k = discord.Server.get_member(j)</code> it says</p> <blockquote> <p>"TypeError: get_member() missing 1 required positional argument: 'user_id'".</p> </blockquote> <p>This code uses <a href="https://pypi.python.org/pypi/...
1
2016-10-10T17:01:18Z
39,964,884
<p>This code is accessing a method of <code>discord.Server</code> as if it was a static method:</p> <pre><code>k = discord.Server.get_member(j) </code></pre> <p>Function <a href="https://github.com/Rapptz/discord.py/blob/v0.13.0/discord/server.py#L132" rel="nofollow"><code>get_member</code> is defined as</a>:</p> <p...
0
2016-10-10T18:50:36Z
[ "python", "python-3.x" ]
Change _FillValue in netCDF file
39,963,309
<p>Is there a python netCDF4 command/example to change the global metadata _FillValue in a netCDF file? I have tried replacing all -ve values in a netCDF file, but till the time the _FillValue attribute is set, that does not work</p>
0
2016-10-10T17:05:10Z
39,965,512
<p>I don't believe python netCDF4 has a specific function for this, but <a href="http://nco.sourceforge.net/nco.html#ncatted-netCDF-Attribute-Editor" rel="nofollow">NCO's ncatted</a> is an ideal tool for this task. </p> <p>From the docs:</p> <p>To change the missing value from the IEEE NaN value to a normal IEEE num...
1
2016-10-10T19:36:56Z
[ "python", "netcdf", "netcdf4" ]
Python to iterate through sheets and drop columns
39,963,349
<p>I need to read one excel file and perform some computations on each sheet. Basically, it needs to drop rows if the column date is not "today".</p> <p>I got this code so far:</p> <p> import datetime import pandas as pd</p> <pre><code>''' Parsing main excel sheet to save transactions != today's date ''' ma...
1
2016-10-10T17:07:51Z
39,963,401
<p>I think you need replace <code>i</code> to <code>dfs[i]</code>, because <code>dfs</code> is dict of <code>DataFrames</code>: </p> <pre><code>df1 = pd.DataFrame({'A':[1,2,3], 'B':[4,5,6], 'C':['10-05-2011','10-05-2012','10-10-2016']}) df1.C = pd.to_datetime(df1.C) print (df1) ...
1
2016-10-10T17:11:24Z
[ "python", "excel", "pandas", "text-parsing" ]
Speed up creation of numpy array from list
39,963,357
<p>I have a 33620x160 <code>pandas</code> <code>DataFrame</code> which has one column that contains lists of numbers. Each list entry in the <code>DataFrame</code> contains 30 elements.</p> <pre><code>df['dlrs_col'] 0 [0.048142470608688, 0.047021138711858, 0.04573... 1 [0.048142470608688, 0.047021138711...
2
2016-10-10T17:08:32Z
39,964,483
<p>you can do it this way:</p> <pre><code>In [140]: df Out[140]: dlrs_col 0 [0.048142470608688, 0.047021138711858, 0.04573] 1 [0.048142470608688, 0.047021138711858, 0.04573] 2 [0.048142470608688, 0.047021138711858, 0.04573] 3 [0.048142470608688, 0.047021138711858, 0.04573]...
1
2016-10-10T18:25:01Z
[ "python", "arrays", "performance", "pandas", "numpy" ]
Speed up creation of numpy array from list
39,963,357
<p>I have a 33620x160 <code>pandas</code> <code>DataFrame</code> which has one column that contains lists of numbers. Each list entry in the <code>DataFrame</code> contains 30 elements.</p> <pre><code>df['dlrs_col'] 0 [0.048142470608688, 0.047021138711858, 0.04573... 1 [0.048142470608688, 0.047021138711...
2
2016-10-10T17:08:32Z
39,965,177
<p>You can first convert to <code>numpy array</code> by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.values.html" rel="nofollow"><code>values</code></a>:</p> <pre><code>df = pd.DataFrame({'dlrs_col':[ [0.048142470608688, 0.047021138711858, 0.04573], [0.048142470608688, 0.047021138711...
0
2016-10-10T19:12:00Z
[ "python", "arrays", "performance", "pandas", "numpy" ]
need user to be able to input up to three letters at a time for python turtle to draw
39,963,364
<p>I have the code all worked out to be able to input one letter at a time but for some reason cant figure out how to make it so the user can input up to three letters for turtle to draw. this is my code so far. any help would be appreciated, thank you in advance</p> <pre><code>import turtle velcro = turtle.Turtle() w...
3
2016-10-10T17:09:00Z
39,964,056
<p>Maybe it's because you're typing multiple letters at once. Your program then checks if e. g. "ABC" matches "A". Try entering single letters.</p>
-1
2016-10-10T17:55:39Z
[ "python", "turtle-graphics" ]
need user to be able to input up to three letters at a time for python turtle to draw
39,963,364
<p>I have the code all worked out to be able to input one letter at a time but for some reason cant figure out how to make it so the user can input up to three letters for turtle to draw. this is my code so far. any help would be appreciated, thank you in advance</p> <pre><code>import turtle velcro = turtle.Turtle() w...
3
2016-10-10T17:09:00Z
40,050,122
<p>Since your letters print relative to the origin (0, 0), the trick is to divide the screen into portions (say thirds) and for each letter, move to the center of the appropriate portion before drawing the letter.</p> <p>I've reworked your code below to do the above (for up to three letters) and simplify some of your ...
0
2016-10-14T18:47:31Z
[ "python", "turtle-graphics" ]
list of strings - remove commonalities of common strings
39,963,368
<p>I'm struggling to come up with a way to solve this problem (and how to come up with a name for this question on stackoverflow).</p> <p>I need to somehow remove commonalities of strings preserving the remainder. </p> <p>Given a list such as the following:</p> <pre><code>l = ('first', 'first.second', 'fi...
1
2016-10-10T17:09:22Z
39,963,718
<p>I believe you need to define your problem a little more exactly before writing a solution. Here's what I infer from your test case:</p> <ol> <li>"Members" are delimited by periods: the same "member" can't appear in two tuple items.</li> <li>Each member should only appear once.</li> </ol> <p>The problem, though, is...
2
2016-10-10T17:32:20Z
[ "python", "algorithm" ]
list of strings - remove commonalities of common strings
39,963,368
<p>I'm struggling to come up with a way to solve this problem (and how to come up with a name for this question on stackoverflow).</p> <p>I need to somehow remove commonalities of strings preserving the remainder. </p> <p>Given a list such as the following:</p> <pre><code>l = ('first', 'first.second', 'fi...
1
2016-10-10T17:09:22Z
39,963,803
<p>If the output order is not important, this solution will give you the expected values.</p> <p>This is by implementation almost the same as @brianpck's answer. But I used sorting to deal with the <code>"x.y.z"</code> problem. And some extra explanations.</p> <pre><code>l = ('first', 'first.second', 'first...
2
2016-10-10T17:38:34Z
[ "python", "algorithm" ]
list of strings - remove commonalities of common strings
39,963,368
<p>I'm struggling to come up with a way to solve this problem (and how to come up with a name for this question on stackoverflow).</p> <p>I need to somehow remove commonalities of strings preserving the remainder. </p> <p>Given a list such as the following:</p> <pre><code>l = ('first', 'first.second', 'fi...
1
2016-10-10T17:09:22Z
39,969,725
<p>I think maybe i was trying too get too fancy with list and dict comprehensions. </p> <p>I believe i was able to solve the problem with the following:</p> <ol> <li>sort in-bound list</li> <li>use a variable for "previous list element" </li> <li>loop, and output the the current element replacing previous element (if...
0
2016-10-11T02:41:44Z
[ "python", "algorithm" ]
list of strings - remove commonalities of common strings
39,963,368
<p>I'm struggling to come up with a way to solve this problem (and how to come up with a name for this question on stackoverflow).</p> <p>I need to somehow remove commonalities of strings preserving the remainder. </p> <p>Given a list such as the following:</p> <pre><code>l = ('first', 'first.second', 'fi...
1
2016-10-10T17:09:22Z
39,988,612
<p>I've thought about this interesting problem some more and came up with a solution.</p> <p>The problem is fundamentally tree structured, regardless of which tree-like technique you end up using: </p> <ul> <li>an actual tree datatype (which is how I initially solved it, but it was much more verbose)</li> <li>recursi...
1
2016-10-12T00:09:07Z
[ "python", "algorithm" ]
Python: open two different tabs via selenium
39,963,422
<p>i try to open two different tabs in browser through Selenium. But when i finished query in first tab and switched to second tab, my next query perform in first tab again. What do i have to change for perform two queries in different tabs (not in one tab like now).</p> <pre><code> &lt;!-- language: python3 --&gt...
-2
2016-10-10T17:12:59Z
39,965,509
<p>The best solution for me is using window_handles, as <strong>Saurabh Gaur</strong> advised me. But before switching beetween tabs i should declare all my tabs. Just after that i can switch tabs like any iterable object. my solution is below:</p> <pre><code>for elem in range(0,3): driver.find_element_by_tag_nam...
0
2016-10-10T19:36:41Z
[ "python", "selenium" ]
Non hexadecimal digit found
39,963,516
<p>I received the following hex string which on conversion to binary throws error </p> <p>hex string : <code>value='(\xd2M\x00\x18\x00\x18\x80\x00\x80\x00\x00\x00\x00\x00\x00\xe0\xd2\xe0\xd2.\xd2\x00\x00\x00\x00\x00\x00\n\x00\x18\x00&amp;\x00\x00\x00\x00\x00\x00\x00\x0f0\xfe/\x010\xff/\x000\xff/\x000\xff/\xff/\xff/\xf...
-3
2016-10-10T17:19:05Z
39,963,544
<p>That's not a hex string. You are confusing the Python <code>repr()</code> output for a bytestring, which aims to make debugging easier, with the contents.</p> <p>Each <code>\xhh</code> is a standard Python string literal escape sequence, and displaying the string like this makes it trivial to copy and paste into an...
1
2016-10-10T17:20:57Z
[ "python" ]
How can I get a python code to run over and over again?
39,963,586
<p>I have a scraper that scrapes data from a website, then saves the data in .csv files. What I am looking for is a way to run this code every 10 minutes, without using a loop. I have very little knowledge on how to do this. What approach would you use?</p>
-3
2016-10-10T17:23:22Z
39,963,771
<p>It's impossible to repeat a code without a loop.</p> <p>I can only think that you want something like Task Scheluding on Windows (<a href="https://msdn.microsoft.com/pt-br/library/windows/desktop/aa383614.aspx" rel="nofollow">https://msdn.microsoft.com/pt-br/library/windows/desktop/aa383614.aspx</a>) or crontab/tim...
0
2016-10-10T17:36:05Z
[ "python", "web-scraping" ]
How can I get a python code to run over and over again?
39,963,586
<p>I have a scraper that scrapes data from a website, then saves the data in .csv files. What I am looking for is a way to run this code every 10 minutes, without using a loop. I have very little knowledge on how to do this. What approach would you use?</p>
-3
2016-10-10T17:23:22Z
39,963,778
<p>Are you using windows or a unix based system?</p> <p>If you're using UNIX, you can schedule jobs to take place at regular intervals with CRON.</p> <p>Execute the following in a terminal window:</p> <pre><code>#edit crontab crontab -e </code></pre> <p>Then add the required file you want to execute prefaced by the...
1
2016-10-10T17:36:30Z
[ "python", "web-scraping" ]
Downloading a file using TCP(Client/Server)?
39,963,631
<p>I am trying to make a TCP (Client and Server) in python to download a file that is available on the Server. I am a total beginner in networking in Python, and following a tutorial for this purpose. The problem I am getting is that whenever I try to download a file from the server I get this error:</p> <pre class="l...
0
2016-10-10T17:26:52Z
39,963,856
<p>You need to be sending <code>bytes</code> to the socket, not a <code>string</code>. You can convert a string to a bytes with <code>.encode()</code> Try:</p> <pre><code>message = "EXISTS " + str(os.path.getsize(filename))) sock.send(message.encode()) </code></pre> <p>As a side note, you don't need semicolons when ...
0
2016-10-10T17:42:27Z
[ "python", "networking", "tcp", "fileserver" ]
Python - Matplotlib in Tkinter: The toolbar pan and zoom doesnt change the cursor
39,963,669
<p>I've been developing a tkinter app, which has a matplotlib graph embeded in it. The problem i am having right now is :</p> <p>Allthough the functionality of the toolbar is working, it doesnt change the cursor which makes a worse user experience since you cant tell if you are zooming or not. From what i have seen fr...
1
2016-10-10T17:29:07Z
40,060,136
<p>Well I have encountered the same problem too, and oddly enough this is caused by the canvas and the toolbar not having the same master. Just making a new frame and putting the canvas and the toolbar in it will solve the problem. You still can place that frame with grid in your layout .</p>
1
2016-10-15T14:18:32Z
[ "python", "python-3.x", "matplotlib", "tkinter" ]
List of tab delimited arrays to numpy array?
39,963,693
<p>Win 7, x64, Python 2.7.12</p> <p>I have data in the form</p> <pre><code>myData = [[a1, b1, c1, d1, e1, f1, g1, h1], [a2, b2, c2, .... ], ..... ] </code></pre> <p>where <code>myData</code> is a <code>np.ndarray</code> of floats. I saved this by using the following...</p> <pre><code>with open('myData.txt', 'w') as...
0
2016-10-10T17:30:33Z
39,963,815
<p>You should use</p> <pre><code>numpy.save('myData.npy', myData) </code></pre> <p>which you can then read like</p> <pre><code>myData = numpy.load('myData.npy') </code></pre>
1
2016-10-10T17:39:06Z
[ "python", "arrays", "numpy", "multidimensional-array" ]
Download files from public S3 bucket with boto3
39,963,745
<p>I cannot download a file or even get a listing of the <strong>public</strong> S3 bucket with <code>boto3</code>.</p> <p>The code below works with my own bucket, but not with public one:</p> <pre><code>def s3_list(bucket, s3path_or_prefix): bsession = boto3.Session(aws_access_key_id=settings.AWS['ACCESS_KEY'], ...
4
2016-10-10T17:34:09Z
39,963,893
<p>I had the similar issue in the past. I have found a key to this bug in <a href="https://github.com/boto/boto3/issues/134" rel="nofollow">https://github.com/boto/boto3/issues/134</a> .</p> <p>You can use undocumented trick:</p> <pre><code>import botocore def s3_list(bucket, s3path_or_prefix, public=False): bs...
0
2016-10-10T17:44:27Z
[ "python", "boto3" ]
Easiest way to "fill" payload?
39,963,798
<p>I wan't to send a UDP packet with a arbitrary packet size depending on my input argument, so whenever my "data" is not enough to fill up the wanted packet payload I want to just "fill" the rest with empty data.</p> <p>So if I send <code>123</code> but I want the packet to be of size 100 bytes, the method will pad t...
-1
2016-10-10T17:38:23Z
39,963,995
<p>You could create a padding <code>bytearray()</code>, and just prepend (or append) it to your payload:</p> <pre><code>payload = b'123' padding_length = 100 - len(payload) padding_byte = b' ' return bytearray(padding_byte * padding_length) + payload </code></pre>
0
2016-10-10T17:51:49Z
[ "python", "sockets", "udp", "scapy" ]
Easiest way to "fill" payload?
39,963,798
<p>I wan't to send a UDP packet with a arbitrary packet size depending on my input argument, so whenever my "data" is not enough to fill up the wanted packet payload I want to just "fill" the rest with empty data.</p> <p>So if I send <code>123</code> but I want the packet to be of size 100 bytes, the method will pad t...
-1
2016-10-10T17:38:23Z
39,964,704
<p>I'm not a networking expert, but you might want to take a look at <a href="https://docs.python.org/3.5/library/struct.html" rel="nofollow">struct.pack()</a></p> <p>This will zero pad a length of characters and should be blazing fast:</p> <pre><code>from struct import pack result = pack('!100s', 'input_value') </c...
0
2016-10-10T18:38:57Z
[ "python", "sockets", "udp", "scapy" ]
Easiest way to "fill" payload?
39,963,798
<p>I wan't to send a UDP packet with a arbitrary packet size depending on my input argument, so whenever my "data" is not enough to fill up the wanted packet payload I want to just "fill" the rest with empty data.</p> <p>So if I send <code>123</code> but I want the packet to be of size 100 bytes, the method will pad t...
-1
2016-10-10T17:38:23Z
39,969,577
<p>Try this way:</p> <pre><code>&gt;&gt;&gt; from scapy.all import * WARNING: No route found for IPv6 destination :: (no default route?) &gt;&gt;&gt; p = IP(dst="62.21.20.21")/UDP() &gt;&gt;&gt; p = p/Raw('a'*(100-len(p))) &gt;&gt;&gt; send(p) . Sent 1 packets. &gt;&gt;&gt; # tcpdump -ni cplane0 udp -e -v -X tcpdump:...
0
2016-10-11T02:22:46Z
[ "python", "sockets", "udp", "scapy" ]
Searching for a named tuple in a list of named tuples
39,963,822
<p>I need to find out if a given named tuple exists in a list of named tuples (the named tuples are points ex. A(2,3) in a 'Polygon' class). If the given tuple doesn't exist in the list, we append the tuple to the list. If it dos exist, a user defined exception is raised. The function works when the given point doesn't...
-1
2016-10-10T17:39:40Z
39,963,915
<p>How about this ?</p> <pre><code>def setter(self,pt): def isThere(pt): if pt in self.points: raise ExistingPointError() print("Setting Point") try: isThere(pt) self.points.append(pt) except ExistingPointError as E: print("Point exists! value: ", E) ...
0
2016-10-10T17:46:08Z
[ "python", "list", "class", "python-3.x", "tuples" ]
Searching for a named tuple in a list of named tuples
39,963,822
<p>I need to find out if a given named tuple exists in a list of named tuples (the named tuples are points ex. A(2,3) in a 'Polygon' class). If the given tuple doesn't exist in the list, we append the tuple to the list. If it dos exist, a user defined exception is raised. The function works when the given point doesn't...
-1
2016-10-10T17:39:40Z
39,964,102
<p>You want to raise a user defined error, ExistingPointError(), yet you haven't really defined what that is. When i run your code and insert a duplicate tuple into a Polygon object, I get the following error:</p> <pre><code>Traceback (most recent call last): File "python", line 27, in &lt;module&gt; File "python", li...
0
2016-10-10T17:59:07Z
[ "python", "list", "class", "python-3.x", "tuples" ]
Why is AttributeError raised twice?
39,963,873
<pre><code>class ValidatingDB(object): def __init__(self): self.exists = 5 def __getattribute__(self, name): print('Called __getattribute__(%s)' % name) try: return super(ValidatingDB, self).__getattribute__(name) except AttributeError: value = 'Value for ...
-3
2016-10-10T17:43:21Z
39,964,057
<p>Your code doesn't allow you to see the difference between an <code>AttributeError</code> and an attribute existing. In both cases you get <em>exactly the same result</em>.</p> <p>So the first <code>data.foo</code> access raises an <code>AttributeError</code>, so a new value is created, set <em>and returned</em>.</p...
0
2016-10-10T17:55:45Z
[ "python", "python-2.7" ]
BeautifulSoup to return div class content
39,963,921
<pre><code>import requests from bs4 import BeautifulSoup url = 'https://weather.com/weather/today/l/90006:4:US' r = requests.get(url) html_content = r.text soup = BeautifulSoup(html_content, 'lxml') weather_row= soup.find('div', {"class" : "today_nowcard-hili"}) print weather_row </code></pre> <p>I found the class ...
1
2016-10-10T17:46:26Z
39,963,968
<p>It is <em>hilo</em> not <em>hili</em>:</p> <pre><code>soup.find('div', {"class" : "today_nowcard-hilo"}) </code></pre> <p>But you can see from what it returns that the data is inserted using Js:</p> <pre><code>&lt;div class="today_nowcard-hilo"&gt; &lt;span class="btn-text" data-ng-bind="::'H' | pfTranslate: {con...
1
2016-10-10T17:49:51Z
[ "python", "beautifulsoup" ]
Python: How to simulate a click using BeautifulSoup
39,963,972
<p><strong>I don't want to use selenium since I dont want to open any browsers.</strong></p> <p>The button triggers a Javascript method that changes something in the page. I want to simulate a button click so I can get the "output" from it.</p> <h2>Example (not what the button actually do) :</h2> <p>I enter a name s...
-2
2016-10-10T17:50:08Z
39,964,037
<p>You can't do what you want. Beautiful soup is a text processor which has no way to run JavaScript. </p>
2
2016-10-10T17:54:17Z
[ "python" ]
Python: How to simulate a click using BeautifulSoup
39,963,972
<p><strong>I don't want to use selenium since I dont want to open any browsers.</strong></p> <p>The button triggers a Javascript method that changes something in the page. I want to simulate a button click so I can get the "output" from it.</p> <h2>Example (not what the button actually do) :</h2> <p>I enter a name s...
-2
2016-10-10T17:50:08Z
39,964,061
<p>BeautifulSoup is an <code>HtmlParser</code> you can't do such thing. Buf if that button calls an API, you could make a <code>request</code> to that api and I guess that would simulate clicking the button.</p>
0
2016-10-10T17:55:47Z
[ "python" ]
Python NameError, global name not defined
39,964,028
<p>I am following <a href="https://code.tutsplus.com/tutorials/creating-a-web-app-from-scratch-using-python-flask-and-mysql--cms-22972" rel="nofollow">this</a> tutorial to create a Python 2.7 and Flask web app with a MySQL database.</p> <p>Why am I getting this error on <code>_password</code>?</p> <p><code>app.py</co...
-1
2016-10-10T17:53:56Z
39,964,464
<p>The reason is that the app can't be instantiated because you're calling upon names that haven't been created yet. It's almost NEVER a good idea to use <code>global</code> to move variables into the global scope. Don't do that.</p> <p>Even if you decided you don't care about best-practices, the variables won't get i...
1
2016-10-10T18:23:14Z
[ "python", "mysql", "flask" ]
Appending links to new rows in pandas df after using beautifulsoup
39,964,034
<p>I'm attempting to extract some links from a chunk of beautiful soup html and append them to rows of a new pandas dataframe. </p> <p>So far, I have this code:</p> <pre><code>url = "http://www.reed.co.uk/jobs datecreatedoffset=Today&amp;isnewjobssearch=True&amp;pagesize=100" r = ur.urlopen(url).read() soup = BShtml(...
0
2016-10-10T17:54:12Z
39,966,523
<p>Your links gives a 404 but the logic should be the same as below. You just need to extract the anchor tags with the <em>page</em> class and join them to the base url:</p> <pre><code>import pandas as pd from urlparse import urljoin import requests base = "http://www.reed.co.uk/jobs" url = "http://www.reed.co.uk/...
0
2016-10-10T20:49:12Z
[ "python", "pandas", "beautifulsoup", "append" ]
How to rotate tick labels in floating cylindrical axes?
39,964,068
<p><a href="http://matplotlib.org/mpl_toolkits/axes_grid/users/overview.html" rel="nofollow">http://matplotlib.org/mpl_toolkits/axes_grid/users/overview.html</a></p> <p>Check out the VERY bottom of this link. I'm interested in that axes in the middle, where the axis objects are curved into the shape of a quarter-washe...
1
2016-10-10T17:56:13Z
39,968,624
<p>The hint was in <code>setup_axes3()</code> from the example you linked. The individual axes in the <code>FloatingSubplot</code> are referred to like <code>ax.axis[side]</code> where <code>side</code> is one of <code>["top","bottom","left","right"]</code>. From there you get the usual.</p> <pre><code>ax = ax2.axis["...
1
2016-10-11T00:13:32Z
[ "python", "matplotlib", "plot" ]
No metadata download
39,964,096
<p>I'm using libtorrent 1.0.9 and custom bindings (reproducible with python). Sometimes I can not download magnets because they're stuck without metadata (while there're >200 DHT nodes available). I'm able to reproduce the issue with this magnet:</p> <pre><code>magnet:?xt=urn:btih:565DB305A27FFB321FCC7B064AFD7BD73AEDD...
0
2016-10-10T17:58:42Z
39,990,864
<p>This is most likely caused by a problem in the 1.0.x series, where some of the first responses from the DHT will make the node change its node ID (to match its external IP address, see <a href="http://libtorrent.org/dht_sec.html" rel="nofollow">this post</a>).</p> <p>It does this by restarting the DHT node. Any in-...
1
2016-10-12T05:05:11Z
[ "python", "bittorrent", "dht", "libtorrent", "libtorrent-rasterbar" ]
How to cast a int from string that contains not only numbers
39,964,234
<p>Casting a string is easy:</p> <pre><code>string1 = "12" int1 = int(string1) </code></pre> <p>But what if I want to extract the int from</p> <pre><code>string1 = "12 pieces" </code></pre> <p>The cast should return 12. Is there a pythonic way to do that and ignore any chars that are not numbers?</p>
0
2016-10-10T18:08:25Z
39,964,280
<p>How about this?</p> <pre><code>&gt;&gt;&gt; string1 = "12 pieces" &gt;&gt;&gt; y = int(''.join([x for x in string1 if x in '1234567890'])) &gt;&gt;&gt; print(y) 12 </code></pre> <p>or better yet:</p> <pre><code>&gt;&gt;&gt; string1 = "12 pieces" &gt;&gt;&gt; y = int(''.join([x for x in string1 if x.isdigit() ])) ...
1
2016-10-10T18:11:59Z
[ "python" ]
How to cast a int from string that contains not only numbers
39,964,234
<p>Casting a string is easy:</p> <pre><code>string1 = "12" int1 = int(string1) </code></pre> <p>But what if I want to extract the int from</p> <pre><code>string1 = "12 pieces" </code></pre> <p>The cast should return 12. Is there a pythonic way to do that and ignore any chars that are not numbers?</p>
0
2016-10-10T18:08:25Z
39,964,296
<blockquote> <p>Is there a way to do that and ignore any chars that are not numbers?</p> </blockquote> <p>Ignoring anything but a digit is, probably, not a good idea. What if a string contains <code>"12 pieces 42"</code>, should it return <code>12</code>, <code>1242</code>, <code>[12, 42]</code>, or raise an excepti...
1
2016-10-10T18:12:42Z
[ "python" ]
How to cast a int from string that contains not only numbers
39,964,234
<p>Casting a string is easy:</p> <pre><code>string1 = "12" int1 = int(string1) </code></pre> <p>But what if I want to extract the int from</p> <pre><code>string1 = "12 pieces" </code></pre> <p>The cast should return 12. Is there a pythonic way to do that and ignore any chars that are not numbers?</p>
0
2016-10-10T18:08:25Z
39,964,417
<p>Assuming that the first part of the string is a number, one way to do this is to use a regex match:</p> <pre><code>import re def strint(str): m=re.match("^[0-9]+", str) if m: return int(m.group(0)) else: raise Exception("String does not start with a number") </code></pre> <p>The advant...
1
2016-10-10T18:20:26Z
[ "python" ]
Python Updating Global variables
39,964,254
<p>Could anyone tell me what I am doing wrong in my code. How come, I cannot update my global variable? To my understanding, if it is a global variable I can modify it anywhere.</p> <p>If the numpy is creating a new array (when I use np.delete), what would be the best way to delete an element in an numpy array. </p> ...
2
2016-10-10T18:10:13Z
39,964,274
<p>If you want to use a global variable in a function, you have to say it's global IN THAT FUNCTION:</p> <pre><code>import numpy as np a = np.array(['a','b','c','D']) def hello(): global a a = np.delete(a, 1) print a hello() </code></pre> <p>If you wouldn't use the line <code>global a</code> in your fun...
5
2016-10-10T18:11:30Z
[ "python", "numpy" ]
Clean data in pandas
39,964,282
<p>I have the following dataframe:</p> <pre><code> Datum Unternehmen Event 0 9 Termine vom 01.01.2016 bis zum 31.12.2017 9 Termine vom 01.01.2016 bis zum 31.12.2017 NaN 1 9 Termine vom 01.01.2016 bis zum 31.12.2017 NaN NaN 2 Datum Unternehmen Event 3 12.05.2017 ADIDAS AG Divid...
0
2016-10-10T18:12:03Z
39,964,448
<p>I think you can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_datetime.html" rel="nofollow"><code>to_datetime</code></a> with parameter <code>errors='coerce'</code> and check where are not <code>NaN</code> with <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#boolean-...
1
2016-10-10T18:22:32Z
[ "python", "pandas" ]
Clean data in pandas
39,964,282
<p>I have the following dataframe:</p> <pre><code> Datum Unternehmen Event 0 9 Termine vom 01.01.2016 bis zum 31.12.2017 9 Termine vom 01.01.2016 bis zum 31.12.2017 NaN 1 9 Termine vom 01.01.2016 bis zum 31.12.2017 NaN NaN 2 Datum Unternehmen Event 3 12.05.2017 ADIDAS AG Divid...
0
2016-10-10T18:12:03Z
39,965,120
<p>I was looking for:</p> <pre><code>df[df['Datum'].str.contains("^[\d.]+$")] </code></pre> <p>Which selects the row according to the expression in the <code>.contains()</code> function.</p>
0
2016-10-10T19:07:28Z
[ "python", "pandas" ]
Instance variable name a reserved word in Python
39,964,360
<p>I checked the Python style guide, and I found no specific references to having instance variable names with reserved words e.g. <code>self.type</code>, <code>self.class</code>, etc.</p> <p>What's the best practice for this?</p>
0
2016-10-10T18:16:56Z
39,964,406
<p>Avoid it if possible.</p> <p>You can get and set such attributes via <code>getattr</code> and <code>setattr</code>, but they can't be accessed with ordinary dot syntax (something like <code>obj.class</code> is a syntax error), so they're a pain to use.</p> <p>As Aurora0001 mentioned in a comment, a convention if y...
1
2016-10-10T18:19:58Z
[ "python" ]
NameError: global name 'isdigit' is not defined. Cannot Understand what this python error means, this is my work using Kivy and python
39,964,384
<pre><code>class ScatterText(ScrollView): def val_change(self): label = ['bar','1','2','3','4','5','6','7','8','9','10','11','12','13'] label_b = self.ids['bar'] label[1] = self.ids['1'] label[2] = self.ids['2'] label[3] = self.ids['3'] label[4] = self.ids['4'] ...
-8
2016-10-10T18:18:43Z
39,964,521
<p><code>isdigit()</code> is a method on string objects, not a standalone method.</p> <p>In other words, you call it like this:</p> <pre><code>s = '1' if s.isdigit(): print 's is a digit!' </code></pre>
0
2016-10-10T18:27:54Z
[ "python" ]
How to generate random non-recurring numbers in a loop and within a range in python?
39,964,444
<blockquote> <p>Hi, I'm still a beginner and a bit lost. I'm working on a project for school that requires me to write different small programs that will 'guess' the given password. This is a bruteforce program, and I need it to guess every possible combination of 4 number passwords like those on the old iPhones. My ...
0
2016-10-10T18:21:52Z
39,964,533
<p>You probably want to check out all possible values for a password under certain rules, e.g "4 digits" or "8 lowercase characters". Consider these answers as starting points:</p> <ul> <li><a href="http://stackoverflow.com/a/7074066/37020">Generating 3-letter strings with itertools.product</a> for using an alphabet a...
0
2016-10-10T18:28:22Z
[ "python", "for-loop", "random", "while-loop", "range" ]
How to generate random non-recurring numbers in a loop and within a range in python?
39,964,444
<blockquote> <p>Hi, I'm still a beginner and a bit lost. I'm working on a project for school that requires me to write different small programs that will 'guess' the given password. This is a bruteforce program, and I need it to guess every possible combination of 4 number passwords like those on the old iPhones. My ...
0
2016-10-10T18:21:52Z
39,964,644
<p>If you really want to try all passwords in random order. this is more easily accomplished by</p> <pre><code>import random digits = [str(i) for i in range(10)] s = [''.join([a,b,c,d]) for a in digits for b in digits for c in digits for d in digits] random.shuffle(s) real_password = '1234' i = 0 for code in s: i...
1
2016-10-10T18:35:40Z
[ "python", "for-loop", "random", "while-loop", "range" ]
How to generate random non-recurring numbers in a loop and within a range in python?
39,964,444
<blockquote> <p>Hi, I'm still a beginner and a bit lost. I'm working on a project for school that requires me to write different small programs that will 'guess' the given password. This is a bruteforce program, and I need it to guess every possible combination of 4 number passwords like those on the old iPhones. My ...
0
2016-10-10T18:21:52Z
39,964,679
<p>You have two <code>while</code> loops, so even though you attempt to <code>break</code> when you find the password, the outer (first) <code>while</code> loop just starts it off all over again.</p> <p>If you want unique guesses then you would have to look into permutations. However, since it's reasonable to assume t...
0
2016-10-10T18:37:08Z
[ "python", "for-loop", "random", "while-loop", "range" ]
Python convert string to categorical - numpy
39,964,451
<p>I'm desperately trying to change my string variables <code>day</code>,<code>car2</code>, in the following dataset. </p> <pre><code>&lt;class 'pandas.core.frame.DataFrame'&gt; Int64Index: 23653 entries, 0 to 23652 Data columns (total 7 columns): day 23653 non-null object clustDep 23653 non-null...
2
2016-10-10T18:22:40Z
39,964,661
<p>It works just fine for me (Pandas 0.19.0):</p> <pre><code>In [155]: train Out[155]: day clustDep clustArr car2 clustRoute scheduled_seg delayed 0 Saturday 12 15 AA 1 5 1 1 Tuesday 12 15 AA 1 1 1 2 Tuesd...
1
2016-10-10T18:36:23Z
[ "python", "numpy", "dataframe", "categorical-data" ]
Read outlook mail in html format
39,964,549
<p>I receive a mail in Microsoft Outlook that contains a html table. I would like to parse this in to a pandas dataframe. </p> <p>I have already written a script that uses beautiful soup to parse the html text in to the dataframe. But I am struggling with reading the email in html in the first place. </p> <p>Having f...
0
2016-10-10T18:29:30Z
39,984,914
<p>Found the answer myself. I should use msg.HTMLBody rather than msg.Body</p>
0
2016-10-11T19:10:29Z
[ "python", "html", "email", "outlook" ]
numpy: efficiently add rows of a matrix
39,964,555
<p>I have a matrix. </p> <pre><code>mat = array([ [ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11] ]) </code></pre> <p>I'd like to get the sum of the rows at certain indices: eg.</p> <pre><code>ixs = np.array([0,2,0,0,0,1,1]) </code></pre> <p>I know I can compute the answer as:</p> <pre><code>mat[...
3
2016-10-10T18:30:02Z
39,964,818
<p>Since we are assuming that <code>ixs</code> could be <em>sparsey</em>, we could modify the strategy to get the summations of rows from the <code>zero-th</code> row and rest of the rows separately based on the given row indices. So, we could use the <code>bincount</code> method for the <code>non-zero-th</code> indexe...
2
2016-10-10T18:46:59Z
[ "python", "numpy", "indexing" ]
numpy: efficiently add rows of a matrix
39,964,555
<p>I have a matrix. </p> <pre><code>mat = array([ [ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11] ]) </code></pre> <p>I'd like to get the sum of the rows at certain indices: eg.</p> <pre><code>ixs = np.array([0,2,0,0,0,1,1]) </code></pre> <p>I know I can compute the answer as:</p> <pre><code>mat[...
3
2016-10-10T18:30:02Z
39,965,947
<p>An alternative to <code>bincount</code> is <code>add.at</code>:</p> <pre><code>In [193]: mat Out[193]: array([[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11]]) In [194]: ixs Out[194]: array([0, 2, 0, 0, 0, 1, 1]) In [195]: J = np.zeros(mat.shape[0],int) In [196]: np.add.at(J, ixs, 1) In [197]: ...
2
2016-10-10T20:05:47Z
[ "python", "numpy", "indexing" ]
numpy: efficiently add rows of a matrix
39,964,555
<p>I have a matrix. </p> <pre><code>mat = array([ [ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11] ]) </code></pre> <p>I'd like to get the sum of the rows at certain indices: eg.</p> <pre><code>ixs = np.array([0,2,0,0,0,1,1]) </code></pre> <p>I know I can compute the answer as:</p> <pre><code>mat[...
3
2016-10-10T18:30:02Z
39,975,586
<p>After much number crunching (see Conclusions of original Question), the best-performing answer, when the inputs are defined as follows:</p> <pre><code>rng = np.random.RandomState(1234) mat = rng.randn(1000, 500) ixs = rng.choice(rng.randint(mat.shape[0], size=mat.shape[0]/10), size=1000) </code></pre> <p>Seems to ...
0
2016-10-11T10:48:04Z
[ "python", "numpy", "indexing" ]
Pandas max value index
39,964,558
<p>I have a Pandas DataFrame with a mix of screen names, tweets, fav's etc. I want find the max value of 'favcount' (which i have already done) and also return the screen name of that 'tweet'</p> <pre><code>df = pd.DataFrame() df['timestamp'] = timestamp df['sn'] = sn df['text'] = text df['favcount'] = fav_count pr...
1
2016-10-10T18:30:08Z
39,964,614
<p>use <code>.argmax()</code> to get the index of the max value. then you can use <code>loc</code></p> <pre><code>df.loc[df['favcount'].argmax(), 'sn'] </code></pre>
1
2016-10-10T18:34:23Z
[ "python", "pandas", "twitter", "indexing", "max" ]
Pandas max value index
39,964,558
<p>I have a Pandas DataFrame with a mix of screen names, tweets, fav's etc. I want find the max value of 'favcount' (which i have already done) and also return the screen name of that 'tweet'</p> <pre><code>df = pd.DataFrame() df['timestamp'] = timestamp df['sn'] = sn df['text'] = text df['favcount'] = fav_count pr...
1
2016-10-10T18:30:08Z
39,964,631
<p>I think you need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.idxmax.html" rel="nofollow"><code>idxmax</code></a> - get index of max value of <code>favcount</code> and then select value in column <code>sn</code> by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas....
1
2016-10-10T18:35:19Z
[ "python", "pandas", "twitter", "indexing", "max" ]
How do I iterate through a list of strings and print each item?
39,964,625
<p>I have a list of strings and print each of the strings in the list, meaning not <code>['word1','word2','word3']</code> but instead: <code>word1</code>, <code>word2</code>, <code>word3</code>.</p> <p>I tried doing this:</p> <pre><code>for i in list: print list[i] </code></pre> <p>but I get the message </p> <...
-1
2016-10-10T18:35:05Z
39,964,700
<pre><code>for i in list: print i </code></pre> <p>I is the list element: in other words, it takes on the values of the member strings, in order.</p>
3
2016-10-10T18:38:50Z
[ "python", "string", "list" ]
How do I iterate through a list of strings and print each item?
39,964,625
<p>I have a list of strings and print each of the strings in the list, meaning not <code>['word1','word2','word3']</code> but instead: <code>word1</code>, <code>word2</code>, <code>word3</code>.</p> <p>I tried doing this:</p> <pre><code>for i in list: print list[i] </code></pre> <p>but I get the message </p> <...
-1
2016-10-10T18:35:05Z
39,964,820
<p>Firstly, don't name your variable <code>list</code>, since that is a python built-in reserved class. You'll save yourself confusion later. Let's call it <code>lst</code>, here. </p> <p>Now, to your error. </p> <blockquote> <p>"list indices must be integers, not str"</p> </blockquote> <p><code>lst[i]</code> is a...
1
2016-10-10T18:47:05Z
[ "python", "string", "list" ]
Error with math equation
39,964,627
<p>My problem is that if you look at 'support' variable. (In the variable list) it doesn't apply to the Current Consumption. For EX. If I press 'S' and enter to start the game then press 'M' to display missions then press 'S' to choose the Survivors mission. And I recieve 2 survivors. That count won't add to the suppo...
0
2016-10-10T18:35:06Z
39,964,870
<p>You're never updating your <code>support</code> variable after you set it the first time so each time you print it out it's the same. Since <code>support</code> is dependent on <code>human</code>, you should either recalculate <code>support</code> every time <code>human</code> is updated or have a function like <co...
1
2016-10-10T18:49:59Z
[ "python" ]
Error with math equation
39,964,627
<p>My problem is that if you look at 'support' variable. (In the variable list) it doesn't apply to the Current Consumption. For EX. If I press 'S' and enter to start the game then press 'M' to display missions then press 'S' to choose the Survivors mission. And I recieve 2 survivors. That count won't add to the suppo...
0
2016-10-10T18:35:06Z
39,964,905
<p>As far as I can see at a quick glance you are only assigning value to the 'support' variable once in the code:</p> <pre><code>support = 0.1 * human </code></pre> <p>and I don't think this code gets to run again. Once support gets a value through this assignment statement it is not going to update even if you updat...
0
2016-10-10T18:51:54Z
[ "python" ]
Error "virtualenv : command not found" but install location is in PYTHONPATH
39,964,635
<p>This has been driving me crazy for the past 2 days. I installed virtualenv on my Macbook using <code>pip install virtualenv</code>. But when I try to create a new virtualenv using <code>virtualenv venv</code>, I get the error saying "virtualenv : command not found".</p> <p>I used <code>pip show virtualenv</code> an...
0
2016-10-10T18:35:23Z
39,972,160
<p>The only workable approach I could figure out (with help from @Gator_Python was to do <code>python -m virtualenv venv</code>. This creates the virtual environment and works as expected.</p> <p>I have custom python installed and maybe that's why the default approach doesn't work for me.</p>
0
2016-10-11T07:17:01Z
[ "python", "python-2.7", "pip" ]
Error "virtualenv : command not found" but install location is in PYTHONPATH
39,964,635
<p>This has been driving me crazy for the past 2 days. I installed virtualenv on my Macbook using <code>pip install virtualenv</code>. But when I try to create a new virtualenv using <code>virtualenv venv</code>, I get the error saying "virtualenv : command not found".</p> <p>I used <code>pip show virtualenv</code> an...
0
2016-10-10T18:35:23Z
39,977,369
<p>As mentioned in the comments, you've got the virtualenv module installed properly in the expected environment since <code>python -m venv</code> allows you to create virtualenv's. </p> <p>The fact that <code>virtualenv</code> is not a recognized command is a result of the <code>virtualenv.py</code> not being in your...
0
2016-10-11T12:34:54Z
[ "python", "python-2.7", "pip" ]
How to use the Xpath and CSS selector in for function
39,964,639
<p>I am a rookie, and want use the scrapy framework to grab something, but I have trouble:</p> <p>Html A:</p> <pre><code>&lt;ul class="tip" id="tip1"&gt; &lt;li id="tip1_0"&gt; &lt;a href="http://***" title="***" target="_self"&gt;*** &lt;/a&gt; &lt;/li&gt; &lt;li id="tip1_1"&gt; &...
0
2016-10-10T18:35:29Z
39,964,681
<p>You could have made your inner expressions context-specific by prepending dots:</p> <pre><code>f = line.xpath('./a/@href').extract() d = line.xpath('./a/@title').extract() </code></pre> <p>Or, point your outer expression to <code>a</code> and get the <code>@href</code> and <code>@title</code>:</p> <pre><code>file...
1
2016-10-10T18:37:13Z
[ "python", "html", "css", "xpath" ]
Splitting one column into many, counting frequency: 'int' object is not iterable
39,964,728
<p>This is my first question on stack overflow and it may be a bit clunky as I learn the ropes - tips or pointers in question formatting welcome!</p> <p>I'm very new to python and have an issue nearly identical to the one below:</p> <p><a href="http://stackoverflow.com/questions/33596216/how-to-split-one-column-into-...
1
2016-10-10T18:40:30Z
39,964,826
<p>Is that what you want?</p> <pre><code>In [8]: df Out[8]: logger page 0 10.1.60.203 3 1 3.75.190.181 5 2 10.1.60.203 4 3 10.1.60.203 6 4 10.1.60.253 1 In [9]: df.pivot_table(index='logger', columns='page', aggfunc='size', fill_value=0) Out[9]: page 1 3 4 5 6 logge...
0
2016-10-10T18:47:24Z
[ "python", "pandas", "dataframe", "pivot-table", "iterable" ]
How to make a list of lists in Python when it has multiple separators?
39,964,756
<p>The sample file looks like this (all on one line, wrapped for legibility):</p> <pre><code> ['&gt;1\n', 'TCCGGGGGTATC\n', '&gt;2\n', 'TCCGTGGGTATC\n', '&gt;3\n', 'TCCGTGGGTATC\n', '&gt;4\n', 'TCCGGGGGTATC\n', '&gt;5\n', 'TCCGTGGGTATC\n', '&gt;6\n', 'TCCGTGGGTATC\n', '&gt;7\n', 'TCCGTGGGTATC\n', '&gt;8\n', 'TCC...
0
2016-10-10T18:42:47Z
39,964,871
<p>You can exploit the smaller length of the headers (and other unwanted items) as the criterion to filter them out. You start by creating a list containing one list and <em>appending</em> the items that pass the length test to the inner list. </p> <p>A new sublist is added to the resulting list when the <em>separator...
2
2016-10-10T18:50:02Z
[ "python", "list", "readfile", "strip" ]
How to make a list of lists in Python when it has multiple separators?
39,964,756
<p>The sample file looks like this (all on one line, wrapped for legibility):</p> <pre><code> ['&gt;1\n', 'TCCGGGGGTATC\n', '&gt;2\n', 'TCCGTGGGTATC\n', '&gt;3\n', 'TCCGTGGGTATC\n', '&gt;4\n', 'TCCGGGGGTATC\n', '&gt;5\n', 'TCCGTGGGTATC\n', '&gt;6\n', 'TCCGTGGGTATC\n', '&gt;7\n', 'TCCGTGGGTATC\n', '&gt;8\n', 'TCC...
0
2016-10-10T18:42:47Z
39,965,048
<p>Here is a variation of Moses Koledoye's answer which examines the first character for <code>&gt;</code> and discards any matches as well as any empty elements. I also included replacing "-" with "Z".</p> <pre><code>lst = ['&gt;1\n', 'TCCGGGGGTATC\n', '&gt;2\n', 'TCCGTGGGTATC\n', '&gt;3\n', 'TCCGTGGGTATC\n', '&g...
1
2016-10-10T19:02:46Z
[ "python", "list", "readfile", "strip" ]
Python IndexError: too many indices for array when trying to append two csv files
39,964,775
<p>I keep getting this error whenever I try to append two csv files together.</p> <pre><code>log1 = np.genfromtxt('log40a.csv', dtype = float, delimiter=',', skip_header =1) log2 = np.genfromtxt('log40b.csv', dtype = float, delimiter=',', skip_header= 1) data = np.append(log1, log2) </code></pre> <p>This is the line ...
1
2016-10-10T18:43:45Z
39,965,088
<p>Just remove <code>,0</code> and everything will work fine.</p> <pre><code>mSec = data[:] </code></pre> <p>This traceback</p> <pre><code> File "C:/Users/Myname/.spyder2-py3/setdataexp.py", line 11, in &lt;module&gt; mSec = data[:,0] </code></pre> <p>said that it is a problem in your code.</p> <p><strong>U...
1
2016-10-10T19:05:14Z
[ "python" ]
Python IndexError: too many indices for array when trying to append two csv files
39,964,775
<p>I keep getting this error whenever I try to append two csv files together.</p> <pre><code>log1 = np.genfromtxt('log40a.csv', dtype = float, delimiter=',', skip_header =1) log2 = np.genfromtxt('log40b.csv', dtype = float, delimiter=',', skip_header= 1) data = np.append(log1, log2) </code></pre> <p>This is the line ...
1
2016-10-10T18:43:45Z
39,965,118
<p>Giving the python documetation and you are using numpay you need to check this method for fusing existing arrays <code>numpy.concatenate</code> Ex taked from the docs: </p> <pre><code>&gt;&gt;&gt; a = np.array([[1, 2], [3, 4]]) &gt;&gt;&gt; b = np.array([[5, 6]]) &gt;&gt;&gt; np.concatenate((a, b), axis=0) array([...
1
2016-10-10T19:07:20Z
[ "python" ]
Unable to update dictionary
39,964,791
<p>I am facing this problem while trying to code a Sudoku solver (with some parts referencing to <a href="http://norvig.com/sudoku.html" rel="nofollow">http://norvig.com/sudoku.html</a>)</p> <p>Here's the code I have made so far with reference to the above URL.</p> <p><div class="snippet" data-lang="js" data-hide="fa...
1
2016-10-10T18:45:11Z
39,964,872
<p>You're calling the function again, so it returns a new dictionary. You need to assign the result of the first call to a variable and mutate that.</p> <pre><code>result = dict_puzzle(puzzle,cell) result['11'] = 'die' print(result) </code></pre>
1
2016-10-10T18:50:09Z
[ "python", "dictionary" ]
Getting 'large' errors that seem too big to be from rounding alone
39,964,995
<p>When I use Python, I'm getting some significant rounding errors that seem too large for simply floating point problems. I have the following variables:</p> <pre><code>p = 2.2*10**9 m = 0.510999*10**6 </code></pre> <p>I then send it through the following:</p> <pre><code>b = 1/np.sqrt((m/p)**2 + 1) = 0.999999973024...
2
2016-10-10T18:58:06Z
39,966,598
<p>It is the operation</p> <pre><code>sqrt(1+x) </code></pre> <p>that loses you that much precision. Or really the <code>1+x</code> part of it. As your <code>x=(m/p)**2</code> has the magnitude <code>1e-6</code>, you lose about 5-6 digits of the 15-16 valid decimal digits of <code>x</code>, so that only 9-10 valid di...
4
2016-10-10T20:54:34Z
[ "python", "python-3.x", "numpy", "math", "rounding" ]
Discontinuity in graphs but no discontinuity in data in plotting dataframes using matplotlib
39,965,003
<p>I'm trying to plot predictions using scikit-learn, pandas, and matplotlib. I'm able to predict the data and able to save them in dataframes. But now when I plot them there are two cases.</p> <h3>1st case</h3> <p>I created a new column for the forecast predictions and plot them with the values i predicted from <cod...
0
2016-10-10T18:59:14Z
39,965,296
<p>if you want the line to be continuous the data needs to overlap or a continuous series from 1 column. an easy way to do this would be to replace NA's in Forecast by adj close before plotting such has:</p> <pre><code>df['Adj. Close'].fillna(df.Forecast, inplace=True).plot() </code></pre>
0
2016-10-10T19:21:42Z
[ "python", "pandas", "matplotlib" ]
Discontinuity in graphs but no discontinuity in data in plotting dataframes using matplotlib
39,965,003
<p>I'm trying to plot predictions using scikit-learn, pandas, and matplotlib. I'm able to predict the data and able to save them in dataframes. But now when I plot them there are two cases.</p> <h3>1st case</h3> <p>I created a new column for the forecast predictions and plot them with the values i predicted from <cod...
0
2016-10-10T18:59:14Z
39,968,124
<p>There <em>is</em> a discontinuity in your data - the last <code>Adj. close</code> value was recorded on 08/24 and the first <code>Forecast</code> value is for 08/25.</p> <p>In order to have no breaks in the line you would need the ends of your two series to overlap by at least one timepoint. You could, for example,...
0
2016-10-10T23:12:19Z
[ "python", "pandas", "matplotlib" ]
Optimizing Python 3n + 1 Programming Challange
39,965,107
<p>I am trying to find a efficient solution for the 3n + 1 problem on <a href="https://uva.onlinejudge.org/index.php?option=com_onlinejudge&amp;Itemid=8&amp;category=3&amp;page=show_problem&amp;problem=36" rel="nofollow">uvaonlinejudge</a>. The code I have uses memoization using a dictionary. Can anyone suggest an impr...
-2
2016-10-10T19:06:18Z
39,965,831
<p>I found the problem in your code. Actually, you are not saving <code>cycLenDict</code> generated on the previous interval for next one. And this is why your code is so "slow" because it will generate all possible endings over and over again. Just move it in global scope or make something like this:</p> <pre><code>i...
0
2016-10-10T19:57:28Z
[ "python", "optimization" ]
Optimizing Python 3n + 1 Programming Challange
39,965,107
<p>I am trying to find a efficient solution for the 3n + 1 problem on <a href="https://uva.onlinejudge.org/index.php?option=com_onlinejudge&amp;Itemid=8&amp;category=3&amp;page=show_problem&amp;problem=36" rel="nofollow">uvaonlinejudge</a>. The code I have uses memoization using a dictionary. Can anyone suggest an impr...
-2
2016-10-10T19:06:18Z
39,965,896
<p>The code seems to do the right thing to execute <code>maxCycle</code> optimally by caching all calculated results in <code>mydict</code>.</p> <p>However, the input to the application consists of many pairs of values to be processed and <code>maxCycle</code> will reset <code>mydict = {}</code> and calculate everythi...
0
2016-10-10T20:01:28Z
[ "python", "optimization" ]