Unnamed: 0 int64 0 15.9k | cleaned_code stringlengths 67 124k ⌀ | cleaned_prompt stringlengths 168 30.3k ⌀ |
|---|---|---|
13,500 | <ASSISTANT_TASK:>
Python Code:
ratings = pd.read_csv(path+'ratings.csv')
ratings.head()
len(ratings)
movie_names = pd.read_csv(path+'movies.csv').set_index('movieId')['title'].to_dict()
users = ratings.userId.unique()
movies = ratings.movieId.unique()
userid2idx = {o:i for i,o in enumerate(users)}
movieid2idx = {o:i f... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Just for display purposes, let's read in the movie names too.
Step2: We update the movie and user ids so that they are contiguous integers, whi... |
13,501 | <ASSISTANT_TASK:>
Python Code:
import graphlab
loans = graphlab.SFrame('lending-club-data.gl/')
loans['safe_loans'] = loans['bad_loans'].apply(lambda x : +1 if x==0 else -1)
loans = loans.remove_column('bad_loans')
features = ['grade', # grade of the loan
'term', # the term of ... | <SYSTEM_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 LendingClub Dataset
Step2: As before, we reassign the labels to have +1 for a safe loan, and -1 for a risky (bad) loan.
Step3: We will be... |
13,502 | <ASSISTANT_TASK:>
Python Code:
# set java path
import os
java_path = r'C:\Program Files\Java\jre1.8.0_192\bin\java.exe'
os.environ['JAVAHOME'] = java_path
from nltk.parse.stanford import StanfordParser
scp = StanfordParser(path_to_jar='E:/stanford/stanford-parser-full-2015-04-20/stanford-parser.jar',
... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: We can see the nested hierarchical structure of the constituents in the preceding output as compared to the flat structure in shallow parsing. R... |
13,503 | <ASSISTANT_TASK:>
Python Code:
import sys
import matplotlib.pyplot as plt
from tqdm import tqdm_notebook as tqn
%matplotlib inline
sys.path.append('../../..')
sys.path.append('../../utils')
import utils
from resnet_with_stochastic_depth import StochasticResNet
from batchflow import B,V,F
from batchflow.opensets 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: In our expements we will work with MNIST dataset
Step2: Firstly, let us define the shape of inputs of our model, loss function and an optimizer... |
13,504 | <ASSISTANT_TASK:>
Python Code:
def load_feat_vec(patientid,sub_name="stage1_feat"):
f=file("./2017datascibowl/"+sub_name+"/"+patientid+"feat_vec","rb")
arr = np.load(f)
f.close()
return arr
def prepare_inputX(sub_name="stage1_feat_lowres64", ratio_of_train_to_total = 0.4,
... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Predictions
Step2: steps towards persisting (saving) SVM models
Step3: Submissions 2
|
13,505 | <ASSISTANT_TASK:>
Python Code:
import sys
import numpy as np
import scipy as sp
import matplotlib as mpl
print('System: {}'.format(sys.version))
print('numpy version: {}'.format(np.__version__))
print('scipy version: {}'.format(sp.__version__))
print('matplotlib version: {}'.format(mpl.__version__))
from numpy 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: We will also need a couple of specific modules and a litle "IPython magic" to show the plots
Step2: Back to top
Step3: We will also setup two ... |
13,506 | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
import pymt.models
cem = pymt.models.Cem()
cem.output_var_names
cem.input_var_names
angle_name = 'sea_surface_water_wave__azimuth_angle_of_opposite_of_phase_velocity'
print("Data type: %s" % cem.get_var_type(angle_name))
print("Units: %s" % cem.get_var_units(angle_na... | <SYSTEM_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 the Cem class, and instantiate it. In Python, a model with a BMI will have no arguments for its constructor. Note that although the class... |
13,507 | <ASSISTANT_TASK:>
Python Code:
import pubchempy as pcp
from IPython.display import Image
coumarin = pcp.Compound.from_cid(323)
Image(url='https://pubchem.ncbi.nlm.nih.gov/image/imgsrv.fcgi?cid=323&t=l')
coumarin_314 = pcp.Compound.from_cid(72653)
Image(url='https://pubchem.ncbi.nlm.nih.gov/image/imgsrv.fcgi?cid=72653&... | <SYSTEM_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 we'll get some compounds. Here we just use PubChem CIDs to retrieve, but you could search (e.g. using name, SMILES, SDF, etc.).
Step2: Th... |
13,508 | <ASSISTANT_TASK:>
Python Code:
from __future__ import division
import numpy as np
import matplotlib.pyplot as plt
from astropy.table import Table
from astropy.time import Time
import tables
from scipy import stats
import tables3_api
from scipy.interpolate import CubicSpline
%matplotlib inline
with tables.open_file('/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: Get acq stats data and clean
Step4: Model definition
Step5: Plotting and validation
Step6: Color != 1.5 fit (this is MOST acq stars)
Step7: ... |
13,509 | <ASSISTANT_TASK:>
Python Code:
import numpy as np
import logging
import pyLDAvis.gensim
import json
import warnings
warnings.filterwarnings('ignore') # To ignore all warnings that arise here to enhance clarity
from gensim.models.coherencemodel import CoherenceModel
from gensim.models.ldamodel import LdaModel
from gens... | <SYSTEM_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 logging
Step2: Set up corpus
Step3: Set up two topic models
Step4: Using U_Mass Coherence
Step5: View the pipeline parameters for one... |
13,510 | <ASSISTANT_TASK:>
Python Code:
d = pd.read_csv("data/dataset_0.csv")
plt.plot(d.x,d.y,'o')
def linear(x,a,b):
return a + b*x
def linear(x,a,b):
return a + b*x
def linear_r(param,x,y):
return linear(x,param[0],param[1]) - y
def linear_r(param,x,y): # copied from previous cell
retur... | <SYSTEM_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 does the following code do?
Step2: Defines a linear function of x with the slope a and the intercept b.
Step3: Defines a residuals functi... |
13,511 | <ASSISTANT_TASK:>
Python Code:
import pandas as pd
import numpy as np
import operator
import re
train = pd.read_csv("../input/train.csv").drop('target', axis=1)
test = pd.read_csv("../input/test.csv")
df = pd.concat([train ,test])
print("Number of texts: ", df.shape[0])
def load_embed(file):
def get_coefs(word,*... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Loading data
Step2: Loading embeddings
Step3: Vocabulary and Coverage functions
Step4: Starting point
Step5: #### Paragram seems to have a s... |
13,512 | <ASSISTANT_TASK:>
Python Code:
def derivada(f, x_0, delta_x):
pendiente = (f(x_0 + delta_x) - f(x_0))/delta_x
return pendiente
def raiz(f, x_0, delta_x):
x_1 = x_0 - f(x_0)/derivada(f, x_0, delta_x)
return x_1
def secante_modificada(f, x_0, delta_x):
print("{0:s} \t {1:15s} \t {2:15s} \t {3:15s}".... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Implementación no vectorizada
Step2: Ejemplo 2
Step3: Ejemplo 3
|
13,513 | <ASSISTANT_TASK:>
Python Code:
import glob
import csv
from collections import Counter
import numpy as np
from matplotlib import pyplot as plt
import re
%matplotlib inline
def get_top_trips(path,N=10):
#the headers on the CSV are slightly different depending on whether the data is from Citi or Capital
if pa... | <SYSTEM_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 looking at the top 10 trips for each station, we see some very interesting results. For Capital bikeshare, the top most common trip and the 4... |
13,514 | <ASSISTANT_TASK:>
Python Code:
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import datetime as dt
import itertools
import pickle
%matplotlib inline
pickle_file = open('../../lectures/data/campusDemand.pkl','rb')
pickled_data = pickle.load(pickle_file)
pickle_file.close()
# Since we pickled th... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: To unpickle just do this
Step2: -=-=-= Exploring hourly and weekly consumption patterns (no seasonality) =-=-=-
Step3: Task #2 (10%)
Step4: T... |
13,515 | <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: Language Translation
Step3: Explore the Data
Step6: Implement Preprocessing Function
Step8: Preprocess all the data and save it
Step10: Chec... |
13,516 | <ASSISTANT_TASK:>
Python Code:
%run ../scripts/1/discretize.py
data
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
# Adding a little bit of noise so that it's easier to visualize
data_with_noise = data.iloc[:, :2] + np.random.normal(loc=0, scale=0.1, size=(150, 2))
plt.scatter(data_with_noise.le... | <SYSTEM_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. Different ways of learning from data
Step2: In the plot we can easily see that the blue points are concentrated on the top-left corner, gree... |
13,517 | <ASSISTANT_TASK:>
Python Code:
#!pip install -I "phoebe>=2.3,<2.4"
import phoebe
from phoebe import u # units
import numpy as np
import matplotlib.pyplot as plt
phoebe.devel_on() # DEVELOPER MODE REQUIRED FOR VISIBLE_PARTIAL - DON'T USE FOR SCIENCE
logger = phoebe.logger()
b = phoebe.default_binary()
b.add_dataset('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: As always, let's do imports and initialize a logger and a new Bundle.
Step2: Let's just compute the mesh at a single time-point that we know sh... |
13,518 | <ASSISTANT_TASK:>
Python Code:
import numpy as np
from scipy.stats import norm
from scipy.io import loadmat
# Load the matrix into memory, assuming for now that it is stored in the home directory
A = loadmat("../dataset/hw1/A11F17108.mat")['A']
# Obtain x, where Ax[:,i] = A[i,:].T
x = np.linalg.lstsq(A,A.T)[0]
# Test
... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Problem #1
Step2: Part (a)
Step3: Part (b)
Step4: Part (c)
Step5: Problem #2
Step6: Part (b)
Step7: Problem #3
Step9: Of course, this sol... |
13,519 | <ASSISTANT_TASK:>
Python Code:
import os
os.system('annotate_variation.pl -buildver hg19 -downdb -webfrom annovar clinvar_20150629 humandb/')
with open('humandb/hg19_clinvar_20150629.txt') as infile:
first_five_lines = [next(infile) for i in range(5)]
print first_five_lines
import pandas as pd
raw_clinvar = pd.re... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Let's look at a few lines of this file
Step2: We can load this file more cleanly with the pandas library (http
Step3: Taking a closer look at ... |
13,520 | <ASSISTANT_TASK:>
Python Code:
# imports
import re
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
import pprint as pp
hdf = pd.HDFStore('../../data/raw/TestMessungen_NEU.hdf')
print(hdf.keys)
df_x1_t1_trx_1_4 = hdf.get('/x1/t1/trx_1_4')
print("Rows:", df_x1_t1_trx_1_4.sha... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Wir öffnen die Datenbank und lassen uns die Keys der einzelnen Tabellen ausgeben.
Step2: Aufgabe 2
Step3: Als nächstes Untersuchen wir exempl... |
13,521 | <ASSISTANT_TASK:>
Python Code:
!sudo chown -R jupyter:jupyter /home/jupyter/training-data-analyst
!pip3 install cloudml-hypertune
import os
%%bash
export PROJECT=$(gcloud config list project --format "value(core.project)")
echo "Your current GCP Project Name is: "${PROJECT}
# TODO: Change these to try this notebook o... | <SYSTEM_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 necessary libraries.
Step2: Set environment variables.
Step3: Check data exists
Step4: Now that we have the Keras wide-and-deep code w... |
13,522 | <ASSISTANT_TASK:>
Python Code:
print("Hello, World!")
print("First this line is printed,")
print("and then this one.")
# imports -- just run this cell
import scipy
import numpy as np
import pandas as pd
import seaborn as sns
from scipy.stats import mode
from ipywidgets import interact
import matplotlib.pyplot as plt
... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: The fundamental building block of Python code is an expression. Cells can contain multiple lines with multiple expressions. When you run a cell,... |
13,523 | <ASSISTANT_TASK:>
Python Code:
#为了让Python能够高效率处理表格数据,我们使用一个非常优秀的数据处理框架Pandas。
import pandas as pd
#然后我们把loans.csv里面的内容全部读取出来,存入到一个叫做df的变量里面。
df = pd.read_csv('loans.csv')
#我们看看df这个数据框的前几行,以确认数据读取无误。因为表格列数较多,屏幕上显示不完整,我们向右拖动表格,看表格最右边几列是否也正确读取。
df.tail()
#统计一下总行数,看是不是所有行也都完整读取进来了。
df.shape
X = df.drop('safe_loans', axis=... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: 运行结果如下:(46508, 13)
Step2: 注意这里有一个问题。Python下做决策树的时候,每一个特征都应该是数值(整型或者实数)类型的。但是我们一眼就可以看出,grade, sub_grade, home_ownership等列的取值都是类别(categorical)型。所... |
13,524 | <ASSISTANT_TASK:>
Python Code:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.pylab as pylab
import astropy.units as u
from radial import estimate, dataset
%matplotlib inline
harps = dataset.RVDataSet(file='../../tests/HIP67620_HARPS.dat', # File name
t_offset=-2.45E6, ... | <SYSTEM_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 then extract the data from the text files located in the tests folder. They will be stored in RVDataSet objects, which are defined in the dat... |
13,525 | <ASSISTANT_TASK:>
Python Code:
# this will install tweepy on your machine
!pip install tweepy
consumer_key = 'xxx'
consumer_secret = 'xxx'
access_token = 'xxx'
access_token_secret = 'xxx'
import tweepy
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
#... | <SYSTEM_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 Twitter app and find your consumer token and secret
Step2: Authentificate with the Twitter API
Step3: Collecting tweets from the Stre... |
13,526 | <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'
class DLProgress(tqdm):
last_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: Image Classification
Step2: Explore the Data
Step5: Implement Preprocess Functions
Step8: One-hot encode
Step10: Randomize Data
Step12: Che... |
13,527 | <ASSISTANT_TASK:>
Python Code:
# These are all the modules we'll be using later. Make sure you can import them
# before proceeding further.
from __future__ import print_function
import numpy as np
import tensorflow as tf
from six.moves import cPickle as pickle
from six.moves import range
pickle_file = 'notMNIST.pickle... | <SYSTEM_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 reload the data we generated in 1_notmnist.ipynb.
Step2: Reformat into a shape that's more adapted to the models we're going to train
Ste... |
13,528 | <ASSISTANT_TASK:>
Python Code:
#Five years of detailed complaint data for all four kinds of facilities (Residential Care, Assisted Living, Nursing, and Adult Foster Home)
detailed = pd.read_excel('../../data/raw/Oregonian Abuse records 5 years May 2016.xlsx', header=3)
#Ten years of non-detailed complaints for Nursing ... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: <h4>There are 52 complaints that have been mislabelled as unsubstantiated.</h4>
Step2: This dataset contains unsubstantiated complaints, which ... |
13,529 | <ASSISTANT_TASK:>
Python Code:
import pandas
titanic = pandas.read_csv("titanic_train.csv")
titanic.head()
print(titanic.describe())
titanic["Age"] = titanic["Age"].fillna(titanic["Age"].median())
print(titanic.describe())
print(titanic["Sex"].unique())
# 对男女进行编号
titanic.loc[titanic["Sex"] == "male", "Sex"] = 0
titan... | <SYSTEM_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: 除了Sex字段,还有Embarked也不是数值的,我们也需要进行转换
Step4: String值得填充我们是用多的填,这里$S$最多,因此用它填。
Step5: 用pandas和sklearn做机器学习还是很简单的,流程... |
13,530 | <ASSISTANT_TASK:>
Python Code:
import random
from matplotlib import pyplot as plt
from mpl_toolkits import axes_grid1
import numpy as np
import tensorflow as tf
from tensorflow import keras
import tensorflow_similarity as tfsim
tfsim.utils.tf_cap_memory()
print("TensorFlow:", tf.__version__)
print("TensorFlow Similarit... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Dataset samplers
Step2: Visualize the dataset
Step3: Embedding model
Step4: Similarity loss
Step5: Indexing
Step6: Calibration
Step7: Visu... |
13,531 | <ASSISTANT_TASK:>
Python Code:
#load tweets
import json
filename = 'AI2.txt'
tweet_list = []
with open(filename, 'r') as fopen:
# each line correspond to a tweet
for line in fopen:
if line != '\n':
tweet_list.append(json.loads(line))
# take the first tweet of the list
tweet = twee... | <SYSTEM_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 look at the informations contained in a tweet
Step2: you can find a description of the fields in the Twitter API documentation
Step10: B... |
13,532 | <ASSISTANT_TASK:>
Python Code:
from chemdataextractor import Document
from chemdataextractor.model import Compound
from chemdataextractor.doc import Paragraph, Heading
d = Document(
Heading(u'Synthesis of 2,4,6-trinitrotoluene (3a)'),
Paragraph(u'The procedure was followed to yield a pale yellow solid (b.p. 24... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Example Document
Step2: What does this look like
Step3: Default Parsers
Step4: Defining a New Property Model
Step5: Writing a New Parser
Ste... |
13,533 | <ASSISTANT_TASK:>
Python Code:
doc_topic = np.genfromtxt('doc_topic.csv',delimiter=',')
topic_word = np.genfromtxt('topic_word.csv',delimiter=',')
with open('vocab.csv') as f:
vocab = f.read().splitlines()
# Show document distributions across topics
plt.imshow(doc_topic.T,interpolation='none')
plt.show()
# Remove 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: Set conference schedule here, session_papers has a list of sessions and the number of papers they can hold
Step2: Cluster papers into sessions,... |
13,534 | <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... |
13,535 | <ASSISTANT_TASK:>
Python Code:
import pandas as pd
%matplotlib inline
import numpy as np
from sklearn.linear_model import LogisticRegression
df = pd.read_csv("hanford.csv")
df
df.describe()
df['Exposure'].max() - df['Exposure'].min()
df['Mortality'].max() - df['Mortality'].min()
df['Exposure'].quantile(q=0.25)
df['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: 2. Read in the hanford.csv file in the data/ folder
Step2: <img src="../../images/hanford_variables.png"></img>
|
13,536 | <ASSISTANT_TASK:>
Python Code:
from myhdl import *
from myhdlpeek import Peeker
def adder_bit(a, b, c_in, sum_, c_out):
'''Single bit adder.'''
@always_comb
def adder_logic():
sum_.next = a ^ b ^ c_in
c_out.next = (a & b) | (a & c_in) | (b & c_in)
# Add some peekers to monitor the 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: Selecting Waveforms to Display
Step2: If you don't like typing all those quotation marks, you can place multiple, space-separated peeker names ... |
13,537 | <ASSISTANT_TASK:>
Python Code:
%tensorflow_version 1.x
!curl -Lo deepchem_installer.py https://raw.githubusercontent.com/deepchem/deepchem/master/scripts/colab_install.py
import deepchem_installer
%time deepchem_installer.install(version='2.3.0')
# Run this cell to see if things work
import deepchem as dc
import nump... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: You can of course run this tutorial locally if you prefer. In this case, don't run the above cell since it will download and install Anaconda on... |
13,538 | <ASSISTANT_TASK:>
Python Code:
import numpy as np
import matplotlib.pyplot as plt
import ipywidgets as wg
from ipywidgets import interactive, fixed
%matplotlib inline
def plot_interactive(w, b, func, ylim=fixed((0, 1)), show_der=False):
plt.figure(0)
x = np.linspace(-10, 10, num=1000)
z = w*x + b
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: Linear
Step2: Sigmoid
Step3: Tanh
Step4: Rectified Linear Unit (ReLU)
Step5: Leaky ReLU
Step6: Exponential Linear Unit (eLU)
|
13,539 | <ASSISTANT_TASK:>
Python Code:
# Create a SystemML MLContext object
from systemml import MLContext, dml
ml = MLContext(sc)
%%sh
mkdir -p data/mnist/
cd data/mnist/
curl -O http://pjreddie.com/media/files/mnist_train.csv
curl -O http://pjreddie.com/media/files/mnist_test.csv
training =
source("mnist_softmax.dml") as ... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Download Data - MNIST
Step3: SystemML Softmax Model
Step5: 2. Compute Test Accuracy
Step6: 3. Extract Model Into Spark DataFrames For Future ... |
13,540 | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
%config InlineBackend.figure_formats = ['svg']
from qutip import *
from qutip.ui.progressbar import BaseProgressBar
import numpy as np
import matplotlib.pyplot as plt
from scipy.integrate import odeint
y_sse = None
import time
def arccoth(x):
return 0.5*np.log((1.+... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Just check that analytical solution coincides with the solution of ODE for the variance
Step2: Test of different SME solvers
Step3: Determinis... |
13,541 | <ASSISTANT_TASK:>
Python Code:
from multilabel import EATINGMEAT_BECAUSE_MAP, EATINGMEAT_BUT_MAP, JUNKFOOD_BECAUSE_MAP, JUNKFOOD_BUT_MAP
LABEL_MAP = JUNKFOOD_BUT_MAP
BERT_MODEL = 'bert-base-uncased'
BATCH_SIZE = 16 if "base" in BERT_MODEL else 2
GRADIENT_ACCUMULATION_STEPS = 1 if "base" in BERT_MODEL else 8
MAX_SEQ_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:
Step1: Data
Step2: Next, we build the label vocabulary, which maps every label in the training data to an index.
Step3: Model
Step4: Training
Step5:... |
13,542 | <ASSISTANT_TASK:>
Python Code:
from chemview import MolecularViewer
import numpy as np
coordinates = np.array([[0.00, 0.13, 0.00], [0.12, 0.07, 0.00], [0.12,-0.07, 0.00],
[0.00,-0.14, 0.00], [-0.12,-0.07, 0.00],[-0.12, 0.07, 0.00],
[ 0.00, 0.24, 0.00], [ 0.21, 0.12, 0.00],... | <SYSTEM_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 display a benzene molecule we need at least two pieces of information
Step2: We can pass those to the class MolecularViewer and call the met... |
13,543 | <ASSISTANT_TASK:>
Python Code:
# Start the Spark Session
# When Using Spark on CERN SWAN, use this and do not select to connect to a CERN Spark cluster
# If you want to use a cluster, please copy the data to a cluster filesystem first
from pyspark.sql import SparkSession
spark = (SparkSession.builder
.appName(... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Getting Started
Step2: <div align="justify">Now that you can access the data, you can use a number of functions which can help you analyse it. ... |
13,544 | <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: Hello Qubit
|
13,545 | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
from matplotlib import pyplot as plt
import numpy as np
from IPython.html.widgets import interact
def char_probs(s):
Find the probabilities of the unique characters in the string s.
Parameters
----------
s : str
A string of characters.
... | <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: Character counting and entropy
Step4: The entropy is a quantiative measure of the disorder of a probability distribution. It is used extensivel... |
13,546 | <ASSISTANT_TASK:>
Python Code:
# DO NOT EDIT !
from pyesdoc.ipython.model_topic import NotebookOutput
# DO NOT EDIT !
DOC = NotebookOutput('cmip6', 'inm', 'inm-cm4-8', 'aerosol')
# Set as follows: DOC.set_author("name", "email")
# TODO - please enter value(s)
# Set as follows: DOC.set_contributor("name", "ema... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Document Authors
Step2: Document Contributors
Step3: Document Publication
Step4: Document Table of Contents
Step5: 1.2. Model Name
Step6: 1... |
13,547 | <ASSISTANT_TASK:>
Python Code:
from os.path import basename, exists
def download(url):
filename = basename(url)
if not exists(filename):
from urllib.request import urlretrieve
local, _ = urlretrieve(url, filename)
print("Downloaded " + local)
download("https://github.com/AllenDowney/Thin... | <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: The estimation game
Step4: The following function simulates experiments where we try to estimate the mean of a population based on a sample wit... |
13,548 | <ASSISTANT_TASK:>
Python Code:
from cobra.io import load_model
model = load_model('textbook')
model.solver = 'glpk'
# or if you have cplex installed
model.solver = 'cplex'
type(model.solver)
<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: For information on how to configure and tune the solver, please see the documentation for optlang project and note that model.solver is simply a... |
13,549 | <ASSISTANT_TASK:>
Python Code:
IPython Notebook v4.0 para python 3.0
Librerías adicionales: numpy, matplotlib
Contenido bajo licencia CC-BY 4.0. Código bajo licencia MIT.
(c) Sebastian Flores, Christopher Cooper, Alberto Rubio, Pablo Bunout.
# Configuración para recargar módulos y librerías dinámicamente
%reload_ext 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: <img src="images/utfsm.png" alt="" width="200px" align="right"/>
Step2: Contenido
Step3: Importante
Step4: 2. Librería Numpy
Step5: 2.1 Arra... |
13,550 | <ASSISTANT_TASK:>
Python Code:
from IPython.display import YouTubeVideo
YouTubeVideo('GlcnxUlrtek')
%pylab inline
#Import code from last time
from partTwo import *
def sigmoid(z):
#Apply sigmoid activation function to scalar, vector, or matrix
return 1/(1+np.exp(-z))
def sigmoidPrime(z):
#Derivative of si... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: <h3 align = 'center'> Variables </h3>
Step2: We can now replace dyHat/dz3 with f prime of z 3.
Step3: We have one final term to compute
Step4:... |
13,551 | <ASSISTANT_TASK:>
Python Code:
from __future__ import print_function
import MDAnalysis as mda
from MDAnalysis.analysis.polymer import PersistenceLength
import matplotlib.pyplot as plt
%matplotlib inline
u = mda.Universe('plength.gro')
print('We have a universe: {}'.format(u))
print('We have {} chains'.format(len(u.res... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Next we'll load up a Universe.
Step2: We'll need to create an AtomGroup (an array of atoms) for each polymer chain.
Step3: It is important tha... |
13,552 | <ASSISTANT_TASK:>
Python Code:
# Import spaCy and load the language library. Remember to use a larger model!
# Choose the words you wish to compare, and obtain their vectors
# Import spatial and define a cosine_similarity function
# Write an expression for vector arithmetic
# For example: new_vector = word1 - word2 + w... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: CHALLENGE
Step2: Task #2
Step3: CHALLENGE
|
13,553 | <ASSISTANT_TASK:>
Python Code:
# boilerplate includes
import sys
import os
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
#from mpl_toolkits.mplot3d import Axes3D
from mpl_toolkits.basemap import Basemap
import matplotlib.patheffects as path_effects
import pandas as pd
import seaborn as sns... | <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: Constants / Parameters
Step3: Read the cleaned temperature data for each site
Step4: The 'good start' column contains the date after which the... |
13,554 | <ASSISTANT_TASK:>
Python Code:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline
import statsmodels.api as sm
# Importing built-in datasets in statsmodels
df = sm.datasets.macrodata.load_pandas().data
df.head()
print(sm.datasets.macrodata.NOTE)
df.head()
df.tail()
# statsmodels.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: Using the Hodrick-Prescott Filter for trend analysis
Step2: ETS Theory (Error-Trend-Seasonality)
Step3: Weakness of SMA
Step4: Full reading o... |
13,555 | <ASSISTANT_TASK:>
Python Code:
# Solution 1 - pure python solution with pandas
with open('irsa_catalog_WISE_iPTF14jg_search_results.tbl') as f:
ll = f.readlines()
for linenum, l in enumerate(ll):
if l[0] == '|':
header = l.replace('|', ',').replace(' ', '')
header = list(header[1... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: That pure python solution is a bit annoying as it requires a for loop with a break, and specific knowledge about how IRSA tables handler data he... |
13,556 | <ASSISTANT_TASK:>
Python Code:
import requests
from shapely.geometry import shape, Point
r = requests.get('https://data.cityofchicago.org/api/geospatial/cauq-8yn6?method=export&format=GeoJSON')
for feature in r.json()['features']:
if feature['properties']['community'] == 'AUSTIN':
austin = feature
poly = sh... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Now let's get the shootings data.
Step2: Now let's iterate through the shootings, generate shapely points and check to see if they're in the ge... |
13,557 | <ASSISTANT_TASK:>
Python Code:
#@title Licensed under the Apache License, Version 2.0 (the "License"); { display-mode: "form" }
# 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 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: TFP 確率的レイヤー
Step2: 迅速に作成
Step3: 注意
Step4: このコラボでは(線形回帰問題のコンテキストで)その方法を紹介します。
Step5: ケース 1
Step6: ケース 2
Step7: ケース 3
Step8: ケース 4
Step9: ... |
13,558 | <ASSISTANT_TASK:>
Python Code:
import pandas as pd
url = 'http://archive.ics.uci.edu/ml/machine-learning-databases/glass/glass.data'
col_names = ['id','ri','na','mg','al','si','k','ca','ba','fe','glass_type']
glass = pd.read_csv(url, names=col_names, index_col='id')
glass.sort_values(by='al', inplace=True)
glass.head()... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Task
Step2: Solving problem using regression
Step3: Solving problem using Logistic Regression
|
13,559 | <ASSISTANT_TASK:>
Python Code:
# all import here
import os
import jsonstat
cache_dir = os.path.abspath(os.path.join("..", "tests", "fixtures", "www.cso.ie"))
jsonstat.cache_dir(cache_dir)
base_uri = 'http://www.cso.ie/StatbankServices/StatbankServices.svc/jsonservice/responseinstance/'
uri = base_uri + "NQQ25"
filena... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: using a cache_dir
Step2: using NQQ25 dataset
Step3: Previous collection contains only a dataset named 'nama_gdp_c'
Step4: Get value for year ... |
13,560 | <ASSISTANT_TASK:>
Python Code:
# Data for manual OHE
# Note: the first data point does not include any value for the optional third feature
sampleOne = [(0, 'mouse'), (1, 'black')]
sampleTwo = [(0, 'cat'), (1, 'tabby'), (2, 'mouse')]
sampleThree = [(0, 'bear'), (1, 'black'), (2, 'salmon')]
sampleDataRDD = sc.paralleli... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: (1b) Vetores Esparsos
Step2: (1c) Atributos OHE como vetores esparsos
Step4: (1d) Função de codificação OHE
Step5: (1e) Aplicar OHE em uma... |
13,561 | <ASSISTANT_TASK:>
Python Code:
# Importamos pandas
%matplotlib inline
import pandas as pd
import matplotlib.pyplot as plt
# Vemos qué pinta tiene el fichero
!head ./tabernas_meteo_data.txt
# Tratamos de cargarlo en pandas
pd.read_csv("./tabernas_meteo_data.txt").head(5)
data = pd.read_csv(
"./tabernas_meteo_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: Cargando los datos y explorándolos
Step2: Vemos que los datos no están en formato CSV, aunque sí tienen algo de estructura. Si intentamos carga... |
13,562 | <ASSISTANT_TASK:>
Python Code:
workDir = '/home/nick/notebook/SIPSim/dev/bac_genome1147/validation_rep3/'
genomeDir = '/var/seq_data/ncbi_db/genome/Jan2016/bac_complete_spec-rep1_rn/'
R_dir = '/home/nick/notebook/SIPSim/lib/R/'
figureDir = '/home/nick/notebook/SIPSim/figures/bac_genome_n1147/'
bandwidth = 0.8
DBL_scali... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Init
Step2: Simulating fragments
Step3: Number of amplicons per taxon
Step4: Converting fragments to kde object
Step5: Checking ampfrag info... |
13,563 | <ASSISTANT_TASK:>
Python Code:
import pandas as pd
census = pd.read_csv("./data/census_data.csv")
census.head()
census['income_bracket'].unique()
def label_fix(label):
if label==' <=50K':
return 0
else:
return 1
# Applying function to every row of the DataFrame
census['income_bracket'] = census... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: TensorFlow won't be able to understand strings as labels, you'll need to use pandas .apply() method to apply a custom function that converts the... |
13,564 | <ASSISTANT_TASK:>
Python Code:
import numpy as np
import scipy as sp
import openpnm as op
%config InlineBackend.figure_formats = ['svg']
import openpnm.models.geometry as gm
import openpnm.models.physics as pm
import openpnm.models.misc as mm
import matplotlib.pyplot as plt
np.set_printoptions(precision=4)
np.random.se... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Generate Two Networks with Different Spacing
Step2: Position Networks Appropriately, then Stitch Together
Step3: Quickly Visualize the Network... |
13,565 | <ASSISTANT_TASK:>
Python Code:
from horsetailmatching import HorsetailMatching, GaussianParameter
from horsetailmatching.demoproblems import TP3
from scipy.optimize import minimize
import numpy as np
import matplotlib.pyplot as plt
def plotHorsetail(theHM, c='b', label=''):
(q, h, t), _, _ = theHM.getHorsetail()
... | <SYSTEM_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 code we setup a horsetail matching optimization using test problem 3, and then run optimizations under three targets
|
13,566 | <ASSISTANT_TASK:>
Python Code:
# Authors: Eric Larson <larson.eric.d@gmail.com>
#
# License: BSD (3-clause)
import os.path as op
import numpy as np
import mne
from mne import find_events, fit_dipole
from mne.datasets.brainstorm import bst_phantom_elekta
from mne.io import read_raw_fif
print(__doc__)
data_path = bst_ph... | <SYSTEM_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 data were collected with an Elekta Neuromag VectorView system at 1000 Hz
Step2: Data channel array consisted of 204 MEG planor gradiometers... |
13,567 | <ASSISTANT_TASK:>
Python Code:
from IPython.core.display import HTML
css_file = 'pynoddy.css'
HTML(open(css_file, "r").read())
%matplotlib inline
# here the usual imports. If any of the imports fails,
# make sure that pynoddy is installed
# properly, ideally with 'python setup.py develop'
# or 'python setup.py instal... | <SYSTEM_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 set-up
Step2: BUG!!!!
Step3: We now define the parameter uncertainties
Step4: And, in a next step, perform the model sampling
Step5: S... |
13,568 | <ASSISTANT_TASK:>
Python Code:
%load exercises/3.1-colors.py
t = np.arange(0.0, 5.0, 0.2)
plt.plot(t, t, t, t**2, t, t**3)
plt.show()
xs, ys = np.mgrid[:4, 9:0:-1]
markers = [".", "+", ",", "x", "o", "D", "d", "", "8", "s", "p", "*", "|", "_", "h", "H", 0, 4, "<", "3",
1, 5, ">", "4", 2, 6, "^", "2", 3, 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: Markers
Step2: Exercise 3.2
Step3: Linestyles
Step4: It is a bit confusing, but the line styles mentioned above are only valid for lines. Whe... |
13,569 | <ASSISTANT_TASK:>
Python Code:
from typing import List
def all_prefixes(string: str) -> List[str]:
result = []
for i in range(len(string)):
result.append(string[:i+1])
return result
<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:
|
13,570 | <ASSISTANT_TASK:>
Python Code:
DATA_FOLDER = 'Data' # Use the data folder provided in Tutorial 02 - Intro to Pandas.
%matplotlib inline
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import datetime
from dateutil.parser import parse
from os import listdir
from os.path impor... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Task 1. Compiling Ebola Data
Step2: sum_row
Step3: Now, we define for each country a function, which, for a given file, returns a dictionnary ... |
13,571 | <ASSISTANT_TASK:>
Python Code:
import magma as m
m.set_mantle_target('ice40')
import mantle
def DefineTriangle(n):
T = m.Bits(n)
class _Triangle(m.Circuit):
name = f'Triangle{n}'
IO = ['I', m.In(T), 'O', m.Out(T)]
@classmethod
def definition(io):
invert = mantle... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: We can wire up the GPIO pins to a logic analyzer to verify that our circuit produces the correct triangle waveform.
Step2: TODO
|
13,572 | <ASSISTANT_TASK:>
Python Code::
import tensorflow as tf
model = tf.keras.model.Sequential()
model.add(tf.keras.layers.Embedding(n_most_words,n_dim,input_length = X_train.shape[1]))
model.add(tf.keras.layers.Dropout(0.25))
model.add(tf.keras.layers.Conv1D(64, 3, padding = 'same', activation = 'relu'))
model.add(tf.keras... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
|
13,573 | <ASSISTANT_TASK:>
Python Code:
json_data = {
"V": ["Letter", "Grade", "Intelligence", "SAT", "Difficulty"],
"E": [["Difficulty", "Grade"],
["Intelligence", "Grade"],
["Intelligence", "SAT"],
["Grade", "Letter"]],
"Vdata": {
"Letter": {
"ord": 4,
"numou... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Conversion
Step2: You may also visualize the directed acylic graph (DAG) of the BBN through networkx.
Step3: Inference
Step4: Here, we visual... |
13,574 | <ASSISTANT_TASK:>
Python Code:
from clifford import Cl, pretty
pretty(precision=1)
# Dirac Algebra `D`
D, D_blades = Cl(1,3, firstIdx=0, names='d')
# Pauli Algebra `P`
P, P_blades = Cl(3, names='p')
# put elements of each in namespace
locals().update(D_blades)
locals().update(P_blades)
from clifford import BladeMap
... | <SYSTEM_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 Space Time Split
Step2: Splitting a space-time vector (an event)
Step3: This can be split into time and space components by multiplying wi... |
13,575 | <ASSISTANT_TASK:>
Python Code:
# Run this cell to set up the notebook.
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib
%matplotlib inline
import matplotlib.pyplot as plt
from client.api.notebook import Notebook
ok = Notebook('lab05.ok')
young_sailors = pd.DataFrame({
"sid": ... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Boat Club
Step2: Question 1
Step3: Question 2
Step4: Question 3
Step5: Question 4
Step6: Question 5
Step7: Question 6
Step8: Question 7
S... |
13,576 | <ASSISTANT_TASK:>
Python Code:
myList = [1,"two", False, 9.99]
len(myList) # A function
print(myList) # A different function!
# the function definition
def myFirstFunc():
print("Nice to meet you!")
# the function call
myFirstFunc()
print(myVariable)
myVariable = "Hallo Hallo!"
myVariable = "Hallo Hallo!"
print(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: Layout of a Function
Step2: Notice that the sequence of function definiton (def) and then function call (function_name()) is important! Think a... |
13,577 | <ASSISTANT_TASK:>
Python Code:
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
x = np.linspace(-10,10)
y = 1/(1+np.exp(-x))
p = plt.plot(x,y)
plt.grid(True)
# Simple example:
# we have 20 students that took an exam and we want to know if we can use
# the number of hours they studied to predict 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: $g(x)\rightarrow 1$ for $x\rightarrow\infty$
Step2: Likelihood of the model
Step3: Here we found the minimum of the loss function simply by co... |
13,578 | <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: Recommending movies
Step2: Preparing the dataset
Step3: As before, we'll split the data by putting 80% of the ratings in the train set, and 20... |
13,579 | <ASSISTANT_TASK:>
Python Code:
import gpytorch
import torch
from gpytorch.likelihoods import GaussianLikelihood
from gpytorch.means import ConstantMean, LinearMean
from gpytorch.kernels import ScaleKernel, MaternKernel
from gpytorch.variational import VariationalStrategy, BatchDecoupledVariationalStrategy
from gpytorch... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Basic settings
Step2: Loading Data
Step3: Create PyTorch DataLoader objects
Step4: Initialize Hidden Layer Inducing Points
Step5: Create The... |
13,580 | <ASSISTANT_TASK:>
Python Code:
# Please install the required packages using `pip install -r requirements.txt` in the current directory
# For all ways to install Modin see official documentation at:
# https://modin.readthedocs.io/en/latest/installation.html
import modin.pandas as pd
import modin.spreadsheet as mss
colu... | <SYSTEM_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 Modin DataFrame
Step2: Generate a spreadsheet widget with the DataFrame
Step3: Displaying the Spreadsheet
Step4: Exporting Changes
S... |
13,581 | <ASSISTANT_TASK:>
Python Code:
import torch
import torch.nn as nn
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.utils import shuffle
%matplotlib inline
df = pd.read_csv('../Data/income.csv')
print(len(df))
df.head()
df['label'].value_counts()
df.columns
# CODE HERE
# RUN THIS CODE... | <SYSTEM_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. Separate continuous, categorical and label column names
Step2: 2. Convert categorical columns to category dtypes
Step3: Optional
Step4: 3.... |
13,582 | <ASSISTANT_TASK:>
Python Code:
from crash_modeling_tools import *
import numpy as np
import pandas as pd
import statsmodels.formula.api as smf
import statsmodels.api as sm
crash_data = pd.read_csv('../data/crash_modeling_tools_demo_data/crash_data_final_90.csv')
crash_data = crash_data.dropna()
crash_data.head()
show... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Load in the initial data and see what predictors are available
Step2: Observe the summary statistics for the variables in our dataset
Step3: S... |
13,583 | <ASSISTANT_TASK:>
Python Code:
import collections
Card = collections.namedtuple('Card', ['rank', 'suit'])
class FrenchDeck:
ranks = [str(n) for n in range(2, 11)] + list('JQKA')
suits = 'spades diamonds clubs hearts'.split()
def __init__(self):
self._cards = [Card(rank, suit) for suit in self.s... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Deck responds to the len() function
Step2: Reading specific cards from the deck is provided by the getitem method
Step3: Get a random item fro... |
13,584 | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
import matplotlib.pyplot as plt
import os, pickle, random
import pandas as pd
import numpy as np
import cvxopt
random.seed(1234554321)
np.random.seed(123456789)
cvxopt.base.setseed(123456789)
%run 'ssvm.ipynb'
fname = os.path.join(data_dir, 'rank-Glas.pkl')
rank_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: Run notebook ssvm.ipynb.
Step2: Load trained RankSVM parameters and prediction results
Step3: Compute evaluation metrics
Step4: Evaluate Rank... |
13,585 | <ASSISTANT_TASK:>
Python Code:
m = 10000 # timesteps
dt = 1/ 250.0 # update loop at 250Hz
t = np.arange(m) * dt
freq = 0.1 # Hz
amplitude = 0.5 # meter
alt_true = 405 + amplitude * np.cos(2 * np.pi * freq * t)
height_true = 5 + amplitude * np.cos(2 * np.pi * freq * t)
vel_true = - amplitude * (2 * np.pi * ... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: II) MEASUREMENTS
Step2: Baro
Step3: GPS
Step4: GPS velocity
Step5: Acceleration
Step6: III) PROBLEM FORMULATION
Step7: Initial uncertainty... |
13,586 | <ASSISTANT_TASK:>
Python Code:
united = Table.read_table('http://inferentialthinking.com/notebooks/united_summer2015.csv')
delay = united.select('Delay')
pop_mean = np.mean(delay.column('Delay'))
pop_mean
delay_opts = {
'xlabel': 'Delay (minute)',
'ylabel': 'Percent per minute',
'xlim': (-20, 200),
'yli... | <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: Now let's take random samples and look at the probability distribution of the sample mean. As usual, we will use simulation to get an empirical ... |
13,587 | <ASSISTANT_TASK:>
Python Code:
import numpy as np
%matplotlib notebook
import scipy.io as sio
from scipy import sparse
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import sys
sys.path.append("pyhks")
from HKS import *
from GeomUtils import *
from ripser import ripser
from persim import plot... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Now, let's include some code that performs a sublevelset filtration by some scalar function on the vertices of a triangle mesh.
Step3: Let's al... |
13,588 | <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: Classification on imbalanced data
Step2: Data processing and exploration
Step3: Examine the class label imbalance
Step4: This shows the small... |
13,589 | <ASSISTANT_TASK:>
Python Code:
import pandas as pd
import numpy as np
import seaborn as sns
%matplotlib inline
import matplotlib.pyplot as plt
# These lines load the tests.
!pip install -U okpy
from client.api.notebook import Notebook
ok = Notebook('lab03.ok')
# Set up (x, y) pairs from 0 to 2*pi
xs = np.linspace(0, 2... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: matplotlib
Step2: matplotlib also conveniently has the ability to plot multiple things on the
Step3: Question 0
Step4: Dataset
Step5: Questi... |
13,590 | <ASSISTANT_TASK:>
Python Code:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from skimage.io import imread, imshow
import cv2
%matplotlib inline
import plotly.offline as py
py.init_notebook_mode(connected=True)
import plotly.graph_objs as go
import plotly.tools as tls
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: We are given training images for each of cervix types. Lets first count them for each class.
Step2: Image types
Step3: Now, lets read the file... |
13,591 | <ASSISTANT_TASK:>
Python Code:
ball = Mesh(geometry=SphereGeometry(radius=1),
material=MeshLambertMaterial(color='red'),
position=[2, 1, 0])
c = PerspectiveCamera(position=[0, 5, 5], up=[0, 1, 0],
children=[DirectionalLight(color='white', position=[3, 5, 1], intensity=0.5)... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Clickable Surface
Step2: Design our own texture
Step3: Lines
Step5: Parametric Functions
Step6: Indexed Geometries
Step7: Buffer Geometries... |
13,592 | <ASSISTANT_TASK:>
Python Code:
# Import modules that contain functions we need
import pandas as pd
import numpy as np
%matplotlib inline
import matplotlib.pyplot as plt
# Read in data that will be used for the calculations.
# The data needs to be in the same directory(folder) as the program
# Using pandas read_csv met... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Getting the data
Step2: Looking at some relationships
|
13,593 | <ASSISTANT_TASK:>
Python Code:
import sys
sys.path.insert(0, '..')
import zarr
print('zarr', zarr.__version__)
from zarr import blosc
import numpy as np
import h5py
import bcolz
# don't let bcolz use multiple threads internally, we want to
# see whether dask can make good use of multiple CPUs
bcolz.set_nthreads(1)
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:
Step2: Profile array copy via dask threaded scheduler
Step3: NumPy arrays
Step4: Zarr arrays (in-memory)
Step5: Without the dask lock, we get better... |
13,594 | <ASSISTANT_TASK:>
Python Code:
!pip install omdb
# Import the library.
import omdb
# Search for movies.
movies = omdb.search("Westworld")
movies
# Since "movies" is a list, we can loop through it.
for movie in movies:
print("Title: " + movie["title"])
print("Type: " + movie["type"])
print("Year: " + movie... | <SYSTEM_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. Access the API
Step2: 3. Present results
Step3: 4. Get more info
Step4: Exercise
|
13,595 | <ASSISTANT_TASK:>
Python Code:
from IPython.html import widgets
[n for n in dir(widgets) if not n.endswith('Widget') and n[0] == n[0].upper() and not n[0] == '_']
widgets.FloatSlider(
value=7.5,
min=5.0,
max=10.0,
step=0.1,
description='Test:',
)
widgets.FloatSlider(
value=7.5,
min=5.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: Numeric widgets
Step2: Sliders can also be displayed vertically.
Step3: FloatProgress
Step4: BoundedFloatText
Step5: FloatText
Step6: Boole... |
13,596 | <ASSISTANT_TASK:>
Python Code:
# these imports let you use opencv
import cv2 #opencv itself
import common #some useful opencv functions
import video # some video stuff
import numpy as np # matrix manipulations
#the following are to do with this interactive notebook code
%matplotlib inline
from matplotlib import pyplo... | <SYSTEM_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 box is useless if you're not using a notebook - they just enable the online notebook drawing stuff.
|
13,597 | <ASSISTANT_TASK:>
Python Code:
import pandas as pd
df = pd.DataFrame({'key1': ['a', 'a', 'b', 'b', 'a', 'c'],
'key2': ['one', 'two', 'gee', 'two', 'three', 'two']})
def g(df):
return df.groupby('key1')['key2'].apply(lambda x: x.str.endswith('e').sum()).reset_index(name='count')
result = g(df.copy... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
|
13,598 | <ASSISTANT_TASK:>
Python Code:
#$HIDE_INPUT$
import pandas as pd
df = pd.read_csv(
"../input/ts-course-data/book_sales.csv",
index_col='Date',
parse_dates=['Date'],
).drop('Paperback', axis=1)
df.head()
#$HIDE_INPUT$
import numpy as np
df['Time'] = np.arange(len(df.index))
df.head()
#$HIDE_INPUT$
import 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: This series records the number of hardcover book sales at a retail store over 30 days. Notice that we have a single column of observations Hardc... |
13,599 | <ASSISTANT_TASK:>
Python Code:
# Author: Martin Luessi <mluessi@nmr.mgh.harvard.edu>
#
# License: BSD (3-clause)
import numpy as np
import mne
from mne import io
from mne.connectivity import spectral_connectivity, seed_target_indices
from mne.datasets import sample
from mne.time_frequency import AverageTFR
print(__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: Set parameters
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.