Unnamed: 0
int64
0
15.9k
cleaned_code
stringlengths
67
124k
cleaned_prompt
stringlengths
168
30.3k
14,400
<ASSISTANT_TASK:> Python Code: import iris import iris.quickplot as qplt temperature = iris.load_cube('air.sig995.2012.nc') qplt.contourf(temperature[0,:,:]) gca().coastlines() print temperature zonal_mean = temperature.collapsed('latitude', iris.analysis.MEAN) qplt.contourf(zonal_mean) #Code is a bit more complicat...
<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 is how iris cube look like Step2: We can perform different operations on cubes. For example create zonal mean Step3: Here we plot timesir...
14,401
<ASSISTANT_TASK:> Python Code: #@title 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writin...
<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: Word embeddings Step2: Download the IMDb Dataset Step3: Take a look at the train/ directory. It has pos and neg folders with movie reviews lab...
14,402
<ASSISTANT_TASK:> Python Code: import numpy as np import tensorflow as tf import tensorflow_datasets as tfds from activation_clustering import ac_model, utils # The same dataset preprocessing as used in the baseline cifar10 model training. def input_fn(batch_size, ds, label_key='label'): dataset = ds.batch(batch_si...
<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: Train an activation clustering model from a baseline model Step2: Activation clustering model's configurations. The first entry in each pair i...
14,403
<ASSISTANT_TASK:> Python Code: # See Anaconda installed packages !conda list # List environments !conda info -e # Create Python 3 environment !conda create -n py3k python=3 anaconda # Activate Python 3 environment !source activate py3k # Deactivate Python 3 environment !source deactivate # Update Anaconda !conda update...
<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: <h2 id="ipython-notebook">IPython Notebook</h2> Step2: | Command | Description | Step3: <h2 id="git">Git</h2> S...
14,404
<ASSISTANT_TASK:> Python Code: DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE from urllib.request import urlretrieve from os.path import isfile, isdir from tqdm import tqdm import problem_unittests as tests import tarfile cifar10_dataset_folder_path = 'cifar-10-batches-py' # Use Floyd's cifar-10 dataset if ...
<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: Image Classification Step2: Explore the Data Step5: Implement Preprocess Functions Step8: One-hot encode Step10: Randomize Data Step12: Che...
14,405
<ASSISTANT_TASK:> Python Code: %matplotlib inline import matplotlib.pyplot as plt import numpy as np def well2d(x, y, nx, ny, L=1.0): Compute the 2d quantum well wave function. scalarfield=(2/L*np.sin(nx*np.pi*x/L)*np.sin(ny*np.pi*y/L)) well=scalarfield return well psi = well2d(np.linspace(0,1,10), np....
<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: Contour plots of 2d wavefunctions Step3: The contour, contourf, pcolor and pcolormesh functions of Matplotlib can be used for effective visuali...
14,406
<ASSISTANT_TASK:> Python Code: # install Pint if necessary try: import pint except ImportError: !pip install pint # download modsim.py if necessary from os.path import exists filename = 'modsim.py' if not exists(filename): from urllib.request import urlretrieve url = 'https://raw.githubusercontent.com/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: So far the systems we have studied have been physical in the sense that they exist in the world, but they have not been physics, in the sense of...
14,407
<ASSISTANT_TASK:> Python Code: %matplotlib inline import matplotlib.pyplot as plt import numpy as np #Review the documentation for NumPy's random module: np.random? #print 5 uniformly distributed numbers between 0 and 1 print(np.random.random(5)) #print another 5 - should be different print(np.random.random(5)) #prin...
<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: Random Processes in Physics Step2: Some basic functions to point out (we'll get to others in a bit) Step3: Notice you have to use 1-11 for the...
14,408
<ASSISTANT_TASK:> Python Code: number_list = [1, 2, 4, 8, 16, 32] the_pythons = ["Graham", "Terry", "Michael", "Eric", "Terry", "John"] mixed = [1, "Terry", 4] print (mixed) monty = ("Graham", "Terry", "Michael", "Eric", "Terry", "John") # the entire tuple print (monty) # one element at a time for name in monty: ...
<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: Tuple Step2: [] brackets or square brackets Step3: Why? Step4: Dictionaries Step5: Retrieving a Value from a Dictionary Step6: Testing for ...
14,409
<ASSISTANT_TASK:> Python Code: strings = "stressed" print(strings[::-1]) strings1 = u"パタトクカシーー" print(strings1[::2]) strings_p = u"パトカー" strings_t = u"タクシー" strings_sum = '' for p, t in zip(strings_p, strings_t): strings_sum += p + t print(strings_sum) strings3 = "Now I need a drink, alcoholic of course, after t...
<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: 01 パタトクカシーー Step2: 02「パトカー」+「タクシー」=「パタトクカシーー」 Step3: 03. 円周率 Step4: 04. 元素記号 Step5: 05 n-gram Step6: 06. 集合 Step7: 07. テンプレートによる文生成 Step8:...
14,410
<ASSISTANT_TASK:> Python Code: import sys sys.path.append('..') sys.path.append('../geostatsmodels') from geostatsmodels import utilities, variograms, model, kriging, geoplot import matplotlib.pyplot as plt import numpy as np import pandas z = utilities.readGeoEAS('../data/ZoneA.dat') P = z[:,[0,1,3]] pt = [2000, 47...
<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'll read the data from ZoneA.dat. Step2: We want the first, second and fourth columns of the data set, representing the x and y spatial coord...
14,411
<ASSISTANT_TASK:> Python Code: import numpy as np import vispy import vispy.gloo as gloo from vispy import app from vispy.util.transforms import perspective, translate, rotate # load the vispy bindings manually for the notebook which enables webGL # %load_ext vispy n = 100 a_position = np.random.uniform(-1, 1, (n, 3))....
<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: Jupyter Notebook backend demo Step3: Every cell above was preparing our GL Canvas for operation. Now we will create the Canvas instance and bec...
14,412
<ASSISTANT_TASK:> Python Code: send(IP(dst="1.2.3.4")/TCP(dport=502, options=[("MSS", 0)])) ans = sr([IP(dst="8.8.8.8", ttl=(1, 8), options=IPOption_RR())/ICMP(seq=RandShort()), IP(dst="8.8.8.8", ttl=(1, 8), options=IPOption_Traceroute())/ICMP(seq=RandShort()), IP(dst="8.8.8.8", ttl=(1, 8))/ICMP(seq=RandShort())], ver...
<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_ Adanced firewalking using IP options is sometimes useful to perform network enumeration. Here is more complicate one-liner Step2: Now that, ...
14,413
<ASSISTANT_TASK:> Python Code: %%capture --no-stderr !pip3 install kfp --upgrade import kfp.components as comp dataproc_submit_spark_job_op = comp.load_component_from_url( 'https://raw.githubusercontent.com/kubeflow/pipelines/1.7.0-rc.3/components/gcp/dataproc/submit_spark_job/component.yaml') help(dataproc_submit...
<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 the component using KFP SDK Step2: Sample Step3: Example pipeline that uses the component Step4: Compile the pipeline Step5: Submit the...
14,414
<ASSISTANT_TASK:> Python Code: li = ["this", "is", "a", "list"] print(li) print(li[1:3]) # Print element 1 (inclusive) to 3 (exclusive) print(li[2:]) # Print element 2 and everything after that print(li[:-1]) # Print everything BEFORE element -1 (the last one) import numpy as np x = np.array([1, 2, 3, 4, 5]) print...
<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: With NumPy arrays, all the same functionality you know and love from lists is still there. Step2: These operations all work whether you're usin...
14,415
<ASSISTANT_TASK:> Python Code: import numpy as np x = np.arange(25) x x = da.arange(25, chunks=(5,)) y = x ** 2 y y.visualize() da.sqrt(x)[-1].visualize() x = da.arange(250, chunks=(5,)) x.visualize() x = da.ones((15, 15), chunks=(5,5)) x.sum(axis=1).visualize() import dask.multiprocessing y.compute(get = dask.multipro...
<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: <h1>MISSING SEPERATOR ARGS FOR SPACE DELIMITED FILE!!!</h1>
14,416
<ASSISTANT_TASK:> Python Code: import crpropa class ObserverPlane(crpropa.ObserverFeature): Detects all particles after crossing the plane. Defined by position (any point in the plane) and vectors v1 and v2. def __init__(self, position, v1, v2): crpropa.ObserverFeature.__init__(self) ...
<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: Custom Observer Step3: As test, we propagate some particles in a random field with a sheet observer Step4: and plot the final position of the ...
14,417
<ASSISTANT_TASK:> Python Code: %matplotlib inline import matplotlib.pyplot as plt import numpy as np !head -n 30 open_exoplanet_catalogue.txt data=np.genfromtxt('open_exoplanet_catalogue.txt',delimiter=",") assert data.shape==(1993,24) plt.hist(data[:,2],range(0,16)); plt.box(False) plt.xlabel("$M sin i (M_JUP)$"); ...
<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: Exoplanet properties Step2: Use np.genfromtxt with a delimiter of ',' to read the data into a NumPy array called data Step3: Make a histogram ...
14,418
<ASSISTANT_TASK:> Python Code: # disable ssl warnings import urllib3 urllib3.disable_warnings() keycloak_url = 'http://localhost:8080' token_endpoint = '/auth/realms/demo/protocol/openid-connect/token' client_id = 'demo' client_secret = 'c083d72c-a262-40b1-ad51-326f6977d74b' token_url = "{}{}".format(keycloak_url, 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: Keycloak client Step2: Get OAuth access token from Keycloak Step3: Execute WPS Process with access token
14,419
<ASSISTANT_TASK:> Python Code: # Hit shift + enter or use the run button to run this cell and see the results print 'hello world11_0_11' print 'hello world' # The last line of every code cell will be displayed by default, # even if you don't print it. Run this cell to see how this works. print 2 + 2 # The result of th...
<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: Nicely formatted results Step2: Creating cells Step3: Once you've run all three cells, try modifying the first one to set class_name to your n...
14,420
<ASSISTANT_TASK:> Python Code: import lasio import datetime import numpy import os import matplotlib.pyplot as plt %matplotlib inline depths = numpy.arange(10, 50, 0.5) fake_curve = numpy.random.random(len(depths)) fake_curve[-10:] = numpy.nan # Add some null values at the bottom plt.plot(depths, fake_curve) l = la...
<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: Step 1 Step2: Step 2 Step3: Let's add some information to the header Step4: Next, let's make a new item in the ~Parameters section for the op...
14,421
<ASSISTANT_TASK:> Python Code: %matplotlib inline import matplotlib.pyplot as plt import matplotlib matplotlib.style.use('ggplot') # set default figure size from pylab import rcParams rcParams['figure.figsize'] = 16, 8 import pandas as pd import urllib2 def load_data(ip_addr): data = pd.read_csv(urllib2.urlopen("h...
<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: Loading Data into a Dataframe Step2: Plotting the Scenarios Step3: Putting it all Together
14,422
<ASSISTANT_TASK:> Python Code: import torch x = torch.Tensor(5, 3) print(x) len(x) x.shape y = torch.rand(5,3) print(y) print(x + y) print(torch.add(x, y)) result = torch.Tensor(5, 3) print(result) torch.add(x, y, out=result) print(result) print('before y:', y) y.add_(x) print('after y:', y) x.t_() # numpy 스럽게 사용 가능 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: x.copy_(y), x.t_()는 x가 변경되는 연산 Step2: 기타 연산 자료 Step3: CharTensor를 제외하고 CPU상의 모든 텐서는 numpy로 변환하는 것을 지원 Step4: tensor들은 .cuda function을 사용해 gpu...
14,423
<ASSISTANT_TASK:> Python Code: import json import requests from requests.adapters import HTTPAdapter from requests.packages.urllib3.util.retry import Retry def requests_retry_session( retries=3, backoff_factor=0.3, status_forcelist=(500, 502, 504), session=None, ): session = session or requests.Sess...
<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: MMW production API endpoint base url. Step2: The job is not completed instantly and the results are not returned directly by the API request th...
14,424
<ASSISTANT_TASK:> Python Code: from dionysus import Simplex, Filtration, StaticPersistence, \ vertex_cmp, data_cmp, data_dim_cmp, \ DynamicPersistenceChains from math import sqrt scx = [Simplex((2,), 0), # C Simplex((0,), 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: We will compute persistent homology of a 2-simplex (triangle) ABC. The filtration is as follows Step2: Now the persistent homology is computed....
14,425
<ASSISTANT_TASK:> Python Code: %pylab inline import subprocess import matplotlib.pyplot as plt import random import numpy as np plt.style.use('ggplot') figsize(10,5) file = "./bwa/input2.sorted.bam" p = subprocess.Popen(["samtools", "view", "-q10", "-F260", file], stdout=subprocess.PIPE) coord...
<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: Calculate the Nonredundant Read Fraction (NRF) Step2: Make figures prettier and biger Step3: Parse the SAM file and extract the unique start c...
14,426
<ASSISTANT_TASK:> Python Code: # Load pickled data import pickle # TODO: Fill this in based on where you saved the training and testing data DATA_DIR = './traffic-signs-data/' training_file = DATA_DIR + 'train.p' validation_file= DATA_DIR + 'valid.p' testing_file = DATA_DIR + 'test.p' with open(training_file, mode='rb'...
<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: Step 1 Step2: Include an exploratory visualization of the dataset Step3: Step 2 Step4: Model Architecture Step5: Features and Labels Step6: ...
14,427
<ASSISTANT_TASK:> Python Code: # Plots will be show inside the notebook %matplotlib notebook import matplotlib.pyplot as plt # NumPy is a package for manipulating N-dimensional array objects import numpy as np # Pandas is a data analysis package import pandas as pd import problem_unittests as tests # Load data and pr...
<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: With Pandas we can load the aforementioned CSV data. Step2: With the data loaded we can plot it as a scatter plot using matplotlib. Step4: Mod...
14,428
<ASSISTANT_TASK:> Python Code: # DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'pcmdi', 'sandbox-3', 'atmos') # Set as follows: DOC.set_author("name", "email") # TODO - please enter value(s) # Set as follows: DOC.set_contributor("name", "ema...
<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: Document Authors Step2: Document Contributors Step3: Document Publication Step4: Document Table of Contents Step5: 1.2. Model Name Step6: 1...
14,429
<ASSISTANT_TASK:> Python Code: import hashlib import os import pickle from urllib.request import urlretrieve import numpy as np from PIL import Image from sklearn.model_selection import train_test_split from sklearn.preprocessing import LabelBinarizer from sklearn.utils import resample from tqdm import tqdm from zipfil...
<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: The notMNIST dataset is too large for many computers to handle. It contains 500,000 images for just training. You'll be using a subset of this...
14,430
<ASSISTANT_TASK:> Python Code: 2 + 3 2*3 2**3 sin(pi) from math import sin, pi sin(pi) a = 10 a c = from pruebas_1 import prueba_1_1 prueba_1_1(_, c) A = [2, 4, 8, 10] A A*2 f = lambda x: x**2 + 1 f(2) def g(x): y = x**2 + 1 return y g(2) def cel_a_faren(grados_cel): grados_faren = # Escrib...
<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: Sin embargo no existen funciones trigonométricas cargadas por default. Para esto tenemos que importarlas de la libreria math Step2: Variables S...
14,431
<ASSISTANT_TASK:> Python Code:: from sklearn.svm import SVC from sklearn.metrics import classification_report # create a linear SVC model with balanced class weights model = SVC(C=1, kernel='linear', class_weight='balanced') # fit model model.fit(X_train, y_train) # make predictions on test data y_pred = model.predict(...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description:
14,432
<ASSISTANT_TASK:> Python Code: !pip install --upgrade pip !pip install -q -U tfx import os import tempfile import urllib import pandas as pd import tensorflow_model_analysis as tfma from tfx.orchestration.experimental.interactive.interactive_context import InteractiveContext from tfx import v1 as tfx print('TFX vers...
<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: Install and import TFX Step2: Please ignore the incompatibility error and warnings. Make sure to re-run the cell. Step3: Import the MLMD libra...
14,433
<ASSISTANT_TASK:> Python Code: df = pd.read_csv('../data/titanic.csv', index_col='PassengerId') df.head() df_no_missing = df[['Survived', 'Pclass', 'Fare', 'Age', 'Sex']].dropna() X_train_withStrings = df_no_missing[['Pclass', 'Fare', 'Age', 'Sex']] y_train = df_no_missing['Survived'] def strings_to_int(df, target_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: 2. Оставьте в выборке четыре признака Step2: 6. Обучите решающее дерево с параметром random_state=241 и остальными параметрами по умолчанию. St...
14,434
<ASSISTANT_TASK:> Python Code: import os import requests import pandas as pd import csv import urllib2 import openpyxl import csv def xls_state(): path_year = os.path.join(os.getcwd()) file_name = path_year + "/" + "MSA_STATE"+ ".xls" url= "https://www.census.gov/2010census/xls/fips_codes_website.xls" ...
<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: INGESTION Step2: Define function taht downloads census xls file that contains cbsa and the corresponding msa name and principal cities that be...
14,435
<ASSISTANT_TASK:> Python Code: from datetime import datetime import matplotlib.pyplot as plt import metpy.calc as mpcalc from metpy.io import get_upper_air_data from metpy.io.upperair import UseSampleData from metpy.plots import SkewT from metpy.units import concatenate with UseSampleData(): # Only needed to use our l...
<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 new figure. The dimensions here give a good aspect ratio
14,436
<ASSISTANT_TASK:> Python Code: %matplotlib inline import pandas as pd import numpy as np import pymc3 as pm import matplotlib.pyplot as plt import seaborn import warnings warnings.filterwarnings('ignore') from collections import OrderedDict from time import time import numpy as np import pandas as pd import matplotlib....
<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 Adult Data Set is commonly used to benchmark machine learning algorithms. The goal is to use demographic features, or variables, to predict ...
14,437
<ASSISTANT_TASK:> Python Code: import numpy as np import cv2 import sys import os sys.path.insert(0, os.path.abspath('..')) import salientregions as sr import cProfile %pylab inline #Load the image path_to_image = 'images/graffiti.jpg' img = cv2.imread(path_to_image) sr.show_image(img) %%timeit #Time: creation of the 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: Binarization Step2: Binary detection Step3: MSER detection Step4: Conclusion
14,438
<ASSISTANT_TASK:> Python Code: from neon.initializers import Gaussian from neon.optimizers import GradientDescentMomentum, Schedule from neon.layers import Conv, Dropout, Activation, Pooling, GeneralizedCost from neon.transforms import Rectlin, Softmax, CrossEntropyMulti, Misclassification from neon.models import Model...
<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: Overfitting Step2: This situation illustrates the importance of plotting the validation loss (blue) in addition to the training cost (red). The...
14,439
<ASSISTANT_TASK:> Python Code: # Put your code here! # Put your code here! from IPython.display import HTML HTML( <iframe src="https://goo.gl/forms/NOKKHPQ0oKn1B7e23?embedded=true" width="80%" height="1200px" frameborder="0" marginheight="0" marginwidth="0"> Loading... </iframe> ) <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: Part 2 Step3: Assignment wrapup
14,440
<ASSISTANT_TASK:> Python Code: # Load libraries from sklearn.tree import DecisionTreeClassifier from sklearn import datasets # Load data iris = datasets.load_iris() X = iris.data y = iris.target # Create decision tree classifer object using gini clf = DecisionTreeClassifier(criterion='gini', random_state=0) # Train ...
<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 Iris Dataset Step2: Create Decision Tree Using Gini Impurity Step3: Train Model Step4: Create Observation To Predict Step5: Predict Obs...
14,441
<ASSISTANT_TASK:> Python Code: import qspectra as qs import numpy as np import matplotlib.pyplot as plt %matplotlib inline # Parameters of the electronic Hamiltonian ham = qs.ElectronicHamiltonian(np.array([[12881., 120.], [120., 12719.]]), bath=qs.DebyeBath(qs.CM_K * 77., 35., 106.), ...
<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: Absorption spectra Step2: 2D spectra
14,442
<ASSISTANT_TASK:> Python Code: from __future__ import division import graphlab products = graphlab.SFrame('amazon_baby_subset.gl/') # The same feature processing (same as the previous assignments) # --------------------------------------------------------------- import json with open('important_words.json', 'r') as 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: Load and process review dataset Step2: Just like we did previously, we will work with a hand-curated list of important words extracted from the...
14,443
<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 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: In order to simulate source time courses, labels of desired active regions Step3: Create simulated source activity Step4: Here, Step5: Simul...
14,444
<ASSISTANT_TASK:> Python Code: %load_ext snakeviz %load_ext memory_profiler %load_ext line_profiler %load_ext autoreload %autoreload 2 import re from collections import Counter def words(text): return re.findall(r'\w+', text.lower()) WORDS = Counter(words(open('big.txt').read())) def P(word, N=sum(WORDS.values())...
<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: amdahl law, focus on one part at a time Step2: Casual Profiling 👕👖 Step3: timeit ⌛⌛⌛ Step4: each run does thousand or millions of repetitio...
14,445
<ASSISTANT_TASK:> Python Code: # Authors: Eric Larson <larson.eric.d@gmail.com> # Alexandre Gramfort <alexandre.gramfort@telecom-paristech.fr> # Mark Wronkiewicz <wronk.mark@gmail.com> # # License: BSD (3-clause) import mne from mne.preprocessing import maxwell_filter print(__doc__) data_path = mne.da...
<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: Set parameters
14,446
<ASSISTANT_TASK:> Python Code: # DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'inpe', 'besm-2-7', 'seaice') # Set as follows: DOC.set_author("name", "email") # TODO - please enter value(s) # Set as follows: DOC.set_contributor("name", "emai...
<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: Document Authors Step2: Document Contributors Step3: Document Publication Step4: Document Table of Contents Step5: 1.2. Model Name Step6: 2...
14,447
<ASSISTANT_TASK:> Python Code: import recordlinkage from recordlinkage.datasets import load_febrl1 dfA = load_febrl1() dfA indexer = recordlinkage.Index() indexer.full() candidate_links = indexer.index(dfA) print (len(dfA), len(candidate_links)) # (1000*1000-1000)/2 = 499500 indexer = recordlinkage.Index() indexer....
<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 dataset is loaded with the following code. The returned datasets are Step2: Make record pairs Step3: With the method index, all possible (...
14,448
<ASSISTANT_TASK:> Python Code: # import common packages import numpy as np from collections import OrderedDict # lib from Qiskit Aqua Chemistry from qiskit_aqua_chemistry import FermionicOperator # lib from Qiskit Aqua from qiskit_aqua import Operator from qiskit_aqua import (get_algorithm_instance, get_optimizer_insta...
<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: Step 1 Step2: Step 2 Step3: We use the classical eigen decomposition to get the smallest eigenvalue as a reference. Step4: Step 3 Step5: Ste...
14,449
<ASSISTANT_TASK:> Python Code: import numpy as np import time import helper source_path = 'data/letters_source.txt' target_path = 'data/letters_target.txt' source_sentences = helper.load_data(source_path) target_sentences = helper.load_data(target_path) source_sentences[:50].split('\n') target_sentences[:50].split('\...
<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 start by examining the current state of the dataset. source_sentences contains the entire input sequence file as text delimited by newline...
14,450
<ASSISTANT_TASK:> Python Code: import GPy, safeopt from SafeRLBench.algo import SafeOptSwarm from SafeRLBench.envs import Quadrocopter, LinearCar from SafeRLBench.policy import NonLinearQuadrocopterController, LinearPolicy from SafeRLBench.measure import BestPerformance, SafetyMeasure from SafeRLBench import Bench # 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: Linear Car Step2: Below we output the results of the safety measure. List comprehension is used to get a more readable format for the Step3: Q...
14,451
<ASSISTANT_TASK:> Python Code: import numpy import numpy as np import sys import math import matplotlib.pyplot as plt def periodic(i,limit,add): Choose correct matrix index with periodic boundary conditions Input: - i: Base index - limit: Highest \"legal\" index - add: Number to ad...
<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: Periodic boundary conditions Step3: Set up spin matrix, initialize to ground state Step4: Create and initialize variables Step5: Setup array ...
14,452
<ASSISTANT_TASK:> Python Code: class Character(object): def __init__(self): self.life = 1000 def attacked(self): self.life -= 10 print(u"공격받음! 생명력 =", self.life) a = Character() b = Character() c = Character() a.life, b.life, c.life a.attacked() b.attacked() a.attacked()...
<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, b, c 세 개의 캐릭터 객체를 생성한다. Step2: 모든 객체의 초기 life 속성값은 모두 1000이다. Step3: 하지만 공격을 받은 캐릭터의 생명력은 감소된다. Step4: 클래스 상속 Step5: 이 클래스의 객체를 만들...
14,453
<ASSISTANT_TASK:> Python Code: poetry_output = !htid2rsync --f data/poetry.txt | rsync -azv --files-from=- data.sharc.hathitrust.org::features/ data/poetry/ scifi_output = !htid2rsync --f data/scifi.txt | rsync -azv --files-from=- data.sharc.hathitrust.org::features/ data/scifi/ outputs = list([poetry_output, scifi_out...
<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 in the previous notebooks, we'll construct FeatureReader objects for each corpus. The line below reads in path files we created to the downlo...
14,454
<ASSISTANT_TASK:> Python Code: %matplotlib inline import pandas as pd import numpy as np import random as rnd import seaborn as sns import matplotlib.pyplot as plt train_df = pd.read_csv('train.csv') test_df = pd.read_csv('test.csv') print(train_df.columns.values) train_df.isnull().sum() print (train_df.info()) trai...
<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: Importamos los datos para entrenar y testear Step2: Miramos los datos, para ver que si hay nulos o datos que rellenar, como la edad y la cabina...
14,455
<ASSISTANT_TASK:> Python Code: %matplotlib inline import numpy as np import matplotlib.pyplot as plt import xarray as xr import climlab # Get the water vapor data #datapath = "http://ramadda.atmos.albany.edu:8080/repository/opendap/latest/Top/Users/BrianRose/CESM_runs/" datapath = "http://thredds.atmos.albany.edu:8080...
<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: Integrate the control model out to equilibrium. Step2: Now let's make two copies of this model and keep them in a list Step3: We are going to ...
14,456
<ASSISTANT_TASK:> Python Code: import datetime import os import time import numpy as np import pandas as pd import tensorflow as tf from google.cloud import aiplatform, storage from google.cloud.aiplatform import gapic as aip from sklearn.preprocessing import StandardScaler # Check the TensorFlow version installed tf._...
<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 Cloud Storage bucket Step2: Load and preview the data Step3: Process data Step6: Scale values Step7: Create sequences of time serie...
14,457
<ASSISTANT_TASK:> Python Code: import numpy import toyplot y = numpy.linspace(0, 1, 20) ** 2 toyplot.scatterplot(y, width=300); canvas = toyplot.Canvas(600, 300) canvas.axes(grid=(1, 2, 0)).plot(y) canvas.axes(grid=(1, 2, 1)).plot(y, marker="o"); canvas = toyplot.Canvas(600, 300) canvas.axes(grid=(1, 2, 0)).plot(y, m...
<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: Markers can also be added to regular plots to highlight the datums (they are turned-off by default) Step2: You can use the size argument to con...
14,458
<ASSISTANT_TASK:> Python Code: # Panda will be usefull for quick data parsing import pandas as pd import numpy as np # Small trick to get a larger display from IPython.core.display import display, HTML display(HTML("<style>.container { width:90% !important; }</style>")) import matplotlib.pyplot as pl %matplotlib inlin...
<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: Pyplot is the Matplotlib plotting backend and the inline magic to see the graph directly in the notebook Step2: Or you can use pylab, which sim...
14,459
<ASSISTANT_TASK:> Python Code: #load packages import pandas as pd import numpy as np import matplotlib.pyplot as plt %matplotlib inline pleiades = pd.read_csv('pleiades.csv') pleiades pleiades.columns pleiades.dtypes pleiades_L = pleiades["Lbol"] pleiades_T = pleiades["Teff"] pleiades_L = pleiades_L - 2 pleiades...
<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: First off, we'll need to read in the data with the pandas function read_csv. A basic example is given below Step2: "pleiades" is now a pandas d...
14,460
<ASSISTANT_TASK:> Python Code: def topo_sort(T, D): Parents = { t: set() for t in T } # dictionary of parents Children = { t: set() for t in T } # dictionary of children for s, t in D: Children[s].add(t) Parents [t].add(s) Orphans = { t for (t, P) in Parents.items() if len(P) == 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: Graphical Representation Step2: The function toDot(Edges, Order) takes two arguments Step3: Testing
14,461
<ASSISTANT_TASK:> Python Code: import tensorflow as tf import tensorflow_data_validation as tfdv import tensorflow_transform as tft print('TF version: {}'.format(tf.__version__)) print('TFT version: {}'.format(tft.__version__)) print('TFDV version: {}'.format(tfdv.__version__)) PROJECT = 'cloud-training-demos' # Rep...
<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: <img valign="middle" src="images/tfx.jpeg"> Step2: 3. Model Training Step3: 3.2 TFRecords Input Function Step4: 3.3 Create feature columns St...
14,462
<ASSISTANT_TASK:> Python Code: #@title 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writin...
<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: Data validation using TFX Pipeline and TensorFlow Data Validation Step2: Install TFX Step3: Did you restart the runtime? Step4: Set up variab...
14,463
<ASSISTANT_TASK:> Python Code: # Useful starting lines %matplotlib inline import numpy as np import matplotlib.pyplot as plt %load_ext autoreload %autoreload 2 1 x = [2,3,4] def my_function(l): l.append(12) my_function(x) x # Matplotlib is used for plotting, plots are directly embedded in the # notebook thanks 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: Notebook Basics Step2: Numpy Basics Step3: Creation of arrays Step4: ndarray basics Step5: Basic operators are working element-wise (+, -, *...
14,464
<ASSISTANT_TASK:> Python Code: # Authors: Eric Larson <larson.eric.d@gmail.com> # License: BSD (3-clause) import numpy as np from scipy import stats from functools import partial import matplotlib.pyplot as plt # this changes hidden MPL vars: from mpl_toolkits.mplot3d import Axes3D # noqa from mne.stats import (spatio...
<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: Set parameters Step2: Construct simulated data Step3: Do some statistics Step4: Now let's do some clustering using the standard method. Step5...
14,465
<ASSISTANT_TASK:> Python Code: help('learning_lab.03_management_interface') from importlib import import_module script = import_module('learning_lab.03_management_interface') from inspect import getsource print(getsource(script.main)) print(getsource(script.demonstrate)) run ../learning_lab/03_management_interface.py...
<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: Implementation Step2: Execution Step3: HTTP
14,466
<ASSISTANT_TASK:> Python Code: # For using the same code in either Python 2 or 3 from __future__ import print_function ## Note: Python 2 users, use raw_input() to get player input. Python 3 users, use input() from IPython.display import clear_output def display_board(board): clear_output() print(' | ...
<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: Step 1 Step2: Step 2 Step3: Step 3 Step4: Step 4 Step5: Step 5 Step6: Step 6 Step7: Step 7 Step8: Step 8 Step9: Step 9 Step10: Step 10
14,467
<ASSISTANT_TASK:> Python Code: import sys python_version = sys.version_info[0] print("Python Version: ", python_version) !pip3 install witwidget import numpy as np import pandas as pd import witwidget from witwidget.notebook.visualization import WitConfigBuilder, WitWidget # Download our Pandas dataframe and our 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: Loading the mortgage test dataset Step2: Preview the Features Step3: Load the test features and labels into numpy arrays Step4: Let's take a ...
14,468
<ASSISTANT_TASK:> Python Code: # DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'nasa-giss', 'giss-e2-1g', 'atmos') # Set as follows: DOC.set_author("name", "email") # TODO - please enter value(s) # Set as follows: DOC.set_contributor("name",...
<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: Document Authors Step2: Document Contributors Step3: Document Publication Step4: Document Table of Contents Step5: 1.2. Model Name Step6: 1...
14,469
<ASSISTANT_TASK:> Python Code: from theano.sandbox import cuda %matplotlib inline from imp import reload import utils; reload(utils) from utils import * from __future__ import division, print_function #path = "data/dogscats/sample/" path = "data/dogscats/" model_path = path + 'models/' if not os.path.exists(model_path...
<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: Are we underfitting? Step2: ...and load our fine-tuned weights. Step3: We're going to be training a number of iterations without dropout, so i...
14,470
<ASSISTANT_TASK:> Python Code: import numpy as np import pandas as pd import oandapy import configparser %matplotlib inline import seaborn as sns import matplotlib.pyplot as plt config = configparser.ConfigParser() config.read('../config/config_v1.ini') account_id = config['oanda']['account_id'] api_key = config['oanda...
<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: Experiment With the Training Data Set Step2: Vectorized Backtesting With the Test Set - Momentum Step3: Vectorized Backtesting With the Test S...
14,471
<ASSISTANT_TASK:> Python Code: import pandas as pd def bayes_table(hypos, prior, likelihood): Make a table showing a Bayesian update. table = pd.DataFrame(dict(prior=prior, likelihood=likelihood), index=hypos) table['unnorm'] = table['prior'] * table['likelihood'] prob_data = table['unnorm'].sum() t...
<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: Flipping USB Connectors Step3: Now suppose that the prior probability is 0.5 that the orientation of the connector is correct, and you have bee...
14,472
<ASSISTANT_TASK:> Python Code: # DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'nims-kma', 'sandbox-1', 'ocean') # Set as follows: DOC.set_author("name", "email") # TODO - please enter value(s) # Set as follows: DOC.set_contributor("name", "...
<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: Document Authors Step2: Document Contributors Step3: Document Publication Step4: Document Table of Contents Step5: 1.2. Model Name Step6: 1...
14,473
<ASSISTANT_TASK:> Python Code: mu = [2, 3] cov = [[1, 0], [0, 1]] rv = sp.stats.multivariate_normal(mu, cov) xx = np.linspace(0, 4, 120) yy = np.linspace(1, 5, 150) XX, YY = np.meshgrid(xx, yy) plt.grid(False) plt.contourf(XX, YY, rv.pdf(np.dstack([XX, YY]))) plt.axis("equal") plt.show() mu = [2, 3] cov = [[2, -1],[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: 경우 2
14,474
<ASSISTANT_TASK:> Python Code: %matplotlib inline from ecell4.prelude import * D = 1 radius = 0.005 N_A = 60 U = 0.5 ka_factor = 0.1 # 0.1 is for reaction-limited N = 20 # a number of samples import numpy kD = 4 * numpy.pi * (radius * 2) * (D * 2) ka = kD * ka_factor kd = ka * N_A * U * U / (1 - U) kon = ka * kD / ...
<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: Parameters are given as follows. D, radius, N_A, U, and ka_factor mean a diffusion constant, a radius of molecules, an initial number of molecul...
14,475
<ASSISTANT_TASK:> Python Code: %matplotlib inline from __future__ import print_function import os import pandas as pd import matplotlib.pyplot as plt import seaborn as sns PROJ_ROOT = os.path.join(os.pardir, os.pardir) ## Try adding parameter index=0 pump_data_path = os.path.join(PROJ_ROOT, ...
<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.1 No more docs-guessing Step3: 3.2 No more copy-pasta Step4: 3.3 No more copy-pasta between notebooks Step5: Restart the kernel, let's try ...
14,476
<ASSISTANT_TASK:> Python Code: from IPython.display import display, HTML display(HTML('''<img src="image1.png",width=800,height=600>''')) import numpy as np # numerical libraries import pandas as pd # for data analysis import matplotlib as mpl # a big library with plotting functionality import matplotlib.pyplot as plt...
<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: Load data and take a peak at it. Step3: Separate data into training, validation, and test sets. (This division is not used ...
14,477
<ASSISTANT_TASK:> Python Code: import psycopg2 from configparser import ConfigParser from pandas import DataFrame from collections import Counter cfg = ConfigParser() cfg.read("db.cfg") knst = psycopg2.connect(host=cfg['db']['host'], port=cfg['db']['port'], database=cfg['db']['db'], user=cfg['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: We moeten verbinding maken met de databank. Step3: De SQL om de gegevens op te halen is niet zo moeilijk Step4: Even de gegevens binnenhalen e...
14,478
<ASSISTANT_TASK:> Python Code: # Initialization import numpy as np import matplotlib.pyplot as plt from matplotlib.patches import Ellipse %matplotlib inline plt.style.use('fivethirtyeight') def logprofile(z,ust): ''' Return u as function of z(array) and u_star Uses Charnock relation for wind-wave interactio...
<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: Basic power estimate Step2: With this simple set-up it is easy to see that a small difference in wind speed translates to a large difference in...
14,479
<ASSISTANT_TASK:> Python Code: %matplotlib inline import matplotlib.pyplot as plt import openpathsampling as paths import openpathsampling.engines.openmm as peng_omm from simtk.openmm import app import simtk.openmm as mm import simtk.unit as unit from openmmtools.integrators import VVVRIntegrator import mdtraj as md 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: Setting up the engine Step2: The storage file will need a template snapshot. In addition, the OPS OpenMM-based Engine has a few properties and ...
14,480
<ASSISTANT_TASK:> Python Code: Image('./res/fig3_1.png') # Transition Graph Image('./res/ex3_3.png') # Example 3.5 from scipy.signal import convolve2d reward_matrix = np.zeros((5, 5)) # kernel kernel = np.array([[0, 1, 0], [1, 0, 1], [0, 1, 0]]) iteration_nums = 100 for _ in rang...
<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: finite MDP Step2: Exercise 3.4
14,481
<ASSISTANT_TASK:> Python Code: %matplotlib inline # You can ignore the pink warning that appears import itertools import math import nltk import string import matplotlib.pyplot as plt from sklearn.feature_extraction.text import TfidfVectorizer import numpy as np from scipy.spatial.distance import pdist, squareform from...
<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: TF-IDF (Term Frequency, Inverse Document Frequency) Step2: What if you change some of those docs, or add another one? Add another c in the last...
14,482
<ASSISTANT_TASK:> Python Code: from myhdl import * from myhdlpeek import Peeker import numpy as np import pandas as pd import matplotlib.pyplot as plt %matplotlib inline from sympy import * init_printing() import random #https://github.com/jrjohansson/version_information %load_ext version_information %version_informati...
<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: RTL and Implimentation Schamatics are from Xilinx Vivado 2016.1 Step2: And if we try writing to the tuple we will get an error Step5: Random a...
14,483
<ASSISTANT_TASK:> Python Code: import matplotlib.pyplot as plt %matplotlib inline from Schelling import SchellingModel model = SchellingModel(20, 20, 0.85, 0.2, 3) while model.running and model.schedule.steps < 100: model.step() print(model.schedule.steps) # Show how many steps have actually run model_out = model....
<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 we instantiate a model instance Step2: Effect of Homophily on segregation Step3: Now, we set up the batch run, with a dictionary of fixed ...
14,484
<ASSISTANT_TASK:> Python Code: import pandas as pd import nltk import string import matplotlib.pyplot as plt #read in our data df = pd.read_csv("../Data/childrens_lit.csv.bz2", sep = '\t', encoding = 'utf-8', compression = 'bz2', index_col=0) df = df.dropna(subset=["text"]) df import numpy as np np.random.seed(1) df =...
<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: Since the number of children literaturs is a lot to analyze, we'll just randomly select 5 books to do a sentiment analysis using the dictionary ...
14,485
<ASSISTANT_TASK:> Python Code: class AlarmSensor: def run(self): print ("Alarm Ring...") class WaterSprinker: def run(self): print ("Spray Water...") class EmergencyDialer: def run(self): print ("Dial 119...") alarm_sensor = AlarmSensor() water_sprinker = WaterSprinker() emergency_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: 在业务中如果需要将三个部件启动,例如,如果有一个烟雾传感器,检测到了烟雾。在业务环境中需要做如下操作: Step2: 但如果在多个业务场景中需要启动三个部件,怎么办?Ctrl+C加上Ctrl+V么?当然可以这样,但作为码农的基本修养之一,减少重复代码是应该会被很轻易想到的方法。这样,需...
14,486
<ASSISTANT_TASK:> Python Code: %matplotlib inline %precision 2 vocabulary = ['see', 'spot', 'run'] num_terms = len(vocabulary) num_topics = 2 # K num_documents = 5 # M mean_document_length = 5 # xi term_dirichlet_parameter = 1 # beta topic_dirichlet_parameter = 1 # alpha from scipy.stats import dirichlet, poisson fro...
<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: Latent Dirichlet Allocation is a generative model for topic modeling. Given a collection of documents, an LDA inference algorithm attempts to de...
14,487
<ASSISTANT_TASK:> Python Code: # Set up feedback system from learntools.core import binder binder.bind(globals()) from learntools.ethics.ex4 import * import pandas as pd from sklearn.model_selection import train_test_split # Load the data, separate features from target data = pd.read_csv("../input/synthetic-credit-card...
<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 dataset contains, for each applicant Step2: The confusion matrices above show how the model performs on some test data. We also print addit...
14,488
<ASSISTANT_TASK:> Python Code: import wasmfun instructions = [('f64.const', 42), ('call', 'print_ln'), ('call', 'make_background_blue')] m = wasmfun.Module( wasmfun.Function('$main', params=[], returns=[], locals=[], instructions=instructions), wasmfun.ImportedFuncion('...
<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: What is Web Assembly? Step2: Instructions are packed into functions ... Step3: Web Assembly modules have a compact binary format Step5: Web A...
14,489
<ASSISTANT_TASK:> Python Code: import pandas as pd from scipy.spatial.distance import cosine # Data was already dlownloaded. data = pd.read_csv('data/lastfm/lastfm-matrix-germany.csv') # check out the data set you can do so using data.head(): data.head(6).ix[:,2:10] #In item based collaborative filtering we do not car...
<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: Item Based Collaborative Filtering Step2: Now we can start to look at filling in similarities. We will use Cosin Similarities. In Python, the S...
14,490
<ASSISTANT_TASK:> Python Code: # Author: Alexandre Barachant <alexandre.barachant@gmail.com> # Jean-Remi King <jeanremi.king@gmail.com> # # License: BSD (3-clause) import matplotlib.pyplot as plt import mne from mne import Epochs from mne.decoding import SPoC from mne.datasets.fieldtrip_cmc import data_path fro...
<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: Plot the contributions to the detected components (i.e., the forward model)
14,491
<ASSISTANT_TASK:> Python Code: # DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'cams', 'sandbox-1', 'seaice') # Set as follows: DOC.set_author("name", "email") # TODO - please enter value(s) # Set as follows: DOC.set_contributor("name", "ema...
<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: Document Authors Step2: Document Contributors Step3: Document Publication Step4: Document Table of Contents Step5: 1.2. Model Name Step6: 2...
14,492
<ASSISTANT_TASK:> Python Code: def number_to_words(n): Given a number n between 1-1000 inclusive return a list of words for the number. x = [] a = {1:'one',2:'two',3:'three',4:'four',5:'five',6:'six',7:'seven',8:'eight',9:'nine',10:'ten', 11:'eleven',12:'twelve',13:'thirteen',14:'fourteen',15:'fift...
<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: Project Euler Step2: Now write a set of assert tests for your number_to_words function that verifies that it is working as expected. Step4: No...
14,493
<ASSISTANT_TASK:> Python Code: #@title ### Install the Graph Nets library on this Colaboratory runtime { form-width: "60%", run: "auto"} #@markdown <br>1. Connect to a local or hosted Colaboratory runtime by clicking the **Connect** button at the top-right.<br>2. Choose "Yes" below to install the Graph Nets library on...
<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: Install dependencies locally Step2: Tutorial of the Graph Nets library Step3: How to represent graphs as a graphs.GraphsTuple Step4: Visualiz...
14,494
<ASSISTANT_TASK:> Python Code: from halomod import AngularCF import halomod halomod.__version__ %matplotlib inline import matplotlib.pyplot as plt import numpy as np acf = AngularCF(z=0.475, zmin=0.45, zmax=0.5) plt.plot(acf.theta * 180/np.pi, acf.angular_corr_gal) plt.xscale('log') plt.yscale('log') plt.xlabel(r"$\th...
<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 problem illustrated Step2: Note that this is pretty much 1000x times what Blake+ got, but does have a similar shape. Step3: OK, this is aw...
14,495
<ASSISTANT_TASK:> Python Code: import numpy as np %matplotlib inline from sherpa import data from sherpa.astro import data as astrodata from sherpa import plot from sherpa.astro import plot as astroplot x1 = np.asarray([100, 200, 600, 1200]) y1 = np.asarray([2000, 2100, 1400, 3050]) d1 = data.Data1D('oned', x1, y1) pl...
<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 dimensional data plots Step2: We can have some fun with the plot options (these are a mixture of generic options, such as xlog, and ones sp...
14,496
<ASSISTANT_TASK:> Python Code: #$HIDE_INPUT$ import geopandas as gpd import pandas as pd # Load a GeoDataFrame containing regions in Ghana regions = gpd.read_file("../input/geospatial-learn-course-data/ghana/ghana/Regions/Map_of_Regions_in_Ghana.shp") print(regions.crs) # Create a DataFrame with health facilities 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: Setting the CRS Step2: How do you interpret that? Step3: In the code cell above, to create a GeoDataFrame from a CSV file, we needed to use bo...
14,497
<ASSISTANT_TASK:> Python Code: from edward.models import Bernoulli, Beta, Empirical, Uniform N = 100 def build_fair_dataset(N): pheads = tf.constant(0.5) c = Bernoulli(probs=pheads, sample_shape = N) return sess.run([pheads, c]) def build_unfair_dataset(N): pheads = tf.constant(0.05) c = Bernoulli(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: inference Step2: exact solution Step3: RECURSIVE INFERENCE Step4: approximate inference Step5: MCMC Step6: MCMC Step7: variational infere...
14,498
<ASSISTANT_TASK:> Python Code: %matplotlib inline from scipy.stats import logistic import numpy as np import matplotlib.pyplot as plt from IPython.display import Image # Esto es para desplegar imágenes en la libreta def logistica(z): Calcula la función logística para cada elemento de z @param z: un ...
<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: 1. Función logística, función de costo y gradiente de la función de costo Step3: Para probar la función vamos a graficar la función logística e...
14,499
<ASSISTANT_TASK:> Python Code: % matplotlib inline from __future__ import print_function import nibabel as nib from nilearn.image import resample_img import matplotlib.pyplot as plt import numpy as np import pandas as pd import os import os.path # The following are a progress bar, these are not strictly necessary: fro...
<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: Define the variables for this analysis. Step2: Next define a function to take the average of an image inside a mask and return it Step3: This...