Unnamed: 0 int64 0 15.9k | cleaned_code stringlengths 67 124k ⌀ | cleaned_prompt stringlengths 168 30.3k ⌀ |
|---|---|---|
9,300 | <ASSISTANT_TASK:>
Python Code:
from sklearn.datasets import load_digits
digits = load_digits()
plt.imshow(digits.images[0], interpolation='nearest');
plt.grid(False)
digits.images[0]
from sklearn.datasets import fetch_20newsgroups
news = fetch_20newsgroups()
print(news.data[0])
from sklearn.feature_extraction.text impo... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: 예측도 출력 데이터가 숫자인가 카테고리 값인가에 따라 회귀 분석(regression analysis)과 분류(classification)로 구분된다.
Step2: 분류
Step3: 클러스터링(Clustering)
Step4: 모사(Approximatio... |
9,301 | <ASSISTANT_TASK:>
Python Code:
# Import required packages
import numpy as np
from sklearn import linear_model, decomposition, datasets
from sklearn.pipeline import Pipeline
from sklearn.model_selection import GridSearchCV, cross_val_score
from sklearn.preprocessing import StandardScaler
# Load the breast cancer data
d... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Load Data
Step2: Create Pipelines
Step3: Create Parameter Space
Step4: Conduct Parameter Optmization With Pipeline
Step5: Use Cross Validati... |
9,302 | <ASSISTANT_TASK:>
Python Code:
import pandas as pd
pd.Timestamp("today")
new_years_dinner = pd.Timestamp("2020-01-01 19:00")
new_years_dinner
time_needed_to_sober_up = pd.Timedelta("1 day")
time_needed_to_sober_up
completely_sober = new_years_dinner + time_needed_to_sober_up
completely_sober
dates = pd.DataFrame(
... | <SYSTEM_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 put in some standard date formats. Pandas' will convert them accordingly.
Step2: We can also create relative time information
Step3: W... |
9,303 | <ASSISTANT_TASK:>
Python Code:
import numpy as np
import matplotlib.pyplot as plt #Esta es otra forma de importar el submódulo pyplot!
#Igual de válida que la que hemos visto en clase
%matplotlib inline
# Introduce aquí tu código
# Introduce aquí tu código
# Introduce aquí tu código
... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Hasta ahora, hemos trabajado con vectores, aplicándolos a la resolución de la ecuación de convección en 1-D. Vamos a ver ahora cómo resolver la ... |
9,304 | <ASSISTANT_TASK:>
Python Code:
import numpy as np
np.random.seed(data_id)
data = np.random.randn(100)
analysis_dict = dict(a=np.mean, b=np.max, c=np.min)
result = analysis_dict[analysis_type](data)
print('Result of analysis "%s" on dataset %d is %.3f.' % (analysis_type, data_id, 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:
Step1: Processing
|
9,305 | <ASSISTANT_TASK:>
Python Code:
#@title Setup Environment
#@test {"output": "ignore"}
import glob
BASE_DIR = "gs://download.magenta.tensorflow.org/models/music_vae/colab2"
print('Installing dependencies...')
!apt-get update -qq && apt-get install -qq libfluidsynth1 fluid-soundfont-gm build-essential libasound2-dev libja... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Copyright 2017 Google LLC.
Step2: 2-Bar Drums Model
Step3: Generate Samples
Step4: Generate Interpolations
Step5: 2-Bar Melody Model
Step6: ... |
9,306 | <ASSISTANT_TASK:>
Python Code:
# This line is a comment -- it does nothing
# you can add comments using the '#' symbol
1+1
3*5 # this will not print
14 % 3 # modulo (remainder) operator - this will print
print(3*5)
print(2**4) # powers use the double star symbol
output = 1+1
type(output)
type(1.+1.2)
1.0+1.2
# ... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: You can do math - any output on the last line of the cell will print to the screen
Step2: You can print anything by passing it to the print fu... |
9,307 | <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 wr... | <SYSTEM_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 colab shows how to use CARLS to train a model with regularization more efficiently.
Step4: Prepare dataset and build the package with baze... |
9,308 | <ASSISTANT_TASK:>
Python Code:
def bread(test_funct):
def hyderabad():
print("</''''''\>")
test_funct()
print("<\______/>")
return hyderabad
def ingredients(test_funct):
def chennai():
print("#tomatoes#")
test_funct()
print("~salad~")
return chennai
def ch... | <SYSTEM_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 Decorators
Step2: !!! Order Matters !!!
Step3: Decorators with arguments
Step4: Class Decorators
Step5: staticmethod()
Step6: When... |
9,309 | <ASSISTANT_TASK:>
Python Code:
import os
import matplotlib.pyplot as plt
import matplotlib.colors as colors
import numpy as np
import openmc
%matplotlib inline
# Create a 7-group structure with arbitrary boundaries (the specific boundaries are unimportant)
groups = openmc.mgxs.EnergyGroups(np.logspace(-5, 7, 8))
uo2_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 now create the multi-group library using data directly from Appendix A of the C5G7 benchmark documentation. All of the data below will b... |
9,310 | <ASSISTANT_TASK:>
Python Code:
import pynq
rails = pynq.get_rails()
rails
recorder = pynq.DataRecorder(rails['12V'].power)
import time
with recorder.record(0.5):
time.sleep(10)
for _ in range(10000000):
pass
time.sleep(10)
recorder.frame
%matplotlib inline
recorder.frame['12V_power'].plot()
rec... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: As can be seen, the keys of the dictionary are the names of the voltage rails while the values are Rail objects which contain three sensors for ... |
9,311 | <ASSISTANT_TASK:>
Python Code:
# DO NOT EDIT !
from pyesdoc.ipython.model_topic import NotebookOutput
# DO NOT EDIT !
DOC = NotebookOutput('cmip6', 'mohc', 'sandbox-1', 'land')
# Set as follows: DOC.set_author("name", "email")
# TODO - please enter value(s)
# Set as follows: DOC.set_contributor("name", "email... | <SYSTEM_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... |
9,312 | <ASSISTANT_TASK:>
Python Code:
ph_sel_name = "None"
data_id = "7d"
# data_id = "7d"
from fretbursts import *
init_notebook()
from IPython.display import display
data_dir = './data/singlespot/'
import os
data_dir = os.path.abspath(data_dir) + '/'
assert os.path.exists(data_dir), "Path '%s' does not exist." % data_dir
... | <SYSTEM_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 software and filenames definitions
Step2: Data folder
Step3: List of data files
Step4: Data load
Step5: Load the leakage coefficient fr... |
9,313 | <ASSISTANT_TASK:>
Python Code:
# Import TensorFlow and some other libraries we'll be using.
import datetime
import numpy as np
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
# Download the MNIST dataset onto the local machine.
mnist = input_data.read_data_sets("MNIST_data/", one_hot=... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Visualizing the MNIST data
Step3: Building a Feed-Forward Neural Network
Step5: Now let's use this to construct a linear softmax classifier as... |
9,314 | <ASSISTANT_TASK:>
Python Code:
from astroquery.gaia import Gaia
tables = Gaia.load_tables(only_names=True)
for table in (tables):
print (table.get_qualified_name())
#obj = ["3C 454.3", 343.49062, 16.14821, 1.0]
obj = ["PKS J0006-0623", 1.55789, -6.39315, 1]
#obj = ["M87", 187.705930, 12.391123, 1.0]
#### name, ra, ... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Try GAIA with 2MASS
Step2: Try GAIA and WISE
Step3: Try GAIA + WISE with ProperMotion limit
Step4: Try GAIA-WISE-2MASS directly
|
9,315 | <ASSISTANT_TASK:>
Python Code:
# Authors: Remi Flamary <remi.flamary@unice.fr>
# Stanislas Chambon <stan.chambon@gmail.com>
#
# License: MIT License
import matplotlib.pylab as pl
import ot
n_samples_source = 150
n_samples_target = 150
Xs, ys = ot.datasets.make_data_classif('3gauss', n_samples_source)
Xt, yt =... | <SYSTEM_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 data
Step2: Transport source samples onto target samples
Step3: Fig 1
Step4: Fig 2
Step5: Fig 3
|
9,316 | <ASSISTANT_TASK:>
Python Code:
#!pip install --user --upgrade python-keystoneclient
#!pip install --user --upgrade python-swiftclient
credentials = {
'auth_uri':'',
'global_account_auth_uri':'',
'username':'xx',
'password':"xx",
'auth_url':'https://identity.open.softlayer.com',
'project':'xx',
'project_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: Find Your Object Storage Credentials
Step2: Now use the SwiftClient connection to programmatically
|
9,317 | <ASSISTANT_TASK:>
Python Code:
# load the training data
data = pd.read_csv(os.path.abspath('__file__' + "/../../../data/TrainSet.txt"),sep='\t')
data.drop(['Intensity','Odor','Replicate','Dilution'],axis=1, inplace=1)
data.columns = ['#oID', 'individual'] + list(data.columns)[2:]
data.head()
# load leaderboard data 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: target data for training
|
9,318 | <ASSISTANT_TASK:>
Python Code:
import sys
import pandas as pd
import matplotlib.pyplot as plt
import datetime as dt
import numpy as np
import seaborn as sns
import statistics
import csv
from scipy import stats
from bs4 import BeautifulSoup as bs
import urll... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Google Places API Configuration
Step2: Write a function to calculate the distance from each listing to top trip advisor attractions
Step3: 2. ... |
9,319 | <ASSISTANT_TASK:>
Python Code:
import numpy as np
import pymc3 as pm
from pymc3.distributions.timeseries import GaussianRandomWalk
from scipy.sparse import csc_matrix
from scipy import optimize
%pylab inline
n = 400
returns = np.genfromtxt("data/SP500.csv")[-n:]
returns[:5]
plt.plot(returns)
model = pm.Model()
with 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: Asset prices have time-varying volatility (variance of day over day returns). In some periods, returns are highly variable, while in others very... |
9,320 | <ASSISTANT_TASK:>
Python Code:
poly = 0x104c1
crc = crcmod.mkCrcFun(poly, initCrc=0, xorOut=0x0, rev=False)
# Now consider two CRC values obtained from two 1-bit messages,
# where the 1 bits are in adjacent positions. The resulting CRCs
# will differ by just one shift-xor cycle. To be precise, if
# C1 corresponds to ... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: crc diffs from observed omnipod single bit diff messages
Step2: Look at single bit diffs with unshift_xor()
|
9,321 | <ASSISTANT_TASK:>
Python Code:
# Run this to import pre-defined problems
from aipython.searchProblem import search_simple1, search_simple2, search_cyclic_delivery, search_acyclic_delivery, search_tree, search_extended_tree, search_cyclic, search_vancouver_neighbour, search_misleading_heuristic, search_multiple_path_pru... | <SYSTEM_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 also define your own problems (how?).
Step2: 3.5.2 Depth-First Search
Step3: 3.6.1 A* Search
Step4: 3.7.2 A* Search with Multiple Pa... |
9,322 | <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: Image classification with TensorFlow Lite Model Maker
Step2: Import the required packages.
Step3: Simple End-to-End Example
Step4: You could ... |
9,323 | <ASSISTANT_TASK:>
Python Code:
from ufl import transpose
from dolfin import *
from rbnics import *
@ExactParametrizedFunctions()
@PullBackFormsToReferenceDomain()
@ShapeParametrization(
("x[0]", "x[1]"), # subdomain 1
("x[0]", "mu[1] / 2. * x[1] + (2. - mu[1])"), # subdomain 2
)
class NavierStokes(NavierStok... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: 3. Affine Decomposition
Step2: 4. Main program
Step3: 4.2. Create Finite Element Space (Taylor-Hood P2-P1)
Step4: 4.3. Allocate an object of ... |
9,324 | <ASSISTANT_TASK:>
Python Code:
import numpy as np
import matplotlib.pyplot as plt
import pytheos as eos
import uncertainties as uct
from uncertainties import unumpy as unp
v0 = {'Pt': 3.9231**3, 'Au': 4.07860**3, 'MgO': 74.698}
k0 = {'Pt': 277.3, 'Au': 167.0, 'MgO': 160.3}
k0p = {'Pt': uct.ufloat(5.226, 0.033), 'Au': ... | <SYSTEM_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. Vinet EOS
Step2: Set pressure range and number of data points.
Step3: Calculate volume of MgO at different pressures.
Step4: 3. What if yo... |
9,325 | <ASSISTANT_TASK:>
Python Code:
import numpy as np
fname = './data/tsurf.nc'
import xarray as xr
ds = xr.open_dataset(fname)
print(ds)
import Nio
f = Nio.open_file(fname,"r")
print(f)
coords = ds.coords
variables = ds.variables
print('--> coords: \n\n', coords)
print('--> variables: \n\n', variables)
coords_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: 1. xarray
Step2: Printing the dataset content gives you an overview of the dimension and variable names, their sizes, and the global file attri... |
9,326 | <ASSISTANT_TASK:>
Python Code:
import numpy as np
import holoviews as hv
hv.notebook_extension()
np.set_printoptions(precision=2, linewidth=80)
%opts HeatMap (cmap="hot")
def f(x,y):
return x+y/3.1
region=(-0.5,-0.5,0.5,0.5)
def coords(bounds,samples):
l,b,r,t=bounds
hc=0.5/samples
return np.mesh... | <SYSTEM_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 consider
Step2: Now let's build a Numpy array regularly sampling this function at a density of 5 samples per mm
Step3: We can vis... |
9,327 | <ASSISTANT_TASK:>
Python Code:
# imports
import h2o
from h2o.estimators.deeplearning import H2ODeepLearningEstimator
from h2o.grid.grid_search import H2OGridSearch
# display matplotlib graphics in notebook
%matplotlib inline
# start and connect to h2o server
h2o.init()
# load clean data
path = '../data/'
# define inp... | <SYSTEM_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 data
Step2: Train MLP using random grid search
Step3: Select best model
Step5: Best known H2O MLP for MNIST
Step7: Create Submission
|
9,328 | <ASSISTANT_TASK:>
Python Code:
sp.random.seed(0)
x = sp.random.normal(size=1000)
ns, bins, ps = plt.hist(x, bins=10)
plt.show()
pd.DataFrame([bins, ns/1000])
ns, bins, ps = plt.hist(x, bins=100)
plt.show()
pd.DataFrame([bins, ns/1000])
x = np.linspace(-3, 3, 100)
y = sp.stats.norm.pdf(x)
plt.plot(x, y)
plt.show()
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: 히스토그램을 그리면 다음과 같다.
Step2: 이 히스토그램에서 -0.143394 부터 0.437156 사이의 값이 전체의 약 24%를 차지하고 있음을 알 수 있다. 그럼 만약 -0.01 부터 0.01 사이의 구간에 대한 정보를 얻고 싶다면? 더 세부적인... |
9,329 | <ASSISTANT_TASK:>
Python Code:
2 + 3
2 / 3
2 * 3
2 ** 3
num = 2 ** 3
print(num)
num
type(num)
name = "The Hacker Within"
type(name)
name + 8
name + str(8)
num_list = [0,1,2,3,4,5,6,7,8]
print(num_list)
type(num_list)
num_list[3]
num_list[3] = 10
print(num_list)
num_list.append(3)
print(num_list)
for num in num_list... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Variables
Step2: Lists
Step3: Appending new items to a list
Step4: Loops and iteration
Step5: If / else conditionals
Step6: Functions
Step7... |
9,330 | <ASSISTANT_TASK:>
Python Code:
s_data = data[['P', 'S', 'L', 'R', 'A', 'RW', 'TS', 'TT']]
s_data.describe()
print(data['CITY_NAME'].value_counts())
print(data.pivot_table(index=['TDQ'], columns=['CITY_NAME']))
print(data.pivot_table(index=['TDQ'], columns=['BLOCK']))
data['P'].hist() ... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: 市区町村別の件数を集計
Step2: 成約時点別×市区町村別の件数を集計
Step3: 成約時点別×地域ブロック別の件数を集計
Step4: Histogram
Step5: 価格(自然対数)
Step6: 建築後年数
Step7: Plot
Step8: Main Ana... |
9,331 | <ASSISTANT_TASK:>
Python Code:
import sys
sys.path.append('../..')
from bestPy import write_log_to
from bestPy.datastructures import Transactions
from bestPy.algorithms import Baseline, CollaborativeFiltering # Additionally import CollaborativeFiltering
logfile = 'logfile.txt'
write_log_to(logfile, 20)
file = 'exampl... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Imports, logging, and data
Step2: Creating a new CollaborativeFiltering object with data
Step3: Parameters of the collaborative filtering algo... |
9,332 | <ASSISTANT_TASK:>
Python Code:
import re
m = re.match('foo', 'foo')
if m is not None: m.group()
m
m = re.match('foo', 'bar')
if m is not None: m.group()
re.match('foo', 'foo on the table').group()
# raise attributeError
re.match('bar', 'foo on the table').group()
m = re.match('foo','seafood')
if m is not None: m.gro... | <SYSTEM_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.3 search
Step2: search 函数将返回字符串开始模式首次出现的位置
Step3: 2.4 匹配多个字符串
Step4: 2.5 匹配任意单个字符(.)
Step5: 2.6 创建字符集合([ ])
Step6: 2.7 分组
Step7: 2.7.2 分... |
9,333 | <ASSISTANT_TASK:>
Python Code:
%load_ext autoreload
%autoreload 2
%matplotlib inline
import os
import matplotlib.pyplot as plt
import numpy as np
from pyspark.sql.functions import col, max
import systemml # pip3 install systemml
from systemml import MLContext, dml
plt.rcParams['figure.figsize'] = (10, 6)
ml = MLContex... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Read in train & val data
Step2: Extract X and Y matrices
Step4: Convert to SystemML Matrices
Step6: Trigger Caching (Optional)
Step8: Save M... |
9,334 | <ASSISTANT_TASK:>
Python Code:
import json
import os
import numpy as np
import pandas as pd
import pickle
import uuid
import time
import tempfile
from googleapiclient import discovery
from googleapiclient import errors
from google.cloud import bigquery
from jinja2 import Template
from kfp.components import func_to_cont... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Run the command in the cell below to install gcsfs package.
Step2: Prepare lab dataset
Step3: Next, create the BigQuery dataset and upload the... |
9,335 | <ASSISTANT_TASK:>
Python Code:
import numpy as np
a = np.array(range(10000000))
b = np.array(range(9999999,-1,-1))
%%time
a = a + b
a = np.array(range(10000000))
b = np.array(range(9999999,-1,-1))
%%time
a +=b
#Apply function to a complete array instead of writing loop to iterate over all elements of the array.
#... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Case 1
Step2: Case 2
Step3: 2. Vectorization
Step4: 3. Slicing and reshape
Step5: Array shape manipulation
Step6: Exercise
Step7: 2. Creat... |
9,336 | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
import openmc
fuel = openmc.Material(name='fuel')
fuel.add_nuclide('U235', 1.0)
fuel.set_density('g/cm3', 10.0)
fuel2 = openmc.Material(name='fuel2')
fuel2.add_nuclide('U238', 1.0)
fuel2.set_density('g/cm3', 10.0)
water = openmc.Material(name='water')
water.add_nuclide(... | <SYSTEM_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 our three materials, we will set up two universes that represent pin-cells
Step2: Now let's create a hexagonal lattice using the HexLattic... |
9,337 | <ASSISTANT_TASK:>
Python Code:
bar = BarGlyph(label='a', values=[1])
bar.data
bar = BarGlyph(label='a', values=[1, 2, 3, 4])
bar.data
bar = BarGlyph('a', 1)
bar.data
bar1 = BarGlyph('foo', 1)
bar2 = BarGlyph('foo', 2)
print('No stacking')
print('bar1 y: %s, bar2 y: %s' % (bar1.data['y'], bar2.data['y']) )
from boke... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Bar from multiple values
Step2: Simplified input using same order
Step3: Operations on Composite Glyphs
Step4: Stacked
Step5: Producing Comb... |
9,338 | <ASSISTANT_TASK:>
Python Code:
!wget ftp://igs.bkg.bund.de/EUREF/BRDC/2022/033/BRDC00WRD_R_20220330000_01D_MN.rnx.gz
pip install wget
import wget
from datetime import date
def download_rinex_navigation(ftp, rpath, my_date):
doy = my_date.strftime('%j')
year = my_date.strftime('%Y')
url = ftp + rpath + year + '... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: In order to use wget inside a Python program, you have to install it with pip
Step2: Then, you have to import the wget package
Step3: Now, let... |
9,339 | <ASSISTANT_TASK:>
Python Code:
from numpy import sqrt
from qutip import *
N = 10 # pick a size for our state-space
a = destroy(N)
n = a.dag()*a
a*a.dag() - a.dag()*a
n*a.dag() - a.dag()*n
n*a.dag() - a.dag()*n == a.dag()
psi = basis(N,2)
psi
a.dag()*psi
a.dag()*basis(N,2) == sqrt(3)*basis(N,3)
a
a.dag()
X = 1/2 ... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Define the standard operators
Step2: Problem 12.1
Step3: Problem 12.2
Step4: Problem 12.3 (use n=2 as a test-case)
Step5: Problem 12.5 and 1... |
9,340 | <ASSISTANT_TASK:>
Python Code:
import numpy as np
g = 9.8 # m/s
l1 = 1.2 # m
l2 = .7 # m
theta1_0 = np.pi/5 # other initial angle
theta2_0 = np.pi # initial angle
m1 = .10 # kg
m2 = .05 # kg
dt = 1.e-3 ... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: How many steps are there?
Step2: Helper functions for various calculations
Step3: The time derivative of $\theta_2$
Step4: The time derivativ... |
9,341 | <ASSISTANT_TASK:>
Python Code:
squares = []
for element in range(10):
squares.append(element ** 2)
print(squares)
squares = [element ** 2 for element in range(10)]
print(squares)
word_counts = {
'the': 10,
'race': 2,
'is': 3,
'on': 5
}
sentences = ['"{}" appears {} times.'.format(word, count) for... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: I know this is repetitive, but let's break down what we have.
Step2: There it is
Step3: and we want to generate a list of sentences
Step4: St... |
9,342 | <ASSISTANT_TASK:>
Python Code:
import os
import matplotlib.pyplot as plt
import matplotlib.colors as colors
import numpy as np
import openmc
%matplotlib inline
# Create a 7-group structure with arbitrary boundaries (the specific boundaries are unimportant)
groups = openmc.mgxs.EnergyGroups(np.logspace(-5, 7, 8))
uo2_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 now create the multi-group library using data directly from Appendix A of the C5G7 benchmark documentation. All of the data below will b... |
9,343 | <ASSISTANT_TASK:>
Python Code:
from math import pi
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
from qiskit.tools.visualization import matplotlib_circuit_drawer as drawer, qx_color_scheme
# We recommend the following options for Jupter notebook
%matplotlib inline
# Create a Quantum Register ca... | <SYSTEM_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 quantum circuit
Step2: Extract OpenQASM
Step3: Visualize Circuit
Step4: Use Stylesheet
Step5: Bundle Classical Registers
Step6: Sh... |
9,344 | <ASSISTANT_TASK:>
Python Code:
import numpy as np
import os
SHOGUN_DATA_DIR=os.getenv('SHOGUN_DATA_DIR', '../../../data')
from scipy.io import loadmat, savemat
from numpy import random
from os import path
import matplotlib.pyplot as plt
%matplotlib inline
import shogun as sg
mat = loadmat(os.path.join(SHOGUN_... | <SYSTEM_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 us plot the first five examples of the train data (first row) and test data (second row).
Step2: Then we import shogun components and conve... |
9,345 | <ASSISTANT_TASK:>
Python Code:
mons["AVERAGE_STAT"] = mons["STAT_TOTAL"]/6
gens = pd.Series([0 for i in range(len(mons.index))], index=mons.index)
for ID, mon in mons.iterrows():
if 0<mon.DEXID<=151:
gens[ID] = 1
elif 151<mon.DEXID<=251:
gens[ID] = 2
elif 251<mon.DEXID<=386:
gens[ID]... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Some Stats
Step2: Machine Learning and Clustering
Step3: PCA
Step4: K-Means Clustering
|
9,346 | <ASSISTANT_TASK:>
Python Code::
from sklearn.ensemble import GradientBoostingRegressor
from sklearn.metrics import mean_squared_error, mean_absolute_error, max_error, explained_variance_score, mean_absolute_percentage_error
# initialise & fit Gradient Boosting Regressor
model = GradientBoostingRegressor(loss='squared_e... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
|
9,347 | <ASSISTANT_TASK:>
Python Code:
import pyspark.sql.functions as F
import pyspark.sql.types as T
from pyspark.sql import SparkSession
# Initialize PySpark with MongoDB and Elastic support
spark = (
SparkSession.builder.appName("Exploring Data with Reports")
# Load support for MongoDB and Elasticsearch
.config... | <SYSTEM_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 Role of Predictions
Step3: Wow, flights arrive late 39.0% of the time! The problem is as big as it seems. But how late is the average fligh... |
9,348 | <ASSISTANT_TASK:>
Python Code:
# First load the .asm and .byte training data and training labels
# sorted_train_data_asm = pd.read_csv('data/sorted-train-malware-features-asm-reduced.csv')
# sorted_train_data_byte = pd.read_csv('data/sorted-train-malware-features-byte.csv')
sorted_train_labels = pd.read_csv('data/sorte... | <SYSTEM_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. Model Selection On The ASM Features Using GridSearchCV
Step2: 2.1 Gradient Boosting
Step3: 2.2.2 Grid Search
Step4: 2.3 Extra Trees Classi... |
9,349 | <ASSISTANT_TASK:>
Python Code:
#!pip install -I "phoebe>=2.4,<2.5"
import phoebe
print(phoebe.list_installed_passbands())
print(phoebe.list_all_update_passbands_available())
print(phoebe.update_passband_available('Johnson:V'))
phoebe.update_all_passbands()
phoebe.update_passband('Johnson:V')
<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: PHOEBE allows you to check for online updates to local install passbands. If we add a new atmosphere table or feature (extinction as in this re... |
9,350 | <ASSISTANT_TASK:>
Python Code:
import pandas as pd
import matplotlib.pyplot as plt
from pylab import rcParams
import seaborn as sns
from array import array
import numpy as np
from scipy.stats import ttest_ind
from scipy.stats import linregress
%matplotlib inline
begins=[]
ends=[]
names =[]
with open ("sequence.gb") 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: Obtaining the sequence annotation
Step2: Obtaining the clone sequence
Step3: Functions to plot interesting positions and gene boundaries
Step4... |
9,351 | <ASSISTANT_TASK:>
Python Code:
# -*- coding: utf-8 -*-
%matplotlib inline
from __future__ import print_function
import pylab as plt
import datetime
import numpy as np
plt.rcParams['figure.figsize'] = (14, 6)
# New snow amount last 24 h 0-60 cm [10 cm intervals]
new_snow_24h_cat = np.array([0, 10, 20, 30, 40, 50, 60])
... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Parameters, categories and scores
Step2: Weighting
Step3: The new_snow_24_72h_scores are used to weight the new_snow_24h_scores prior to multi... |
9,352 | <ASSISTANT_TASK:>
Python Code:
import numpy as np
import matplotlib.pyplot as plt
from lxml import etree
import pandas as pd
import os
import matplotlib.cm as cm
import seaborn as sns
%pylab inline
# Get read and position data of each fluorescence reading section
def get_wells_from_section(path):
reads = path.xpat... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Calculating Molar Fluorescence (MF) of Free Ligand
Step2: Curve-fitting to binding saturation curve
|
9,353 | <ASSISTANT_TASK:>
Python Code:
from agents import *
class BlindDog(Agent):
def eat(self, thing):
print("Dog: Ate food at {}.".format(self.location))
def drink(self, thing):
print("Dog: Drank water at {}.".format( self.location))
dog = BlindDog()
print(dog.alive)
class Food(Thing):... | <SYSTEM_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 we have just done is create a dog who can only feel what's in his location (since he's blind), and can eat or drink. Let's see if he's aliv... |
9,354 | <ASSISTANT_TASK:>
Python Code:
# Boring prerequisites
import pandas as pd # Beautiful tool for data wrangling! e.g. '!pip install pandas' from a Notebook
import datetime
import numpy as np
pd.set_option("display.max_rows",25) # Useful when having large Pandas DataFrames like we do here
import mysql.connector as mariadb... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Setup a connection with local MariaDB
Step2: Read SQL tables directly into Pandas DataFrame
Step3: Ooops! We get the original bytearray object... |
9,355 | <ASSISTANT_TASK:>
Python Code:
# Load libraries
from sklearn.datasets import make_classification
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import roc_curve, roc_auc_score
from sklearn.model_selection import train_test_split
import matplotlib.pyplot as plt
# Create feature matrix and targ... | <SYSTEM_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 Features And Target
Step2: Split Data Intro Training And Test Sets
Step3: Training Binary Classifier
Step4: Create Predicted Probabi... |
9,356 | <ASSISTANT_TASK:>
Python Code:
# Additional Libraries
%matplotlib inline
import matplotlib.pyplot as plt
# Import relevant libraries:
import time
import numpy as np
import pandas as pd
from sklearn.neighbors import KNeighborsClassifier
from sklearn import preprocessing
from sklearn.preprocessing import MinMaxScaler
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: Local, individual load of updated data set (with weather data integrated) into training, development, and test subsets.
Step2: Logistic Regress... |
9,357 | <ASSISTANT_TASK:>
Python Code:
import random
N = 5000 # Default size of the population
MU = 100. # Default mean of the population
population = [random.gauss(mu=MU, sigma=MU/5) for actor in range(N)]
def gini(y):
"Compute the Gini coefficient (a measure of equality/inequality) in a population, y."
y = sorted(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: Population Statistics and Visualization
Step2: We'll define the function hist to plot a histogram of a population. Our hist wraps plt.hist, but... |
9,358 | <ASSISTANT_TASK:>
Python Code:
import math
def decBinary(arr , n ) :
k = int(math . log2(n ) )
while(n > 0 ) :
arr[k ] = n % 2
k = k - 1
n = n // 2
def binaryDec(arr , n ) :
ans = 0
for i in range(0 , n ) :
ans = ans +(arr[i ] <<(n - i - 1 ) )
return ans
def concat(m , n ) :
k = 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:
|
9,359 | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
from ipywidgets.widgets import Image
from IPython.display import display, display_svg, display_png
# xxxxxxxxxx Add the parent folder to the python path. xxxxxxxxxxxxxxxxxxxx
import sys
parent_dir = "../"
sys.path.append(parent_dir)
# xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Set the parameters, create the cluster and the channels, etc
Step2: Calculate the distances between each user and each base station
Step3: Plo... |
9,360 | <ASSISTANT_TASK:>
Python Code:
from lxml import etree
# We open our file
with open("data/books.xml") as file:
# We use the etree.parse property
parsed = etree.parse(file)
# We print the object
print(parsed)
# We initiate a new parser from etree, asking it to remove nodes of text which are empty
parser = etree... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: 1.3 From file to XML object
Step2: As you can see, we obtained an instance of type lxml.etree._ElementTree. It means the xml markup has been tr... |
9,361 | <ASSISTANT_TASK:>
Python Code:
from numpy import pi
from qutip import sigmaz, sigmax, identity, basis, fidelity, tensor
from qutip_qip.device import OptPulseProcessor
from qutip_qip.circuit import QubitCircuit
from qutip_qip.operations import expand_operator, toffoli
num_qubits = 1
# Drift Hamiltonian
H_d = sigmaz()
#... | <SYSTEM_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 qutip.OptPulseProcessor is a noisy quantum device simulator integrated with the optimal pulse algorithm from the qutip.control module. It is... |
9,362 | <ASSISTANT_TASK:>
Python Code::
sns.distplot(dataset[columns], kde = False, bins = 30, color = 'red', hist_kws=dict(edgecolor="k", linewidth=1) )
<END_TASK>
| <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
|
9,363 | <ASSISTANT_TASK:>
Python Code:
ages = [65, 34, 96, 47]
print len(ages)
names = ["Wilfred", "Manfred", "Wadsworth", "Jeeves"]
ages = [65, 34, 96, 47]
print len(ages) == len(names)
ages = [65, 34, 96, 47]
for hippopotamus in ages:
print hippopotamus
ages = [65, 34, 96, 47]
print ages[1:3]
names = ["Wilfred", "Man... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Your guess
Step2: Your guess
Step3: Your guess
Step4: Your guess
Step5: Your guess
Step6: Your guess
Step7: Your guess
Step8: Your guess
... |
9,364 | <ASSISTANT_TASK:>
Python Code:
import numpy as np
data = np.array([[4, 2, 5, 6, 7],
[ 5, 4, 3, 5, 7]])
bin_size = 3
bin_data_mean = data[:,:(data.shape[1] // bin_size) * bin_size].reshape(data.shape[0], -1, bin_size).mean(axis=-1)
<END_TASK> | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
|
9,365 | <ASSISTANT_TASK:>
Python Code:
#current
import requests
endpoint = 'https://wikimedia.org/api/rest_v1/metrics/pageviews/aggregate/{project}/{access}/{agent}/{granularity}/{start}/{end}'
headers={'User-Agent' : 'https://github.com/your_github_username', 'From' : 'abhiv@uw.edu'}
params = {'project' : 'en.wikipedia.org',
... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Scrape Pageview Mobile App traffic (current api)
Step2: Scrape Pageview Desktop Site traffic (current api)
Step3: Scrape Pageview All Site tra... |
9,366 | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
from scipy import stats
plt.style.use('seaborn')
from sklearn.datasets.samples_generator import make_blobs
X, y = make_blobs(n_samples=50, centers=2,
random_state=0, cluster_std=0.60)
plt.scatter(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: Motivating Support Vector Machines
Step2: A discriminative classifier attempts to draw a line between the two sets of data. Immediately we see ... |
9,367 | <ASSISTANT_TASK:>
Python Code:
from stable_baselines3 import PPO
from stable_baselines3.ppo import MlpPolicy
import gym
import seals
env = gym.make("seals/CartPole-v0")
expert = PPO(
policy=MlpPolicy,
env=env,
seed=0,
batch_size=64,
ent_coef=0.0,
learning_rate=0.0003,
n_epochs=10,
n_step... | <SYSTEM_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 generate some expert trajectories, that the discriminator needs to distinguish from the learner's trajectories.
Step2: Now we are ready to s... |
9,368 | <ASSISTANT_TASK:>
Python Code:
csvfile = open(
reader =
data = []
for line in reader:
line[3] = line[3].decode('utf-8')
# getting the number of rows
#taking a look at the first row
comment_text =
comment_text
# strings are like lists of characters
# use a colon for start:end indexes
# they can be stuck toge... | <SYSTEM_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 python string manipulation
Step2: CHALLENGE
Step3: Introducing TextBlob
Step4: Summarizing/keywording text
Step5: Challenge
Step6: We... |
9,369 | <ASSISTANT_TASK:>
Python Code:
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import math
from IPython import display
try:
import torch
except ModuleNotFoundError:
%pip install -qq torch
import torch
from torch import nn
from torch.nn import functional as F
from torch.utils import 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:
Step12: Required functions for text preprocessing
Step13: Data
Step17: Encoder-decoder
Step19: Encoder
Step21: Decoder
Step23: Loss function
Step2... |
9,370 | <ASSISTANT_TASK:>
Python Code:
!pip install tensorflow==2.1
import numpy as np
import tensorflow as tf
print(tf.__version__)
users = ['Ryan', 'Danielle', 'Vijay', 'Chris']
movies = ['Star Wars', 'The Dark Knight', 'Shrek', 'The Incredibles', 'Bleu', 'Memento']
features = ['Action', 'Sci-Fi', 'Comedy', 'Cartoon', 'Dr... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Make sure to restart your kernel to ensure this change has taken place.
Step2: To start, we'll create our list of users, movies and features. W... |
9,371 | <ASSISTANT_TASK:>
Python Code:
# To use interactive plots (mouse clicks, zooming, panning) we use the notebook back end. We want our graphs
# to be embedded in the notebook, inline mode, this combination is defined by the magic "%matplotlib notebook".
%matplotlib notebook
import SimpleITK as sitk
%run update_path_to_do... | <SYSTEM_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 Data and Select Seed Point(s)
Step2: ConnectedThreshold
Step3: ConfidenceConnected
Step4: VectorConfidenceConnected
Step5: Clean up, Cl... |
9,372 | <ASSISTANT_TASK:>
Python Code:
import tensorflow as tf
tf.random.set_seed(10)
def get_values():
A = tf.random.normal([100,100])
B = tf.random.normal([100,100])
return A,B
@tf.function
def compute():
A,B = get_values()
return tf.reduce_sum(tf.matmul(A,B))
result = compute()
<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:
|
9,373 | <ASSISTANT_TASK:>
Python Code:
%pylab inline
!cd toy_datasets; wget -O MiniBooNE_PID.txt -nc MiniBooNE_PID.txt https://archive.ics.uci.edu/ml/machine-learning-databases/00199/MiniBooNE_PID.txt
import numpy, pandas
from rep.utils import train_test_split
import numpy, pandas
from rep.utils import train_test_split
from 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: Loading data
Step2: Variables needed for analysis
Step3: Factory of different models
Step4: Define classifiers (that will be compared)
Step5:... |
9,374 | <ASSISTANT_TASK:>
Python Code:
# import sqlexperiment as sqle
# from sqlexperiment import experimentlog
from explogger import ExperimentLog
# log some JSON data
e = ExperimentLog(":memory:", ntp_sync=False)
e.log("mouse", data={"x":0, "y":0})
e.log("mouse", data={"x":0, "y":1})
e.log("mouse", data={"x":0, "y":2})
e.clo... | <SYSTEM_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 paths
Step2: A more complex example
Step3: Setting up the database
Step4: Sessions
Step5: We'd usually only want to do this metadata c... |
9,375 | <ASSISTANT_TASK:>
Python Code:
import numpy as np
import pandas as pd
import seaborn as sns
import numpy as np
import scipy.stats as st
import matplotlib.pyplot as plt
%matplotlib inline
xl = pd.ExcelFile("Data/CSCEng.xls")
dfc = xl.parse("Sheet1")
dfc.columns
xl = pd.ExcelFile("Data/SystEng.xls")
dfi = xl.parse("She... | <SYSTEM_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 the first file
Step2: and the seconed one
Step3: The contour plot of the joint distribution of two variables (columns) is colored with a ... |
9,376 | <ASSISTANT_TASK:>
Python Code:
import datetime, time
# timestamp is not correct; it is 8 hours ahead
print (datetime.datetime.now() - datetime.timedelta(hours=8)).strftime('%Y-%m-%d %H:%M:%S')
import importlib
import pip
def _install(package):
pip.main(['install', package])
def _import(package):
importlib.impo... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step2: 1. Install and import libraries
Step3: 2. Load dataset, in this case MovieLens data
Step4: 3. Convert dataset to Dataframe
Step6: 4. Determin... |
9,377 | <ASSISTANT_TASK:>
Python Code:
from tethne.readers import dfr
dfr_corpus = dfr.read('/Users/erickpeirson/Dropbox/HSS ThatCamp Workshop/sample_data/DfR')
from tethne.readers import wos
wos_corpus = wos.read('/Users/erickpeirson/Dropbox/HSS ThatCamp Workshop/sample_data/wos')
len(dfr_corpus), len(wos_corpus)
from tet... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Once again, read() accepts a string containing a path to either a single DfR dataset, or a directory containing several. Here, "DfR dataset" ref... |
9,378 | <ASSISTANT_TASK:>
Python Code:
# Enable importing of utilities.
import sys
import os
sys.path.append(os.environ.get('NOTEBOOK_ROOT'))
import numpy as np
import xarray as xr
import pandas as pd
import matplotlib.pyplot as plt
# Load Data Cube Configuration
import datacube
import utils.data_cube_utilities.data_access_api... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: <span id="plat_prod">Choose Platforms and Products ▴</span>
Step2: Choose products
Step3: <span id="extents">Get the Extents of the Cube... |
9,379 | <ASSISTANT_TASK:>
Python Code:
%%bash
export PROJECT=$(gcloud config list project --format "value(core.project)")
echo "Your current GCP Project Name is: "$PROJECT
%%bash
# Create a BigQuery dataset for feat_eng if it doesn't exist
datasetexists=$(bq ls -d | grep -w feat_eng)
if [ -n "$datasetexists" ]; then
echo ... | <SYSTEM_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 source dataset
Step2: Create the training data table
Step3: Verify table creation
Step4: Baseline Model
Step5: Note, the query takes sev... |
9,380 | <ASSISTANT_TASK:>
Python Code:
ph_sel_name = "None"
data_id = "27d"
# data_id = "7d"
from fretbursts import *
init_notebook()
from IPython.display import display
data_dir = './data/singlespot/'
import os
data_dir = os.path.abspath(data_dir) + '/'
assert os.path.exists(data_dir), "Path '%s' does not exist." % data_dir... | <SYSTEM_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 software and filenames definitions
Step2: Data folder
Step3: List of data files
Step4: Data load
Step5: Laser alternation selection
Ste... |
9,381 | <ASSISTANT_TASK:>
Python Code:
from os.path import join, exists, split, sep, expandvars
from os import makedirs, getpid
from glob import glob
from shutil import rmtree
import csv
import json
import tempfile
from itertools import product
from qiime2.plugins import feature_classifier
from qiime2 import Artifact
from job... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Utility Methods
Step2: Preparing data set sweep
Step3: Preparing the method/parameter combinations and generating commands
Step4: Preparing t... |
9,382 | <ASSISTANT_TASK:>
Python Code:
# DO NOT EDIT !
from pyesdoc.ipython.model_topic import NotebookOutput
# DO NOT EDIT !
DOC = NotebookOutput('cmip6', 'miroc', 'miroc6', 'seaice')
# Set as follows: DOC.set_author("name", "email")
# TODO - please enter value(s)
# Set as follows: DOC.set_contributor("name", "email... | <SYSTEM_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... |
9,383 | <ASSISTANT_TASK:>
Python Code:
%%bash
source ~/kerai/bin/activate
%matplotlib inline
import numpy as np
import matplotlib
from matplotlib import pyplot as plt
from keras.models import Sequential
from keras.optimizers import Adam
from keras.callbacks import ModelCheckpoint
from keras.models import load_model
from 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:
Step1: Imports
Step2: Import helper functions
Step3: Change matplotlib graph style
Step4: Constants
Step5: Get number of classes
Step6: Fetch and ... |
9,384 | <ASSISTANT_TASK:>
Python Code:
import pandas as pd
df = pd.DataFrame.from_dict({'id': ['A', 'B', 'A', 'C', 'D', 'B', 'C'],
'val': [1,2,-3,1,5,6,-2],
'stuff':['12','23232','13','1234','3235','3236','732323']})
def g(df):
df['cumsum'] = df.groupby('id')['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:
|
9,385 | <ASSISTANT_TASK:>
Python Code:
import gensim
import os
import collections
import smart_open
import random
# Set file names for train and test data
test_data_dir = '{}'.format(os.sep).join([gensim.__path__[0], 'test', 'test_data'])
lee_train_file = test_data_dir + os.sep + 'lee_background.cor'
lee_test_file = test_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: What is it?
Step2: Define a Function to Read and Preprocess Text
Step3: Let's take a look at the training corpus
Step4: And the testing corpu... |
9,386 | <ASSISTANT_TASK:>
Python Code:
# ignore the first two lines: they allow you to show multiple outputs per cell
from IPython.core.interactiveshell import InteractiveShell
InteractiveShell.ast_node_interactivity = "all"
import this
print("The classic view of the central dogma of biology states that \
'the coded genetic ... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: <span style="color
Step2: <span style="color
Step3: Python's built-in mathematical operators include +, -, *, **, for exponentiation, / for di... |
9,387 | <ASSISTANT_TASK:>
Python Code:
## Imports!
%matplotlib inline
import os
import re
import string
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from matplotlib.mlab import PCA
from scipy.cluster.vq import kmeans, vq
os.chdir("/home/ryan/School/scientific_computing/labs/lab4/books")
filenames = 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: Loading Fifty Books
Step2: Cleaning up the Data
Step3: Next, we iterate through all of the words, strip all characters that are not upper or l... |
9,388 | <ASSISTANT_TASK:>
Python Code:
#$HIDE_INPUT$
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns
from IPython.display import display
from sklearn.feature_selection import mutual_info_regression
plt.style.use("seaborn-whitegrid")
plt.rc("figure", autolayout=True)
plt.rc(
"axe... | <SYSTEM_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've selected four features that cover a range of properties. Each of these features also has a high MI score with the target, price. We'll sta... |
9,389 | <ASSISTANT_TASK:>
Python Code:
# DO NOT EDIT !
from pyesdoc.ipython.model_topic import NotebookOutput
# DO NOT EDIT !
DOC = NotebookOutput('cmip6', 'ec-earth-consortium', 'ec-earth3-aerchem', 'aerosol')
# Set as follows: DOC.set_author("name", "email")
# TODO - please enter value(s)
# Set as follows: DOC.set_... | <SYSTEM_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... |
9,390 | <ASSISTANT_TASK:>
Python Code:
# To use Planet's CLI from this Notebook, begin your line as follows:
!planet data
# Here is an example of using Planet's CLI to search for a known item id:
# !planet data download --item-type PSScene --asset-type ortho_analytic_4b_sr --dest data --string-in id 20160831_180302_0e26
# To ... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Option 2
Step2: Option 3
Step3: Step 3. Perform the NDVI calculation
Step4: As a quick check of our calculations, let's print the minimum and... |
9,391 | <ASSISTANT_TASK:>
Python Code:
n = 1
print n.bit_length()
a = n.bit_length()
print bin(n)
print '%0*d' % (a, int(bin(n)[2:]))
print '{0:08b}'.format(n)
n = 10
print n.bit_length()
a = n.bit_length()
print bin(n)
print '%0*d' % (a, int(bin(n)[2:]))
print '{0:08b}'.format(n)
n = 10
print n.bit_length()
a = n.bit_length... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: n = 10
Step2: n=100
Step3: converting binary to decimal
Step4: testing more binary to decimal conversions
|
9,392 | <ASSISTANT_TASK:>
Python Code:
# Initialize profile
import IPython
import os.path as path
# Create a profile
profile, = !ipython locate profile
if not profile:
!ipython profile create
print 'Your profile is located at:\t', profile
# Get local paths for later use
ip = IPython.get_ipython()
nbext = path.join(ip.ipyth... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Install useful extensions
Step2: Then need to edit the file
Step3: and add an IPython load statment
Step4: The following command will downloa... |
9,393 | <ASSISTANT_TASK:>
Python Code:
def cdf_to_dataframe(netcdf_file, exclude_qc=True):
Takes in a netCDF object and returns a pandas DataFrame object
# import packages
from netCDF4 import Dataset
import pandas as pd
import datetime
with Dataset(netcdf_file, 'r') as D:
... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Working with Data
Step2: What can we do from here?
|
9,394 | <ASSISTANT_TASK:>
Python Code:
from bs4 import BeautifulSoup
from urllib.request import urlopen
html = urlopen("http://static.decontextualize.com/cats.html").read()
document = BeautifulSoup(html, "html.parser")
cafe_list = list()
cafe_table = document.find('table', {'class': 'cafe-list'})
tbody = cafe_table.find('tbod... | <SYSTEM_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 tackle the list of cafes first. In the cell below, write some code that creates a list of dictionaries with information about each cafe, a... |
9,395 | <ASSISTANT_TASK:>
Python Code:
# Let's find out the number of neighbors that individual #7 has.
G.neighbors(7)
nx.degree_centrality(G)
# Your answer here.
nx.draw(G, with_labels=True)
def path_exists(node1, node2, G):
This function checks whether a path exists between two nodes (node1, node2) in graph 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: Exercise
Step2: If you inspect the dictionary closely, you will find that node 19 is the one that has the highest degree centrality, just as we... |
9,396 | <ASSISTANT_TASK:>
Python Code:
url = "https://raw.githubusercontent.com/vincentarelbundock/Rdatasets/master/csv/ggplot2/diamonds.csv"
data = np.genfromtxt(url, delimiter=",", dtype=None, names=True)
data
data[0][2]
data[0]["cut"]
data["price"].mean()
data["price_per_carat"] = data["price"] / data["carat"]
cuts = 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: data is now a "structured" numpy array. We can access it like a normal 2d array
Step2: but we can also access columns using their names
Step3:... |
9,397 | <ASSISTANT_TASK:>
Python Code:
#@title Upgrade tensorflow_federated and load TensorBoard
#@test {"skip": true}
!pip install --quiet --upgrade tensorflow-federated
!pip install --quiet --upgrade nest-asyncio
import nest_asyncio
nest_asyncio.apply()
%load_ext tensorboard
import sys
if not sys.warnoptions:
import warn... | <SYSTEM_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 Federated での画像分類
Step2: load_data() によって返されるデータセットは、tff.simulation.datasets.ClientData という、ユーザーのセットを列挙して、特定のユーザーのデータを表現する tf.data.Da... |
9,398 | <ASSISTANT_TASK:>
Python Code:
number = "3DB"
base = 16
result = 0
digits = "0123456789ABCDEF"
power = 0
for digit in reversed(number):
result += digits.index(digit) * base**power
power += 1
print("Resultaat: {}".format(tgt_number))
# Van collega Peter kreeg ik een mooie recursieve oplossing
# die ik jullie toc... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Opgave 2. Nu je de programma's hebt om de conversie van een willekeurig talstelsel
Step2: Opgave 3. Pas het programma uit opgave 2 aan zodat de... |
9,399 | <ASSISTANT_TASK:>
Python Code:
# Authors: Denis Engemann <denis.engemann@gmail.com>
# Jona Sassenhagen <jona.sassenhagen@gmail.com>
#
# License: BSD (3-clause)
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
from mne.viz import plot_topomap
import mne
... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Set parameters
Step2: Read epochs for the channel of interest
Step3: Find the FieldTrip neighbor definition to setup sensor connectivity
Step4... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.