Unnamed: 0
int64
0
15.9k
cleaned_code
stringlengths
67
124k
cleaned_prompt
stringlengths
168
30.3k
7,900
<ASSISTANT_TASK:> Python Code: last_match_winner = defaultdict(int) dataset['HomeTeamWonLast'] = 0 for index,row in dataset.iterrows(): home_team = row['home'] visitor_team = row['visitor'] teams = tuple(sorted([home_team,visitor_team])) row['HomeTeamWonLast'] = 1 if last_match_winner[teams] == home_tea...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: 特征数增加后,决策 Step2: 决策树可以用这些特征值进行训练,但DecisionTreeClassifier仍把它们当作连续型特 Step3: 使用随机森林
7,901
<ASSISTANT_TASK:> Python Code: # Import modules import numpy as np # Import PySwarms import pyswarms as ps # Some more magic so that the notebook will reload external python modules; # see http://stackoverflow.com/questions/1907993/autoreload-of-modules-in-ipython %load_ext autoreload %autoreload 2 def distance(query,...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: IK as an Optimization Problem Step2: We are going to use the distance function to compute the cost, the further away the more costly the positi...
7,902
<ASSISTANT_TASK:> Python Code: import numpy as np import os import pandas as pd import datetime as dt import matplotlib.pyplot as plt import torch from torch.utils.data import DataLoader from deep4cast.forecasters import Forecaster from deep4cast.models import WaveNet from deep4cast.datasets import TimeSeriesDataset im...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Dataset Step2: Divide into train and test Step3: We've also found that it is not necessary to train on the full dataset, so we here select a 1...
7,903
<ASSISTANT_TASK:> Python Code: %pylab inline import seaborn as sns import warnings warnings.filterwarnings("ignore") import pandas as pd def strip_parentheses(col, df): ''' splits single column strings of "value (error)" into two columns of value and error input: -string name of column to split in...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: The tables define the value and error as a string Step2: Table 1 - Basic data on sources Step3: Table 3- IRAC photometry Step4: Convert spect...
7,904
<ASSISTANT_TASK:> Python Code: import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns %matplotlib inline df = pd.read_csv('kyphosis.csv') df.head() sns.pairplot(df,hue='Kyphosis',palette='Set1') from sklearn.model_selection import train_test_split X = df.drop('Kyphosis',axis=1) ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Get the Data Step2: EDA Step3: Train Test Split Step4: Decision Trees Step5: Prediction and Evaluation Step6: Tree Visualization Step7: Ra...
7,905
<ASSISTANT_TASK:> Python Code: import warnings warnings.filterwarnings("ignore") import numpy as np import scipy.stats as st from sci_analysis import analyze %matplotlib inline import numpy as np import scipy.stats as st from sci_analysis import analyze np.random.seed(987654321) data = st.norm.rvs(size=1000) analyze(...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: This will tell python to import the sci-analysis function analyze(). Step2: Now, sci-analysis should be ready to use. Try the following code St...
7,906
<ASSISTANT_TASK:> Python Code: import numpy as np import active import experiment import logistic_regression as logr from sklearn import datasets # The Iris dataset is imported from here. from IPython.display import display import matplotlib.pyplot as plt %matplotlib inline %load_ext autoreload %autoreload 1 %aimport a...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Importing and processing the Iris data set Step2: Experimental procedure Step3: The experiment
7,907
<ASSISTANT_TASK:> Python Code: upload_dir = './sketch' import boto runThis = 0 if runThis: conn = boto.connect_s3() b = conn.create_bucket('sketchpad_basic_pilot2_sketches') all_files = [i for i in os.listdir(upload_dir) if i != '.DS_Store'] for a in all_files: print a k = b.new_key(a) ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: build stimulus dictionary Step2: upload stim dictionary to mongo (db = 'stimuli', collection='sketchpad_basic_recog') Step4: crop 3d objects
7,908
<ASSISTANT_TASK:> Python Code: width = 20 height = 5*9 width * height tax = 8.25 / 100 price = 100.50 price * tax price + _ round(_, 2) print('spam email') # This would cause error print('doesn't') # One way of doing it correctly print('doesn\'t') # Another way of doing it correctly print("doesn't") print(''' Usag...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Calculator Step2: Strings Step3: show ' and " in a string Step4: span multiple lines Step5: slice and index Step6: Index in the Python way ...
7,909
<ASSISTANT_TASK:> Python Code: NAME = "Michelle Appel" NAME2 = "Verna Dankers" NAME3 = "Yves van Montfort" EMAIL = "michelle.appel@student.uva.nl" EMAIL2 = "verna.dankers@student.uva.nl" EMAIL3 = "yves.vanmontfort@student.uva.nl" %pylab inline plt.rcParams["figure.figsize"] = [20,10] def true_mean_function(x): re...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Lab 3 Step2: Part 1 Step3: 1. Sampling from the Gaussian process prior (30 points) Step4: 1.2 computeK( X1, X2, thetas ) (10 points) Step5: ...
7,910
<ASSISTANT_TASK:> Python Code: import logging logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO) from gensim import corpora, models, similarities dictionary = corpora.Dictionary.load('/tmp/deerwester.dict') corpus = corpora.MmCorpus('/tmp/deerwester.mm') # comes from the first ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Similarity Interface Step2: To follow Deerwester’s example, we first use this tiny corpus to define a 2-dimensional LSI space Step3: Now suppo...
7,911
<ASSISTANT_TASK:> Python Code: import h2o import imp from h2o.estimators.kmeans import H2OKMeansEstimator # Start a local instance of the H2O engine. h2o.init(); iris = h2o.import_file(path="https://github.com/h2oai/h2o-3/raw/master/h2o-r/h2o-package/inst/extdata/iris_wheader.csv") iris.describe() try: imp.find_...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: The next step of using H2O is to parse and load data into H2O's in-memory columnar compressed storage. Today we will be using the Iris flower d...
7,912
<ASSISTANT_TASK:> Python Code: import numpy as np # returns a random d dimensional vector, a direction to peturb in def direction(d,t): # if type == uniform if(t == 'u'): return np.random.uniform(-2/np.sqrt(d), 2/np.sqrt(d), d) elif(t == 'n'): return np.random.normal(0, 1/np.sqrt(d), d) ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: So from the histograms above we can see all these methods give us points on the unit sphere. (Uniform gives us almost) But are they all uncorrel...
7,913
<ASSISTANT_TASK:> Python Code: import numpy as np from cStringIO import StringIO import matplotlib.pyplot as plt import caffe from IPython.display import clear_output, Image, display import cv2 import PIL.Image import os os.chdir("start_deep/") caffe.set_mode_cpu() caffe.set_device(0) caffe.set_mode_gpu() net = caff...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Caffe computation mode Step2: GPU Step3: Network loading and tests Step4: The cell bellows checks that opencv and its python bindings are pro...
7,914
<ASSISTANT_TASK:> Python Code: class Node : def __init__(self , data ) : self . data = data self . next = None   def fun1(head ) : if(head == None ) : return  fun1(head . next ) print(head . data , end = "▁ ")  def fun2(start ) : if(start == None ) : return  print(start . data , end =...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description:
7,915
<ASSISTANT_TASK:> Python Code: %matplotlib inline import matplotlib.pyplot as plt import seaborn as sns import numpy as np sns.set_style('white') from scipy.interpolate import griddata from scipy.interpolate import interp1d from scipy.interpolate import interp2d xb=np.array([-5,-4,-3,-2,-1,0,1,2,3,4,5]) yb=np.array([-...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Sparse 2d interpolation Step2: The following plot should show the points on the boundary and the single point in the interior Step3: Use meshg...
7,916
<ASSISTANT_TASK:> Python Code: # Import all necessary libraries, this is a configuration step for the exercise. # Please run it before the simulation code! import numpy as np import matplotlib.pyplot as plt import matplotlib.animation as animation # Show the plots in the Notebook. plt.switch_backend("nbagg") # Initial...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: 1. Initialization of setup Step2: 2. Finite Volumes setup Step3: 3. Initial condition Step4: 4. Solution for the scalar advection problem
7,917
<ASSISTANT_TASK:> Python Code: %matplotlib inline import random, datetime import numpy as np import matplotlib.pyplot as plt import matplotlib import statsmodels.api as sm from scipy.stats import norm from scipy.stats.stats import pearsonr # str, int, float str(3) "chengjun wang" # int int('5') # float float('7.1') ra...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Variable Type Step2: dir & help Step3: type Step4: Data Structure Step5: 定义函数 Step6: For 循环 Step7: map Step8: if elif else Step9: while循...
7,918
<ASSISTANT_TASK:> Python Code: from __future__ import print_function, division % matplotlib inline from thinkbayes2 import Hist, Pmf, Suite pmf = Pmf() for x in [1,2,3,4,5,6]: pmf[x] = 1 pmf.Print() pmf.Normalize() pmf.Print() pmf = Pmf([1,2,3,4,5,6]) pmf.Print() pmf.Prob(1) pmf[1] pmf = Pmf() pmf['Bowl...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: The Pmf class Step2: To be true probabilities, they have to add up to 1. So we can normalize the Pmf Step3: The return value from Normalize i...
7,919
<ASSISTANT_TASK:> Python Code: from __future__ import print_function %matplotlib inline import openpathsampling as paths import numpy as np old_store = paths.Storage("mstis_bootstrap.nc", mode='r') print("PathMovers: "+ str(len(old_store.pathmovers))) print("Samples: " + str(len(old_store.samples))) print("Ensembles...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Setting up the simulation Step2: A lot of information can be recovered from the old storage, and so we don't have the recreate it. However, we ...
7,920
<ASSISTANT_TASK:> Python Code: import numpy as np a = np.array([1,2,3,4,5,6]) # Print the contents of a a print("The vector a has " + str(a.ndim) + " dimension(s) and has the shape " + str(a.shape) + ".") m = np.array([[1,2,3], [4,5,6]]) m print("The matrix m has " + str(m.ndim) + " dimension(s) and has the shape "...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Make a vector with 6 elements Step2: Get some information about the vector Step3: Create a matrix like this Step4: Get some information about...
7,921
<ASSISTANT_TASK:> Python Code: from IPython.display import YouTubeVideo YouTubeVideo('Ti5zUD08w5s') YouTubeVideo('jmsFC0mNayM') import matplotlib.pyplot as plt import numpy as np %matplotlib inline def parab(x): return x**2 x = np.linspace(0,1) y = parab(x) plt.fill_between(x,y) plt.text(0.8,0.2,'$\mathcal{D}$',fo...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Integración Montecarlo tipo 1 Step2: Entonces, lo que queremos es aproximar el área de la región $\mathcal{D}$. Llamaremos esta área $A(\mathca...
7,922
<ASSISTANT_TASK:> Python Code: # Author: Ivana Kojcic <ivana.kojcic@gmail.com> # Eric Larson <larson.eric.d@gmail.com> # Kostiantyn Maksymenko <kostiantyn.maksymenko@gmail.com> # Samuel Deslauriers-Gauthier <sam.deslauriers@gmail.com> # License: BSD-3-Clause import os.path as op import numpy as ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: In order to simulate source time courses, labels of desired active regions Step3: Create simulated source activity Step4: Here, Step5: Simul...
7,923
<ASSISTANT_TASK:> Python Code: import numpy as np my_list = [2, 5, 7, 8] my_list type(my_list) multi_list = [[1, 2, 3], [4, 5, 6]] # my_array = np.array(my_list) type(my_array) my_array.dtype multi_array.shape multi_array = np.array([[1, 2, 3], [4, 5, 6]], np.int32) # # # # Pandas DataFrames as table elements i...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Lists in native Python Step2: This list is one-dimensional, let's make it multidimensional! Step3: How do we access the 6 element in the secon...
7,924
<ASSISTANT_TASK:> Python Code: empty_dictionary = {} print empty_dictionary filled_dictionary = {'first_name': 'abhinav', 'last_name': 'upadhyay'} print filled_dictionary food_menu = {} food_menu['pizza'] = 300 food_menu['sandwich'] = 30 food_menu['tea'] = 10 print food_menu pizza_price = food_menu['pizza'] print pi...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Creating dictionary with values Step2: Adding values to the dictionary Step3: Notice the ordering of the items in the output above Step4: Del...
7,925
<ASSISTANT_TASK:> Python Code: %matplotlib inline %matplotlib notebook from threeML import * import os trigger="GRB110731A" dec=-28.546 ra=280.52 xrt_dir='xrt' xrt = SwiftXRTLike("XRT",pha_file=os.path.join(xrt_dir,"xrt_src.pha"), bak_file=os.path.join(xrt_dir,"xrt_bkg.pha"), rsp_...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Load XRT data Step2: Load GBM data Step3: View the light curve Step4: Make energy selections and check them out Step5: Setup the model Step6...
7,926
<ASSISTANT_TASK:> Python Code: # Copyright 2019 The TensorFlow Hub Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step3: Fast Style Transfer for Arbitrary Styles Step4: Let's get as well some images to play with. Step5: Import TF Hub module Step6: The signature ...
7,927
<ASSISTANT_TASK:> Python Code: import datetime import numpy as np # Install and pin to versions that seem to work together !pip3 install pandas-gbq==0.10.0 google-cloud-bigquery==1.11.2 google-api-core==1.8.2 !pip3 install matplotlib # Inline all matplotlib plots %matplotlib inline from google.cloud import bigquery # ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Kubeflow Stats Step2: Compute cluster stats Step3: Number of new deployments Step4: Number of active deployments Step5: Compute histogram of...
7,928
<ASSISTANT_TASK:> Python Code: # First check the Python version import sys if sys.version_info < (3,4): print('You are running an older version of Python!\n\n', 'You should consider updating to Python 3.4.0 or', 'higher as the libraries built for this course', 'have only been tested in...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Session 4 Step2: <a name="part-1---pretrained-networks"></a> Step3: Now we can load a pre-trained network's graph and any labels. Explore the...
7,929
<ASSISTANT_TASK:> Python Code: def sat(f): return f.cumsum(axis=1).cumsum(axis=0) def satarea(sat,r0_c0,r1_c1): a,b,c,d = 0,0,0,0 r0,c0 = r0_c0 r1,c1 = r1_c1 if ((r0 - 1 >= 0) and (c0 - 1 >= 0)): a = sat[r0-1,c0-1] if (r0 - 1 >= 0): b = sat[r0-1,c1] if (c0 - 1 >= 0): ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Examples Step2: Numerical example Step3: Image example Step4: Calculating a rectangle area with SAT (Summed Area Table)
7,930
<ASSISTANT_TASK:> Python Code: import pyquil.quil as pq import pyquil.forest as forest from pyquil.gates import * qvm = forest.Connection() p = pq.Program() p.inst(X(0)).measure(0, 0) print p classical_regs = [0] # A list of which classical registers to return the values of. qvm.run(p, classical_regs) qvm.run(p, [...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Next, we want to open a connection to the QVM. Step2: Now we can make a program by adding some Quil instruction using the inst method on a Prog...
7,931
<ASSISTANT_TASK:> Python Code: import os import sys import numpy # Path for TubeTK libs and bin #Values takend from TubeTK launcher #sys.path.append("C:/src/TubeTK_Python_ITK/SlicerExecutionModel-build/GenerateCLP/") #sys.path.append("C:/src/TubeTK_Python_ITK/SlicerExecutionModel-build/GenerateCLP/Release") #sys.path.a...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Initialization Step2: Read the input images Step3: STEP 1 Step4: STEP 2 Step5: STEP 3 Step6: STEP 4 Step7: STEP 5 Step8: STEP 6 Step9: S...
7,932
<ASSISTANT_TASK:> Python Code: %load_ext Cython %%cython import math def erathostene_sieve(int n): cdef list primes = [False, False] + [True] * (n - 1) # from 0 to n included cdef int max_divisor = math.floor(math.sqrt(n)) cdef int i = 2 for divisor in range(2, max_divisor + 1): if primes[divis...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Problem 51 Step2: Let's try to obtain the examples given in the problem statement, with the smallest prime giving a 6-sized family being 13 and...
7,933
<ASSISTANT_TASK:> Python Code: import numpy as np import matplotlib.pyplot as plt def param_plot(): this function creates the graph on page 189 of Sargent Macroeconomic Theory, second edition, 1987 fig, ax = plt.subplots(figsize=(12, 8)) ax.set_aspect('equal') # Set axis xmin, ymin = -3, -2 xmax...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: OOP in Action Step3: Explanation of the graph Step5: none Step7: Manual or “by hand” root calculations Step9: none Step10: none Step11: no...
7,934
<ASSISTANT_TASK:> Python Code: from nltk.corpus import propbank pb_instances = propbank.instances() print(pb_instances) inst = pb_instances[103] print("File ID:", inst.fileid) print("Sentence Number:", inst.sentnum) print("Word Number:", inst.wordnum) inst.tagger inst.inflection infl = inst.inflection infl.form, infl....
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Each propbank instance defines the following member variables Step2: The location of the predicate and of the arguments are encoded using Propb...
7,935
<ASSISTANT_TASK:> Python Code: %gui from PyQt5 import QtWidgets b1 = QtWidgets.QPushButton("Click Me") %gui qt5 from PyQt5 import QtWidgets b1 = QtWidgets.QPushButton("Click Me") b1.show() def on_click_cb(): print("Clicked") b1.clicked.connect(on_click_cb) %connect_info !jupyter kernel list %qtconsole b1.show()...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: A pop up will appear saying Step2: Step3: Now, if you click the button, the callback will be called. Step4: Now the Jupyter QtConsole will...
7,936
<ASSISTANT_TASK:> Python Code: import heapq nums = [1, 8, 2, 23, 7, -4, 18, 23, 42, 37, 2] print(heapq.nlargest(3, nums)) # Prints [42, 37, 23] print(heapq.nsmallest(3, nums)) # Prints [-4, 1, 2] portfolio = [ {'name': 'IBM', 'shares': 100, 'price': 91.1}, {'name': 'AAPL', 'shares': 50, 'price': 543.22...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Example 2 Step2: Example 2
7,937
<ASSISTANT_TASK:> Python Code: %matplotlib inline import matplotlib.pyplot as plt def lin_regplot(X, y, model): plt.scatter(X, y, c='blue') plt.plot(X, model.predict(X), color='red') return X = np.array([ 1, 2, 3, 4, 5])[:, np.newaxis] y = np.array([ 1, 2, 3, 4, 5]) ne_lr = LinearRegression(solver='nor...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: <br> Step2: <br> Step3: <br> Step4: <br>
7,938
<ASSISTANT_TASK:> Python Code: MU = 3.9 N = int(10E4) INITIAL = 0.5 MIN_SIZE = 2 MAX_SIZE = 26 BITS_RANGE = array(list(range(MIN_SIZE, MAX_SIZE + 1))) def generate(x, mu, n): current = x for _ in range(n): yield current current = mu * current * (1 - current) def bin_to_dec(sequence, bits): a...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Generate a sequence Step2: Entropies Step3: Now we have mappings from binary block size to entropies of sequences Step4: Now we will calculat...
7,939
<ASSISTANT_TASK:> Python Code: from utils import load_buzz, select, write_result from features import featurize, get_pos from containers import Questions, Users, Categories %matplotlib inline import numpy as np from scipy import linalg import matplotlib.pyplot as plt import matplotlib as mpl from sklearn import mixtur...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Right, now, you can use those module. Step3: B. Modeling Step4: n_iter=10
7,940
<ASSISTANT_TASK:> Python Code: couleurs = ["rouge", "orange", "jaune", "vert", "bleu", "indigo", "violet"] tailles = ["page", "homme", "demi patron", "patron", "grand patron"] [(couleur, taille) for couleur in couleurs for taille in tailles] couleurs_et_tailles = ((couleur, taille) for couleur in couleurs for taille in...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: As you can see, it doesn't generate the complete list like the listcomp above. Genexps don't produce entire lists in memory. You need to iterate...
7,941
<ASSISTANT_TASK:> Python Code: from IPython.display import YouTubeVideo # WATCH THE VIDEO IN FULL-SCREEN MODE YouTubeVideo("JXJQYpgFAyc",width=640,height=360) # Numerical integration # Put your code here import math Nstep = 10 begin = 0.0 end = 3.1415926 dx = (end-begin)/Nstep sum = 0.0 xpos = 0.0 for i in range(Nst...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Question 1 Step2: Question 2 Step4: Question 3
7,942
<ASSISTANT_TASK:> Python Code: from __future__ import print_function import mne import os.path as op from matplotlib import pyplot as plt # Load an example dataset, the preload flag loads the data into memory now data_path = op.join(mne.datasets.sample.data_path(), 'MEG', 'sample', 'sample_audvis_r...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Continuous data is stored in objects of type Step2: Information about the channels contained in the Step3: You can also pass an index direct...
7,943
<ASSISTANT_TASK:> Python Code: from bs4 import BeautifulSoup import requests r = requests.get('https://en-marche.fr/emmanuel-macron/le-programme') soup = BeautifulSoup(r.text, 'html.parser') proposals = soup.find_all(class_='programme__proposal') proposals = [p for p in proposals if 'programme__proposal--category' not ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: On peut maintenant extraire le lien vers l'image. Step2: On peut afficher ceci dans le notebook. Step5: On peut répeter ce processus et faire ...
7,944
<ASSISTANT_TASK:> Python Code: # Importing pandas to read CSV file import pandas as pd # Read breast cancer csv file to pandas data frame data data = pd.read_csv('wisconsin_breast_cancer.csv') # Display the first 5 rows of the csv file data.head() data.shape # It is always a good idea to understand your data # There ar...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Delete rows with missing data Step2: Getting ready to do classification Step3: Now let us create a confusion matrix to identify sensitivity sp...
7,945
<ASSISTANT_TASK:> Python Code: MAX = 10005 MOD = 1000000007 def countNum(idx , sum , tight , num , len1 , k ) : if(len1 == idx ) : if(sum == 0 ) : return 1  else : return 0   if(dp[idx ][sum ][tight ] != - 1 ) : return dp[idx ][sum ][tight ]  res = 0 if(tight == 0 ) : limit = num[idx ]...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description:
7,946
<ASSISTANT_TASK:> Python Code: import sys sys.path.append('/Users/c242587/Desktop/projects/git/ngboost') from ngboost import NGBRegressor from sklearn.datasets import load_boston from sklearn.model_selection import train_test_split from sklearn.metrics import mean_squared_error X, Y = load_boston(True) X_train, X_test,...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Getting the estimated distributional parameters at a set of points is easy. This returns the predicted mean and standard deviation of the first ...
7,947
<ASSISTANT_TASK:> Python Code: import numpy as np from scipy import stats import matplotlib.pyplot as plt %matplotlib inline def clf_preds(accuracy, truth_vector): # accuracy of classifier # truth_vector is the actual value of the target preds = [] for i in range(len(truth)): pred = np.random.ch...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: The Power of Ensembles Step2: The accuracy of a majority-vote system from an ensemble of weak classifiers is a big improvement on the accuracy ...
7,948
<ASSISTANT_TASK:> Python Code: def caps(val): caps returns double the value of the provided value return val*2 a = caps("TEST ") print(a) print(caps.__doc__) a = caps(1234) print(a) def is_valid(data): if 10 in data: return True return False a = is_valid([10, 200, 33, "asf"]) print(a...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Functions Step3: In the above example, we have caps as function, which takes val as argument and returns val * 2. Step4: Functions can return ...
7,949
<ASSISTANT_TASK:> Python Code: # change these to try this notebook out BUCKET = 'cloud-training-demos-ml' PROJECT = 'cloud-training-demos' REGION = 'us-central1' import os os.environ['BUCKET'] = BUCKET os.environ['PROJECT'] = PROJECT os.environ['REGION'] = REGION os.environ['TFVERSION'] = '1.13' %%bash gcloud config se...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Now that we have the TensorFlow code working on a subset of the data, we can package the TensorFlow code up as a Python module and train it on C...
7,950
<ASSISTANT_TASK:> Python Code: def vol(rad): pass def ran_check(num,low,high): pass def ran_bool(num,low,high): pass ran_bool(3,1,10) def up_low(s): pass def unique_list(l): pass unique_list([1,1,1,1,2,2,3,3,3,3,4,5]) def multiply(numbers): pass multiply([1,2,3,-4]) def palindrome(s): ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Write a function that checks whether a number is in a given range (Inclusive of high and low) Step2: If you only wanted to return a boolean Ste...
7,951
<ASSISTANT_TASK:> Python Code: !pip install -I "phoebe>=2.0,<2.1" %matplotlib inline import phoebe from phoebe import u # units import numpy as np import matplotlib.pyplot as plt logger = phoebe.logger() b = phoebe.default_binary() b['rpole@primary'] = 1.8 b['rpole@secondary'] = 0.96 b['teff@primary'] = 10000 b['grav...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: As always, let's do imports and initialize a logger and a new bundle. See Building a System for more details. Step2: Let's make our system so ...
7,952
<ASSISTANT_TASK:> Python Code: probe_x_offset = 5 # i.e. probe is 5 mm to the right of the nozzle probe_y_offset = -31 # i.e. probe is 31mm "down" from the nozzle probe_z_offset = -22.5 # i.e. probe clicks with nozzle 22.5mm above the bed min_y = 41 min_x = 5 max_y = 147 # Moving beyond this value after homing will cr...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step2: Display results Step4: Need to remove the tilt from this. Get the best fit orthoganal distance regression plane using approach here Step5: Wha...
7,953
<ASSISTANT_TASK:> Python Code: from random import choices lnct_few_friends = ["Jyoti Pancholi", "Amit Shrivastava", "Mukesh Bansal", "Preeti Saraswat", "Manish Nandle"] list_of_prob = [0.2, 0.1, 0.3, 0.2, 0.2] lnct_few_friends = choices(lnct_few_friends, weights=list_of_prob, k=200) for name in set(population): pri...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Lets try some graphs on them Step2: In the above graph, you can see that everytime, "X" were the lowest and "Mukesh" & "Manish" were the highes...
7,954
<ASSISTANT_TASK:> Python Code: # Make sure the base overlay is loaded from pynq.overlays.base import BaseOverlay base = BaseOverlay("base.bit") from pynq.lib.arduino import Arduino_Analog from pynq.lib.arduino import ARDUINO_GROVE_A1 from pynq.lib.arduino import ARDUINO_GROVE_A4 analog1 = Arduino_Analog(base.ARDUINO,A...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: 1. Instantiate individual analog controller Step2: 2. Read voltage value out Step3: 3. Read raw value out Step4: 4. Logging multiple sample v...
7,955
<ASSISTANT_TASK:> Python Code: from IPython.display import Image Image(url='http://www.phdcomics.com/comics/archive/phd101212s.gif') %%bash git status <END_TASK>
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: If that hasn't convinced you, here are some other benefits
7,956
<ASSISTANT_TASK:> Python Code: from QGL import * cl = ChannelLibrary("example") q1 = cl["q1"] # Repeat similar configuration for q2 q2 = cl.new_qubit("q2") aps2_3 = cl.new_APS2("BBNAPS3", address="192.168.5.103") aps2_4 = cl.new_APS2("BBNAPS4", address="192.168.5.104") dig_2 = cl.new_X6("X6_2", address=0) cl.set_con...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: See Auspex example notebooks on how to configure a channel library. Step2: One can define simultaneous operations on qubits using the * operato...
7,957
<ASSISTANT_TASK:> Python Code: import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns from empiricaldist import Pmf from utils import decorate # set the random seed so we get the same results every time np.random.seed(17) # make the directory for the figures import os if not os.pat...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Class size Step3: I generate a sample from this distribution, assuming a uniform distribution in each range and an upper bound of 300. Step4: ...
7,958
<ASSISTANT_TASK:> Python Code: from pyoptools.all import * from numpy import pi P1=Plane(shape=Circular(radius=(25))) Plot3D(P1,center=(0,0,0),size=(60,60),rot=[(0,0,0)],scale=6) P2=Plane(shape=Rectangular(size=(50,50))) Plot3D(P2,center=(0,0,0),size=(60,60),rot=[(0,0,0)],scale=6) P3=Plane(shape=Triangular(coord=((0,2...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Plane Surface Step2: Spherical Surface Step3: Cylindrical Surface Step4: The second class is the Cylindrical. Step5: Aspherical Surface
7,959
<ASSISTANT_TASK:> Python Code: sushi_order = ['unagi', 'hamachi', 'otoro'] prices = [6.50, 5.50, 15.75] print(sushi_order) print(prices) print(sushi_order[0]) print(sushi_order[2]) print(len(sushi_order)) print(sushi_order[-3]) everyones_order = [['california roll'], ['unagi', 'dragon roll'], sushi_order] print(eve...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: You can access a single element in a list by indexing in using brackets. List indexing starts at 0 so to get the first element, you use 0, the s...
7,960
<ASSISTANT_TASK:> Python Code: import sys import numpy as np # the following line is not required if BatchFlow is installed as a python package. sys.path.append("../..") from batchflow import Dataset, DatasetIndex, Batch # number of items in the dataset NUM_ITEMS = 10 # number of items in a batch when iterating BATCH_S...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Create a dataset Step2: The dataset index Step3: drop_last=True skips the last batch if it contains fewer than BATCH_SIZE items Step4: shuffl...
7,961
<ASSISTANT_TASK:> Python Code: from sklearn.model_selection import cross_val_score, KFold from sklearn.neighbors import KNeighborsRegressor # generate toy dataset: x = np.linspace(-3, 3, 100) rng = np.random.RandomState(42) y = np.sin(4 * x) + x + rng.normal(size=len(x)) X = x[:, np.newaxis] cv = KFold(shuffle=True) # ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: There is a function in scikit-learn, called validation_plot to reproduce the cartoon figure above. It plots one parameter, such as the number of...
7,962
<ASSISTANT_TASK:> Python Code: from sympy import * init_printing() x = symbols('x') x**2 eq = Eq(x + 3, 2, evaluate=False) eq Eq(x**2 + 3*x -1, 0, evaluate = False) solve(eq, [x], dict=True) eq = Eq(3*x, -2, evaluate=False) eq solve(eq, [x], dict=True) eq = Eq(x**2, 3, evaluate=False) eq tentativi = list(map(S, ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: $\mathbb{N}$ Step2: Quando leggi la scrittura matematica $x + 3 = 2$, questa significa la seguente cosa Step3: puoi leggere la scrittura matem...
7,963
<ASSISTANT_TASK:> Python Code: import sys import numpy def main(): script = sys.argv[0] filename = sys.argv[1] data = numpy.loadtxt(filename, delimiter=',') for m in data.mean(axis=1): print(m) import sys import numpy def main(): script = sys.argv[0] filename = sys.argv[1] data = nu...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: This function gets the name of the script from sys.argv[0], because that’s where it’s always put, and the name of the file to process from sys.a...
7,964
<ASSISTANT_TASK:> Python Code: letters_map = {'2':'ABC', '3':'DEF', '4':'GHI', '5':'JKL', '6':'MNO', '7':'PQRS', '8':'TUV', '9':'WXYZ'} def printWords(number, ): #number is phone number def printWordsUtil(numb, curr_digit, output, n): if curr_digit == n: print('%s ' % output) ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Print Longest Common Subsequence Step2: Time Travelling dictionary Step3: Alien Dictionary Step4: Binary Search
7,965
<ASSISTANT_TASK:> Python Code: import ga4gh.client as client c = client.HttpClient("http://1kgenomes.ga4gh.org") dataset = c.search_datasets().next() print(dataset) reference_set = c.search_reference_sets().next() print(reference_set) references = [r for r in c.search_references(reference_set_id=reference_set.id)] ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: We will continue to refer to this client object for accessing the remote server. Step2: Access the reference set Step3: With the reference set...
7,966
<ASSISTANT_TASK:> Python Code: %matplotlib inline import numpy as np import pandas as pd import statsmodels.api as sm import matplotlib.pyplot as plt from pandas_datareader.data import DataReader cpi_apparel = DataReader('CPIAPPNS', 'fred', start='1986') cpi_apparel.index = pd.DatetimeIndex(cpi_apparel.index, freq='MS...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Although most operations related to state space models rely on the Kalman filtering recursions, in some special cases one can use a separate met...
7,967
<ASSISTANT_TASK:> Python Code: from IPython.lib.display import YouTubeVideo YouTubeVideo('6O43gOxtaWo', start=14) %matplotlib inline import pandas as pd import numpy as np import matplotlib.pyplot as plt # Import Users Data unames = ['user_id','gender','age','occupation','zip'] users = pd.read_table('data/users.dat', ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: TEAM Members Step2: Compute some Summary Statistics for the data Step3: How many movies have an average rating over 4.5 overall? Step4: How m...
7,968
<ASSISTANT_TASK:> Python Code: import pandas as pd from bokeh.charts import TimeSeries, output_notebook, show # Get data df = pd.read_csv('data/Land_Ocean_Monthly_Anomaly_Average.csv') # Process data df['datetime'] = pd.to_datetime(df['datetime']) df = df[['anomaly','datetime']] # Output option output_notebook() # Crea...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Exercise Step2: Exercise
7,969
<ASSISTANT_TASK:> Python Code: # Author: Alexandre Gramfort <alexandre.gramfort@telecom-paristech.fr> # # License: BSD (3-clause) from mne.datasets import sample from mne.minimum_norm import read_inverse_operator print(__doc__) data_path = sample.data_path() fname = data_path fname += '/MEG/sample/sample_audvis-meg-oct...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Show result on 3D source space
7,970
<ASSISTANT_TASK:> Python Code: from pextant.mesh.abstractmesh import NpDataset import numpy as np xx,yy= np.mgrid[0:5,0:5] basic_terrain = NpDataset(0.1*(xx**2+yy**2), resolution=1) basic_terrain basic_terrain[1,1] basic_terrain.get_datapoint(np.array(([1,1],[1.5,1.5]))) from pextant.EnvironmentalModel import GridMe...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: This dataset is wrapped around numpy so we can access can easily access entries Step2: Or access several entries, and even interpolate Step3: ...
7,971
<ASSISTANT_TASK:> Python Code: ## Interactive magics %matplotlib inline import sys import warnings warnings.filterwarnings('ignore') import re import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns import patsy as pt from scipy import optimize # pymc3 libraries import pymc3 as pm i...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Local Functions Step2: Generate Data Step3: View means of the various combinations (poisson mean values) Step4: Briefly Describe Dataset Step...
7,972
<ASSISTANT_TASK:> Python Code: count = 1 for elem in range(1, 3 + 1): count *= elem print(count) from math import factorial as f f(3) def n_max(): inpt = eval(input("Please enter some values: ")) maximum = max_val(inpt) print("The largest value is", maximum) def max_val(ints): Input: col...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: 3. Extend your program to n objects. How many different combinations do I have for 5 objects? How about 15? What is the max number of objects I ...
7,973
<ASSISTANT_TASK:> Python Code: import os import matplotlib.pyplot as plt import pandas as pd import torch from torch.nn import Parameter import pyro import pyro.contrib.gp as gp import pyro.distributions as dist import pyro.ops.stats as stats smoke_test = ('CI' in os.environ) # ignore; used to check code integrity in ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Dataset Step2: Modelling Step3: Now comes the most interesting part. We know that the observed data $y$ has latent structure Step4: We will u...
7,974
<ASSISTANT_TASK:> Python Code: import sys print('Python version:', sys.version) import IPython print('IPython:', IPython.__version__) import numpy print('numpy:', numpy.__version__) import scipy print('scipy:', scipy.__version__) import matplotlib print('matplotlib:', matplotlib.__version__) import pandas print('pandas...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: I. Python Overview Step2: (If you're typing this into an IPython notebook, or otherwise using notebook file, you hit shift-Enter to evaluate a ...
7,975
<ASSISTANT_TASK:> Python Code: !pip install meterstick !git clone https://github.com/google/meterstick.git import sys, os sys.path.append(os.getcwd()) import matplotlib.pyplot as plt import numpy as np import pandas as pd from meterstick import * np.random.seed(42) platform = ('Desktop', 'Mobile', 'Tablet') exprs = (...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: or from GitHub for the latest version. Step2: Demo Starts Step3: Simple Metrics Step4: Count Step5: Dot (inner product) Step6: It can also ...
7,976
<ASSISTANT_TASK:> Python Code: # Import data import math # Create list of values data = [3,2,3,4,2,3,5,2,2,33,3,5,2,2,5,6,62,2,2,3,6,6,2,23,3,2,3] # Calculate n n = len(data) # Calculate the mean mean = sum(data)/len(data) # Create a list of all deviations from the mean all_deviations_from_mean_squared = [] # For eac...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Create Data Step2: Calculate Population Variance Step3: Calculate Population Standard Deviation
7,977
<ASSISTANT_TASK:> Python Code: import seaborn import pandas as pd import pylab as pl import yaml %pylab inline df = pd.read_pickle("../yelp-challenge/data_urbana_champaign/business_urbana_champaign.p") df.reset_index(drop=True, inplace=True) print df.shape print df.columns.values len(df.business_id.unique()) df.head(2...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: geo Step2: 1. 'city' Step3: we only consider Champaign and Urbana as our target in this dataset Step4: 2. 'is_open' Step5: we only consider ...
7,978
<ASSISTANT_TASK:> Python Code: from indicnlp.morph import unsupervised_morph morph = unsupervised_morph.UnsupervisedMorphAnalyzer("bn") text = u\ করা করেছিলাম করেছি করতে করেছিল হয়েছে হয়েছিল হয় হওয়ার হবে আবিষ্কৃত আবিষ্কার অভিষিক্ত অভিষেক অভিষেকের আমি আমার আমাদের তুমি তোমার তোমাদের বসা বসেছিল বসে বসি বসেছিলাম বস বসার\ w...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Using Indic NLP Library Step2: Transliteration Step3: Using Silpa Step4: Using BengaliStemmer Step5: Using BanglaStemmer Step6: Using Avro
7,979
<ASSISTANT_TASK:> Python Code: import tataaq YOUR_API_KEY_HERE = "" api = tataaq.TataAQ(apikey=YOUR_API_KEY_HERE) # Ping the server to see if we have valid auth credentials resp = api.ping() print (resp.status_code) import pandas as pd import feather # Request decice information for EBAM001 resp = api.device("EBAM001...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Import Things Step2: Retrieve Information about a Device Step3: Access the status of the previous request Step4: Access the header informatio...
7,980
<ASSISTANT_TASK:> Python Code: import numpy as np # from fastai.core def even_mults(start:float, stop:float, n:int)->np.ndarray: "Build evenly stepped schedule from `star` to `stop` in `n` steps." mult = stop/start step = mult**(1/(n-1)) return np.array([start*(step**i) for i in range(n)]) layer_groups...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: let's say for a hypothetical network with 3 layer groups (conv_group_1, conv_group_2, linear_group). Step2: Interesting, so if you have multipl...
7,981
<ASSISTANT_TASK:> Python Code: psource(Chart) chart = Chart(E0) print(chart.parses('the stench is in 2 2')) chart_trace = Chart(nlp.E0, trace=True) chart_trace.parses('the stench is in 2 2') print(chart.parses('the stench 2 2')) import os, sys sys.path = [os.path.abspath("../../")] + sys.path from nlp4e import * f...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Example Step2: And then we simply call the parses function Step3: You can see which edges get added by setting the optional initialization arg...
7,982
<ASSISTANT_TASK:> Python Code: %pylab notebook %precision 4 Zline = 38.2 + 140.0j # [Ohm] Zeq = 0.10 + 0.4j # [Ohm] V_high = 14e3 # [V] V_low = 2.4e3 # [V] Pout = 90e3 # [W] load PF = 0.8 # lagging VS = 2.3e3 # [V] secondary voltage a = V_high / V_low a Z_line = (1/a)**2 * Zline print('Z_line = ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Description Step2: (a) Step3: The feeder’s impedance referred to the secondary side is Step4: The secondary current $I_S$ is given by Step5:...
7,983
<ASSISTANT_TASK:> Python Code: # Loading data, dividing, modeling and EDA below import pandas as pd from sklearn.ensemble import RandomForestRegressor from sklearn.linear_model import LinearRegression from sklearn.model_selection import train_test_split data = pd.read_csv('../input/new-york-city-taxi-fare-prediction/tr...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: The following two cells may also be useful to understand the values in the training data Step2: Question 1 Step3: Question 2 Step4: Uncomment...
7,984
<ASSISTANT_TASK:> Python Code: from urllib.request import urlretrieve from os.path import isfile, isdir from tqdm import tqdm vgg_dir = 'tensorflow_vgg/' # Make sure vgg exists if not isdir(vgg_dir): raise Exception("VGG directory doesn't exist!") class DLProgress(tqdm): last_block = 0 def hook(self, block_...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Flower power Step2: ConvNet Codes Step3: Below I'm running images through the VGG network in batches. Step4: Building the Classifier Step5: ...
7,985
<ASSISTANT_TASK:> Python Code: from sklearn.datasets import load_iris from sklearn.cross_validation import train_test_split from sklearn.neighbors import KNeighborsClassifier from sklearn import metrics # read in the iris data iris = load_iris() X = iris.data y = iris.target for i in xrange(1,5): print "random_stat...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: 上面的测试准确率可以看出,不同的训练集、测试集分割的方法导致其准确率不同,而交叉验证的基本思想是:将数据集进行一系列分割,生成一组不同的训练测试集,然后分别训练模型并计算测试准确率,最后对结果进行平均处理。这样来有效降低测试准确率的差异。 Step2: 3. 使用交叉验证的建议 Ste...
7,986
<ASSISTANT_TASK:> Python Code: %matplotlib inline from pylab import * N = 10**5 lambda_ = 2.0 ######################################## # Supply the missing coefficient herein below V1 = -1.0/lambda_ data = V1*log(rand(N)) ######################################## m = mean(data) v = va...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: 2) The discrete valued random variable $X$ follows a Poisson distribution if its probabilities depend on a parameter $\lambda$ and are such that...
7,987
<ASSISTANT_TASK:> Python Code: X = np.array([[7, 5],[5, 7],[7, 7],[4, 4],[4, 6],[1, 4],[0, 0],[2, 2],[8, 7],[6, 8],[5, 5],[3, 7]], dtype=float) plt.scatter(X[:,0], X[:,1], s=100) plt.show() from sklearn.cluster import KMeans model = KMeans(n_clusters=2, init="random", n_init=1, max_iter=1, random_state=1).fit(X) c0, c1...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: K-Means++ Step2: 예
7,988
<ASSISTANT_TASK:> Python Code: def printArr(arr , n ) : arr . sort() if(arr[0 ] == arr[n - 1 ] ) : print("No ")  else : print("Yes ") for i in range(n ) : print(arr[i ] , end = "▁ ")  print()   if __name__== ' __main __' : arr =[1 , 2 , 2 , 1 , 3 , 1 ] N = len(arr ) printArr(arr , N ) ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description:
7,989
<ASSISTANT_TASK:> Python Code: from __future__ import absolute_import from __future__ import division from __future__ import print_function import hashlib import math import os.path import random import re import sys import tarfile import numpy as np import librosa as rosa from six.moves import urllib from six.moves im...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: One shot keyword trigger Step2: Wav MFCC loader Step3: Conv Network Step4: Siamese Network
7,990
<ASSISTANT_TASK:> Python Code: import bqplot.pyplot as plt # first, let's create two vectors x and y to plot using a Lines mark import numpy as np x = np.linspace(-10, 10, 100) y = np.sin(x) # 1. Create the figure object fig = plt.figure(title="Simple Line Chart") # 2. By default axes are created with basic defaults. I...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Steps for building plots in pyplot Step1: For creating other marks (like scatter, pie, bars, etc.), only step 2 needs to be changed. Lets look a simple...
7,991
<ASSISTANT_TASK:> Python Code: summaryDf = pd.DataFrame([extractSummaryLine(l) for l in open('../../data/learnedModel/anto/summary.txt').readlines()], columns=['bidirectional', 'strict', 'clf', 'feature', 'post', 'precision', 'recall', 'f1']) summaryDf.sort_values('f1', ascending=False)[:10] !p...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: We can observe quite good f1-score on RandomForest with normalised projected cosine similarity.
7,992
<ASSISTANT_TASK:> Python Code: from __future__ import (absolute_import, division, print_function, unicode_literals) from astropy.time import Time import astropy.units as u from astroplan import Observer, FixedTarget # Observe from Keck obs = Observer.at_site("Keck") # Observe these three stars n...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Make a list of constraints to compute Step2: Now combine those constraint results with non-trivial boolean logic Step3: Simple visualization o...
7,993
<ASSISTANT_TASK:> Python Code: from sklearn import datasets import matplotlib.pyplot as plt iris = datasets.load_iris() def plot(dataset, ax, i, j): ax.scatter(dataset.data[:,i], dataset.data[:,j], c=dataset.target, s=50) ax.set_xlabel(dataset.feature_names[i], fontsize=20) ax.set_ylabel(dataset.feature_nam...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Clustering Step2: k-means Step3: Aplicación a datos Step4: ¿Es necesario reinventar la rueda? Step5: ¿Cómo seleccionar k?
7,994
<ASSISTANT_TASK:> Python Code: import random, datetime import numpy as np import pylab as plt import statsmodels.api as sm from scipy.stats import norm from scipy.stats.stats import pearsonr # str, int, float str(3) # int int('5') # float float('7.1') range(10) range(1, 10) dir dir(str)[-5:] help(str) x = ' Hello Wor...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Variable Type Step2: dir & help Step3: type Step4: Data Structure Step5: 定义函数 Step6: For 循环 Step7: map Step8: if elif else Step9: while循...
7,995
<ASSISTANT_TASK:> Python Code: import matplotlib.pyplot as plt import numpy as np import pandas as pd import seaborn as sns %matplotlib inline df = pd.read_csv("../kyphosis.csv") df.head() # TODO 1 sns.pairplot(df, hue="Kyphosis", palette="Set1") from sklearn.model_selection import train_test_split X = df.drop("Kyph...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Get the Data Step2: Exploratory Data Analysis Step3: Train Test Split Step4: Decision Trees Step5: Prediction and Evaluation Step6: Tree Vi...
7,996
<ASSISTANT_TASK:> Python Code: import numpy as np import pandas as pd %matplotlib inline import matplotlib.pyplot as plt import seaborn as sns import sqlalchemy !pip install -U okpy from client.api.notebook import Notebook ok = Notebook('hw4.ok') my_URI = "postgres://sam:@localhost:5432/fec" %load_ext sql %sql $my_URI...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Now, let's connect to your Postgres database. On your Heroku Postgres details, Step2: Table Descriptions Step3: For longer queries, you can sa...
7,997
<ASSISTANT_TASK:> Python Code: %matplotlib inline import matplotlib.pyplot as plt import pandas as pd import numpy as np import re !ls -liLah ../../share/Data # generate the raw_data from CSV raw_data = pd.read_csv("../../share/Data/SPON_complete", delimiter=",", skipinitialspace=True) # Stopwords are downloaded and ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Rohdaten Step2: Stopwörter Step3: Aufbereiten der Rohdaten Step5: Zählen Step6: Aufbereiten der Daten und schreiben in CSV-Dateien
7,998
<ASSISTANT_TASK:> Python Code: %run ../linked_list/linked_list.py %load ../linked_list/linked_list.py class MyLinkedList(LinkedList): def kth_to_last_elem(self, k): # TODO: Implement me pass # %load test_kth_to_last_elem.py from nose.tools import assert_equal class Test(object): def test_kth_to...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Unit Test
7,999
<ASSISTANT_TASK:> Python Code: import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.axes_grid1 import ImageGrid %matplotlib inline def dd(t1, t2, nu): return -nu*(3*np.cos(t1)*np.cos(t2) - np.cos(t1-t2)) def anis(t1, t2, sigma): return sigma*(np.sin(t1)**2 + np.sin(t2)**2) def tot(t1, t2, nu, s...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Individual energy terms Step2: The unnormalised probability of state $\theta_1\theta_2$ Step3: 2-dimensional Boltzmann distribution Step4: An...