Unnamed: 0 int64 0 15.9k | cleaned_code stringlengths 67 124k ⌀ | cleaned_prompt stringlengths 168 30.3k ⌀ |
|---|---|---|
8,400 | <ASSISTANT_TASK:>
Python Code:
#@test {"skip": true}
!pip install --quiet --upgrade tensorflow-federated-nightly
!pip install --quiet --upgrade nest-asyncio
import nest_asyncio
nest_asyncio.apply()
import collections
import time
import tensorflow as tf
import tensorflow_federated as tff
source, _ = tff.simulation.datas... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: 单机模拟
|
8,401 | <ASSISTANT_TASK:>
Python Code:
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
%matplotlib inline
def mnist_loader():
Load MNIST data in tensorflow readable format
The sc... | <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: mnist_loader
Step3: Test mnist data
Step4: We are generating synthetic data in this project, so all the 55000 samples can be used for training... |
8,402 | <ASSISTANT_TASK:>
Python Code:
def simple_coroutine():
print('-> coroutine started')
# 如果协程只需要从客户那里接收数据,那么产出的值是 None
# 这个值是隐式指定的,因为 yield 关键字右面没有表达式
x = yield
print('-> croutine received:', x)
my_coro = simple_coroutine()
my_coro
# 先调用 next(...) 函数,因为生成器还没启动,没在 yield 语句暂停,所以无法发送数据
next(my_coro)... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: 协程可以处于 4 个状态中的一个。当前状态可以使用 inspect.getgeneratorstate(...) 函数确定,该函数会返回下面字符串中的一个
Step2: 注意错误描述,描述的很清楚
Step3: 注意这个是产出值的时间
Step4: 使用协程计算移动平均值
Step... |
8,403 | <ASSISTANT_TASK:>
Python Code:
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, sof... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: # Pandas 간단 소개
Step2: Pandas의 기본 데이터 구조는 두 가지 클래스로 구현됩니다.
Step3: DataFrame 객체는 string 열 이름과 매핑되는 'dict'를 각각의 Series에 전달하여 만들 수 있습니다. Series의 길... |
8,404 | <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 Lattice の缶詰 Estimator
Step2: 必要なパッケージをインポートします。
Step3: UCI Statlog(心臓)データセットをダウンロードします。
Step4: このガイドのトレーニングに使用されるデフォルト値を設定します。
Step5: 特徴量... |
8,405 | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
%load_ext autoreload
%autoreload 2
import numpy as np
import matplotlib.pyplot as plt
from pymks.datasets import make_checkerboard_microstructure
X = make_checkerboard_microstructure(square_size=21, n_squares=8)
from pymks.tools import draw_microstructures
draw_micros... | <SYSTEM_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-Point Statistics for Checkerboard Microstructure
Step2: Now let's take a look at how the microstructure looks.
Step3: Compute Periodic 2-Poi... |
8,406 | <ASSISTANT_TASK:>
Python Code:
# Load data
dat = pd.read_csv("lol_base_stats.tsv", sep="\t")
dat.head()
from bs4 import BeautifulSoup
import requests
primary_role = []
for url in dat.href:
html_data = requests.get(url).text
soup = BeautifulSoup(html_data, "html5lib")
role = soup.find('div', attrs={'cl... | <SYSTEM_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 class data
Step2: Visualizing high-dimensional data
Step3: t-distributed Stochastic Neighbor Embedding (TSNE)
Step4: Principal component ... |
8,407 | <ASSISTANT_TASK:>
Python Code:
# DO NOT EDIT !
from pyesdoc.ipython.model_topic import NotebookOutput
# DO NOT EDIT !
DOC = NotebookOutput('cmip6', 'cmcc', 'cmcc-esm2-hr5', 'aerosol')
# Set as follows: DOC.set_author("name", "email")
# TODO - please enter value(s)
# Set as follows: DOC.set_contributor("name",... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Document Authors
Step2: Document Contributors
Step3: Document Publication
Step4: Document Table of Contents
Step5: 1.2. Model Name
Step6: 1... |
8,408 | <ASSISTANT_TASK:>
Python Code:
imp_bi = Imputer(missing_values='NaN', strategy='most_frequent', axis = 0)
imp_bi.fit(Predictor[:,bi_no_index])
Predictor[:,bi_no_index] = imp_bi.transform(Predictor[:,bi_no_index])
imp_num = Imputer(missing_values='NaN', strategy='median', axis = 0)
imp_num.fit(Predictor[:,numeric_index]... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Use the self-written function to assess the fit
Step2: Returns the evaluators by self-written functions (we first fit HT+CL)
Step3: Plot a dia... |
8,409 | <ASSISTANT_TASK:>
Python Code:
import math
import torch
import gpytorch
from matplotlib import pyplot as plt
# Make plots inline
%matplotlib inline
import urllib.request
import os
from scipy.io import loadmat
from math import floor
# this is for running the notebook in our testing framework
smoke_test = ('CI' in os.en... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: For this example notebook, we'll be using the elevators UCI dataset used in the paper. Running the next cell downloads a copy of the dataset tha... |
8,410 | <ASSISTANT_TASK:>
Python Code:
s = "Maison 3 pièce(s) - 68.05 m² - 860 € par mois charges comprises"
re.findall(r'\d+\.?\d*', s)
re.findall(r'\b\d+\.?\d*\b', s)
s = "Maison 3 pièce(s) - 68.05 m² - 860 € par mois charges comprises"
if re.search(r'Maison', s):
print("Found!")
else:
print("Not found!")
if re.sear... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Search patterns
Step2: Search and capture patterns
Step3: Case insensitive search
Step4: Without re.compile()
Step5: With re.compile()
|
8,411 | <ASSISTANT_TASK:>
Python Code:
import pandas as pd # pandas for handling mixed data sets
import numpy as np # numpy for basic math and matrix operations
# imbalanced-learn for oversampling
from imblearn.over_sampling import RandomOverSampler
scratch_df = pd.DataFrame({'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: Proportional oversampling
Step2: If the event in a classification problem or the value in a prediction problem is imbalanced (usually toward ze... |
8,412 | <ASSISTANT_TASK:>
Python Code:
kids = resp['numkdhh']
kids
pmf = thinkstats2.Pmf(kids)
thinkplot.Pmf(pmf, label='PMF')
thinkplot.Show(xlabel='# of Children', ylabel='PMF')
def BiasPmf(pmf, label=''):
Returns the Pmf with oversampling proportional to value.
If pmf is the distribution of true values, the result... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Display the PMF.
Step3: Define <tt>BiasPmf</tt>.
|
8,413 | <ASSISTANT_TASK:>
Python Code:
from pynq import Overlay
from pynq.iop import Pmod_OLED
from pynq.iop import PMODB
ol = Overlay("base.bit")
ol.download()
oled = Pmod_OLED(PMODB)
oled.write("Hello World")
oled.clear()
from pynq.iop import Pmod_ALS
from pynq.iop import PMODA
als = Pmod_ALS(PMODA)
als.read()
oled.write(... | <SYSTEM_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 writing a message to the OLED.
Step2: Import the ALS library, create an instance of the ALS Pmod, and read the value from the sensor.
Step3... |
8,414 | <ASSISTANT_TASK:>
Python Code:
# Import python-igraph library
import igraph
from IPython.display import Image
# Note: email graph is too large for the fast execution of the Girvan-Newman method, so we use karate graph,
# which is available on github and was taken from http://www.cise.ufl.edu/research/sparse/matrices/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: Task 5.1. Apply Girvan-Newman method
Step2: Apply available Girvan-Newman algorithm and compare results
|
8,415 | <ASSISTANT_TASK:>
Python Code:
import numpy as np, pandas as pd
import matplotlib.pyplot as plt
from sklearn import *
%matplotlib inline
random_state = np.random.RandomState( None )
def collect_result( grid_, names = [ ] ) :
df = pd.DataFrame( { "2-Отклонение" : [ np.std(v_[ 2 ] ) for v_ in grid_.grid_scores_ ],
... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Данные были взяты из репозитория UCI Machine Learning Repository по адресу http
Step2: В исследуемых данных мы имеем следующее число точек
Step... |
8,416 | <ASSISTANT_TASK:>
Python Code:
iris.data
from sklearn.preprocessing import StandardScaler
# 标准化, 返回值为标准化后的数据
iris_standard = StandardScaler().fit_transform(iris.data)
from sklearn.preprocessing import MinMaxScaler
#区间缩放,返回值为缩放到[0, 1]区间的数据
iris_minmax = MinMaxScaler().fit_transform(iris.data)
from sklearn.preprocessin... | <SYSTEM_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: 标准化与归一化的区别
|
8,417 | <ASSISTANT_TASK:>
Python Code:
## Add JS-based table of contents
from IPython.display import HTML as add_TOC
add_TOC( u<h1 id="tocheading">Table of Contents</h1></br><div id="toc"></div>
<script src="https://kmahelona.github.io/ipython_notebook_goodies/ipython_notebook_toc.js"></script></br></hr></br> )
import os, tim... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: <p style = "font-size
Step2: Preamble
Step3: EM and MNIST
Step4: Classify using the maximum aposteriori rule.
Step5: A procedure to compute ... |
8,418 | <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: <table class="tfo-notebook-buttons" align="left">
Step2: Vectorize an example sentence
Step3: Create a vocabulary to save mappings from tokens... |
8,419 | <ASSISTANT_TASK:>
Python Code:
audio_dir = '../Cogitch/Audio/Eurovision/'
euro_dict = utils.dataset_from_dir(audio_dir)
data_dir = '../Cogitch/Data/Eurovision/'
# base_features.compute_and_write(audio_dir, data_dir)
pitch_features.melody_dir = data_dir + 'melody/'
pitch_features.chroma_dir = data_dir + 'hpcp/'
featur... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Base features
Step2: Pitch Features
Step3: Feature Transforms
Step4: The above tells the module where to look for base features.
Step5: Outp... |
8,420 | <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='... | <SYSTEM_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 I'm plotting an example image from the MNIST dataset. These are 28x28 grayscale images of handwritten digits.
Step2: We'll train an autoe... |
8,421 | <ASSISTANT_TASK:>
Python Code:
height = 70.
width = 50.
thickness = 30.
pnt1 = [-width/2., 0., 0.]
pnt2 = [-width/2., -thickness/4., 0.]
pnt3 = [0., -thickness/2., 0.]
pnt4 = [width/2., -thickness/4., 0.]
pnt5 = [width/2., 0., 0.]
edge1 = Edge().createLine(start=pnt1, end=pnt2)
edge2 = Ed... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: VTK Viewer
|
8,422 | <ASSISTANT_TASK:>
Python Code:
def mi_funcion(x,y,z):
a = x * y * z
b = x/2 + y/4 + z/8
c = a + b
return c
a = 1.0
b = 2.0
a = mi_funcion(a, b, 3.0)
print a
def mi_funcion(x,y,z):
a = x * y * z
b = x/2 + y/4 + z/8
c = a + b
return c
a = 1
b = 2
a = mi_funcion(a, b, 3)
print a
def f(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: <table border="1">
Step2: <table border="1">
Step3: <table border="1">
Step4: <table border="1">
Step5: 2.1 Central Hidroelectrica de Bombeo... |
8,423 | <ASSISTANT_TASK:>
Python Code:
import os
import matplotlib.pyplot as plt
import pandas as pd
import swat # SAS Viya Python interface
%matplotlib inline
DATA_URL = 'https://ti.arc.nasa.gov/m/project/prognostic-repository/Challenge_Data.zip'
DATA_DIR = '.'
train_tsv = os.path.join(DATA_DIR, 'train.txt')
test_tsv = os.... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Download and Prep NASA's Turbofan Engine Degradation Simulation (PHM08 Challenge) Data Set
Step2: Read training data into a DataFrame.
Step3: ... |
8,424 | <ASSISTANT_TASK:>
Python Code:
df = pd.DataFrame({
'colA': ['aaa', NaN, NaN, NaN, 'bbb', 'ccc'],
'colB': ['xxx', 'yyy', NaN, 'zzz', NaN, 'www'],
#'colC': [NaN, 3, NaN, 1, 0, 9]
})
df
cond = df.colA.isnull() & ~df.colB.isnull()
cond
df[cond]
df.loc[cond, 'colA'] = df.loc[cond, 'colB']
df
<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: Task
Step2: We can use this to extract the desired columns if we wish.
Step3: Now we can do the assignment. Note that we use the .loc operator... |
8,425 | <ASSISTANT_TASK:>
Python Code:
# load some modules
import pandas as pd
import matplotlib.pylab as plt
import numpy as np
import pygslib
# see block model help
help(pygslib.blockmodel)
# Create an empty block model
mymodel=pygslib.blockmodel.Blockmodel(nx=5,ny=5,nz=5,xorg=-6,yorg=-6,zorg=-6,dx=3,dy=3,dz=3)
# there is no... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Export blocks to a VTK file
Step2: The results can be ploted in an external viewer, for example mayavi or paraview
|
8,426 | <ASSISTANT_TASK:>
Python Code:
import os
PROJECT = "your-project-here" # REPLACE WITH YOUR PROJECT ID
# Do not change these
os.environ["PROJECT"] = PROJECT
%%bash
rm -r bqml_data
mkdir bqml_data
cd bqml_data
curl -O 'http://files.grouplens.org/datasets/movielens/ml-20m.zip'
unzip ml-20m.zip
yes | bq rm -r $PROJECT:movi... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Exploring the data
Step2: A quick exploratory query yields that the dataset consists of over 138 thousand users, nearly 27 thousand movies, and... |
8,427 | <ASSISTANT_TASK:>
Python Code:
import numpy as np
a = np.random.rand(1_000_000)
b = np.random.rand(1_000_000)
%%timeit
a @ b
la = list(a)
lb = list(b)
%%timeit
mysum = 0
for i in range(len(la)):
mysum += la[i] * lb[i]
import math
%%timeit
for i, x in enumerate(la):
lb[i] = math.sin(x)
%%timeit
b = np.sin(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: We begin by defining two <tt>NumPy</tt> arrays a and b that are each filled with a million random numbers.
Step2: Next, we compute the <em styl... |
8,428 | <ASSISTANT_TASK:>
Python Code:
# imports
import numpy as np # It will be used a lot, so the shorthand is helpful.
import matplotlib.pyplot as plt # Same here.
%matplotlib inline
# these can be useful if you plan on using the respective functions a lot:
np.random.seed(42) # Seeding is ... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Numpy array basics
Step2: Under the hood
Step3: You can check whether an array actually owns its data by looking at its flags (you should unde... |
8,429 | <ASSISTANT_TASK:>
Python Code:
from sklearn.datasets import load_iris
iris = load_iris()
iris.keys()
n_samples, n_features = iris.data.shape
n_samples, n_features
iris.data[0]
iris.target
iris.target_names
%matplotlib inline
import matplotlib.pyplot as plt
plt.style.use('fivethirtyeight')
x_index = 3
y_index = 2
# thi... | <SYSTEM_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 information about the class of each sample is stored in the target attribute of the dataset
Step4: scikit-learn interface
Step5: For a giv... |
8,430 | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
numberOfPoints = 100
numberOfIterations = 1000
lengthOfDomain = 1.0
dx = lengthOfDomain/numberOfPoints
xPoints = np.linspace(0.0, lengthOfDomain, numberOfPoints)
initialCondition = np.sin(xPoints*np.pi/lengthOfDomain)
... | <SYSTEM_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 addition to the simulation parameters, we start with an initial seed of concentration data. Unlike our other analytical strategies there are ... |
8,431 | <ASSISTANT_TASK:>
Python Code:
import numpy as np
import matplotlib.pyplot as plt
from scipy import optimize
import seaborn as sns
%pylab inline
# We define a Kd,
Kd = 2e-9 # M
# a protein concentration,
Ptot = 1e-9 * np.ones([12],np.float64) # M
# and a gradient of ligand concentrations for our experiment.
Ltot = 20.... | <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: We use the same setup here as we do in the 'Simulating Experimental Fluorescence Binding Data' notebook.
Step3: Now make this a fluorescence ex... |
8,432 | <ASSISTANT_TASK:>
Python Code:
def get_drop_dates_and_len(df, allow_missing_num=3):
Find missing values and get records to drop
missing_num = df.total.isnull().astype(int).groupby(df.total.notnull().astype(int).cumsum()).sum()
drop_missing_num = missing_num[missing_num > allow_missing_num]
dro... | <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: Network Traffic Forecasting with AutoTS
Step3: Download raw dataset and load into dataframe
Step4: Below are some example records of the data
... |
8,433 | <ASSISTANT_TASK:>
Python Code:
%pylab inline
from scipy.stats import norm
# Create a normal distribution
mu = 50
sigma = 10 # standard deviation
rv = norm(loc = mu, scale = sigma)
start = rv.ppf(0.00001)
stop = rv.ppf(0.99999)
x = np.linspace(start, stop, 100)
print(start, stop)
plt.plot(x, rv.pdf(x))
plt.xlabel('Cel... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: <H2> Theoretical distribution</H2>
Step2: <H2>Empirical distribution</H2>
Step3: note that cells with ID <12 or > 87 receive almost zero condu... |
8,434 | <ASSISTANT_TASK:>
Python Code:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# We'll generate a random factor
current_factor_values = np.random.normal(0, 1, 10000)
equity_names = ['Equity ' + str(x) for x in range(10000)]
# Put it into a dataframe
factor_data = pd.Series(current_factor_values, ... | <SYSTEM_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 that we have factor values and returns, we can see what would happen if we ranked our equities based on factor values, and then entered the ... |
8,435 | <ASSISTANT_TASK:>
Python Code:
import datetime
# scientific python add-ons
import numpy as np
import pandas as pd
# plotting stuff
# first line makes the plots appear in the notebook
%matplotlib inline
import matplotlib.pyplot as plt
# finally, we import the pvlib library
import pvlib
import pvlib
from pvlib.location ... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: SPA output
Step2: Speed tests
Step3: This numba test will only work properly if you have installed numba.
Step4: The numba calculation takes ... |
8,436 | <ASSISTANT_TASK:>
Python Code:
from numpy.fft import *
import numpy
t = numpy.arange(0,100)
data = 5*numpy.sin(t) + 3*numpy.sin(0.5*t)
%pylab inline
plot(data)
fft_out = abs(fft.fft(data))
fft_out.max()
plot(fft_out)
from scipy.signal import find_peaks_cwt
peak_ind = find_peaks_cwt(fft_out, numpy.arange(1,3))
fft_out[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: Note, this also holds for interference between waves of different amplitudes. I've verified this with beam simulations.
Step2: The step size $\... |
8,437 | <ASSISTANT_TASK:>
Python Code:
import numpy as np
import doubletdetection
import scanpy as sc
import matplotlib.pyplot as plt
sc.settings.n_jobs=8
sc.set_figure_params()
%matplotlib inline
adata = sc.read_10x_h5(
"pbmc_10k_v3_filtered_feature_bc_matrix.h5",
backup_url="https://cf.10xgenomics.com/samples/cell-... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Download Data from 10x
Step2: Run Doublet Detection
Step3: Visualize Results
Step4: Doublets on umap
Step5: Number of predicted doublets at ... |
8,438 | <ASSISTANT_TASK:>
Python Code:
from landlab import RasterModelGrid
from landlab.components import LinearDiffuser
?RasterModelGrid
?LinearDiffuser
grid = RasterModelGrid((10, 10), xy_spacing=(3, 4))
?grid.add_ones
<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 look at the RTFD section on RasterModelGrid you'll notice that it contains the same information.
Step2: Note also that the ? works for ... |
8,439 | <ASSISTANT_TASK:>
Python Code:
# Set up some imports that we will need
from pymatgen.core import Lattice, Structure
from pymatgen.analysis.diffraction.xrd import XRDCalculator
from IPython.display import Image, display
%matplotlib inline
# Create CsCl structure
a = 4.209 #Angstrom
latt = Lattice.cubic(a)
structure = 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: $\alpha$-CsCl ($Pm\overline{3}m$)
Step2: Compare it with the experimental XRD pattern below.
Step3: $\beta$-CsCl ($Fm\overline{3}m$)
Step4: C... |
8,440 | <ASSISTANT_TASK:>
Python Code:
%%cython -a
# cython: boundscheck=False
from math import sin, cos
cdef inline double versine(double x):
return 1.0 - cos(x)
def versine_array_py(double[:] x):
cdef int i, n = x.shape[0]
for i in range(n):
x[i] = versine(x[i])
%%cython -a
# cython: boundscheck=False
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: Approach 2
Step2: Speed test
Step3: Roughly 13 X slower than using C math directly
|
8,441 | <ASSISTANT_TASK:>
Python Code:
import time
from collections import namedtuple
import numpy as np
import tensorflow as tf
with open('anna.txt', 'r') as f:
text=f.read()
vocab = set(text)
vocab_to_int = {c: i for i, c in enumerate(vocab)}
int_to_vocab = dict(enumerate(vocab))
encoded = np.array([vocab_to_int[c] 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: First we'll load the text file and convert it into integers for our network to use. Here I'm creating a couple dictionaries to convert the chara... |
8,442 | <ASSISTANT_TASK:>
Python Code:
### Load libraries
%matplotlib inline
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
help(plt.legend)
%%time
df = pd.read_excel('/home/data/APD/COBRA083016_2015.xlsx', sheetname='Query')
df.shape
for c in df.columns:
print(c)
df[0:5]
df.describe()
df.offense_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: Load data (don't change this if you're running the notebook on the cluster)
Step2: Exploring Dates
Step3: Convert into date-time type
Step4: ... |
8,443 | <ASSISTANT_TASK:>
Python Code:
# to install iPython notebook on your computer, use this in Terminal
sudo pip install "ipython[notebook]"
# in Terminal
git clone https://github.com/tuwien-musicir/rp_extract.git
# in Terminal
sudo pip install numpy scipy matplotlib
# in Terminal
sudo pip install soundcloud urllib unic... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: RP Extract Library
Step2: Python Libraries
Step3: Additional Libraries
Step4: MP3 Decoder
Step5: Import + Test your Environment
Step6: <a n... |
8,444 | <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: Automatic differentiation and gradient tape
Step2: Gradient tapes
Step3: You can also request gradients of the output with respect to intermed... |
8,445 | <ASSISTANT_TASK:>
Python Code:
import sqlite3
import datetime as dt
import pandas as pd
import numpy as np
%load_ext version_information
%version_information pandas, numpy
conn = sqlite3.connect('pybodb.sqlite')
# ejemplo con PostgreSQL usando psycopg2
# import psycopg2
# conn = psycopg2.connect(database='ejemplodb',... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Mi configuración es la siguiente
Step2: Primero necesitamos poder conectar con la base de datos. Esto es de lo poco que diferirá con respecto a... |
8,446 | <ASSISTANT_TASK:>
Python Code:
# librerias
import pandas as pd
data = pd.read_csv('../../data/wine.csv', names = ["Cultivator", "Alchol", "Malic_Acid", "Ash", "Alcalinity_of_Ash", "Magnesium", "Total_phenols", "Falvanoids", "Nonflavanoid_phenols", "Proanthocyanins", "Color_intensity", "Hue", "OD280", "Proline"])
# veri... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Train Test Split
Step2: Preprocesamiento de la información
Step3: Entrenamiento del modelo
Step4: Predicciones y Evaluación
|
8,447 | <ASSISTANT_TASK:>
Python Code:
pip freeze | grep nltk || pip install nltk
import os
import pickle
import sys
import nltk
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
import tensorflow as tf
from tensorflow.keras.layers import (
Dense,
Embedding,
GRU,
Input,... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Downloading the Data
Step2: From the utils_preproc package we have written for you,
Step3: Sentence Integerizing
Step4: The outputted tokeniz... |
8,448 | <ASSISTANT_TASK:>
Python Code:
%pylab inline
from __future__ import division
import numpy as np
import pandas as pd
import skbio
import qiime_default_reference
###
## UPDATE THIS CELL TO USE THE DEFAULT REFERENCE AGAIN!!
###
unaligned_ref_fp = qiime_default_reference.get_reference_sequences()
aligned_ref_fp = "/Users/... | <SYSTEM_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're going to work with the qiime-default-reference so we have easy access to some sequences. For reasons we'll look at below, we're going to l... |
8,449 | <ASSISTANT_TASK:>
Python Code:
import pip
requires = ['numpy','xmltodict']
installed_packages = pip.get_installed_distributions()
installed_packages_list = sorted(["%s==%s" % (i.key, i.version) for i in installed_packages])
matching = [[libs for libs in installed_packages_list if x in libs] for x in requires]
if len(ma... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: NOTE
Step2: How to manage .xml and image files? -- theupdate files are prepared in the folder "data"
Step3: obtain the file names
Step4: Usin... |
8,450 | <ASSISTANT_TASK:>
Python Code:
import matplotlib
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
data = [('year', 'location', 'attendees'),
(2002, 'Charleroi', 240),
(2003, 'Charleroi', 300),
(2004, 'Göteborg', 'nan'),
(2005, 'Göteborg', 'nan'),
(2006, 'Genev... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Attendees evolution
|
8,451 | <ASSISTANT_TASK:>
Python Code:
csv_list = open("../data/GP02/US_births_1994-2003_CDC_NCHS.csv").read().split("\n")
csv_list[0:10]
def read_csv(filename):
string_data = open(filename).read()
string_list = string_data.split("\n")[1:]
final_list = []
for row in string_list:
string_fields = ro... | <SYSTEM_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
Step2: 3
Step3: 4
Step4: 5
|
8,452 | <ASSISTANT_TASK:>
Python Code:
# Load required packages
import numpy as np
import datetime as dt
from datetime import timedelta
import pandas as pd
from tqdm import tqdm
import os
import pkg_resources as pkg
import geopandas as gpd
from shapely.geometry import Point
from bokeh.plotting import Figure, show, output_noteb... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Notes
Step2: Define parameters
Step3: Load WWLN data and analyze it
Step4: Save data
Step5: Load data (Blitzortung)
Step6: Plot lightning r... |
8,453 | <ASSISTANT_TASK:>
Python Code:
% reset -f
from __future__ import print_function
from __future__ import division
import math
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
import torch
import sys
print('__Python VERSION:', sys.version)
print('__pyTorch VERSION:', torch.__version__)
print('__CUDA V... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Alloocate a PyTorch Tensor on the GPU
|
8,454 | <ASSISTANT_TASK:>
Python Code:
# Authors: Denis Engemann <denis.engemann@gmail.com>
# Eric Larson <larson.eric.d@gmail.com>
# Alexandre Gramfort <alexandre.gramfort@inria.fr>
# Alex Rockhill <aprockhill@mailbox.org>
#
# License: BSD-3-Clause
import numpy as np
import matplotlib.pyplot as plt
... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Set parameters
Step2: We have to make sure all conditions have the same counts, as the ANOVA
Step3: Create TFR representations for all conditi... |
8,455 | <ASSISTANT_TASK:>
Python Code:
!pip3 uninstall -y google-cloud-aiplatform
!pip3 install google-cloud-aiplatform
import IPython
app = IPython.Application.instance()
app.kernel.do_shutdown(True)
import sys
if "google.colab" in sys.modules:
from google.colab import auth
auth.authenticate_user()
MY_PROJECT = "YOUR... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Enter your project and GCS bucket
Step2: Initialize Vertex SDK for Python
Step6: Write your Training Script
Step7: Launch a Training Job to C... |
8,456 | <ASSISTANT_TASK:>
Python Code:
def PrimeDigitNumber(N , size ) :
ans =[""] * size
ns = 0 ;
small = 0 ;
p =[0 , 0 , 1 , 1 , 0 , 1 , 0 , 1 , 0 , 0 ]
prevprime =[0 , 0 , 0 , 2 , 3 , 3 , 5 , 5 , 7 , 7 ]
if(size == 1 ) :
ans[0 ] = prevprime[ord(N[0 ] ) - ord('0' ) ] + ord('0' ) ;
ans[1 ] = ' ' ;
return '... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
|
8,457 | <ASSISTANT_TASK:>
Python Code:
# Nom de fichiers
fichierParrain = "parrains.csv"
fichierFilleul = "filleuls.csv"
fichierResultat = "parrainage.csv"
# Imports
import csv
import glob
import pulp # LP
# pulp.pulpTestAll() # Test
def fetch_row_parrain(row, line, file):
Renvoie une ligne de type `parrain`
... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step5: Données
Step7: Programmation linéaire
Step8: Variables et Objectif
Step9: Contraintes
Step10: Résolution
Step11: Parrainage
|
8,458 | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
import random
import time
import copy
import numpy as np
import numpy.core.defchararray as npstr
import matplotlib.pyplot as plt
# generates a random string of letters for a given length
def generateWord(length):
abc = 'abcdefghijklmnopqrstuvwxyz'
word = ''
... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Synthetic test data generation
Step2: Testing syntehtic data functions
Step3: Implimenting word search using string comparison (base line tech... |
8,459 | <ASSISTANT_TASK:>
Python Code:
import ipytest
ipytest.autoconfig()
%%ipytest
# define the tests
def test_my_func():
assert my_func(0) == 0
assert my_func(1) == 0
assert my_func(2) == 2
assert my_func(3) == 2
def my_func(x):
return x // 2 * 2
%%ipytest
import pytest
@pytest.mark.parametr... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Execute tests
Step2: Using pytest fixtures
|
8,460 | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
import pymc3 as pm
import pandas as pd
url = "https://github.com/twiecki/WhileMyMCMCGentlySamples/blob/master/content/downloads/notebooks/radon.csv?raw=true"
data = pd.read_csv(url)
county_names = data.county.unique()
c... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: The relevant part of the data we will model looks as follows
Step2: As you can see, we have multiple radon measurements (log-converted to be on... |
8,461 | <ASSISTANT_TASK:>
Python Code:
channel = m.monitor.channels["valid_y_nll"]
hl.Curve(zip(channel.epoch_record, channel.val_record),label="valid_y_nll")
channel = m.monitor.channels["valid_y_nll"]
plt.plot(channel.epoch_record, channel.val_record)
ch1 = m.monitor.channels["valid_y_nll"]
ch2 = m.monitor.channels["train_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: Hard to see whether it is still learning...
|
8,462 | <ASSISTANT_TASK:>
Python Code:
#! cat /Users/gully/.ipython/profile_default/startup/start.ipy
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
%config InlineBackend.figure_format = 'retina'
%matplotlib inline
import os
for i in range(16):
fn = 'http://cdn.gea.esac.esa.int/Gaia/tgas_source/c... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: 1. Batch download the data
Step2: Compare to a Gaia full catalog source (download from previous notebook or manually)
Step3: 2. Compare TGAS a... |
8,463 | <ASSISTANT_TASK:>
Python Code:
# Read data.
import os
# Folder containing all NIPS papers.
data_dir = 'nipstxt/'
# Folders containin individual NIPS papers.
yrs = ['00', '01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12']
dirs = ['nips' + yr for yr in yrs]
# Read all texts into a list.
docs = []
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: Pre-process and vectorize the documents
Step2: We use the WordNet lemmatizer from NLTK. A lemmatizer is preferred over a stemmer in this case b... |
8,464 | <ASSISTANT_TASK:>
Python Code:
# import the dataset
from quantopian.interactive.data.eventvestor import mergers_and_acquisitions_free as dataset
# or if you want to import the free dataset, use:
#from quantopian.data.eventvestor import buyback_auth_free
# import data operations
from odo import odo
# import other librar... | <SYSTEM_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 go over the columns
Step2: <a id='pipeline'></a>
Step5: Filtering out ANNOUNCED targets
Step9: Filtering out PROPOSED targets
|
8,465 | <ASSISTANT_TASK:>
Python Code:
x = np.arange(1, 101)
x
y = np.arange(101, 201)
y
%%time #c로 할 경우
z = np.zeros_like(x)
for i, (xi, yi) in enumerate(zip(x, y)):
z[i] = xi + yi
z
%%time
z = x + y
z
x = np.arange(10)
x
a = 100
a * x
x = np.arange(10)
y = np.arange(10)
x * y
np.dot(x, y)
x.dot(y)
a = np.array([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: 그러나 NumPy는 벡터화 연산을 지원하므로 다음과 같이 덧셈 연산 하나로 끝난다. 위에서 보인 선형 대수의 벡터 기호를 사용한 연산과 코드가 완전히 동일하다.
Step2: 연산 속도도 벡터화 연산이 훨씬 빠른 것을 볼 수 있다.
Step3: NumPy ... |
8,466 | <ASSISTANT_TASK:>
Python Code:
import math
import numpy as np
import h5py
import matplotlib.pyplot as plt
import tensorflow as tf
from tensorflow.python.framework import ops
from tensorflow.examples.tutorials.mnist import input_data
%matplotlib inline
a = tf.constant(2)
b = tf.constant(10)
c = tf.multiply(a,b)
print(c... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Writing and running programs in TensorFlow has the following steps
Step2: As expected, you will not see 20! You got a tensor saying that the re... |
8,467 | <ASSISTANT_TASK:>
Python Code:
from tweet import Tweet
import numpy as np
from csv_handling import load_tweet_csv
import matplotlib.pyplot as plt
tweets = load_tweet_csv("train.csv", use_pickle=False, use_cache=False)
len(tweets)
tweets[:10]
[t["tweet"] for t in tweets[:5]]
fig, ax = plt.subplots()
classes = Tweet.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: Zunächst werden die Daten geladen.
Step2: So sehen die Daten aus
Step3: Sehen wir uns die Verteilung der Klassen an
Step4: Wenn die Klassen v... |
8,468 | <ASSISTANT_TASK:>
Python Code:
from jyquickhelper import add_notebook_menu
add_notebook_menu()
# !!!!! Attention à bien mettre votre token ici !!!!!
token_auth = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
import keyring, os
if "XXXXXX" in token_auth:
token_auth = keyring.get_password("sncf", "key")
import pandas as pd
imp... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Partie 0 - modules recommandés et connexion à l'API
Step2: Partie 1 - Trouver les gares accessibles via la SNCF
Step3: Les trajets depuis la G... |
8,469 | <ASSISTANT_TASK:>
Python Code:
import pandas
import scipy.stats
import matplotlib
import pylab
import numpy
import statsmodels.sandbox.stats.multicomp
import igraph
import math
gene_matrix_for_network_df =
gene_matrix_for_network =
gene_matrix_for_network.shape
help(numpy.corrcoef)
gene_matrix_for_network_cor =
... | <SYSTEM_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 pandas.read_csv, load the tab-deliminted text file of gene expression measurements (rows correspond to genes, columns correspond to bladde... |
8,470 | <ASSISTANT_TASK:>
Python Code:
# Import Pandas data handing module
import pandas as pd
# For pretty display of tables
from IPython.display import display
# Load the data
data = pd.read_csv('data.csv', index_col=['subject', 'cue-english', 'association-english'])
data = data.sort_index()
# Transform the "raw" N400 amplit... | <SYSTEM_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 behavior of the participants was very systematic. Except for the occasional error, whenever two words belonged to the same "animal" or "furn... |
8,471 | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
import sklearn.datasets as datasets
import seaborn as sns
iris = datasets.load_iris()
### BEGIN SOLUTION
### END SOLUTION
import sklearn.neighbors as neighbors
### BEGIN SOLUTION
### END SOLUTION
try:
train_knn
exc... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: B
Step2: C
|
8,472 | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
from common import *
datadir = os.path.join("//media", "disk", "Data")
#datadir = os.path.join("..", "..", "..", "..", "..", "Data")
import open_cp.logger
open_cp.logger.log_to_true_stdout()
south_side, points = load_data(datadir)
points.time_range
masked_grid = grid_fo... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Fit the model
Step2: We recall that the "aftershock kernel" has the form
Step3: In the following plot, for the 5 grid cells with the highest c... |
8,473 | <ASSISTANT_TASK:>
Python Code:
# DO NOT EDIT !
from pyesdoc.ipython.model_topic import NotebookOutput
# DO NOT EDIT !
DOC = NotebookOutput('cmip6', 'nerc', 'hadgem3-gc31-hm', 'toplevel')
# Set as follows: DOC.set_author("name", "email")
# TODO - please enter value(s)
# Set as follows: DOC.set_contributor("nam... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Document Authors
Step2: Document Contributors
Step3: Document Publication
Step4: Document Table of Contents
Step5: 1.2. Model Name
Step6: 2... |
8,474 | <ASSISTANT_TASK:>
Python Code:
# import the dataset
# from quantopian.interactive.data.eventvestor import dividends as dataset
# or if you want to import the free dataset, use:
from quantopian.interactive.data.eventvestor import dividends_free as dataset
# import data operations
from odo import odo
# import other libr... | <SYSTEM_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 go over the columns
Step2: We've done much of the data processing for you. Fields like timestamp and sid are standardized across all our ... |
8,475 | <ASSISTANT_TASK:>
Python Code:
# importing
import numpy as np
from scipy import stats, special
from decimal import Decimal
import matplotlib.pyplot as plt
import matplotlib
# showing figures inline
%matplotlib inline
# plotting options
font = {'size' : 20}
plt.rc('font', **font)
plt.rc('text', usetex=True)
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: Simulation of Sequence of Coins
Step2: Discussing Probability of Sequences
Step3: Again
|
8,476 | <ASSISTANT_TASK:>
Python Code:
# These are all the modules we'll be using later. Make sure you can import them
# before proceeding further.
from __future__ import print_function
import numpy as np
import tensorflow as tf
from six.moves import cPickle as pickle
from six.moves import range
pickle_file = 'notMNIST.pickle... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: First reload the data we generated in 1_notmist.ipynb.
Step2: Reformat into a shape that's more adapted to the models we're going to train
Step... |
8,477 | <ASSISTANT_TASK:>
Python Code:
import oommfc as oc
import discretisedfield as df
%matplotlib inline
# Define macro spin mesh (i.e. one discretisation cell).
p1 = (0, 0, 0) # first point of the mesh domain (m)
p2 = (1e-9, 1e-9, 1e-9) # second point of the mesh domain (m)
cell = (1e-9, 1e-9, 1e-9) # discretisation cel... | <SYSTEM_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 can create a micromagnetic system object.
Step2: Let us assume we have a simple Hamiltonian which consists of only Zeeman energy term
S... |
8,478 | <ASSISTANT_TASK:>
Python Code:
# POS Tag frequencies
from nltk.tag import pos_tag_sents
all_pos_tags = [pos_tag_sents(pos_tokenize(tokens)) for tokens in cb_feat_postText]
tag_list = []
for tweets in all_pos_tags:
tweet_tokens=""
for elements in tweets:
tweet_tokens += elements[0][1] + " "
tag_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: POS TAG Frequencies
Step2: tweet length
Step3: Learn from the extracted features from here on
|
8,479 | <ASSISTANT_TASK:>
Python Code:
import numpy as np
import matplotlib.pylab as plt
import seaborn as sns
np.set_printoptions(precision=4, suppress=True)
sns.set_context('notebook')
%matplotlib inline
# True parameter
theta = .5
# Sample size
n = int(1e2)
# Independent variable, N(0,1)
X = np.random.normal(0, 1, n)
# Sor... | <SYSTEM_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: Plot the data and the model
Step3: Maximize log-likelihood
Step4: Plot objective function, true parameter, and the estim... |
8,480 | <ASSISTANT_TASK:>
Python Code:
%run ../bst/bst.py
%load ../bst/bst.py
def check_balance(root):
# TODO: Implement me
pass
# %load test_check_balance.py
from nose.tools import assert_equal
class TestCheckBalance(object):
def test_check_balance(self):
node = Node(5)
insert(node, 3)
ins... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Unit Test
|
8,481 | <ASSISTANT_TASK:>
Python Code:
!cat Examples/c-grammar.g
!cat Pure.g4
!cat -n Grammar.g4
!antlr4 -Dlanguage=Python3 Grammar.g4
from GrammarLexer import GrammarLexer
from GrammarParser import GrammarParser
import antlr4
class GrammarRule:
def __init__(self, variable, body):
self.mVariable = variable
... | <SYSTEM_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 use <span style="font-variant
Step2: The annotated grammar is stored in the file Grammar.g4.
Step3: We start by generating both scanner and... |
8,482 | <ASSISTANT_TASK:>
Python Code:
# Initialize notebook environment.
%matplotlib inline
import boto3
import botocore
import datetime
import matplotlib.pyplot as plt
import os.path
import xarray as xr
era5_bucket = 'era5-pds'
# AWS access / secret keys required
# s3 = boto3.resource('s3')
# bucket = s3.Bucket(era5_bucket)... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Setting Up S3 Access Using Boto
Step2: ERA5 Data Structure on S3
Step3: Let's take a look at the objects available for a specific month using ... |
8,483 | <ASSISTANT_TASK:>
Python Code:
# See requirements.txt to set up your dev environment.
import sys
import os
import json
import scipy
import urllib
import datetime
import urllib3
import rasterio
import subprocess
import numpy as np
import pandas as pd
import seaborn as sns
from osgeo import gdal
from planet import api
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: Make a slippy map to get GeoJSON
Step2: Querying the Planet API.
Step3: Cleanup
Step4: Filtering our search using pandas.
Step5: Visualizing... |
8,484 | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
import GEOparse
import pandas as pd
import pylab as pl
import seaborn as sns
pl.rcParams['figure.figsize'] = (14, 10)
pl.rcParams['ytick.labelsize'] = 12
pl.rcParams['xtick.labelsize'] = 11
pl.rcParams['axes.labelsize'] = 23
pl.rcParams['legend.fontsize'] = 20
sns.set_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: We also prepared a simple tabulated file with the description of each GSM. It will be usefull to calculate LFC.
Step2: We can look in to this f... |
8,485 | <ASSISTANT_TASK:>
Python Code:
import skrf as rf
import numpy as np
import matplotlib.pyplot as plt
from skrf.media import MLine
rf.stylely()
# Model Parameters
freq = rf.Frequency(1, 20, unit='GHz', npoints=191)
w1 = 20*rf.mil # conductor width [m]
w2 = 90*rf.mil # conductor width [m]
h = 20*rf.mil # dielectric th... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Geometry
Step2: The idea is hence to forge a transmission line of variable characteristic impedance. In this example, the width of the metalliz... |
8,486 | <ASSISTANT_TASK:>
Python Code:
def BiasPmf(pmf):
new_pmf = pmf.Copy()
for x, p in pmf.Items():
new_pmf.Mult(x, x)
new_pmf.Normalize()
return new_pmf
def PmfOfWaitTime(pmf_zb):
metapmf = thinkbayes.Pmf()
for gap, prob in pmf_zb.Items():
uniform = MakeUniformPmf(0, gap)
me... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: pmf is the actual distribution; new_pmf is the biased
Step2: PmfOfWaitTime makes a meta-Pmf that maps from each uniform
Step3: low and high ar... |
8,487 | <ASSISTANT_TASK:>
Python Code:
# For reading/writing CSV files
import csv
# For listing system file folders
from subprocess import check_output
# Use with open to ensure file is closed when block ends
# The wb flag opens file for writing
with open('data/fileops/vehicles.csv', 'wb') as csv_file:
# Prepare csv writer... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: CSV to List
Step2: Dictionary to CSV
Step3: CSV to Dictionary
Step4: Pandas for CSV file operations
Step5: CSV to DataFrame
Step6: DataFram... |
8,488 | <ASSISTANT_TASK:>
Python Code:
import numpy as np
import logging
import sys
import espressomd
import espressomd.accumulators
import espressomd.observables
logging.basicConfig(level=logging.INFO, stream=sys.stdout)
# Constants
KT = 1.1
STEPS = 400000
# System setup
system = espressomd.System(box_l=[16] * 3)
system.time_... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: 3. Data analysis
Step2: 3.2 Calculating the diffusion coefficient
Step3: Use the function <tt>curve_fit()</tt> from the module <tt>scipy.optim... |
8,489 | <ASSISTANT_TASK:>
Python Code:
import cppyy
# first, pull in all headers from the GSL installation directory (/usr/include on my system).
import glob, os
GSL_HOME = '/usr/include'
gsl_headers = [os.path.relpath(x, GSL_HOME) for x in glob.glob(GSL_HOME+'/gsl/*.h')]
%%file gsl_selection.xml
<lcgdict>
<struct pattern... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: For simplicity, we will use gsl_blas_dgemm as a stand-in for the "C/C++ library based on GSL." To make our life easier, we will wrap up the bind... |
8,490 | <ASSISTANT_TASK:>
Python Code:
import numpy as np
import pandas as pd
X_returns = np.random.normal(0, 1, 100) # Generate the daily returns
# sum them and shift all the prices up into a reasonable range
X = pd.Series(np.cumsum(X_returns), name='X') + 50
X.plot()
some_noise = np.random.normal(0, 1, 100)
Y = X + 5 + some... | <SYSTEM_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 generate Y. Remember that Y is supposed to have a deep economic link to X, so the price of Y should vary pretty similarly. We model this ... |
8,491 | <ASSISTANT_TASK:>
Python Code:
import pandas as pd, requests, json
# API endpoint for city of Berkeley's 311 calls
endpoint_url = 'https://data.cityofberkeley.info/resource/k489-uv4i.json?$limit=20'
# fetch the URL and load the data
response = requests.get(endpoint_url)
data = response.json()
# turn the json data int... | <SYSTEM_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 download data from the city of Berkeley's API. You can use Socrata's $limit parameter to specify how many rows to grab (otherwise the defa... |
8,492 | <ASSISTANT_TASK:>
Python Code:
import numpy as np
a = np.array([[0, 1], [2, 1], [4, 8]])
mask = (a.min(axis=1,keepdims=1) == a)
<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:
|
8,493 | <ASSISTANT_TASK:>
Python Code:
! pip3 install google-cloud-storage
import os
if not os.getenv("AUTORUN"):
# Automatically restart kernel after installs
import IPython
app = IPython.Application.instance()
app.kernel.do_shutdown(True)
PROJECT_ID = "[your-project-id]" # @param {type:"string"}
if 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: Restart the Kernel
Step2: Before you begin
Step3: Region
Step4: Timestamp
Step5: Authenticate your GCP account
Step6: Create a Cloud Storag... |
8,494 | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
try:
import seaborn
except ImportError:
pass
pd.options.display.max_rows = 10
df = pd.DataFrame({'key':['A','B','C','A','B','C','A','B','C'],
'data': [0, 5, 10, 5, 10, 15,... | <SYSTEM_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 'theory'
Step2: And now applying this on some real data
Step3: <div class="alert alert-success">
Step4: <div class="alert alert-success"... |
8,495 | <ASSISTANT_TASK:>
Python Code:
import numpy as np
import os
import pandas as pd
import warnings
import nelpy as nel
warnings.filterwarnings("ignore")
datadirs = ['/Users/ckemere/Development/Data/Buzsaki']
fileroot = next( (dir for dir in datadirs if os.path.isdir(dir)), None)
# conda install pandas=0.19.2
if fileroot ... | <SYSTEM_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 experimental data
Step2: Define subset of sessions to score
Step3: Parallel scoring
Step4: Save results to disk
|
8,496 | <ASSISTANT_TASK:>
Python Code:
import docx
import os
os.chdir('files')
d = docx.Document('demo.docx')
type(d)
d.paragraphs
d.paragraphs[0]
d.paragraphs[0].text
d.paragraphs[1].text
p = d.paragraphs[1]
p.runs
p.runs[0].text
p.runs[1].text
p.runs[2].text
p.runs[2].bold
p.runs[3].text
p.runs[3].underline = 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: Documents have a few more features than plaintext files. They have the following objects in this module
Step2: We then use the Document() funct... |
8,497 | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
from __future__ import division, print_function
import numpy as np
import matplotlib.pyplot as plt
from quantecon.markov import MarkovChain
P = np.zeros((6, 6))
P[0, 0] = 1
P[1, 4] = 1
P[2, [2, 3, 4]] = 1/3
P[3, [0, 5]] = 1/2
P[4, [1, 4]] = 1/2
P[5, [0, 3]] = 1/2
print... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Example 1
Step2: Create a MarkovChain instance
Step3: Classification of states
Step4: Determine the communication classes
Step5: Classify th... |
8,498 | <ASSISTANT_TASK:>
Python Code:
names = [
'mpg'
, 'cylinders'
, 'displacement'
, 'horsepower'
, 'weight'
, 'acceleration'
, 'model_year'
, 'origin'
, 'car_name'
]
# reading the file and assigning the header
df = pd.read_csv("http://archive.ics.uci.edu/ml/machine-learning-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: factorplot and FacetGrid
|
8,499 | <ASSISTANT_TASK:>
Python Code:
from time import sleep
import skrf as rf
%matplotlib inline
from pylab import *
rf.stylely()
!rm -rf tmp
!mkdir tmp
wg = rf.wr10 # just a dummy media object to generate data
wg.frequency.npoints = 101
for k in range(10):
# timestamp generated with `rf.now_string()`
ntwk = wg.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: Lets take a look at what we made
Step2: Not sorted (default)
Step3: Sort it
Step4: Sorting using key argument
Step5: Extracting Datetimes
St... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.