Unnamed: 0 int64 0 15.9k | cleaned_code stringlengths 67 124k ⌀ | cleaned_prompt stringlengths 168 30.3k ⌀ |
|---|---|---|
6,100 | <ASSISTANT_TASK:>
Python Code:
import os.path as op
import numpy as np
import nibabel as nib
from scipy import linalg
import mne
from mne.io.constants import FIFF
data_path = mne.datasets.sample.data_path()
subjects_dir = op.join(data_path, 'subjects')
raw_fname = op.join(data_path, 'MEG', 'sample', 'sample_audvis_raw.... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: .. raw
Step2: Coordinate frame definitions
Step3: A good example
Step4: Visualizing the transformations
Step5: Now that we've transformed al... |
6,101 | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
import networkx as nx
import matplotlib.cm as cm
import matplotlib.pyplot as plt
import networkx as nx
G=nx.Graph() # G = nx.DiGraph() # 有向网络
# 添加(孤立)节点
G.add_node("spam")
# 添加节点和链接
G.add_edge(1,2)
print(G.nodes())
print(G.edges())
# 绘制网络
nx.draw(G, with_labels = True)
... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: WWW Data download
Step2: 描述网络
Step3: 网络直径
Step4: 密度
Step5: 作业:
Step6: Spacing in Math Mode
Step7: Degree centrality measures.(度中心性)
Step8:... |
6,102 | <ASSISTANT_TASK:>
Python Code:
from jyquickhelper import add_notebook_menu
add_notebook_menu()
%matplotlib inline
from ensae_teaching_cs.data import generate_sells
import pandas
df = pandas.DataFrame(generate_sells())
df.head()
import matplotlib.pyplot as plt
fig, ax = plt.subplots(1, 2, figsize=(14, 4))
df.iloc[-30:... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Données
Step2: Premiers graphiques
Step3: Elle a une vague tendance, on peut calculer un tendance à l'ordre 1, 2, ...
Step4: Autocorrélations... |
6,103 | <ASSISTANT_TASK:>
Python Code:
w = "file.txt"
x = "r"
with open(w,x) as y:
z = y.read()
# "r"
# .read()
# .readlines()
# "w", "a"
# .write(stuff)
w = "file.txt"
x = "w"
with open(w,x) as y:
for i in range(3):
y.write(f"{i}")
grades = ['A', 'B+','A','C+','B-']
grades[:2]
#List operators
... | <SYSTEM_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. w - variable that holds the filename
Step2: A. 0 1 2 3
Step3: A. ['A','B+','A']
Step4: Built-In List Functions
|
6,104 | <ASSISTANT_TASK:>
Python Code:
import pandas as pd
import sklearn
import seaborn as sns
import matplotlib.pyplot as plt
%matplotlib inline
ad_data = pd.read_csv('./advertising.csv')
ad_data.head()
ad_data.info()
ad_data.describe()
ad_data['Age'].plot(kind='hist', bins=40)
sns.jointplot(x='Age', y='Area Income', 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: Get the Data
Step2: Check the head of ad_data
Step3: Use info and describe() on ad_data
Step4: Exploratory Data Analysis
Step5: Create a joi... |
6,105 | <ASSISTANT_TASK:>
Python Code:
!pip install -U -q tensorflow
!pip install -U -q tensorflow_data_validation
!pip install -U -q pandas
# Automatically restart kernel after installs
import IPython
app = IPython.Application.instance()
app.kernel.do_shutdown(True)
PROJECT_ID = "sa-data-validation"
BUCKET = "sa-data-valid... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Configure Google Cloud environment settings
Step2: Authenticate your GCP account
Step3: Import libraries
Step4: Create a local workspace
Step... |
6,106 | <ASSISTANT_TASK:>
Python Code:
# change these to try this notebook out
BUCKET = 'cloud-training-demos-ml'
PROJECT = 'cloud-training-demos'
REGION = 'us-central1'
import os
os.environ['BUCKET'] = BUCKET
os.environ['PROJECT'] = PROJECT
os.environ['REGION'] = REGION
os.environ['TFVERSION'] = '1.8'
if 'COLAB_GPU' in os.env... | <SYSTEM_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 look at the titles of articles and figure out whether the article came from the New York Times, TechCrunch or GitHub.
Step2: Let's do ... |
6,107 | <ASSISTANT_TASK:>
Python Code:
from six.moves import range
all_divides = lambda m, *numbers: all(m % n == 0 for n in numbers)
all_divides(2520, *range(1, 10))
# First we need a predicate to test
# if all elements of a list are equal
# There are a number of ways to do this
pairs = lambda lst: zip(lst[1:], lst[:-1])
al... | <SYSTEM_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 least common multiple of the numbers 1 to 10 is 2520. We are asked to find that of the numbers 1 to 20.
Step2: This is way too slow! Let's ... |
6,108 | <ASSISTANT_TASK:>
Python Code:
from trappy.stats.Topology import Topology
from bart.sched.SchedMultiAssert import SchedMultiAssert
from bart.sched.SchedAssert import SchedAssert
import trappy
import os
import operator
import json
#Define a CPU Topology (for multi-cluster systems)
BIG = [1, 2]
LITTLE = [0, 3, 4, 5]
CLUS... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Periodic Yield
Step2: CPU Hog
Step3: Changing Reservations
|
6,109 | <ASSISTANT_TASK:>
Python Code:
from qiskit_aqua_chemistry import AquaChemistry
# Input dictionary to configure Qiskit Aqua Chemistry for the chemistry problem.
aqua_chemistry_dict = {
'problem': {'random_seed': 50},
'driver': {'name': 'PYSCF'},
'PYSCF': {'atom': 'O 0.0 0.0 0.0; H 0.757 0.586 0.0; H -0.757 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: With the above input problem dictionary for water we now create an AquaChemistry object and call run on it passing in the dictionary to get a re... |
6,110 | <ASSISTANT_TASK:>
Python Code:
# Create a csv file
text = (
'col1,col2,col3\n'
'hello,5/4/82,1\n'
'one,1/1/15,2\n'
'happy,7/4/92,3\n')
f = StringIO(text)
f.seek(0)
# Load the file
records = io.read_csv(f)
# Records are an iterator over the rows
row = next(records)
row
# Replace first row so as not to lo... | <SYSTEM_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 run some operations on the type casted data
Step2: Reading data
Step3: Processing data
Step4: Note
Step5: Text processing (à la csvkit)
... |
6,111 | <ASSISTANT_TASK:>
Python Code:
sample_docs = [
'The quick brown fox jumped over the lazy dog',
'The dog jumped over squirrel',
'Four score and seven years ago'
]
# First we'll vectorize our documents, as we did last week
vectorizer = CountVectorizer()
features = vectorizer.fit_transform(sample_docs).toarra... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: We'll use those sample docs to start. Intuitively, you should be able to see that documents 0 and 1 have some similar elements ("dog," "jumped o... |
6,112 | <ASSISTANT_TASK:>
Python Code:
from sklearn import cross_validation, grid_search, linear_model, metrics, pipeline, preprocessing
import numpy as np
import pandas as pd
%pylab inline
raw_data = pd.read_csv('bike_sharing_demand.csv', header = 0, sep = ',')
raw_data.head()
raw_data.datetime = raw_data.datetime.apply(pd.... | <SYSTEM_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: Pipeline
Step4: Подбор параметров
Step5: Оценка по отложенному тесту
Step6: Другая модел... |
6,113 | <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... |
6,114 | <ASSISTANT_TASK:>
Python Code:
def generate_data():
# 2 layer model with some random error
ml = ModelMaq(kaq=[10, 20], z=[0, -20, -22, -42], c=[1000],
Saq=[0.0002, 0.0001], tmin=0.001, tmax=100)
w = Well(ml, 0, 0, rw=0.3, tsandQ=[(0, 800)])
ml.solve()
t = np.logspace(-2, 1, 100)
... | <SYSTEM_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 as semi-confined
|
6,115 | <ASSISTANT_TASK:>
Python Code:
import numpy as np
import sys
sys.path.append('utils/')
import os
os.environ['OMP_NUM_THREADS'] = str(1)
import matplotlib.pyplot as plt
% matplotlib inline
import scipy.stats as stats
import statsmodels.api as sm
import multiprocessing as mp
import sklearn.preprocessing as preprocessing
... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: ESSENTIAL parameters to modify
Step2: Basic simulation parameters
Step3: 1.0 Construct sample network matrix and visualize group FC matrices
S... |
6,116 | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets('MNIST_data', validation_size=0)
img = mnist.train.images[2]
plt.imshow(img.reshape((28, 28)), cmap='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: Network Architecture
Step2: Training
Step3: Denoising
Step4: Checking out the performance
|
6,117 | <ASSISTANT_TASK:>
Python Code:
import numpy as np
import pandas as pd
from sklearn.datasets import load_breast_cancer
cancer = load_breast_cancer()
# print(cancer.DESCR)
cancer.keys()
# You should write your whole answer within the function provided. The autograder will call
# this function and compare the return va... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: The object returned by load_breast_cancer() is a scikit-learn Bunch object, which is similar to a dictionary.
Step2: Question 0 (Example)
Step3... |
6,118 | <ASSISTANT_TASK:>
Python Code:
# Imports / plotting configuration
import numpy as np
%matplotlib inline
import matplotlib.pyplot as plt
import seaborn as sns
sns.set_context('poster')
plt.rcParams['image.cmap'] = 'viridis'
np.random.seed(13)
import json
import os
# Change this to `'tensorflow'` if you prefer
backend = ... | <SYSTEM_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: We'll start with our old friend the single-layer perceptron that we implemented in the "Basic Neural Network Exercise." The perce... |
6,119 | <ASSISTANT_TASK:>
Python Code:
import os
from IPython.display import HTML
from IPython.display import display, Image
from PIL import Image as PILImage
def files_at_relpath(rel_path):
return [os.path.join(rel_path, f) for f in os.listdir(rel_path)]
def display_images(img_path, **kwargs):
scale = kwargs.get('scal... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Introduction
Step2: Activity Stream and Top Styles
Step3: Data Source
Step5: Data Processing
Step9: Helper functions
Step13: RateBeer Revie... |
6,120 | <ASSISTANT_TASK:>
Python Code:
import pg8000
conn = pg8000.connect(database="homework2")
conn.rollback()
cursor = conn.cursor()
statement = "SELECT movie_title, release_date FROM uitem WHERE scifi = 1 AND horror = 1 ORDER BY release_date DESC;
"
cursor.execute(statement)
for row in cursor:
print(row[0])
cursor ... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: If you get an error stating that database "homework2" does not exist, make sure that you followed the instructions above exactly. If necessary, ... |
6,121 | <ASSISTANT_TASK:>
Python Code:
import numpy as np
from numpy import linalg
#note z^2 doesn't affect our answer
a_matrix = [[6, 4,-1],\
[1, -1, 0],\
[2, -2, -1]]
b_matrix = [0, 6, -4]
#convert them to numpy arrays/matrices
np_a_matrix = np.array(a_matrix)
np_b_matrix = np.array(b_matrix).transpos... | <SYSTEM_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. Chemical Reaction (6 Points)
Step2: 2.4 Answer
Step3: 3. Python Practice (20 Points)
Step4: 4. Integration (12 Points)
Step5: 5. Numerica... |
6,122 | <ASSISTANT_TASK:>
Python Code:
% matplotlib inline
from pylab import *
import numpy as np
import scipy.stats as stats
import datetime
from netCDF4 import netcdftime
from netCDF4 import Dataset as netcdf # netcdf4-python module
from netcdftime import utime
import matplotlib.pyplot as plt
from mpl_toolkits.basemap 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: 2. Read monthly precipitation data
Step2: 2.2 Parse times
Step3: 3. Trend analysis
Step4: 3.2 Visualize trend
Step5: 4. Climatological annua... |
6,123 | <ASSISTANT_TASK:>
Python Code:
## Example of a simple python code cell
print "Hello little world"
a = 1
## The last statement in a cell prints its value
a
## (this is sometimes a little confusing - add a pass statement to get rid of this !)
#pass
print "Run number {}".format(a)
a += 1
## The simplest possib... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: When you run a code cell, it is just the same as typing all the code into the interpreter. If you run a cell twice it is the same as if you type... |
6,124 | <ASSISTANT_TASK:>
Python Code:
import os
import random
import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
import tensorflow as tf
from tensorflow import keras
from learntools.core import binder; binder.bind(globals())
from learntools.embeddings.ex2_factorization import *
#_RM_
input_dir = '../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: Part 1
Step3: Suppose we're interested in the somewhat more open-ended problem of generating recommendations. i.e. given some user ID and some ... |
6,125 | <ASSISTANT_TASK:>
Python Code:
# Array
import numpy as np
x0 = np.array(12)
x0
x1 = np.array([12, 3, 6, 14])
x1
x1.ndim
x2 = np.array([[5, 78, 2, 34, 0],
[6, 79, 3, 35, 1],
[7, 80, 4, 36, 2]])
x2.ndim
x3 = np.array([[[5, 78, 2, 34, 0],
[6, 79, 3, 35, 1],
[7, 80, 4, 36, 2]],
[[5, 78, 2, 34, 0],
[6, 79, 3, 35, 1],
[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: Vectores (Tensores 1D)
Step2: El anterior vector tiene 5 entradas, por lo tanto es llamado vector 5-dimensional. La dimensionalidad puede denot... |
6,126 | <ASSISTANT_TASK:>
Python Code:
!date
import torch
import numpy as np
import math
import random
import torch.nn.functional as F
import matplotlib.pyplot as plt
from sklearn import gaussian_process
from sklearn.gaussian_process.kernels import Matern, WhiteKernel, ConstantKernel, RBF
from sklearn.utils import check_rando... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Introduction
Step2: Utility methods
Step3: Simulator
Step4: Core Idea
Step5: In order to find the optimal parameterization for the proposal ... |
6,127 | <ASSISTANT_TASK:>
Python Code:
!ls -la $LISA_HOME/libs/utils/platforms/
!cat $LISA_HOME/libs/utils/platforms/hikey.json
# Check which Android devices are available
!adb devices
ADB_DEVICE = '00b43d0b08a8a4b8'
# Unified configuration dictionary
my_conf = {
# Target platform
"platform" : 'android',
# Loca... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Single configuration dictionary
Step2: Energy Meters Support
Step3: Channels mapping support
Step4: Direct usage
Step5: Usage via TestEnv
St... |
6,128 | <ASSISTANT_TASK:>
Python Code:
import gcp.bigquery as bq
%%sql --module hn
DEFINE QUERY top_types
SELECT type, COUNT(*) c
FROM [fh-bigquery:hackernews.full_201510]
GROUP BY 1
ORDER BY 2
LIMIT 100
DEFINE QUERY counts
SELECT a.month month, stories, comments, comment_authors, story_authors
FROM (
SELECT STRFTIME_UTC_U... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Let's see what's our content, and how many of each we have
Step2: Nice start
Step3: Why is there a big drop on comments in 2014? I don't know,... |
6,129 | <ASSISTANT_TASK:>
Python Code:
import ipcoal
import toytree
import ipyrad.analysis as ipa
import ipyparallel as ipp
# connect to a running client
ipyclient = ipp.Client()
# show number of engines
ipyclient.ids
# make a random tree
tree = toytree.rtree.unittree(ntips=5, treeheight=5e5, seed=1243)
tree.draw(ts='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: Start an ipcluster instance
Step2: Simulate loci under a known scenario
Step3: Setup BPP
Step4: Submit BPP jobs to run on cluster (using ._ru... |
6,130 | <ASSISTANT_TASK:>
Python Code:
from __future__ import division, print_function, unicode_literals
[10.5, 5.2, 3.25, 7.0]
import numpy as np
video = np.array([10.5, 5.2, 3.25, 7.0])
video
video.size
video[2] # 3rd element
%matplotlib inline
import matplotlib.pyplot as plt
u = np.array([2, 5])
v = np.array([3, 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: Vectors
Step2: Since we plan to do quite a lot of scientific calculations, it is much better to use NumPy's ndarray, which provides a lot of co... |
6,131 | <ASSISTANT_TASK:>
Python Code:
x = (1,2,3,0,2,1) # Declaración de una tupla con valores numéricos
x # Imprimo tupla
x = (0, 'Hola', (1,2)) # Declaración de una tupla con diferentes tipos de datos
x[1] # Imprimo contenido de la posición 1
id(x)
x = (0, 'Cambio', (1,2))
id(x)
x
x... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Las tuplas son inmutables.
Step2: Listas
Step3: ¿Qué es más rapido
Step4: Referencia / asignacion
Step5: Diccionarios
Step6: Sets
Step7: ... |
6,132 | <ASSISTANT_TASK:>
Python Code:
import numpy as np
import pandas as pd
import statsmodels.api as sm
dta = sm.datasets.macrodata.load_pandas().data
dta.index = pd.PeriodIndex(start='1959Q1', end='2009Q3', freq='Q')
class LocalLevel(sm.tsa.statespace.MLEModel):
_start_params = [1., 1.]
_param_names = ['var.level'... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Introduction
Step2: There are two parameters in this model that must be chosen
Step3: We can look at the results from the numerical optimizer ... |
6,133 | <ASSISTANT_TASK:>
Python Code:
fruit = "pinapple"
letter = fruit[1]
print(letter)
letter = fruit[0]
print(letter)
letter = fruit[1.5]
fruit = 'banana'
len(fruit)
length = len(fruit)
fruit[length]
fruit[length-1]
fruit = 'pinapple'
index = 0
while index < len(fruit):
letter = fruit[index]
print(letter)
... | <SYSTEM_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 second statement selects character number 1 from fruit and assigns it to letter.
Step2: For most people, the first letter of 'pinapple' is ... |
6,134 | <ASSISTANT_TASK:>
Python Code:
# Plotting library.
import matplotlib.pyplot as plt
# For some math we need to do.
import numpy as np
# The HTRU 2 profile data is split - one file containing the real pulsar
# profiles, one file containing noise/interference profiles. We load both
# these data sources here. First we cons... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Now we plot a single example of both classes, to show what the data looks like. First the pulsar example.
Step2: It is clear that the peak is n... |
6,135 | <ASSISTANT_TASK:>
Python Code:
from openpathsampling.ensemble import SlicedTrajectoryEnsemble, SequentialEnsemble, AllInXEnsemble, AllOutXEnsemble, LengthEnsemble
from openpathsampling.collectivevariable import FunctionCV
from openpathsampling.volume import CVDefinedVolume
from openpathsampling.engines import Trajector... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Slicing the global trajectory for the whole SequentialEnsemble
Step2: Slicing the subtrajectory for a member of the SequentialEnsemble
Step3: ... |
6,136 | <ASSISTANT_TASK:>
Python Code:
from kaggle_environments import make, evaluate
# Create the game environment
# Set debug=True to see the errors if your agent refuses to run
env = make("connectx", debug=True)
# List of available default agents
print(list(env.agents))
# Two random agents play one game round
env.run(["ran... | <SYSTEM_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 "random" agent selects (uniformly) at random from the set of valid moves. In Connect Four, a move is considered valid if there's still spac... |
6,137 | <ASSISTANT_TASK:>
Python Code:
import graphlab
sales = graphlab.SFrame('kc_house_data.gl/')
# In the dataset, 'floors' was defined with type string,
# so we'll convert them to int, before using it below
sales['floors'] = sales['floors'].astype(int)
import numpy as np # note this allows us to refer to numpy as np 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: Load in house sales data
Step2: If we want to do any "feature engineering" like creating new features or adjusting existing ones we should do t... |
6,138 | <ASSISTANT_TASK:>
Python Code:
b = True
if b:
print('b is True')
b = False
if b:
print('b is True')
print('b is False')
b = False
if b:
print('b is True')
print('b is False')
b = False
if b:
print('b is True')
print('b is False')
b = True
if b:
print('b is True')
else:
print('b 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: Here, since b is in fact True, it passes the test, causing the code that is inset after the 'if b
Step2: will skip both print lines if b is Fal... |
6,139 | <ASSISTANT_TASK:>
Python Code:
# give access to importing dwarfz
import os, sys
dwarfz_package_dir = os.getcwd().split("dwarfz")[0]
if dwarfz_package_dir not in sys.path:
sys.path.insert(0, dwarfz_package_dir)
import dwarfz
# back to regular import statements
%matplotlib inline
from matplotlib import pyplot 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: Turn magnitudes into colors
Step2: Filter out bad data
Step3: Get FRANKENZ photo-z's
Step4: Create classification labels
Step5: Build Classi... |
6,140 | <ASSISTANT_TASK:>
Python Code:
import numpy as np
import matplotlib.pyplot as plt
import uncertainties as uct
from uncertainties import unumpy as unp
import pandas as pd
import pytheos as eos
v0 = uct.ufloat(74.698, 0.004)
k0 = uct.ufloat(160., 3.)
k0p = uct.ufloat(4.0, 0.3)
n_pts = 20
vv0 = np.linspace(1.,0.8, n_pt... | <SYSTEM_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. Assign uncertainties to the EOS parameters
Step2: We make a numpy array for volume at high pressure.
Step3: Calculate pressure from pytheos... |
6,141 | <ASSISTANT_TASK:>
Python Code:
import sys
sys.path.append('C:\Anaconda2\envs\dato-env\Lib\site-packages')
import graphlab
sales = graphlab.SFrame('kc_house_data.gl/')
from math import log, sqrt
sales['sqft_living_sqrt'] = sales['sqft_living'].apply(sqrt)
sales['sqft_lot_sqrt'] = sales['sqft_lot'].apply(sqrt)
sales['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: Load in house sales data
Step2: Create new features
Step3: Squaring bedrooms will increase the separation between not many bedrooms (e.g. 1) a... |
6,142 | <ASSISTANT_TASK:>
Python Code:
from pywed import * # Tore Supra database library
%pylab inline
pulse_list = np.loadtxt('data/liste_choc_fci.txt', dtype=int)
pulse_list = np.arange(44092, 48311, dtype='int')
ts_max_power = []
ts_max_duration = []
for pulse in pulse_list:
#print('Retrieve date for pulse {}'.format(pu... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: JET database
Step2: LHD
Step3: EAST
Step4: Plot
|
6,143 | <ASSISTANT_TASK:>
Python Code:
theta = 0.6
rv = sp.stats.bernoulli(theta)
rv
xx = [0, 1]
plt.bar(xx, rv.pmf(xx), align="center")
plt.xlim(-1, 2)
plt.ylim(0, 1)
plt.xticks([0, 1], ["X=0", "X=1"])
plt.ylabel("P(x)")
plt.title("pmf of Bernoulli distribution")
plt.show()
x = rv.rvs(100, random_state=0)
x
sns.countplot(x... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: pmf 메서드를 사용하면 확률 질량 함수(pmf
Step2: 시뮬레이션을 하려면 rvs 메서드를 사용한다.
Step3: 결과를 seaborn의 countplot 명령으로 시각화한다.
Step4: 이론적인 확률 분포와 샘플의 확률 분포를 동시에 나타내려면... |
6,144 | <ASSISTANT_TASK:>
Python Code:
import os
import collections
import json
import numpy as np
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
import tensorflow_hub as hub
import tensorflow_text as text
import tensorflow_addons as tfa
import matplotlib.pyplot as plt
import matplotli... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Prepare the data
Step2: Process and save the data to TFRecord files
Step3: Create tf.data.Dataset for training and evaluation
Step4: Implemen... |
6,145 | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
import numpy as np
import emcee
import matplotlib.pyplot as plt
def lnp(x, mu, icov):
diff = x-mu
return -np.dot(diff, np.dot(icov, diff))/2.0
ndim = 50
means = np.random.rand(ndim)
cov = 0.5 - np.random.rand(ndim**2).reshape((ndim,ndim))
cov = np.triu(cov)
co... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: function to evaluate $p(\vec{x}, \vec{\mu}, \Sigma^-1)$. Note that emcee requires log probability ($\ln p$) so this simplifies this problem.
Ste... |
6,146 | <ASSISTANT_TASK:>
Python Code:
from IPython.html.widgets import interact
from math import (sin, cos, tan)
from ipytangle import tangle
@interact
def interactor(fn=dict(sin=sin, cos=cos, tan=tan), x=(0, 360)):
print(fn(x))
trig_talk = tangle(interactor)
trig_talk
<END_TASK> | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: If you have defined an interact function, you can pull out all of the variables and put them in a tangle.
Step2: The fn_label function
|
6,147 | <ASSISTANT_TASK:>
Python Code:
import numpy
import pandas
from sklearn.cross_validation import cross_val_score
from sklearn.preprocessing import LabelEncoder, label_binarize
from sklearn.cross_validation import StratifiedKFold
from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import Pipeline
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: Load dataset
Step2: Dataset overview
Step3: Basic split
Step4: A basic benchmark
Step5: Social plane
|
6,148 | <ASSISTANT_TASK:>
Python Code:
from __future__ import division, print_function, unicode_literals
import numpy as np
np.zeros(5)
np.zeros((3,4))
a = np.zeros((3,4))
a
a.shape
a.ndim # equal to len(a.shape)
a.size
np.zeros((2,3,4))
type(np.zeros((3,4)))
np.ones((3,4))
np.full((3,4), np.pi)
np.empty((2,3))
np.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: Now let's import numpy. Most people import it as np
Step2: np.zeros
Step3: It's just as easy to create a 2D array (ie. a matrix) by providing ... |
6,149 | <ASSISTANT_TASK:>
Python Code:
from tf.fabric import Fabric
ETCBC = 'hebrew/etcbc4c'
PHONO = 'hebrew/phono'
TF = Fabric( modules=[ETCBC, PHONO], silent=False )
api = TF.load('''
book chapter verse
sp nu gn ps vt vs st
otype
det
g_word_utf8 trailer_utf8
lex_utf8 lex voc_utf8
g_prs_utf8 g_uvf_... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: 성서 본문을 큰 단위의 word node가 아닌 각 단어 요소들로 잘라서 출력함
Step2: Text feature가 아닌 feature의 g_word_utf8의 값을 이용하여 첫 번째 word node 출력
Step4: 위를 응용하여 창세기 1
Step... |
6,150 | <ASSISTANT_TASK:>
Python Code:
import scipy.optimize as so
import numpy
import toyplot
# if the coin is fair (p=0.5) then the probability isn't very high
p = 0.5
p * p * p * p * p
# but if the coin is really unfair then the probability if quite high
p = 0.99
p * p * p * p * p
# the probability of observing 20 heads 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: Optimization
Step2: Making things more concise
Step3: The goal of Maximum likelihood
Step4: Here we print the parameter of value of p used to... |
6,151 | <ASSISTANT_TASK:>
Python Code:
# DO NOT EDIT !
from pyesdoc.ipython.model_topic import NotebookOutput
# DO NOT EDIT !
DOC = NotebookOutput('cmip6', 'pcmdi', 'sandbox-3', 'toplevel')
# Set as follows: DOC.set_author("name", "email")
# TODO - please enter value(s)
# Set as follows: DOC.set_contributor("name", "... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Document Authors
Step2: Document Contributors
Step3: Document Publication
Step4: Document Table of Contents
Step5: 1.2. Model Name
Step6: 2... |
6,152 | <ASSISTANT_TASK:>
Python Code:
pct = cpm.PortfolioConsumerType(T_sim=5000, AgentCount=200)
pct.cycles = 0
# Solve the model under the given parameters
pct.solve()
pct.track_vars += [
"mNrm",
"cNrm",
"Share",
"aNrm",
"Risky",
"Adjust",
"PermShk",
"TranShk",
"bNrm",
"who_dies"
]
pc... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: TODO
Step2: Visualizing the Transition Equations
Step3: Building the Solver [INCOMPLETE]
|
6,153 | <ASSISTANT_TASK:>
Python Code:
from operator import itemgetter
rows_by_fname = sorted(rows, key=itemgetter('fname'))
rows_by_uid = sorted(rows, key=itemgetter('uid'))
rows_by_fname
rows_by_uid
rows_by_lfname = sorted(rows, key=itemgetter('lname','fname'))
rows_by_lfname
rows_by_fname = sorted(rows, key=lambda r: 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: The itemgetter() function can also accept multiple keys.
Step2: The functionality of itemgetter() is sometimes replaced by lambda expressions.
|
6,154 | <ASSISTANT_TASK:>
Python Code:
import torch
import torchvision
import torchvision.transforms as transforms
transform = transforms.Compose(
[transforms.ToTensor(),
transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])
trainset = torchvision.datasets.CIFAR10(root='./data', train=True,
... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: The output of torchvision datasets are PILImage images of range [0, 1].
Step2: Let us show some of the training images, for fun.
Step3: Define... |
6,155 | <ASSISTANT_TASK:>
Python Code:
import graphlab
loans = graphlab.SFrame('lending-club-data.gl/')
loans.column_names()
loans['safe_loans'] = loans['bad_loans'].apply(lambda x : +1 if x==0 else -1)
loans = loans.remove_column('bad_loans')
target = 'safe_loans'
features = ['grade', # grade of the lo... | <SYSTEM_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: Let's quickly explore what the dataset looks like. First, let's print out the column names to see what features... |
6,156 | <ASSISTANT_TASK:>
Python Code:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt # Plotting library
from sklearn.utils import shuffle
# Allow matplotlib to plot inside this notebook
%matplotlib inline
# Set the seed of the numpy random number generator so that the result is reproducable
np.random.... | <SYSTEM_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 2nd and 3rd column is numeric and need to be normalized. 1st, 4th and 5th colums are categorized variable. 5th column time_of_day will need ... |
6,157 | <ASSISTANT_TASK:>
Python Code:
import numpy as np
import tensorflow as tf
with open('../sentiment-network/reviews.txt', 'r') as f:
reviews = f.read()
with open('../sentiment-network/labels.txt', 'r') as f:
labels = f.read()
reviews[:2000]
from string import punctuation
all_text = ''.join([c for c in reviews 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: Data preprocessing
Step2: Encoding the words
Step3: Encoding the labels
Step4: If you built labels correctly, you should see the next output.... |
6,158 | <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: Quantization aware training comprehensive guide
Step2: Define quantization aware model
Step3: Quantize some layers
Step4: While this example ... |
6,159 | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
import pandas as pd
import requests as req
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
from scipy.stats import ttest_ind, ttest_rel
from scipy.stats import gaussian_kde
from statsmodels.formula.api import ols, mixedlm, gee
from statsmodels.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: Carregando dados de IDH-M da Wikipedia
Step2: Análise
Step3: Testando hipótese
Step4: A resposta de diversos testes, para um nível de 5% de s... |
6,160 | <ASSISTANT_TASK:>
Python Code:
from IPython.display import Image
Image(filename="YoungTwoSlitExperiment.JPG")
from IPython.display import Image
Image(filename="ExperimentoYoung.jpg")
from matplotlib.pyplot import *
from numpy import *
%matplotlib inline
style.use('fivethirtyeight')
###################################... | <SYSTEM_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 experiments I am about to relate ... may be repeated with great ease,
Step2: Según la figura, $\Delta = r_2 - r_1$ lo podemos escribir c... |
6,161 | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
!pip install -q numpyro@git+https://github.com/pyro-ppl/numpyro arviz
!pip install arviz
!pip install seaborn
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import arviz as az
import seaborn as sns
import numpyro
from numpyro.infer import MCMC, N... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Then, we'll load the data
Step2: The relevant part of the data we will model looks as follows
Step3: As you can see, we have multiple radon me... |
6,162 | <ASSISTANT_TASK:>
Python Code:
import pandas as pd
import numpy as np
import seaborn as sns
sns.set(rc={'figure.figsize':(10, 10)})
def set_payment_type(prob):
# 30% of transactions are cash
if prob < 0.3:
return 'Cash'
# stretch the remaining 0.3-1.0 to 0-1
prob = (prob-0.3)/0.7
if prob < 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: Bridging
Step2: How many samples do we need to evaluate properly?
Step3: Looking at this, it is clear that (on this problem) 3500 eval samples... |
6,163 | <ASSISTANT_TASK:>
Python Code:
%pylab inline
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from keras.datasets import mnist
from keras.models import Sequential
from keras.layers.core import Dense, Dropout, Activation
from keras.optimizers import SGD, RMSprop
from keras.utils import np_utils
fro... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Load the MNIST dataset, flatten the images, convert the class labels, and scale the data.
Step2: I. Basic example
Step3: Fit the model over 25... |
6,164 | <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:
Step1: Again, I'll load the NSFG pregnancy file and select live births
Step2: Here's the histogram of birth weights
Step3: To normalize the disrtibut... |
6,165 | <ASSISTANT_TASK:>
Python Code:
import collections
import glob
import os
from os import path
import matplotlib_venn
import pandas as pd
rome_path = path.join(os.getenv('DATA_FOLDER'), 'rome/csv')
OLD_VERSION = '337'
NEW_VERSION = '338'
old_version_files = frozenset(glob.glob(rome_path + '/*{}*'.format(OLD_VERSION)))
new... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: First let's check if there are new or deleted files (only matching by file names).
Step2: So we have the same set of files in both versions
Ste... |
6,166 | <ASSISTANT_TASK:>
Python Code:
temperature = float(input("Please enter the temperature: "))
if temperature<15:
print("It is too cold.")
print("Turn up the heating.")
temperature = float(input("Please enter the temperature: "))
if temperature<15:
print("It is too cold.")
print("Turn up the heating.")
el... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: If you've done it right, you should see a message to turn up heating the first time, but no message the second time
Step2: If you've done it ri... |
6,167 | <ASSISTANT_TASK:>
Python Code:
DATE = "170530" # "170704", "170530"
PLATE = "SI0012"
CONF = "conf170511mpc" # "conf170623mpc", "conf170511mpc"
QUADRANTS = [1] # [1, 2, 3, 4]
WRITE_PKL = False
UPDATE_SIMILAR = False
UPDATE_DATASTORE = False
for quadrant in QUADRANTS:... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Report Current Plate with Existing Data
Step2: Reference Plates
|
6,168 | <ASSISTANT_TASK:>
Python Code:
# Prepare my slides
%pylab inline
%cd working
!pncaqsraw4pnceval.py --help
from shapely.wkt import loads
geom = loads("POLYGON ((30 10, 40 35, 20 40, 10 20, 30 10))")
x, y = geom.exterior.xy
plt.plot(x, y, ls = '-', marker = 'o')
!pncaqsraw4pnceval.py -O --timeresolution=daily \
--... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Process AQS for evaluation
Step2: wktpolygon
Step3: CHECK POINT
Step4: Review Output
Step5: Extract GEOS-Chem at AQS
Step6: Reproduced in ... |
6,169 | <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: 使用 tf.function 提高性能
Step2: 定义一个辅助函数来演示可能遇到的错误类型:
Step3: 基础知识
Step4: Function 中可以嵌套其他 Function。
Step5: Function 的执行速度比 Eager 代码快,尤其是对于包含很多简单运... |
6,170 | <ASSISTANT_TASK:>
Python Code:
%pylab inline
pylab.style.use('ggplot')
import numpy as np
import pandas as pd
import cv2
import os
image_dir = os.path.join(os.getcwd(), 'font_images')
if not os.path.isdir(image_dir) or len(os.listdir(image_dir)) == 0:
print('no images found in {}'.format(image_dir))
img_mat = cv2.... | <SYSTEM_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 outline the processing for a single image.
Step2: Now we're ready to build image features. Let's take one of the images and work out ... |
6,171 | <ASSISTANT_TASK:>
Python Code:
import numpy as np
# We are going to implement five strategies.
# Each strategy takes as input the history of the turns played so far
# and returns 1 for cooperation and 0 for defection.
# 1) Always defect
def always_defect(previous_steps):
return 0
# 2) Always cooperate
def always_... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Implement the five strategies
Step2: Write a function that accepts the name of two strategies and competes them in a game of iterated prisone... |
6,172 | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
import numpy
import matplotlib.pyplot as plt
def A(P, r, n):
return P / r * ((1 + r)**n - 1)
n = numpy.linspace(0, 20, 100)
target = 5000
plt.hold(True)
for r in [0.02, 0.05, 0.08, 0.1, 0.12]:
plt.plot(n, A(100, r, n))
plt.plot(n, numpy.ones(n.shape) * target, '... | <SYSTEM_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 race
Step2: We need to calculate the function $f(x)$'s arc-length from $[0, 4 \pi]$
|
6,173 | <ASSISTANT_TASK:>
Python Code:
sp.random.seed(0)
x = sp.random.normal(size=1000)
x
ns, bins, ps = plt.hist(x, bins=10)
ns
bins
ps
pd.DataFrame([bins, ns/1000])
ns, bins, ps = plt.hist(x, bins=100)
pd.DataFrame([bins, ns/1000])
x = np.linspace(-3, 3, 100)
y = sp.stats.norm.pdf(x)
plt.plot(x, y)
<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: 이 히스토그램에서 -0.143394 부터 0.437156 사이의 값이 전체의 약 24%를 차지하고 있음을 알 수 있다. 그럼 만약 -0.01 부터 0.01 사이의 구간에 대한 정보를 얻고 싶다면? 더 세부적인 구간에 대해 정보를 구하고 싶다면 히스토그램의 ... |
6,174 | <ASSISTANT_TASK:>
Python Code:
Minimal character-level Vanilla RNN model. Written by Andrej Karpathy (@karpathy)
BSD License
import numpy as np
# data I/O
data = open('methamorphosis.txt', 'r').read() # should be simple plain text file
chars = list(set(data))
data_size, vocab_size = len(data), len(chars)
print 'data ha... | <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: Minimal character-level Vanilla RNN model.
Step5: If you are not a NN expert, the code is not easy to understand.
Step6: Encode/Decode char/... |
6,175 | <ASSISTANT_TASK:>
Python Code:
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import statsmodels.api as sm
from statsmodels import regression
from scipy import poly1d
x = np.arange(10)
y = 2*np.random.randn(10) + x**2
xs = np.linspace(-0.25, 9.25, 200)
lin = np.polyfit(x, y, 1)
quad = np.polyfit... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: When working with real data, there is unlikely to ever be a situation where a ninth-degree polynomial is appropriate
Step2: However, when we us... |
6,176 | <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... |
6,177 | <ASSISTANT_TASK:>
Python Code:
%reload_ext XTIPython
%matplotlib inline
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
from ipywidgets import FloatProgress
from IPython.display import display
import subprocess,sys,os,json
FFPROBE_BIN = "ffprobe.exe"
FFMPEG_BIN = "ffmpeg.exe"
def get_json_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: Loading a video and extracting the frames
Step2: Estimate the background
Step3: Maggots extraction
Step4: An additional step (not absolutely ... |
6,178 | <ASSISTANT_TASK:>
Python Code:
%run "recurrences.py"
%run "sums.py"
%run "start_session.py"
from itertools import accumulate
def accumulating(acc, current): return Eq(acc.lhs + current.lhs, acc.rhs + current.rhs)
mapped = list(accumulate(mapped, accumulating))
mapped
clear_cache()
m,v,r = to_matrix_notation(mapped, 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: A generalization using accumulation
Step2: According to A162741, we can generalize the pattern above
Step3: Unfolding a recurrence with generi... |
6,179 | <ASSISTANT_TASK:>
Python Code:
2 * (1 + 2 + 3 + 4 + 5 + 6)
3.2 * 18 - 2.1
1.5e-10 * 1000
import math
math.sqrt(2)
width = 20
length = 30
area = length*width
area
'I love Structural Geology!'
"I love Structural Geology!"
'''I love
Structural
Geology'''
"He's a geologist"
'She asked, "Are you crazy?"'
greeting = "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: Scientific notation
Step2: Python has a number of defined operators for handling numbers through arithmetic calculations, logic operations (tha... |
6,180 | <ASSISTANT_TASK:>
Python Code:
#sign:max: MAXBOX8: 03/02/2021 18:34:41
# optimal moving average OMA for market index signals ARIMA study- Max Kleiner
# v2 shell argument forecast days - 4 lines compare - ^GDAXI for DAX
# pip install pandas-datareader
# C:\maXbox\mX46210\DataScience\princeton\AB_NYC_2019.csv AB_NYC_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:
Step2: <a href="https
Step3: Step by Step Code Order
Step4: A p-value less than 0.05 (typically ≤ 0.05) is statistically significant. It indicates st... |
6,181 | <ASSISTANT_TASK:>
Python Code:
theta0 = 0.6
x = sp.stats.bernoulli(theta0).rvs(1000)
N0, N1 = np.bincount(x, minlength=2)
N = N0 + N1
theta = N1/N
theta
theta0 = np.array([0.1, 0.3, 0.6])
x = np.random.choice(np.arange(3), 1000, p=theta0)
N0, N1, N2 = np.bincount(x, minlength=3)
N = N0 + N1 + N2
theta = np.array([N0, ... | <SYSTEM_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: 다변수 정규 분포의 모수 추정
|
6,182 | <ASSISTANT_TASK:>
Python Code:
import ipyrad as ip
## create an Assembly object named data1.
data1 = ip.Assembly("data1")
## create an Assembly object linked to 8 engines using MPI
data1 = ip.Assembly("data1", N=4, controller="MPI")
## setting/modifying parameters for this Assembly object
data1.set_params('project_... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Assembly objects
Step2: The printout tells us that we created the object data1, and also that it found 4 engines on our system that can be used... |
6,183 | <ASSISTANT_TASK:>
Python Code:
# enable plotting in notebook
%matplotlib notebook
from simulation_results import example_simulations
import physical_validation
simulation_vrescale = example_simulations.get(
"900 water molecules, NVT at 298K with v-rescale thermostat"
)
simulation_berendsen = example_simulations.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: The results imported here are the time series of kinetic and potential energy from example simulations, which are
Step2: In this example, we wi... |
6,184 | <ASSISTANT_TASK:>
Python Code:
def func(x):
return x[0]**2 + 2*x[1]**2 + 3*x[2]**2
def con(x):
return x[0] + x[1] + x[2] - 3.5 # rewritten in form c <= 0
x = [1.0, 1.0, 1.0]
sigma = [0.00, 0.06, 0.2]
import numpy as np
def stats(n):
f = np.zeros(n)
c = np.zeros(n)
for i in range(n):
x1 = x... | <SYSTEM_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 use randn, which gives us a random number k sampled from a normal distribution. It is sampled from a unit normal with zero mean and a s... |
6,185 | <ASSISTANT_TASK:>
Python Code:
from jyquickhelper import add_notebook_menu
add_notebook_menu()
from pyensae.datasource import download_data
download_data("ensae_competition_2016.zip",
url="https://github.com/sdpython/ensae_teaching_cs/raw/master/_doc/competitions/2016_ENSAE_2A/")
%matplotlib inline
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: Données
Step2: Choix du Classifieur
Step3: Calcul du critère AUC
Step4: Tous les critères sont détaillés là. Attention au sens de la matrice ... |
6,186 | <ASSISTANT_TASK:>
Python Code:
import keras
from keras.models import Sequential
from PIL import Image
import numpy as np
import tarfile
# 下載 dataset
url = "https://www.cs.toronto.edu/~kriz/cifar-10-python.tar.gz"
import os
import urllib
from urllib.request import urlretrieve
def reporthook(a,b,c):
print("\rdownload... | <SYSTEM_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: Q
|
6,187 | <ASSISTANT_TASK:>
Python Code:
#!pip install -I "phoebe>=2.4,<2.5"
import phoebe
import numpy as np
b = phoebe.default_binary()
b.flip_constraint('mass@secondary', solve_for='q')
b.set_value(qualifier='mass', component='secondary', value=0.2)
b.set_value(qualifier='requiv', component='secondary', value=0.2)
b.set_val... | <SYSTEM_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 set reasonable (although not necessarily physical) values fo... |
6,188 | <ASSISTANT_TASK:>
Python Code:
# Installation
#!pip install boruta
import pandas as pd
from sklearn.datasets import load_iris
from sklearn.ensemble import RandomForestClassifier
from boruta import BorutaPy
def load_data():
# URLS for dataset via UCI
train_data_url='https://archive.ics.uci.edu/ml/machine-learnin... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Boruta conforms to the sklearn api and can be used in a Pipeline as well as on it's own. Here we will demonstrate stand alone operation.
Step2: ... |
6,189 | <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: Keras Tuner 소개
Step2: Keras Tuner를 설치하고 가져옵니다.
Step3: 데이터세트 다운로드 및 준비하기
Step4: 모델 정의하기
Step5: 튜너를 인스턴스화하고 하이퍼튜닝 수행하기
Step6: Hyperband 튜닝 알고... |
6,190 | <ASSISTANT_TASK:>
Python Code:
# Load libraries
from sklearn import preprocessing
import numpy as np
# Create feature
x = np.array([[-500.5],
[-100.1],
[0],
[100.1],
[900.9]])
# Create scaler
minmax_scale = preprocessing.MinMaxScaler(feature_range=(0, 1))
# ... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Create Feature
Step2: Rescale Feature Using Min-Max
|
6,191 | <ASSISTANT_TASK:>
Python Code:
# Initialize
import pandas as pd
import numpy as np
import pip #needed to use the pip functions
# Show versions of all installed software to help debug incompatibilities.
for i in pip.get_installed_distributions(local_only=True):
print(i)
try:
df_label_vendors = pd.io.parsers.rea... | <SYSTEM_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 the vendor training data
Step2: Use a grid search to tune the ML algorithm
Step3: Run the ML classifier with optimum parameters on the... |
6,192 | <ASSISTANT_TASK:>
Python Code:
# DO NOT EDIT !
from pyesdoc.ipython.model_topic import NotebookOutput
# DO NOT EDIT !
DOC = NotebookOutput('cmip6', 'ipsl', 'sandbox-3', 'landice')
# Set as follows: DOC.set_author("name", "email")
# TODO - please enter value(s)
# Set as follows: DOC.set_contributor("name", "em... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Document Authors
Step2: Document Contributors
Step3: Document Publication
Step4: Document Table of Contents
Step5: 1.2. Model Name
Step6: 1... |
6,193 | <ASSISTANT_TASK:>
Python Code:
import pandas as pd
df = pd.read_excel("https://github.com/chris1610/pbpython/blob/master/data/sample-sales-reps.xlsx?raw=true")
df.head()
df["commission"] = .02
df.head()
df.loc[df["category"] == "Shirt", ["commission"]] = .025
df.head()
df.loc[(df["category"] == "Belt") & (df["quanti... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Add a default commision rate of 2% for all sales
Step2: Since shirts are high margin, adjust all products in the shirt categort with a commissi... |
6,194 | <ASSISTANT_TASK:>
Python Code:
import graphlab
people = graphlab.SFrame('people_wiki.gl/')
people.head()
len(people)
obama = people[people['name'] == 'Barack Obama']
obama
obama['text']
clooney = people[people['name'] == 'George Clooney']
clooney['text']
obama['word_count'] = graphlab.text_analytics.count_words(ob... | <SYSTEM_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 some text data - from wikipedia, pages on people
Step2: Data contains
Step3: Explore the dataset and checkout the text it contains
Step4:... |
6,195 | <ASSISTANT_TASK:>
Python Code:
# ### uncomment below if you want...
# ## ... copious amounts of logging info
# import logging
# logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)
# rootLogger = logging.getLogger()
# rootLogger.setLevel(logging.INFO)
# ## ... or auto-reload of ge... | <SYSTEM_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 define a super simple parser
Step2: And put everything together in a review generator that provides tokenized sentences and the numbe... |
6,196 | <ASSISTANT_TASK:>
Python Code:
import xml.etree.ElementTree as ET
parameter_values = (('num_sweeps', '30'),
('num_simulations', '1'),
('num_banks', '1'),
('num_firms', '1'),
('num_households', '1'),
('bank_directory', '... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Below you will find the parameter inputs for this model.
Step2: To translate this to an xml document, which the framework can read, we first ne... |
6,197 | <ASSISTANT_TASK:>
Python Code:
%config InlineBackend.figure_format = 'retina'
import numpy as np
import matplotlib.pyplot as plt
def f(x):
r = np.exp(-1 / x ** 2)
r[x == 0] = 0
return r
rg = np.linspace(-10, 10, 401)
plt.plot(rg, f(rg))
def get_expansion(sigma):
nexpansion = 6
N = 1000
X = sigm... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Doesn't look too promising! It's very flat at 0. All of its derivatives are exactly 0. However, even though its Taylor expansion is null, we can... |
6,198 | <ASSISTANT_TASK:>
Python Code:
!pip install -q numpyro@git+https://github.com/pyro-ppl/numpyro
from functools import partial
import numpy as np
import jax.numpy as jnp
from jax import random
import numpyro
import numpyro.distributions as dist
from numpyro.diagnostics import summary
from numpyro.infer import MCMC, NUTS
... | <SYSTEM_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 begin by writing a helper function to do NUTS inference.
Step2: Evaluating HMC/NUTS
Step3: To deal with the bad geometry that results form ... |
6,199 | <ASSISTANT_TASK:>
Python Code:
# this line is required to see visualizations inline for Jupyter notebook
%matplotlib inline
# importing modules that we need for analysis
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
# read the data from file and print out first few rows and columns
thanksgiving... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Hypothesis 1 - "The most preferred food for Thanksgiving is turkey."
Step2: Let's look at all unique answers given for main dish at Thanksgivin... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.