Unnamed: 0
int64
0
15.9k
cleaned_code
stringlengths
67
124k
cleaned_prompt
stringlengths
168
30.3k
12,200
<ASSISTANT_TASK:> Python Code: import pandas as pd diabetes = pd.read_csv('Class01_diabetes_data.csv') diabetes.head() diabetes.dropna(inplace=True) diabetes.head() diabetes.plot(x='Age',y='Target',kind='scatter') diabetes.plot(x='Sex',y='Target',kind='scatter') diabetes.plot(x='BMI',y='Target',kind='scatter') dia...
<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 will be to copy the data file that we will be using for this tutorial into the same folder as these notes. We will be looking at a...
12,201
<ASSISTANT_TASK:> Python Code: quotient = 7 / 3 print(format(quotient, '.2f')) remainder = 7 % 3 print(remainder) 5 == 5 5 == 6 type(True), type(False) x = 10 y = 9 if x < y: print('x is less than y') elif x > y: print('x is greater than y') else: print('x and y are equal') x = 18 y = 20 if x == y: ...
<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 modulus operator turns out to be surprisingly useful. For example, you can check whether one number is divisible by another Step2: The True...
12,202
<ASSISTANT_TASK:> Python Code: import numpy as np import pandas as pd pd.__version__ np.__version__ # set some options to control output display pd.set_option('display.notebook_repr_html',False) pd.set_option('display.max_columns',10) pd.set_option('display.max_rows',10) # create one item series s1 = pd.Series(1) s1 ...
<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 Series Step2: '0' is the index and '1' is the value. The data type (dtype) is also shown. We can also retrieve the value using the ass...
12,203
<ASSISTANT_TASK:> Python Code: # DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'ncar', 'sandbox-1', 'landice') # Set as follows: DOC.set_author("name", "email") # TODO - please enter value(s) # Set as follows: DOC.set_contributor("name", "em...
<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...
12,204
<ASSISTANT_TASK:> Python Code: %matplotlib inline import numpy as np import matplotlib.image as mpimg import matplotlib.pyplot as plt import sys,os ia898path = os.path.abspath('/etc/jupyterhub/ia898_1s2017/') if ia898path not in sys.path: sys.path.append(ia898path) import ia898.src as ia from numpy.fft import fft2 ...
<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: Numeric sample Step2: See that f and h are periodic images and the period is (H,W) that is the shape of f. Step3: gg and g need to be equal St...
12,205
<ASSISTANT_TASK:> Python Code: import sys import os sys.path.append(os.environ.get('NOTEBOOK_ROOT')) from utils.data_cube_utilities.clean_mask import landsat_clean_mask_full # landsat_qa_clean_mask, landsat_clean_mask_invalid from utils.data_cube_utilities.dc_mosaic import create_hdmedians_multiple_band_mosaic from uti...
<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: <span id="Composites_retrieve_data">Load Data from the Data Cube &#9652;</span> Step2: <span id="Composites_most_common">Most Common Composites...
12,206
<ASSISTANT_TASK:> Python Code: import luigi as lg import json import pickle import sys basedir = '/Users/joewandy/git/lda/code/' sys.path.append(basedir) from multifile_feature import SparseFeatureExtractor from lda import MultiFileVariationalLDA class ExtractSpectra(lg.Task): datadir = lg.Parameter() prefix =...
<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: These are what we want from the new pipeline. Step2: Example Step 2 Step3: Example Step 3 Step4: Run the pipeline Step5: And run the pipelin...
12,207
<ASSISTANT_TASK:> Python Code: # Authors: Laura Gwilliams <laura.gwilliams@nyu.edu> # Jean-Remi King <jeanremi.king@gmail.com> # Alex Barachant <alexandre.barachant@gmail.com> # Alexandre Gramfort <alexandre.gramfort@telecom-paristech.fr> # # License: BSD (3-clause) import numpy as np import ...
<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 and read data Step2: Loop through frequencies, apply classifier and save scores Step3: Plot frequency results Step4: Loop thro...
12,208
<ASSISTANT_TASK:> Python Code: import time import numpy as np import h5py import matplotlib.pyplot as plt import scipy from PIL import Image from scipy import ndimage from dnn_app_utils_v2 import * %matplotlib inline plt.rcParams['figure.figsize'] = (5.0, 4.0) # set default size of plots plt.rcParams['image.interpolati...
<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 - Dataset Step2: The following code will show you an image in the dataset. Feel free to change the index and re-run the cell multiple times t...
12,209
<ASSISTANT_TASK:> Python Code: # Setup taken from notebook 17. import itertools import sys import bson import h5py import keras.layers import keras.models import matplotlib.pyplot import numpy import pandas import sklearn.cross_validation import sklearn.dummy import sklearn.linear_model import sklearn.metrics sys.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: Baseline &mdash; logistic regression with CNN, astro, and distance features Step2: Scaling inputs Step3: Scaling inputs = good. This isn't ter...
12,210
<ASSISTANT_TASK:> Python Code: # Authors: Alex Rockhill <aprockhill206@gmail.com> # # License: BSD (3-clause) import numpy as np import matplotlib.pyplot as plt import mne from mne.datasets import sample print(__doc__) data_path = sample.data_path() raw = mne.io.read_raw_fif(data_path + '/MEG/sample/sample_audvis_raw....
<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 sample subject data Step2: Plot the raw data and CSD-transformed raw data Step3: Also look at the power spectral densities Step4: CSD ca...
12,211
<ASSISTANT_TASK:> Python Code: from collections import defaultdict dict_of_colors = defaultdict(list) with open('input.txt', 'r') as fd: for line in fd: if 'no other bags' not in line: sentence = line.split(' ') main_color = ' '.join(line.split(' ')[:2]) for i, word 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: Problem 2
12,212
<ASSISTANT_TASK:> Python Code: !pip3 install bayesian-optimization def black_box_function(x, y): return -x ** 2 - (y - 1) ** 2 + 1 from bayes_opt import BayesianOptimization # 파라미터 경계 정의 pbounds = {'x': (2, 4), 'y': (-3, 3)} optimizer = BayesianOptimization( f=black_box_function, pbounds=pbounds, verb...
<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. 최적화할 함수 정의 Step2: 2. 최적화 시작 Step3: n_iter Step4: 최상의 조합은 optimizer.max로 확인 가능 Step5: 2.1 범위 수정 Step6: 3. 최적화 가이드 Step7: 4. 저장, 로딩, 재시작...
12,213
<ASSISTANT_TASK:> Python Code: set1 = set('Moment of Truth') set1 set2 = set() set2.add('A') set2 # set is similar to dictionary but containing only keys setA = {'Apple','America','August'} setA set3 = set() set3.add('Blue') set3.add('Green') print(set3) set3.add('Blue') print(set3) # please note set is case-sensitive...
<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 can contain only unique entries. If you try to duplicate an entry in the set Step2: Sets will not allow any mutable objects. As you can see...
12,214
<ASSISTANT_TASK:> Python Code: # возьмем лог, который "penalize higher values more than smaller values" ts_log = np.log(rub["Adj Close"]) test_stationarity(ts_log) # далее вычтем скользящее среднее moving_avg = pd.rolling_mean(ts_log,50) plt.plot(ts_log) plt.plot(moving_avg, color='red') ts_log_moving_avg_diff = ts_log...
<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: Два способа убрать сезонность
12,215
<ASSISTANT_TASK:> Python Code: import sys print('{0[0]}.{0[1]}'.format(sys.version_info)) pi = 3.1416 radio = 5 area= pi * radio**2 print(area) color_list_1 = set(["White", "Black", "Red"]) color_list_2 = set(["Red", "Green"]) color_list_1 - color_list_2 path = 'C:/Users/Margarita/Documents/Mis_documentos/Biologia_...
<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. Calcule el área de un circulo de radio 5 Step2: 3. Escriba código que imprima todos los colores de que están en color_list_1 y no estan pres...
12,216
<ASSISTANT_TASK:> Python Code: import seaborn as sns %matplotlib inline tips = sns.load_dataset('tips') tips.head() sns.distplot(tips['total_bill']) # Safe to ignore warnings sns.distplot(tips['total_bill'],kde=False,bins=30) sns.jointplot(x='total_bill',y='tip',data=tips,kind='scatter') sns.jointplot(x='total_bill...
<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 Step2: distplot Step3: To remove the kde layer and just have the histogram use Step4: jointplot Step5: pairplot Step6: rugplot Step7: ...
12,217
<ASSISTANT_TASK:> Python Code: X = ["Some say the world will end in fire,", "Some say in ice."] len(X) from sklearn.feature_extraction.text import CountVectorizer vectorizer = CountVectorizer() vectorizer.fit(X) vectorizer.vocabulary_ X_bag_of_words = vectorizer.transform(X) X_bag_of_words.shape X_bag_of_words X_b...
<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 Encoding Step2: tf-idfs are a way to represent documents as feature vectors. tf-idfs can be understood as a modification of the raw term...
12,218
<ASSISTANT_TASK:> Python Code: # DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'csiro-bom', 'sandbox-2', 'seaice') # 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: 2...
12,219
<ASSISTANT_TASK:> Python Code: %matplotlib inline import matplotlib.pyplot as plt import numpy as np import math def radius(x): length of a vector if len(x.shape) == 1: return math.sqrt(np.inner(x,x)) # elif len(x.shape) == 2: def potential(pos): potential, defined as a negative number...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step6: The Plummer potential for mass $M_p$ and core radius $r_c$ is given by Step11: Integrator Step13: Helper functions Step14: Initial conditions...
12,220
<ASSISTANT_TASK:> Python Code: !sudo chown -R jupyter:jupyter /home/jupyter/training-data-analyst pip install --user apache-beam[gcp]==2.16.0 # Ensure the right version of Tensorflow is installed. !pip freeze | grep tensorflow==2.1 import apache_beam as beam print(beam.__version__) # change these to try this notebook...
<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: Run the command again if you are getting oauth2client error. Step2: You may receive a UserWarning about the Apache Beam SDK for Python 3 as not...
12,221
<ASSISTANT_TASK:> Python Code: # 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 writing, software ...
<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: Reformer Step2: Load example data and model Step3: Sample from the model Step4: Sampling is an inherently serial process and will take up to ...
12,222
<ASSISTANT_TASK:> Python Code: #urllib is used to download the utils file from deeplearning.net from urllib import request response = request.urlopen('http://deeplearning.net/tutorial/code/utils.py') content = response.read() target = open('utils.py', 'wb') target.write(content) target.close() #Import the math function...
<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: Constructing the Layers of RBMs Step2: The MNIST Dataset Step3: Creating the Deep Belief Network Step4: RBM Train Step5: Now we can convert ...
12,223
<ASSISTANT_TASK:> Python Code: import numpy as np import tensorflow as tf # Implement forward path # TensorFlow figures out backprop w = tf.Variable(0, dtype=tf.float32) cost = tf.add(tf.add(w ** 2, tf.multiply(-10.0, w)), 25) learning_rate = 0.01 train = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost)...
<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: Taken from Andrew Ng's Coursera Deep Learning series Step2: An alternative way of identifying the cost is to use overloaded operations Step3: ...
12,224
<ASSISTANT_TASK:> Python Code: #read data df = pd.read_fwf('linear_regression_demo/brain_body.txt') x_values = df[['Brain']] y_values = df[['Body']] #train model on data body_reg = linear_model.LinearRegression() body_reg.fit(x_values, y_values) #visualize results plt.scatter(x_values, y_values) plt.plot(x_values, body...
<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: Siraj's Week 1 challange Step2: So now we have simple trained dataset. now to make a prediction. Step3: Linear Regression Quiz Step4: Program...
12,225
<ASSISTANT_TASK:> Python Code: from IPython.display import HTML def Complex(a, b): # constructor return (a,b) def real(c): # method return c[0] def imag(c): return c[1] def str_complex(c): return "{0}+{1}i".format(c[0], c[1]) c1 = Complex(1,2) # constructor print(real(c1), " ", str_complex(c1)) 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: Motiviation Step2: But things aren't hidden so I can get through the interface Step3: Because I used a tuple, and a tuple is immutable, I can'...
12,226
<ASSISTANT_TASK:> Python Code: import numpy as np import pandas as pd import itertools from scipy import stats from statsmodels.stats.descriptivestats import sign_test from statsmodels.stats.weightstats import zconfint %pylab inline weight_data = pd.read_csv('weight.txt', sep = '\t', header = 0) weight_data.head() pyl...
<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: Двухвыборочные критерии для связных выборок Step3: Критерий знаков Step4: Критерий знаковых рангов Вилкоксона Step5: ...
12,227
<ASSISTANT_TASK:> Python Code: from __future__ import division import numpy from matplotlib import pyplot %matplotlib notebook dt = 1e-5 dx = 1e-2 x = numpy.arange(0,1+dx,dx) y = numpy.zeros_like(x) y = x * (1 - x) def update_heat(y, dt, dx): dydt = numpy.zeros_like(y) dydt[1:-1] = dt/dx**2 * (y[2:] + y[:-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: Note Step2: The solution looks good - smooth, the initial profile is diffusing nicely. Try with something a bit more complex, such as $y(0, x) ...
12,228
<ASSISTANT_TASK:> Python Code: def pretty_print_review_and_label(i): print(labels[i] + "\t:\t" + reviews[i][:80] + "...") g = open('reviews.txt','r') # What we know! reviews = list(map(lambda x:x[:-1],g.readlines())) g.close() g = open('labels.txt','r') # What we WANT to know! labels = list(map(lambda x:x[:-1].uppe...
<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: Note Step2: Lesson Step3: Project 1 Step4: We'll create three Counter objects, one for words from postive reviews, one for words from negativ...
12,229
<ASSISTANT_TASK:> Python Code: # DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'inpe', 'sandbox-3', 'atmoschem') # 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...
12,230
<ASSISTANT_TASK:> Python Code: %tensorflow_version 1.x import tensorflow as tf print(tf.__version__) # Silence deprecation warnings for now. tf.logging.set_verbosity(tf.logging.ERROR) device_name = tf.test.gpu_device_name() if device_name != '/device:GPU:0': print('GPU device not found') gpu = False else: 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: Set up FFN code and sample data Step2: Run inference
12,231
<ASSISTANT_TASK:> Python Code: %%writefile requirements.txt joblib~=1.0 numpy~=1.20 scikit-learn~=0.24 google-cloud-storage>=1.26.0,<2.0.0dev # Required in Docker serving container %pip install -U -r requirements.txt # For local FastAPI development and running %pip install -U "uvicorn[standard]>=0.12.0,<0.14.0" fastapi...
<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: Restart the kernel Step2: Before you begin Step3: Otherwise, set your project ID here. Step4: Authenticate your Google Cloud account Step5: ...
12,232
<ASSISTANT_TASK:> Python Code: %pip install 'firebase_admin>=4.1.0' %pip install 'tensorflow>=2.1.0' import ipywidgets uploader = ipywidgets.FileUpload( accept='.json', multiple=False ) service_acct_file = {} def handle_upload(change): service_acct_file['name'] = next(iter(change['owner'].value)) servi...
<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. Set up a Firebase project Step2: 4. Set your Google Application Credentials location Step3: 5. Initialize Firebase Admin Step4: 6. Train y...
12,233
<ASSISTANT_TASK:> Python Code: print('Hello, world!') 2 + 2 import numpy a_integer = 5 a_float = 1.41421356237 a_integer + a_float a_number = a_integer + a_float print(a_number) a_string = 'How you doing, world?' print(a_string) a_integer + a_string print(a_integer, a_string) str(a_integer) + a_string a_float = 3.1417...
<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: Define Variables Step3: Comments are handy to temporarily turn some lines on or off and to document Python files. In Jupyter notebooks using ma...
12,234
<ASSISTANT_TASK:> Python Code: %pylab inline import numpy as np import seaborn as sns import pandas as pd from Lec08 import * plot_svc(); x = np.linspace(-1, 1, 100); plt.plot(x, x**2) plt.xlabel("$y-\hat{f}$", size=18); x = np.linspace(-1, 1, 100); plt.plot(x, np.abs(x)); plt.xlabel("$y-\hat{f}$", size=18); plt.yla...
<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: EECS 445 Step2: Separating Hyperplanes Step3: Absolute Loss Step4: 0-1 Loss Step5: Logistic Loss Step6: Hinge Loss Step7: Exponential Loss...
12,235
<ASSISTANT_TASK:> Python Code: from math import fabs def bisection(x1, x2, f1, f2, fh, sizevec): This function finds the root of a function using bisection. Parameters ---------- x1 : float lower bound x2 : float upper bound f1 : float function value at lower bo...
<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: Bracketing Methods (Bisection example) Step2: We are interseted in optimization, so we don't want to find the root of our
12,236
<ASSISTANT_TASK:> Python Code: import sys, os import re from os import listdir from os.path import isfile, join def fromFileToCSV (folderpath,csvfilename) : files = [f for f in listdir(folderpath) if isfile(join(folderpath, f))] random.shuffle(files) for filepath in files: if filepath.endswith(".pn...
<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: Nous créeons ensuite notre fonction que nous appellerons fromFileToCSV. Cette fonction prend deux arguements Step2: La variable files est une ...
12,237
<ASSISTANT_TASK:> Python Code: # Load library import numpy as np # Create two vectors vector_a = np.array([1,2,3]) vector_b = np.array([4,5,6]) # Calculate dot product np.dot(vector_a, vector_b) # Calculate dot product vector_a @ vector_b <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: Create Two Vectors Step2: Calculate Dot Product (Method 1) Step3: Calculate Dot Product (Method 2)
12,238
<ASSISTANT_TASK:> Python Code: import numpy as np size = 50 x = np.array((np.random.randint(1,10,size), np.random.randint(1,10,size))).T print x mu = np.average(x, 0) # This performs the average over the two main dimensions mu x0_bar = 0 x1_bar = 0 for xi in x: x0_bar += xi[0] x1_bar += xi[1] x0_bar /= float(...
<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: Unweighted Mean Step2: To verify... Step3: Standard Deviation Step4: This time we will verify using vectorized code... Step5: Variance Step6...
12,239
<ASSISTANT_TASK:> Python Code: %%bash # Install packages to test model locally. apt-get update apt-get install -y python-numpy python-dev cmake zlib1g-dev libjpeg-dev xvfb libav-tools xorg-dev python-opengl libboost-all-dev libsdl2-dev swig libffi-dev pip install gym pip install gym[atari] pip install opencv-python apt...
<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 run locally to make sure everything is working. Step2: Run on ML-Engine Step3: TODO Step4: Launch tensorboard
12,240
<ASSISTANT_TASK:> Python Code: import pandas as pd import numpy as np import matplotlib.pyplot as plt from sklearn import svm, datasets from sklearn.cross_validation import train_test_split from sklearn.metrics import confusion_matrix import matplotlib from matplotlib import pyplot as plt %matplotlib inline #load 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: Classification problem with Unbalanced classes Step2: Precision, Recall and F measures
12,241
<ASSISTANT_TASK:> Python Code: from ipyparallel import Client cluster = Client() dview = cluster[:] dview.use_dill() lview = cluster.load_balanced_view() len(dview) # import os # from scripts.hpc05 import HPC05Client # os.environ['SSH_AUTH_SOCK'] = os.path.join(os.path.expanduser('~'), 'ssh-agent.socket') # cluster = ...
<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 next cell is for internal use with our cluster at the department, a local ipcluster will work Step2: Make sure to add the correct path lik...
12,242
<ASSISTANT_TASK:> Python Code: print 'The default path: '+fp.fhd_base() fp.set_fhd_base(os.getcwd().strip('scripts')+'katalogss/data') print 'Our path: '+fp.fhd_base() fhd_run = 'mock_run' s = '%sfhd_%s'%(fp.fhd_base(),fhd_run) !ls -R $s obsids = fp.get_obslist(fhd_run) obsids comps = fp.fetch_comps(fhd_run, obsids...
<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 also need to define the version specifying the name of the run. This is equivalent to the case string in eor_firstpass_versions.pro, or the s...
12,243
<ASSISTANT_TASK:> Python Code: from larray import * age_category = Axis(["0-9", "10-17", "18-66", "67+"], "age_category") age_category age_category = Axis("age_category=0-9,10-17,18-66,67+") age_category a = Axis('a=a0,a1,a2,a3') a a = Axis('a=a0..a3') a arr = zeros("a=a0..a2; b=b0,b1; c=c0..c5") arr immigration ...
<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 LArray library offers two syntaxes to build axes and make selections and aggregations. Step2: The second one consists of using strings that...
12,244
<ASSISTANT_TASK:> Python Code: from importlib import reload import xml_parser reload(xml_parser) from xml_parser import Xml_parser #Xml_parser = Xml_parser().collect_data("../pmi_data") authorID_to_titles = utils.load_pickle("../pmi_data/authorID_to_publications.p") authorID_to_count = {k:len(v['titles']) for k,v in 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: Observation of the data Step2: We can observe that most of the authors have between 1 and 50 publications. A few author have around 50 and 200 ...
12,245
<ASSISTANT_TASK:> Python Code: import json import os import numpy as np import pandas as pd import pickle import uuid import time import tempfile from googleapiclient import discovery from googleapiclient import errors from google.cloud import bigquery from jinja2 import Template from kfp.components import func_to_cont...
<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: Run the command in the cell below to install gcsfs package. Step2: Prepare lab dataset Step3: Next, create the BigQuery dataset and upload the...
12,246
<ASSISTANT_TASK:> Python Code: import tensorflow as tf # Create a tensorflow constant hello = tf.constant("Hello World!") # Print this variable as is print(hello) # Create a new session sess = tf.Session() # Print the constant print("Printing using Session.run()") print(sess.run(hello)) # Also print("Printing using ev...
<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: Oops! That is not what we wanted! This is because the variable hello hasn't been evaluated yet. Tensorflow needs a session to run the graph in! ...
12,247
<ASSISTANT_TASK:> Python Code: from oemof.solph import EnergySystem import pandas as pd # initialize energy system energysystem = EnergySystem(timeindex=pd.date_range('1/1/2016', periods=168, freq='H')) # import e...
<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 input data Step2: Add entities to energy system Step4: Optimize energy system and plot results Step5: Adding the gas sector Step6: Ad...
12,248
<ASSISTANT_TASK:> Python Code: from fretbursts import * sns = init_notebook(apionly=True) print('seaborn version: ', sns.__version__) # Tweak here matplotlib style import matplotlib as mpl mpl.rcParams['font.sans-serif'].insert(0, 'Arial') mpl.rcParams['font.size'] = 12 %config InlineBackend.figure_format = 'retina' u...
<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 and process data Step2: Filtering method Step3: DCBS Method Step4: The function bext.burst_search_and_gate() Step5: Before plotting we s...
12,249
<ASSISTANT_TASK:> Python Code: <image> <section data-background="img/cover.jpg" data-state="img-transparent no-title-footer"> <div class="intro-body"> <div class="intro_h1"><h1>Title</h1></div> <h3>Subtitle of the Presentation</h3> <p><strong><span class="a">Speaker 1</span></strong> <span class="b"></span> <span>Job 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: Step2: Cover Slide 2 Step3: Headline Subslide
12,250
<ASSISTANT_TASK:> Python Code: import essentia.streaming as ess import essentia audio_file = '../../../test/audio/recorded/mozart_c_major_30sec.wav' # Initialize algorithms we will use. loader = ess.MonoLoader(filename=audio_file) framecutter = ess.FrameCutter(frameSize=4096, hopSize=2048, silentFrames='noise') windowi...
<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 plot the resulting HPCP Step2: Now we can run a naive estimation of chords with 2-second sliding window over the computed HPCPgram
12,251
<ASSISTANT_TASK:> Python Code: # Import relevant libraries: import time import numpy as np import pandas as pd from sklearn.neighbors import KNeighborsClassifier from sklearn import preprocessing from sklearn.preprocessing import MinMaxScaler from sklearn.preprocessing import StandardScaler from sklearn.naive_bayes imp...
<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: DDL to construct table for SQL transformations Step2: Note Step3: Model Prototyping
12,252
<ASSISTANT_TASK:> Python Code: xy = np.random.multivariate_normal([0,0], [[10,7],[7,10]],1000) plt.plot(xy[:,0],xy[:,1],"o") plt.show() pca = PCA(n_components=2) xy_pca = pca.fit(xy) plt.plot(xy[:,0],xy[:,1],"o") scalar = xy_pca.explained_variance_[0] plt.plot([0,xy_pca.components_[0,0]*scalar/2],[0,xy_pca.component...
<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 Principle Component Analysis (PCA) object Step2: num_components is the number of axes on which you spread the data out. You can only ...
12,253
<ASSISTANT_TASK:> Python Code: folder = os.path.join('..', 'data') newsbreaker.init(os.path.join(folder, 'topic_model'), 'topic_model.pkl', 'vocab.txt') entries = load_entries(folder) entries_dict = defaultdict(list) for entry in entries: entries_dict[entry.feed].append(entry) client = MongoClient() db = client.new...
<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: Algorithm Step2: Save coefs (X) and Y, along with tests (to know what each row refers to) to work with it later Step3: What without NEs Step4:...
12,254
<ASSISTANT_TASK:> Python Code: import numpy as np, matplotlib.pyplot as plt, pandas as pd, pymc as mc import dismod_mr model = dismod_mr.data.load('pd_sim_data') model.keep(areas=['europe_western'], sexes=['female', 'total']) summary = model.input_data.groupby('data_type')['value'].describe() np.round(summary,3).sort...
<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: DisMod-MR uses the integrative systems modeling (ISM) approach to produce simultaneous Step2: Of the 348 rows of data, here is how the values b...
12,255
<ASSISTANT_TASK:> Python Code: # As usual, a bit of setup import time import numpy as np import matplotlib.pyplot as plt from cs231n.classifiers.fc_net import * from cs231n.data_utils import get_CIFAR10_data from cs231n.gradient_check import eval_numerical_gradient, eval_numerical_gradient_array from cs231n.solver impo...
<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: Batch Normalization Step2: Batch normalization Step3: Batch Normalization Step4: Batch Normalization Step5: Fully Connected Nets with Batch ...
12,256
<ASSISTANT_TASK:> Python Code: # Ensure the right version of Tensorflow is installed. !pip freeze | grep tensorflow==2.1 %pip install apache-beam[gcp]==2.13.0 import apache_beam as beam print(beam.__version__) # change these to try this notebook out BUCKET = 'cloud-training-demos-ml' PROJECT = 'cloud-training-demos' ...
<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: After installing Apache Beam, restart your kernel by selecting "Kernel" from the menu and clicking "Restart kernel..." Step2: You may receive a...
12,257
<ASSISTANT_TASK:> Python Code: %load_ext autoreload %autoreload 2 import skrf as rf import numpy as np from numpy import real, log10, sum, absolute, pi, sqrt import matplotlib.pyplot as plt from scipy.optimize import minimize, differential_evolution rf.stylely() # Load raw measurements MSL100_raw = rf.Network('MSL100....
<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: Measurement of two microstripline with different lengths Step2: The measured data shows that the electrical length of MSL200 is approximately t...
12,258
<ASSISTANT_TASK:> Python Code: import numpy as np from scipy.optimize import linprog import quantecon.game_theory as gt U = np.array( [[0, -1, 1], [1, 0, -1], [-1, 1, 0]] ) p0 = gt.Player(U) p1 = gt.Player(-U.T) g = gt.NormalFormGame((p0, p1)) print(g) gt.lemke_howson(g) gt.support_enumeration(g) m, 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: じゃんけん・ゲームを例に計算してみる. Step2: quantecon.game_theory でナッシュ均衡を求める Step3: プレイヤー1の行列は -U の転置 (.T) であることに注意. Step4: scipy.optimize.linprog で線形計画問題を解く...
12,259
<ASSISTANT_TASK:> Python Code: class Directions: NORTH = 'North' SOUTH = 'South' EAST = 'East' WEST = 'West' STOP = 'Stop' def P_1(eps, E_N, E_S): ''' Calculates: P(X=x|E_{N}=e_{N},E_{S}=e_{S}) Arguments: E_N, E_S \in {True,False} 0 <= eps <= 1 (epsilon) Returns: dict...
<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. Bayes' net for instant perception and position. Step2: ii. $P(E_{E}=e_{E}|E_{N}=e_{N},E_{S}=E_{S})$ Step3: iii. $P(S)$, where $S\subseteq{e...
12,260
<ASSISTANT_TASK:> Python Code: from explauto.environment import environments environments.keys() from explauto.environment import available_configurations available_configurations('simple_arm').keys() available_configurations('simple_arm')['mid_dimensional'] available_configurations('pendulum').keys() from explauto...
<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: According to your installation, you will see at least two available environments Step2: For example, the 'mid_dimensional' configuration corres...
12,261
<ASSISTANT_TASK:> Python Code: from pynq.overlays.base import BaseOverlay base = BaseOverlay("base.bit") from time import sleep from pynq.lib import Pmod_Timer pt = Pmod_Timer(base.PMODA,0) pt.stop() # Generate a 10 ns pulse every period*10 ns period=100 pt.generate_pulse(period) # Sleep for 4 seconds and stop the ti...
<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: Instantiate Pmod_Timer class. The method stop() will stop both timer sub-modules. Step2: 2. Generate pulses for a certain period of time Step3:...
12,262
<ASSISTANT_TASK:> Python Code: %pylab notebook %precision %.4g V = 240 # [V] Z1 = 10.0 * exp(1j* 30/180*pi) Z2 = 10.0 * exp(1j* 45/180*pi) Z3 = 10.0 * exp(1j*-90/180*pi) I1 = V/Z1 I2 = V/Z2 I1_angle = arctan(I1.imag/I1.real) I2_angle = arctan(I2.imag/I2.real) print('''I1 = {:.1f} A ∠{:.1f}° I2 = {:.1f} 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: Description Step2: Answer the following questions about this power system. Step3: Therefore the total current from the source is $\vec{I} = \v...
12,263
<ASSISTANT_TASK:> Python Code: # change these to try this notebook out BUCKET = 'cloud-training-demos-ml' PROJECT = 'cloud-training-demos' REGION = 'us-east1' #'us-central1' import os os.environ['BUCKET'] = BUCKET os.environ['PROJECT'] = PROJECT os.environ['REGION'] = REGION %%bash if ! gsutil ls | grep -q gs://${BUCKE...
<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 Keras model Step2: Next, define the feature columns. mother_age and gestation_weeks should be numeric. Step3: We can visualize the DNN ...
12,264
<ASSISTANT_TASK:> Python Code: # Imports import sys,math sys.path.insert(0, '..') # path to ../common.py import numpy as np import matplotlib.pyplot as plt from common import * # READ PRESSURES AND FLOWS FROM FILE qVals = np.loadtxt('Qgeneral') pVals = np.loadtxt('Pgeneral') print('Total Number of interfaces: %d' % (qV...
<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, the model selected for this tutorial has 20 outlets. Step2: PART II Step3: We would like to use legendre polynomials for regre...
12,265
<ASSISTANT_TASK:> Python Code: # DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'mohc', 'sandbox-3', 'atmos') # 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: 1...
12,266
<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...
12,267
<ASSISTANT_TASK:> Python Code: from IPython.display import YouTubeVideo YouTubeVideo(id="JjpbztqP9_0", width="100%") from nams import load_data as cf G = cf.load_sociopatterns_network() from nams.solutions.paths import bfs_algorithm # UNCOMMENT NEXT LINE TO GET THE ANSWER. # bfs_algorithm() # FILL IN THE BLANKS BELOW...
<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: Graph traversal is akin to walking along the graph, node by node, Step4: Exercise Step5: Visualizing Paths Step6: As you can see, it returns ...
12,268
<ASSISTANT_TASK:> Python Code: import facebook # for connecting to Facebook Graph API import pprint import datetime import pandas as pd import logging logger = logging.Logger('catch_all') # send request to Facebook Graph API, fetching last 50 posts of each page : def collector(page, token, lim) : graph = facebook.G...
<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 up variables Step2: First, run this code to create new csv files of all pages Step3: A csv file example Step4: Then, run this code hour...
12,269
<ASSISTANT_TASK:> Python Code: import my_util as my_util; from my_util import * HOME_DIR = 'd:/larc_projects/job_analytics/' DATA_DIR = HOME_DIR + 'data/clean/' title_df = pd.read_csv(DATA_DIR + 'new_titles_2posts_up.csv') def distTitle(agg_df, for_domain=False, for_func=False): fig = plt.figure() plt.hist(agg...
<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: Helpers Step2: Distribution of job posts among job titles Step3: Job posts distribution among standard job titles Step4: Statistics for Domai...
12,270
<ASSISTANT_TASK:> Python Code: # You will need these things! import numpy as np import pandas as pd # the structure of a function is like this: def dir2cart(dec,inc,R): # first line starts with 'def', has the name and the input parameters (data) # all subsequent lines are indented # continue this function ...
<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 write a little function to do the conversion. Step2: Now let's read in a data file with some geomagnetic field vectors in it. Step3: Pro...
12,271
<ASSISTANT_TASK:> Python Code: import numpy as np import sympy as sp from devito import Grid, TimeFunction # Create our grid (computational domain) Lx = 10 Ly = Lx Nx = 11 Ny = Nx dx = Lx/(Nx-1) dy = dx grid = Grid(shape=(Nx,Ny), extent=(Lx,Ly)) # Define u(x,y,t) on this grid u = TimeFunction(name='u', grid=grid, time_...
<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, lets look at the output of $\partial u/\partial x$ Step2: By default the 'standard' Taylor series expansion result, where h_x represents t...
12,272
<ASSISTANT_TASK:> Python Code: import os # Google Cloud Notebook if os.path.exists("/opt/deeplearning/metadata/env_version"): USER_FLAG = "--user" else: USER_FLAG = "" ! pip3 install --upgrade google-cloud-aiplatform $USER_FLAG ! pip3 install -U google-cloud-storage $USER_FLAG if os.getenv("IS_TESTING"): !...
<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 the latest GA version of google-cloud-storage library as well. Step2: Restart the kernel Step3: Before you begin Step4: Region Step5:...
12,273
<ASSISTANT_TASK:> Python Code: exec(open('tbc.py').read()) # define TBC and TBC_above import astropy.io.fits as pyfits import numpy as np import matplotlib.pyplot as plt %matplotlib inline from io import StringIO # StringIO behaves like a file object import scipy.stats as st from pygtc import plotGTC import incredibl...
<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: Once again, we will read in the X-ray image data, and extract a small image around an AGN that we wish to study. Step2: Fitting for 2 parameter...
12,274
<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) def load_pumps_data(values_path, labels_path): # YOUR CODE HERE pass values = os.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: Use debugging tools throughout! Step4: Exercise 2 Step6: Exercise 3
12,275
<ASSISTANT_TASK:> Python Code: import ipywidgets as widgets out = widgets.Output(layout={'border': '1px solid black'}) out with out: for i in range(10): print(i, 'Hello world!') from IPython.display import YouTubeVideo with out: display(YouTubeVideo('eWzY2nGfkXk')) with out: display(widgets.IntS...
<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 Output widget can capture and display stdout, stderr and rich output generated by IPython. You can also append output directly to an output ...
12,276
<ASSISTANT_TASK:> Python Code: class Node : def __init__(self , key ) : self . key = key self . left = None self . right = None   def printSingles(root ) : if root is None : return  if root . left is not None and root . right is not None : printSingles(root . left ) printSingles(root . right...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description:
12,277
<ASSISTANT_TASK:> Python Code: import cvxpy as cp import matplotlib.pyplot as plt import numpy as np import tensorflow as tf from cvxpylayers.tensorflow.cvxpylayer import CvxpyLayer from sklearn.datasets import make_blobs from sklearn.model_selection import train_test_split tf.random.set_seed(0) np.random.seed(0) 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: We are given training data $(x_i, y_i){i=1}^{N}$, Step2: Assume that our training data is subject to a data poisoning attack, Step3: Below, we...
12,278
<ASSISTANT_TASK:> Python Code: from nussl import datasets, separation, evaluation import os import multiprocessing from concurrent.futures import ThreadPoolExecutor import logging import json import tqdm import glob import numpy as np import termtables # set up logging logger = logging.getLogger() logger.setLevel(loggi...
<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 Step2: Evaluation
12,279
<ASSISTANT_TASK:> Python Code: %matplotlib inline import numpy as np import pandas as pd import xarray as xr import cartopy.crs as ccrs from matplotlib import pyplot as plt print("numpy version : ", np.__version__) print("pandas version : ", pd.__version__) print("xarray version : ", xr.version.version) ! curl -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: As an example, consider this dataset from the xarray-data repository. Step2: In this example, the logical coordinates are x and y, while the ph...
12,280
<ASSISTANT_TASK:> Python Code: # To enable Tensorflow 2 instead of TensorFlow 1.15, uncomment the next 4 lines #try: # %tensorflow_version 2.x #except Exception: # pass # library to store and manipulate neural-network input and output data import numpy as np # library to graphically display any data import matplotl...
<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: Build the artificial neural-network Step3: Train the artificial neural-network model Step4: Evaluate the model Step5: Pr...
12,281
<ASSISTANT_TASK:> Python Code: # the output of plotting commands is displayed inline within frontends, # directly below the code cell that produced it %matplotlib inline from __future__ import print_function # this python library provides generic shallow (copy) and deep copy (deepcopy) operations from copy import dee...
<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 project directory Step2: Genesis Field file dfl Step3: Statistical properties postprocessing
12,282
<ASSISTANT_TASK:> Python Code: %matplotlib inline import matplotlib import numpy as np import matplotlib.pyplot as plt import math x = np.linspace(.25,1,num=201) obj = [] for i in range(len(x)): obj.append(math.sqrt(1/x[i]**2-1)) plt.plot(x,obj) import cvxpy as cp x = cp.Variable(pos=True) obj = cp.sqrt(cp.inv_pos(...
<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: Minimizing this objective function subject to constraints representing payload requirements is a standard aerospace design problem. In this case...
12,283
<ASSISTANT_TASK:> Python Code: %matplotlib inline import numpy as np import matplotlib.pyplot as plt from matplotlib import animation, rc from IPython.display import HTML # first set up the figure, the axes and the plot element we want to animate fig, ax = plt.subplots() ax.set_xlim( 0, 2) ax.set_ylim(-1, 2) line, = ax...
<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: To show the animation, anim uses its conversion of the video to html5 using its method to_html5_video(), and the result is shown through the HTM...
12,284
<ASSISTANT_TASK:> Python Code: import numpy as np def isccsym2(F): if len(F.shape) == 1: F = F[np.newaxis,np.newaxis,:] if len(F.shape) == 2: F = F[np.newaxis,:,:] n,m,p = F.shape x,y,z = np.indices((n,m,p)) Xnovo = np.mod(-1*x,n) Ynovo = np.mod(-1*y,m) Znovo = np.mod(-1*z,p) aux = ...
<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: Numeric Example Step3: Numeric Example Step4: Numeric Example Step5: Numeric Example Step6: Image Example Step7: Image Exa...
12,285
<ASSISTANT_TASK:> Python Code: import numpy as np import pyiast import pandas as pd import matplotlib.pyplot as plt plt.style.use('fivethirtyeight') %config InlineBackend.rc = {'font.size': 13, 'lines.linewidth':3,\ 'axes.facecolor':'w', 'legend.numpoints':1,\ 'fig...
<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 synthetic pure-component isotherm data, fit Langmuir models to them. Step2: Generate data according to Langmuir model, store in list o...
12,286
<ASSISTANT_TASK:> Python Code: # Case Study : Predicting Housing Price import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns %matplotlib inline # Importing Boston housing data from sklearn.datasets import load_boston boston = load_boston() boston.keys() boston.feature_names X = bo...
<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: Validating the assumptions made in regression Step2: How can you improve the accuracy of a regression model ? Step3: Evaluation Metrics
12,287
<ASSISTANT_TASK:> Python Code: import graphlab people = graphlab.SFrame('people_wiki.gl/') people.head() len(people) obama = people[people['name'] == 'Barack Obama'] obama obama['text'] obama['word_count'] = graphlab.text_analytics.count_words(obama['text']) print obama['word_count'] obama_word_count_table = obama...
<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: Cargar el dataset Step2: Los datos contienen articulos de wikipedia sobre diferentes personas. Step3: Buscaremos al expresidente Barack Obama ...
12,288
<ASSISTANT_TASK:> Python Code: DON'T MODIFY ANYTHING IN THIS CELL import helper data_dir = './data/simpsons/moes_tavern_lines.txt' text = helper.load_data(data_dir) # Ignore notice, since we don't use it for analysing the data text = text[81:] view_sentence_range = (8, 100) DON'T MODIFY ANYTHING IN THIS CELL import 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: TV Script Generation Step3: Explore the Data Step6: Implement Preprocessing Functions Step9: Tokenize Punctuation Step11: Preprocess all the...
12,289
<ASSISTANT_TASK:> Python Code: from goatools.base import get_godag godag = get_godag("go-basic.obo", optional_attrs={'relationship'}) go_leafs = set(o.item_id for o in godag.values() if not o.children) virion = 'GO:0019012' from goatools.gosubdag.gosubdag import GoSubDag gosubdag_r0 = GoSubDag(go_leafs, godag) nt_vir...
<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) Depth-01 term, GO Step2: Notice that dcnt=0 for GO Step3: 3) Depth-01 term, GO Step4: 4) Depth-01 term, GO Step5: 5) Descendants under GO...
12,290
<ASSISTANT_TASK:> Python Code: %pylab inline import calin.simulation.detector_efficiency import calin.simulation.atmosphere import calin.provenance.system_info data_dir = calin.provenance.system_info.build_info().data_install_dir() + "/simulation/" print("Simulation data directory:",data_dir) det_eff = calin.simulati...
<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 - Get location of calin simulation data files Step2: 2 - Construct detector efficiency Step3: 3 - Load lightcone efficiency Step4: 4 - Resc...
12,291
<ASSISTANT_TASK:> Python Code: import random import time import matplotlib.pyplot as plt import numpy as np import pandas as pd from fct import normalize_min_max, plot_2d, plot_clusters def build_d(datas, centers): Return a 2D-numpy array of the distances between each point in the dataset and the centers. The ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step6: Algorithm Step7: Application
12,292
<ASSISTANT_TASK:> Python Code: import pandas as pd import numpy as np l = [('A', '1', 'a'), ('A', '1', 'b'), ('A', '2', 'a'), ('A', '2', 'b'), ('B', '1','a'), ('B', '1','b')] np.random.seed(1) df = pd.DataFrame(np.random.randn(5, 6), columns=l) def g(df): df.columns = pd.MultiIndex.from_tuples(df.columns, names=[...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description:
12,293
<ASSISTANT_TASK:> Python Code: class BinaryTree(): def __init__(self, children = None): A binary tree is either a leaf or a node with two subtrees. INPUT: - children, either None (for a leaf), or a list of size excatly 2 of either two bina...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step7: Arbres binaires Step8: Il y a 5 arbres binaires de taille 3. L'un deux est celui que nous venons de construire. Step19: Le but de ce TP est d...
12,294
<ASSISTANT_TASK:> Python Code: import copy try: import ujson as json except ImportError: import json import math import operator import random from mpl_toolkits.mplot3d import Axes3D import numpy as np from numpy.linalg import norm as np_norm import matplotlib.pyplot as plt import pandas as pd from scipy.sp...
<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: Simple, visualizable spaces Step2: We have a 2-dimensional feature space containing 1000 pieces of data. Each coordinate is orthogonal, and we ...
12,295
<ASSISTANT_TASK:> Python Code: from owslib.csw import CatalogueServiceWeb from owslib import fes import numpy as np #endpoint = 'https://dev-catalog.ioos.us/csw' #endpoint = 'http://gamone.whoi.edu/csw' endpoint = 'https://data.ioos.us/csw' #endpoint = 'https://ngdc.noaa.gov/geoportal/csw' csw = CatalogueServiceWeb(en...
<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: Search first for records containing the two text strings Step3: Now let's print out the references (service endpoints) to see what types of ser...
12,296
<ASSISTANT_TASK:> Python Code: %matplotlib inline import pandas as pd import matplotlib.pyplot as plt import seaborn as sns import numpy as np plt.rcParams['figure.figsize'] = (20.0, 10.0) plt.rcParams['font.family'] = "serif" df = pd.read_csv('../../../datasets/movie_metadata.csv') df.head() # split each movie's genr...
<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: For the bar plot, let's look at the number of movies in each category, allowing each movie to be counted more than once. Step2: Basic plot Step...
12,297
<ASSISTANT_TASK:> Python Code: def generator1(): yield 1 yield 2 yield 3 for value in generator1(): print(value) def generator2(): yield "Hello" yield "World" my_gen = generator2() print(next(my_gen)) print(next(my_gen)) def check_for_value(num): try: while True: rec...
<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: Coroutines Step2: Coroutine Pipelines Step3: Asynchronous Python Step4: Async and Await (python 3.5+)
12,298
<ASSISTANT_TASK:> Python Code: %%capture !wget https://github.com/cltl/python-for-text-analysis/raw/master/zips/Data.zip !wget https://github.com/cltl/python-for-text-analysis/raw/master/zips/images.zip !wget https://github.com/cltl/python-for-text-analysis/raw/master/zips/Extra_Material.zip !unzip Data.zip -d ../ !unz...
<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: Chapter 6 - Lists Step2: Square brackets surround lists, and commas separate the elements in the list Step3: Please note that there are two wa...
12,299
<ASSISTANT_TASK:> Python Code: df['Age'].describe() df.groupby('Gender')['Income'].describe() df['Income'].describe() df['SchoolMajor'].value_counts() df['SchoolDegree'].value_counts() df.sort_values(by='StudentDebtOwe', ascending=False).head() df[(df['BootcampFullJobAfter']==1) & (df['BootcampLoanYesNo']==1)].he...
<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. What are the maximum income for female programmers? Step2: 3. how much does a programmer make on average per year? Step3: 4. what is the mo...