text_prompt
stringlengths
168
30.3k
code_prompt
stringlengths
67
124k
<SYSTEM_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-D series Step2: DataFrame Step3: Data types Step4: converting types Step5: Filtering with Pandas Step6: Creating a new index not on the v...
<ASSISTANT_TASK:> Python Code: import pandas as pd s = pd.Series([3, 5, 67, 2, 4]) s s.name = "OneDArray" s s.index s.values s.sum() s.min() s.count() s * 3 s.sort_values() s.value_counts() s.abs? eu = pd.read_csv('data/eu_revolving_loans.csv', header=[1,2,3], index_col=0, skiprows=1) eu.tail(4) eu.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: Integrating MinDiff with MinDiffModel Step2: First, download the data. For succinctness, the input preparation logic has been factored out into...
<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: We will output to a static html file. Step2: See many examples of configuring plot tools at http Step3: Here we'll interact with Glue from th...
<ASSISTANT_TASK:> Python Code: import bokeh import numpy as np from astropy.table import Table sdss = Table.read('data/sdss_galaxies_qsos_50k.fits') sdss from bokeh.models import ColumnDataSource from bokeh.plotting import figure, gridplot, output_notebook, output_file, show umg = sdss['u'] - sdss['g'] gmr = sdss['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: Load data Step2: Create the figure
<ASSISTANT_TASK:> Python Code: import shapefile import numpy as np from matplotlib import cm, rcParams import matplotlib.pyplot as plt from mpl_toolkits.basemap import Basemap rcParams.update({'font.size': 16}) # Increase font-size # Load the topo file to get header information etopo1name = 'data/basemap/etopo1_bedroc...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Online Prediction with scikit-learn on AI Platform Step2: Download the data Step3: Part 1 Step4: Part 2 Step5: Note Step6: Part 3 Step7: P...
<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, sof...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description:
<ASSISTANT_TASK:> Python Code: import numpy as np value = 1.0 result = np.degrees(np.arcsin(value)) <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: The following example loads a cube from iris-sample-data and displays it as follows Step2: With HoloViews, you can quickly view the data in the...
<ASSISTANT_TASK:> Python Code: import holoviews as hv import holocube as hc from cartopy import crs from cartopy import feature as cf hv.notebook_extension() %%opts GeoFeature [projection=crs.Geostationary()] coasts = hc.GeoFeature(cf.COASTLINE) borders = hc.GeoFeature(cf.BORDERS) ocean = hc.GeoFeature(cf.OCEAN) oce...
<SYSTEM_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...
<ASSISTANT_TASK:> Python Code: # DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'ec-earth-consortium', 'sandbox-3', 'ocean') # Set as follows: DOC.set_author("name", "email") # TODO - please enter value(s) # Set as follows: DOC.set_contributo...
<SYSTEM_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 Step2: You can also supply more extensive metadata Step3: <div class="alert alert-info"><h4>Note</h4><p>When assigning new values to...
<ASSISTANT_TASK:> Python Code: import mne import numpy as np # Create some dummy metadata n_channels = 32 sampling_rate = 200 info = mne.create_info(n_channels, sampling_rate) print(info) # Names for each channel channel_names = ['MEG1', 'MEG2', 'Cz', 'Pz', 'EOG'] # The type (mag, grad, eeg, eog, misc, ...) of each c...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Datos LHC Step2: Utilidades Step3: Columnas Step4: Y si quiero imprimir columnas, una por una? Step5: Recuerda Step6: Dividir datos Step7: ...
<ASSISTANT_TASK:> Python Code: import pandas as pd import numpy as np # modulo de computo numerico import matplotlib.pyplot as plt # modulo de graficas # esta linea hace que las graficas salgan en el notebook import seaborn as sns %matplotlib inline df = pd.read_csv('files/mini-LHC.csv') df.head() print(df.shape) pri...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Creating an ICsound object automatically starts the engine Step2: You can set the properties of the Csound engine with parameters to the startE...
<ASSISTANT_TASK:> Python Code: import numpy as np import matplotlib.pyplot as plt %load_ext csoundmagics cs = ICsound(port=12894) help(cs.startEngine) cs.startEngine() %%csound 1 gkinstr init 1 %%csound print i(gkinstr) cs.printLog() cs.fillTable(1, np.array([8, 7, 9, 1, 1, 1])) cs.fillTable(2, [4, 5, 7, 0, 8, 7,...
<SYSTEM_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 1 Step2: Generate a set of $50$ one-dimensional inputs regularly spaced between -5 and 5 and store them in a variable called x, then co...
<ASSISTANT_TASK:> Python Code: %matplotlib inline import numpy as np import matplotlib.pyplot as plt from scipy.spatial.distance import cdist from numpy.random import multivariate_normal from numpy.linalg import inv from numpy.linalg import slogdet from scipy.optimize import fmin def SEKernel(par, x1, x2): A, Gamm...
<SYSTEM_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...
<ASSISTANT_TASK:> Python Code: # DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'bnu', 'sandbox-1', 'landice') # 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: Set parameters
<ASSISTANT_TASK:> Python Code: # Author: Martin Luessi <mluessi@nmr.mgh.harvard.edu> # # License: BSD (3-clause) import mne from mne import io from mne.connectivity import spectral_connectivity from mne.datasets import sample from mne.viz import plot_sensors_connectivity print(__doc__) data_path = sample.data_path() r...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Constants Step2: You probably noticed that DROPOUT_RATE has been set 0.0. Dropout has been used Step3: Implementing the DeiT variants of ViT S...
<ASSISTANT_TASK:> Python Code: from typing import List import tensorflow as tf import tensorflow_addons as tfa import tensorflow_datasets as tfds import tensorflow_hub as hub from tensorflow import keras from tensorflow.keras import layers tfds.disable_progress_bar() tf.keras.utils.set_random_seed(42) # Model MODEL_TY...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step5: plotting a neuron Step6: Testing function Step7: Testing function Step8: Testing seq2seq Step9: We may have to write our own dense --> seq w...
<ASSISTANT_TASK:> Python Code: import numpy as np import McNeuron from keras.models import Sequential from keras.layers.core import Dense, Reshape from keras.layers.recurrent import LSTM import matplotlib.pyplot as plt from copy import deepcopy import os %matplotlib inline neuron_list = McNeuron.visualize.get_all_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: Model parameters (parameters of the Generalized Maxwell model) Step2: Cantilever and general simulation paramters Step3: Main portion of the s...
<ASSISTANT_TASK:> Python Code: import sys sys.path.append('d:\github\pycroscopy') from pycroscopy.simulation.afm_lib import sfs_genmaxwell_lr, compliance_maxwell from pycroscopy.simulation.nls_fit import nls_fit, linear_fit_nob from pycroscopy.simulation.rheology import chi_th, j_t, theta_v, theta_g from pycroscopy.sim...
<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: Alternative model Step3: Study corpus Step4: Not really zipfian so far. Maybe read that if we really care about that.
<ASSISTANT_TASK:> Python Code: import numpy as np from dictlearn.generate_synthetic_data import FakeTextGenerator V = 100 embedding_size = 50 markov_order = 6 temperature=1.0 sentence_size = 20 model = FakeTextGenerator(V, embedding_size, markov_order, temperature) n_sentences=1000 sentences = model.create_corpus(n_sen...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: From a sample of the RMS Titanic data, we can see the various features present for each passenger on the ship Step3: The very same sample of th...
<ASSISTANT_TASK:> Python Code: import numpy as np import pandas as pd # RMS Titanic data visualization code from titanic_visualizations import survival_stats from IPython.display import display %matplotlib inline # Load the dataset in_file = 'titanic_data.csv' full_data = pd.read_csv(in_file) # Print the first few ent...
<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: Even though the top code cell contains no instructions to draw, Vpython's way of integrating into Jupyter Notebook seems to be by adding a scene...
<ASSISTANT_TASK:> Python Code: from vpython import * class Vector: def __init__(self, x, y, z): self.v = vector(x, y, z) def __add__(self, other): v_sum = self.v + other.v return Vector(*v_sum.value) def __neg__(self): return Vector(*((-self.v).value)) ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Next, let's define our potential by a $1\,\rm M_\odot$ point mass, and put our tracer particle initially at $1\,\rm AU$. Step2: Let's also plac...
<ASSISTANT_TASK:> Python Code: from __future__ import print_function, division import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt import astropy.units as u from astropy.constants import G import streakline %matplotlib inline mpl.rcParams['figure.figsize'] = (8,8) mpl.rcParams['font.size'] = 18 ...
<SYSTEM_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 allows inline graphics in IPython (Jupyter) notebooks and imports functions nessesary for ploting as plt. In addition we import numpy as np...
<ASSISTANT_TASK:> Python Code: %matplotlib inline import matplotlib.pylab as plt import numpy as np x = np.linspace(0,10,20) y = x ** 2 plt.plot(x,y); plt.plot(x, y, 'r--o') plt.xlabel('x') plt.ylabel('y') plt.title('title'); plt.plot(x, y, 'r--o', x, y ** 1.1, 'bs', x, y ** 1.2, 'g^-' ); mu, sigma = 100, 15 x = 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: Para inserir website, o display do IPython tem suporte para mostrar um IFrame, onde é possível colocar o endereço de um website
<ASSISTANT_TASK:> Python Code: from IPython.display import YouTubeVideo # a talk about IPython at Sage Days at U. Washington, Seattle. # Video credit: William Stein. YouTubeVideo('1j_HxD4iLn8') from IPython.display import IFrame IFrame('http://adessowiki.fee.unicamp.br/rnpi', width=700, height=350) <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: <a id='pyenv'></a> Step2: Creating a VE Step3: Notice that the * is missing. Step4: Automatically activating and deactivating VEs
<ASSISTANT_TASK:> Python Code: %%bash echo -n "System Python version: " python --version %%bash which python %%bash echo -n "Trying to import pip-install-test ... " python -c " try: import pip_install_test except ModuleNotFoundError: print('pip-install-test is not installed') else: print('pip-install-test i...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Análise manual Step2: O deputado que mais usou a cota parlamentar totalizou R\$ 516.027,24 em 2015, uma média de um pouco mais que R$ 43.000,00...
<ASSISTANT_TASK:> Python Code: import pandas as pd ceap = pd.read_csv('dados/ceap2015.csv.zip') linhas, colunas = ceap.shape print('Temos {} entradas com {} colunas cada.'.format(linhas, colunas)) print('Primeira entrada:') ceap.iloc[0] colunas = ['txNomeParlamentar', 'sgPartido', 'sgUF', 'vlrLiquido'] grupo = ['txNom...
<SYSTEM_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...
<ASSISTANT_TASK:> Python Code: # DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'ipsl', '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: Load Annotated Data Step2: Params Step3: Prep Data Step4: Sklearn Experiments Step5: No tfidf Step6: With tfidf Step7: TFIDF improves the ...
<ASSISTANT_TASK:> Python Code: def get_best_estimator(cv): params = cv.best_params_ model = cv.estimator model = model.set_params(**params) return model def save_best_estimator(cv, directory, name): model = get_best_estimator(cv) save_pipeline(model, directory, name) task = 'attack' data =...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Lower Dropout Step2: It's definitely overfitting. Step3: It takes longer to reach a slightly lower validation score, but does not overfit.
<ASSISTANT_TASK:> Python Code: import pylearn2.utils import pylearn2.config import theano import neukrill_net.dense_dataset import neukrill_net.utils import numpy as np %matplotlib inline import matplotlib.pyplot as plt import holoviews as hl %load_ext holoviews.ipython import sklearn.metrics m = pylearn2.utils.serial...
<SYSTEM_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 code sets up everything we need Step2: Put your code below this!
<ASSISTANT_TASK:> Python Code: import numpy as np %matplotlib inline import matplotlib.pyplot as plt from IPython.display import display, clear_output def calc_total_distance(table_of_distances, city_order): ''' Calculates distances between a sequence of cities. Inputs: N x N table containing distances...
<SYSTEM_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 would now like to classify the test data with the kNN classifier. Recall that we can break down this process into two steps Step2: Inline Qu...
<ASSISTANT_TASK:> Python Code: # Run some setup code for this notebook. import random import numpy as np from cs231n.data_utils import load_CIFAR10 import matplotlib.pyplot as plt # This is a bit of magic to make matplotlib figures appear inline in the notebook # rather than in a new window. %matplotlib inline plt.rcPa...
<SYSTEM_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: Now, let's start with the ANTs normalization workflow! Step3: Experiment parameters (ANTs) Step4: Note if you're not using the co...
<ASSISTANT_TASK:> Python Code: %%bash datalad get -J 4 -d /data/ds000114 /data/ds000114/derivatives/fmriprep/sub-0[2345789]/anat/*h5 !ls /data/ds000114/derivatives/fmriprep/sub-*/anat/*h5 from os.path import join as opj from nipype import Workflow, Node, MapNode from nipype.interfaces.ants import ApplyTransforms 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: <h2> Input </h2> Step2: <h2> Create features out of input data </h2> Step3: <h2> train_and_evaluate </h2>
<ASSISTANT_TASK:> Python Code: # Ensure the right version of Tensorflow is installed. !pip freeze | grep tensorflow==2.6 import tensorflow as tf import numpy as np import shutil print(tf.__version__) CSV_COLUMNS = ['fare_amount', 'pickuplon','pickuplat','dropofflon','dropofflat','passengers', 'key'] LABEL_COLUMN = 'fa...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Fix the Contents sheet to correctly reflect the Worksheet names Step2: Tidy up Data Step3: One down, 31 to go... Step4: Those '\n (Quarter 4 ...
<ASSISTANT_TASK:> Python Code: from bs4 import BeautifulSoup import pandas as pd import requests # Pull the latest pages of https://www.finance-ni.gov.uk/publications/ni-house-price-index-statistical-reports and extract links base_url= 'https://www.finance-ni.gov.uk/publications/ni-house-price-index-statistical-reports...
<SYSTEM_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 test is condected at a fully confined two-aquifer system. Both the pumping well and the observation piezometer are screened at the second aq...
<ASSISTANT_TASK:> Python Code: %matplotlib inline import numpy as np import matplotlib.pyplot as plt import pandas as pd from ttim import * Q = 82.08 #constant discharge in m^3/d zt0 = -46 #top boundary of upper aquifer in m zb0 = -49 #bottom boundary of upper aquifer in m zt1 = -52 #top boundary of lower aquifer in 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: Set Caffe to CPU mode, load the net in the test phase for inference, and configure input preprocessing. Step2: Let's start with a simple classi...
<ASSISTANT_TASK:> Python Code: import numpy as np import matplotlib.pyplot as plt %matplotlib inline # Make sure that caffe is on the python path: caffe_root = '/home/ubuntu/digits/caffe/' # this file is expected to be in {caffe_root}/examples import sys sys.path.insert(0, caffe_root + 'python') import caffe plt.rcPar...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Preparing the data Step2: Counting word frequency Step3: Let's keep the first 10000 most frequent words. As Andrew noted, most of the words in...
<ASSISTANT_TASK:> Python Code: import pandas as pd import numpy as np import tensorflow as tf import tflearn from tflearn.data_utils import to_categorical reviews = pd.read_csv('reviews.txt', header=None) labels = pd.read_csv('labels.txt', header=None) from collections import Counter total_counts = Counter() for i, r...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Compile and build. Step2: We can wire up the GPIO pins to a logic analyzer to verify that our circuit produces the correct sine waveform. Step3...
<ASSISTANT_TASK:> Python Code: import math import numpy as np def sine(x): return np.sin(2 * math.pi * x) x = np.linspace(0., 1., num=256, endpoint=False) import magma as m m.set_mantle_target('ice40') import mantle def DefineDDS(n, has_ce=False): class _DDS(m.Circuit): name = f'DDS{n}' IO = ['I...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: 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...
<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:
<ASSISTANT_TASK:> Python Code: import pandas as pd df = pd.DataFrame({'Sp': ['MM1', 'MM1', 'MM1', 'MM2', 'MM2', 'MM2', 'MM4', 'MM4', 'MM4'], 'Mt': ['S1', 'S1', 'S3', 'S3', 'S4', 'S4', 'S2', 'S2', 'S2'], 'Value': ['a', 'n', 'cb', 'mk', 'bg', 'dgd', 'rd', 'cb', 'uyi'], ...
<SYSTEM_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 Captured Streaming Data in Python Step3: Load Data in SparkSQL
<ASSISTANT_TASK:> Python Code: sc sqlContext import time import simplejson as json filename = '/home/anaconda/md0/data/2016_potus/stream/tweets.json' langs = {} start_time = time.time() f_p = open(filename,'r') for line in f_p: tweet = json.loads(line) if 'lang' in tweet: if tweet['lang'] in langs: ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: 6.2 Updating dictionaries Step2: An implication of this is that we can start with an empty dictionary and add keys as we go along. Step3: 6.2...
<ASSISTANT_TASK:> Python Code: # creating a dictionary and assigning it to a variable staff = {'name': 'Andy', 'age': 28, 'email': 'andy@company.com' } staff['name'] staff['age'] print(staff['email']) # A dictionary is of class dict print(type(staff)) # list of all keys, note the brackets at the end. # .keys is a me...
<SYSTEM_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 the structure Step2: Result from VASP DFPT calculations using the supercell structure Step3: Initialize phonopy and set the force constant...
<ASSISTANT_TASK:> Python Code: import os import numpy as np import pymatgen as pmg from pymatgen.io.vasp.outputs import Vasprun from phonopy import Phonopy from phonopy.structure.atoms import Atoms as PhonopyAtoms %matplotlib inline Si_primitive = PhonopyAtoms(symbols=['Si'] * 2, scaled_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: Second, let's create the motion correction and smoothing node. For an explanation about this step, see the Nodes and Interfaces tutorial. Step2:...
<ASSISTANT_TASK:> Python Code: from nipype import SelectFiles, Node # Create SelectFiles node templates={'func': '{subject_id}/func/{subject_id}_task-flanker_run-1_bold.nii.gz'} sf = Node(SelectFiles(templates), name='selectfiles') sf.inputs.base_directory = '/data/ds102' sf.inputs.subject_id = 'sub-01' 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: In this example, we will download some text from wikipedia, split it up into chunks and then plot it. We will use the wikipedia package to retri...
<ASSISTANT_TASK:> Python Code: import hypertools as hyp import wikipedia as wiki %matplotlib inline def chunk(s, count): return [''.join(x) for x in zip(*[list(s[z::count]) for z in range(count)])] chunk_size = 5 dog_text = wiki.page('Dog').content cat_text = wiki.page('Cat').content dog = chunk(dog_text, int(len(...
<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: Task Step3: A toy example Step4: See some of the co-occrrence statistics Step5: this says us that idea was seen with time 258 times in the co...
<ASSISTANT_TASK:> Python Code: # This is a code cell. It can be executed by pressing CTRL+Enter print('Hello') %matplotlib inline import warnings warnings.filterwarnings('ignore') import pandas pandas.options.display.max_columns = 11 pandas.options.display.max_rows = 5 import matplotlib matplotlib.rcParams['font.size'...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Given an ordered binary tree $t$, the expression $t.\texttt{isEmpty}()$ checks whether $t$ is the empty tree. Step2: Given an ordered binary tr...
<ASSISTANT_TASK:> Python Code: class Set: def __init__(self): self.mKey = None self.mLeft = None self.mRight = None self.mHeight = 0 def isEmpty(self): return self.mKey == None Set.isEmpty = isEmpty def member(self, key): if self.isEmpty(): return elif sel...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Indefinite integrals Step2: Integral 1 Step3: Integral 2 Step4: Integral 3 Step5: Integral 4 Step6: Integral 5
<ASSISTANT_TASK:> Python Code: %matplotlib inline import matplotlib.pyplot as plt import numpy as np import seaborn as sns from scipy import integrate def integrand(x, a): return 1.0/(x**2 + a**2) def integral_approx(a): # Use the args keyword argument to feed extra arguments to your integrand I, e = integ...
<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: Euler's method Step4: The midpoint method is another numerical method for solving the above differential equation. In general it is more accura...
<ASSISTANT_TASK:> Python Code: %matplotlib inline import matplotlib.pyplot as plt import numpy as np from scipy.integrate import odeint from IPython.html.widgets import interact, fixed def solve_euler(derivs, y0, x): Solve a 1d ODE using Euler's method. Parameters ---------- derivs : 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: Survey Step2: Trivariate
<ASSISTANT_TASK:> Python Code: import dit from dit.pid.helpers import compare_measures from dit.pid.distributions import bivariates, trivariates dit.ditParams['print.exact'] = dit.ditParams['repr.print'] = True dit.ditParams['text.font'] = 'linechar' for name, dist in bivariates.items(): compare_measures(dist, nam...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: 1.3 Lecture des données métier Step2: 2 Exploration par Analyse en composantes principales Step3: La fonction définie ci-après affiche un nuag...
<ASSISTANT_TASK:> Python Code: # Importation des principals librairies et # Affichage des graphiques dans le notebook %matplotlib inline import numpy as np import pandas as pd import matplotlib.pyplot as plt import time # Lecture des données d'apprentissage # Attention, il peut y avoir plusieurs espaces comme sépara...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Language Translation Step3: Explore the Data Step6: Implement Preprocessing Function Step8: Preprocess all the data and save it Step10: Chec...
<ASSISTANT_TASK:> Python Code: DON'T MODIFY ANYTHING IN THIS CELL import helper import problem_unittests as tests source_path = 'data/small_vocab_en' target_path = 'data/small_vocab_fr' source_text = helper.load_data(source_path) target_text = helper.load_data(target_path) view_sentence_range = (0, 10) DON'T MODIFY AN...
<SYSTEM_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 1 Step2: Generate a set of $50$ one-dimensional inputs regularly spaced between -5 and 5 and store them in a variable called x, then co...
<ASSISTANT_TASK:> Python Code: %matplotlib inline import numpy as np import matplotlib.pyplot as plt from scipy.spatial.distance import cdist from numpy.random import multivariate_normal from numpy.linalg import inv from numpy.linalg import slogdet from scipy.optimize import fmin def SEKernel(par, x1, x2): A, Gamm...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description:
<ASSISTANT_TASK:> Python Code: def get_row(lst, x): coords = [(i, j) for i in range(len(lst)) for j in range(len(lst[i])) if lst[i][j] == x] return sorted(sorted(coords, key=lambda x: x[1], reverse=True), key=lambda x: x[0]) <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: Loss under a Mixture of Gaussians model Step2: We use autograd for functions that deliver gradients of those losses Step3: Just a pretty displ...
<ASSISTANT_TASK:> Python Code: def sigmoid(phi): return 1.0/(1.0 + np.exp(-phi)) def calc_prob_class1(params): # Sigmoid perceptron ('logistic regression') tildex = X - params['mean'] W = params['wgts'] phi = np.dot(tildex, W) return sigmoid(phi) # Sigmoid perceptron ('logistic regression') def...
<SYSTEM_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's the Fast Inverse Root Method you ask? Step2: Close Enough! Step3: Here, $$\begin{align} Step4: A Tale of two Variables Step5: Recall ...
<ASSISTANT_TASK:> Python Code: setup_html = r''' <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/github-fork-ribbon-css/0.2.0/gh-fork-ribbon.min.css" /> <!--[if lt IE 9]> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/github-fork-ribbon-css/0.2.0/gh-fork-ribbon.ie.min.css" /...
<SYSTEM_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 1 Step2: The first two sentences have very similar content, and as such the SCM should be large. Before we compute the SCM, we want to rem...
<ASSISTANT_TASK:> Python Code: # Initialize logging. import logging logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO) sentence_obama = 'Obama speaks to the media in Illinois'.lower().split() sentence_president = 'The president greets the press in Chicago'.lower().split() sente...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: 建立 ndarray Step2: 看 ndarray 的第一件事情: shape , dtype Step3: 有時候,可以看圖 Step4: 有很多其他建立的方式 Step5: 這是一堆資料 Step6: Q0 Step7: Q1 Step8: Indexing St...
<ASSISTANT_TASK:> Python Code: # 起手式 import numpy as np np.array([1,2,3,4]) x = _ y = np.array([[1.,2,3],[4,5,6]]) y x.shape y.shape x.dtype y.dtype # import matplotlib %matplotlib inline import matplotlib.pyplot as plt # 畫圖 plt.plot(x, 'x'); # 建立 0 array np.zeros_like(y) np.zeros((10,10)) # 跟 range 差不多 x = np.aran...
<SYSTEM_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 1 Step2: Notes
<ASSISTANT_TASK:> Python Code: from collections import defaultdict, Counter from itertools import zip_longest import json import os import re import sys import urllib import numpy as np import requests from eva_cttv_pipeline.clinvar_xml_io.clinvar_xml_io import * %matplotlib inline import matplotlib.pyplot as plt 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: Toy Network Step2: Centrality Step3: Eigenvector Centrality Step4: Betweenness Centrality Step5: Centrality Measures Are Different Step6: T...
<ASSISTANT_TASK:> Python Code: import pandas as pd import networkx as nx import numpy as np import scipy as sp import itertools import matplotlib.pyplot as plt import statsmodels.api as sm %matplotlib inline G = nx.Graph() G.add_nodes_from(['A','B','C','D','E','F','G']) G.add_edges_from([('A','B'),('A','C'), ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Simulating A/B testing to build intuition Step2: Each test is like flipping a fair coin N times Step3: Run the cell above a few times. Step4: ...
<ASSISTANT_TASK:> Python Code: from IPython.display import Image Image(filename='img/treat_aud_reward.jpg') import matplotlib import matplotlib.pyplot as plt import numpy as np import seaborn as sns import pandas as pd from numpy.random import binomial from ggplot import * import random import sys plt.figure(figsize=(...
<SYSTEM_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 the following cell, complete the code with an expression that evaluates to a list of integers derived from the raw numbers in numbers_str, as...
<ASSISTANT_TASK:> Python Code: numbers_str = '496,258,332,550,506,699,7,985,171,581,436,804,736,528,65,855,68,279,721,120' number_list = numbers_str.split(",") numbers = [int(item) for item in number_list] max(numbers) #len(numbers) sorted(numbers)[10:] from math import sqrt squared = [] for item in numbers: 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: Exercise A.1.1 Step2: Exercise A.1.2 Step3: Exercise A.1.3 Step4: Exercise A.1.4 Step5: Exercise A.1.5 Step6: Exercise A.1.6 Step7: <a id=...
<ASSISTANT_TASK:> Python Code: import random x=random.random() print ("The Value of x is", x) # Skeleton def GenerateData(N,min,max): out = [] ### BEGIN SOLUTION # Fill in your solution here ### END SOLUTION return out Data=GenerateData(1000,-10,10) print ("Data Type:", type(Data)) print ("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: Linear regression Step2: Quick exploration Step3: You can also do quick plotting of the data. The results are not aesthetically the best, but ...
<ASSISTANT_TASK:> Python Code: # Cumulative probability P(X<120) where X ~ N(100, 10^2) print("P(X<120) where X ~ N(100, 10^2) = %.3f" % stats.norm.cdf(120, loc=100, scale=10)) # Calculate value print("x for which P(X < x = 0.97) = %.1f" % stats.norm.ppf(0.97, loc=100, scale=10)) # Cumulative probability P(X<120) where...
<SYSTEM_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...
<ASSISTANT_TASK:> Python Code: # DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'bnu', 'sandbox-3', 'atmoschem') # Set as follows: DOC.set_author("name", "email") # TODO - please enter value(s) # Set as follows: DOC.set_contributor("name", "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: BERT Question Answer with TensorFlow Lite Model Maker Step2: Import the required packages. Step3: The "End-to-End Overview" demonstrates a sim...
<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: Question 1 Step2: We can then print the Sum of the costs of all those rows. (The cost column is named total_cost.) Step3: Question 2 Step4: W...
<ASSISTANT_TASK:> Python Code: import agate table = agate.Table.from_csv('examples/realdata/ks_1033_data.csv') print(table) kansas_city = table.where(lambda r: r['county'] in ('JACKSON', 'CLAY', 'CASS', 'PLATTE')) print(len(table.rows)) print(len(kansas_city.rows)) print('$%d' % kansas_city.aggregate(agate.Sum('total...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description:
<ASSISTANT_TASK:> Python Code: import numpy as np import pandas as pd import torch softmax_output = load_data() y = torch.argmax(softmax_output, dim=1).view(-1, 1) <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: Reading data from BigQuery with TFX and Vertex Pipelines Step2: Did you restart the runtime? Step3: Login in to Google for this notebook Step4...
<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: There is much, much more to know, but these few operations are fundamental to what we'll Step2: The CSR representation can be very efficient fo...
<ASSISTANT_TASK:> Python Code: import numpy as np # Generating a random array X = np.random.random((3, 5)) # a 3 x 5 array print(X) # Accessing elements # get a single element print(X[0, 0]) # get a row print(X[1]) # get a column print(X[:, 1]) # Transposing an array print(X.T) # Turning a row vector into a column vec...
<SYSTEM_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 Step2: Part 3 Step4: Assignment wrapup
<ASSISTANT_TASK:> Python Code: # put your code here! myfile = open('oshea.txt','w') myfile.write('I love pizza.\n') myfile.write('I have two children, both of whom are girls.\n') myfile.write('I also have two dogs.\n') myfile.write('Arguably, I spend far too much time on the computer.\n') myfile.close() myfilenew = ope...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Language Detection Step2: Tokenization Step3: Part of Speech Tagging Step4: Named Entity Recognition Step5: Polarity Step6: Embeddings Step...
<ASSISTANT_TASK:> Python Code: import polyglot from polyglot.text import Text, Word text = Text("Bonjour, Mesdames.") print("Language Detected: Code={}, Name={}\n".format(text.language.code, text.language.name)) zen = Text("Beautiful is better than ugly. " "Explicit is better than implicit. " "S...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step2: 2. Build map Step4: 2.2. HTML for popups Step5: 2.3. Create map
<ASSISTANT_TASK:> Python Code: df = pd.read_csv('toc_trends_long_format.csv') df.dropna(subset=['latitude', 'longitude'], inplace=True) df = df.query('(analysis_period == "1990-2016") and (non_missing > 0)') base = "http://77.104.141.195/~icpwater/wp-content/core_plots/trends_plots_1990-2016/" fname = df['station_id']....
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Simulation setup Step2: Create the coordinate systems Step3: Step 1 Step4: Step 2 Step5: Now compute the point-spread function via Step6: S...
<ASSISTANT_TASK:> Python Code: import sys %pylab inline import scipy.special from scipy.interpolate import interp1d from scipy.interpolate import RectBivariateSpline print('Python {}\n'.format(sys.version)) print('NumPy\t\t{}'.format(np.__version__)) print('matplotlib\t{}'.format(matplotlib.__version__)) print('SciPy\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: This was developed using Python 3.5.2 (Anaconda) and TensorFlow version Step2: The VGG-16 model is downloaded from the internet. This is the de...
<ASSISTANT_TASK:> Python Code: %matplotlib inline import matplotlib.pyplot as plt import tensorflow as tf import numpy as np import PIL.Image tf.__version__ import vgg16 # vgg16.data_dir = 'vgg16/' vgg16.maybe_download() def load_image(filename, max_size=None): image = PIL.Image.open(filename) if max_size is...
<SYSTEM_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...
<ASSISTANT_TASK:> Python Code: # DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'test-institute-2', 'sandbox-3', 'ocean') # Set as follows: DOC.set_author("name", "email") # TODO - please enter value(s) # Set as follows: DOC.set_contributor("...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description:
<ASSISTANT_TASK:> Python Code: import numpy as np from sklearn.preprocessing import MinMaxScaler a = np.array([[-1, 2], [-0.5, 6]]) scaler = MinMaxScaler() a_one_column = a.reshape(-1, 1) result_one_column = scaler.fit_transform(a_one_column) result = result_one_column.reshape(a.shape) <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: The speech commands Step2: The below code is generating a label ID for a command. The ID will be -1 for any command not in the to_keep list. Ot...
<ASSISTANT_TASK:> Python Code: import cmsisdsp as dsp import cmsisdsp.fixedpoint as fix import numpy as np import os.path import glob import pathlib import random import soundfile as sf import matplotlib.pyplot as plt from IPython.display import display,Audio,HTML import scipy.signal from numpy.lib.stride_tricks 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: As always, let's do imports and initialize a logger and a new Bundle. See Building a System for more details. Step2: In order for apsidal moti...
<ASSISTANT_TASK:> Python Code: !pip install -I "phoebe>=2.1,<2.2" %matplotlib inline import phoebe from phoebe import u # units import numpy as np import matplotlib.pyplot as plt logger = phoebe.logger() b = phoebe.default_binary() b['ecc'] = 0.2 b['dperdt'] = 2.0 * u.deg/u.d b.add_dataset('lc', times=np.linspace(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: Error plots for MiniZephyr vs. the AnalyticalHelmholtz response Step2: Relative error of the MiniZephyr solution (in %)
<ASSISTANT_TASK:> Python Code: import sys sys.path.append('../') import numpy as np from zephyr.backend import MiniZephyr, SparseKaiserSource, AnalyticalHelmholtz import matplotlib.pyplot as plt import matplotlib.cm as cm import matplotlib %matplotlib inline from IPython.display import set_matplotlib_formats set_matplo...
<SYSTEM_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 datasets Step2: Feature Space Step3: We'll be using the popular data manipulation framework pandas. Step4: We can use head() to get a ...
<ASSISTANT_TASK:> Python Code: %matplotlib inline import math, keras, datetime, pandas as pd, numpy as np, keras.backend as K import matplotlib.pyplot as plt, xgboost, operator, random, pickle from utils2 import * np.set_printoptions(threshold=50, edgeitems=20) limit_mem() from isoweek import Week from pandas_summary i...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: EXPLORE THE DATA Step2: SUBSET THE DATA Step3: STANDARDIZE THE DATA Step5: K-MEANS ANALYSIS - INITIAL CLUSTER SET Step6: Interpret 2 cluster...
<ASSISTANT_TASK:> Python Code: # read training and test data from the url link and save the file to your working directory url = "http://archive.ics.uci.edu/ml/machine-learning-databases/poker/poker-hand-training-true.data" urllib.request.urlretrieve(url, "poker_train.csv") url2 = "http://archive.ics.uci.edu/ml/machine...
<SYSTEM_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 goal of this notebook is to illustrate how a model can wrapped and used in different tasks in Emukit. Step2: Define the objective function ...
<ASSISTANT_TASK:> Python Code: # General imports and parameters of figures should be loaded at the beginning of the overview import numpy as np from emukit.test_functions import branin_function from emukit.core import ParameterSpace, ContinuousParameter from emukit.core.initial_designs import RandomDesign from GPy.mod...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Interactive Line Plotting of Data Frames Step2: Plotting independent series Step3: This does not affect filtering or pivoting in any way Step4...
<ASSISTANT_TASK:> Python Code: import sys,os sys.path.append("..") import numpy.random import pandas as pd import shutil import tempfile import trappy trace_thermal = "./trace.txt" trace_sched = "../tests/raw_trace.dat" TEMP_BASE = "/tmp" def setup_thermal(): tDir = tempfile.mkdtemp(dir="/tmp", prefix="trappy_doc",...
<SYSTEM_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 driver is used to execute the harmonization. It will handle the data formatting needed to execute the harmonizaiton operation and stores the...
<ASSISTANT_TASK:> Python Code: import pandas as pd import seaborn as sns import matplotlib.pyplot as plt import pyomo.environ as pyomo import aneris from aneris.tutorial import load_data %matplotlib inline model, hist, driver = load_data() driver.overrides = model[["Model", "Scenario", "Region", "Variable", "Unit"]]....
<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: OLS Analysis Using Full PSU dataset Step3: Partitioning a dataset in training and test sets Step4: Determine Feature Importances Step5: Test ...
<ASSISTANT_TASK:> Python Code: #Import required packages import pandas as pd import numpy as np import datetime import matplotlib.pyplot as plt def format_date(df_date): Splits Meeting Times and Dates into datetime objects where applicable using regex. df_date['Days'] = df_date['Meeting_Times'].str.ex...
<SYSTEM_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 command %matplotlib inline is not a Python command, but an IPython command. When using the console, or the notebook, it makes the plots appe...
<ASSISTANT_TASK:> Python Code: from matplotlib import pyplot %matplotlib inline from math import sin, pi x = [] y = [] for i in range(201): x.append(0.01*i) y.append(sin(pi*x[-1])**2) pyplot.plot(x, y) pyplot.show() from math import sin, pi x = [] y = [] for i in range(201): x.append(0.01*i) y.append(...
<SYSTEM_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. Load and prepare the data Step3: Tokenize Step5: Padding Step7: Preprocess pipeline Step8: Split the data into training and test sets Ste...
<ASSISTANT_TASK:> Python Code: import numpy as np import matplotlib.pyplot as plt import seaborn as sns import helper import keras helper.info_gpu() np.random.seed(9) %matplotlib inline %load_ext autoreload %autoreload 2 with open('data/small_vocab_en', "r") as f: english_sentences = f.read().split('\n') with open...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Login to and initialize wandb. You will need to use your wandb API key to run this demo. Step2: Dataset and Dataloader for Custom Object Detect...
<ASSISTANT_TASK:> Python Code: import torch import numpy as np import wandb import label_utils from torch.utils.data import DataLoader from torchvision import transforms from PIL import Image wandb.login() config = { "num_workers": 4, "pin_memory": True, "batch_size": 32, "dataset": "drinks", "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: Load Digits Dataset Step2: Create Pipeline Step3: Create k-Fold Cross-Validation Step4: Conduct k-Fold Cross-Validation Step5: Calculate Mea...
<ASSISTANT_TASK:> Python Code: # Load libraries import numpy as np from sklearn import datasets from sklearn import metrics from sklearn.model_selection import KFold, cross_val_score from sklearn.pipeline import make_pipeline from sklearn.linear_model import LogisticRegression from sklearn.preprocessing import Standard...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: That's all we need to create and train a model Step2: Movielens 100k Step3: Here's some benchmarks on the same dataset for the popular Librec ...
<ASSISTANT_TASK:> Python Code: user,item,title = 'userId','movieId','title' path = untar_data(URLs.ML_SAMPLE) path ratings = pd.read_csv(path/'ratings.csv') ratings.head() data = CollabDataBunch.from_df(ratings, seed=42) y_range = [0,5.5] learn = collab_learner(data, n_factors=50, y_range=y_range) learn.fit_one_cycle(...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Exercise 1 Step2: Exercise 2 Step3: Exercise 3
<ASSISTANT_TASK:> Python Code: # Import all necessary libraries, this is a configuration step for the exercise. # Please run it before the simulation code! import numpy as np import matplotlib.pyplot as plt # Show the plots in the Notebook. plt.switch_backend("nbagg") def fourier_derivative(f, dx): # Length of vec...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Read in train & val data Step2: Extract X and Y matrices Step4: Convert to SystemML Matrices Step6: Trigger Caching (Optional) Step8: Save M...
<ASSISTANT_TASK:> Python Code: %load_ext autoreload %autoreload 2 %matplotlib inline import os import matplotlib.pyplot as plt import numpy as np from pyspark.sql.functions import col, max import systemml # pip3 install systemml from systemml import MLContext, dml plt.rcParams['figure.figsize'] = (10, 6) ml = MLContex...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Dados Step2: Análise modal Step3: Ordenação dos modos Step4: Normalização dos modos de vibração relativamente à matriz de massa Step5: Massa...
<ASSISTANT_TASK:> Python Code: import sys import math import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt %matplotlib inline print('System: {}'.format(sys.version)) for package in (np, mpl): print('Package: {} {}'.format(package.__name__, package.__version__)) MM = np.matrix(np.diag([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:
<ASSISTANT_TASK:> Python Code:: import tensorflow as tf from tensorflow.keras.losses import MeanAbsoluteError y_true = [1., 0.] y_pred = [2., 3.] mae_loss = MeanAbsoluteError() loss = mae_loss(y_true, y_pred).numpy() <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: Date string for filenames Step2: Load data Step3: Because the 2017 facility dataframe only includes annually reporting facilities I'm going to...
<ASSISTANT_TASK:> Python Code: %matplotlib inline import matplotlib.pyplot as plt import os from os.path import join import pandas as pd from sklearn import neighbors, metrics from sklearn.preprocessing import LabelEncoder from sklearn.model_selection import train_test_split, GridSearchCV from collections import Counte...
<SYSTEM_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 Noisy Data Step2: Model Fitting Step3: Fit result from an lmfit Model can be inspected with Step4: These methods a re convenient but e...
<ASSISTANT_TASK:> Python Code: import numpy as np from numpy import sqrt, pi, exp, linspace from lmfit import Model import matplotlib.pyplot as plt %matplotlib inline %config InlineBackend.figure_format='retina' # for hi-dpi displays import lmfit print('lmfit: %s' % lmfit.__version__) import pybroom as br x = np.lins...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: aws cli Step2: IAM (identity and access management) Step3: Find cheapest prices Step4: Finding AMIs
<ASSISTANT_TASK:> Python Code: import boto3 s3=boto3.client('s3') list=s3.list_objects(Bucket='mert01')['Contents'] list[1:3] # https://stackoverflow.com/questions/3337912/quick-way-to-list-all-files-in-amazon-s3-bucket import boto s3 = boto.connect_s3() bucket = s3.get_bucket('mert01') #bl = bucket.list() #for key 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: And the distribution of time between goals is given by the exponential Step2: I use the variable lam because lambda is a Step3: Figure 7.1 Ste...
<ASSISTANT_TASK:> Python Code: def EvalPoissonPmf(k, lam): return (lam)**k * math.exp(-lam) / math.factorial(k) def EvalExponentialPdf(x, lam): return lam * math.exp(-lam * x) from hockey import * import thinkplot suite1 = Hockey('bruins') suite1.UpdateSet([0, 2, 8, 4]) suite2 = Hockey('canucks') suite2.Updat...
<SYSTEM_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 explore the Lorenz system of differential equations Step2: For the default set of parameters, we see the trajectories swirling around two po...
<ASSISTANT_TASK:> Python Code: %matplotlib inline from ipywidgets import interactive, fixed from lorenz import solve_lorenz w=interactive(solve_lorenz,sigma=(0.0,50.0),rho=(0.0,50.0)) w t, x_t = w.result w.kwargs xyz_avg = x_t.mean(axis=1) xyz_avg.shape from matplotlib import pyplot as plt plt.hist(xyz_avg[:,0]) 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: La clase poly1D representa polinomios unidimensionales con base en sus coeficientes. Sea el polinomio Step2: Se puede evaluar el valor de $p(x)...
<ASSISTANT_TASK:> Python Code: import numpy as np p = np.poly1d([6., 1., -2.]) p(0), p(1), p(10) p.order p.roots # Comprobando las raíces p(p.roots) np.poly1d([2.,-3.,7.]).roots import matplotlib.pyplot as plt xvalues = np.linspace(-10.,10.,100) plt.plot(xvalues, p(xvalues), '-') plt.show() y = p(xvalues) + np.r...