Unnamed: 0 int64 0 15.9k | cleaned_code stringlengths 67 124k ⌀ | cleaned_prompt stringlengths 168 30.3k ⌀ |
|---|---|---|
12,100 | <ASSISTANT_TASK:>
Python Code:
# Importa la librería financiera.
# Solo es necesario ejecutar la importación una sola vez.
import cashflows as cf
x = cf.cashflow(const_value=[1000]*10, start='2016')
x
cf.const2curr(cflo=x,
inflation=cf.interest_rate(const_value=[5]*10, start='2016'))
cf.const2curr(cflo... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Inflación
Step2: Ejemplo.-- Considere el mismo ejemplo anterior. Conviertalo a dinero del período 10.
Step3: Ejemplo.-- Considere un flujo de ... |
12,101 | <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 time
from tensorflow.python.client import timeline
import matplotlib.pyplot as plt
%matplotlib inline
FLAGS = tf.app.flags.FLAGS
... | <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... |
12,102 | <ASSISTANT_TASK:>
Python Code:
from dx import *
me = market_environment(name='me', pricing_date=dt.datetime(2015, 1, 1))
me.add_constant('initial_value', 0.01)
me.add_constant('volatility', 0.1)
me.add_constant('kappa', 2.0)
me.add_constant('theta', 0.05)
me.add_constant('paths', 1000)
me.add_constant('frequency', '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: Second, the instantiation of the class.
Step2: The following is an example list object containing datetime objects.
Step3: The call of the met... |
12,103 | <ASSISTANT_TASK:>
Python Code:
import glob
import numpy as np
import pandas as pd
from sklearn.metrics import precision_score, recall_score, roc_auc_score
def get_data(datadir):
Read the data files from different subdirectories of datadir corresponding
to different HOG configurations.
Inputs
... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step4: (1) average the scores between the _0,_1,_2,_3 directions to get average score per image in each HOG configuration.
Step5: Test on Mock
Step6:... |
12,104 | <ASSISTANT_TASK:>
Python Code:
import sys
print('Hello, Colaboratory from Python {}!'.format(sys.version_info[0]))
import tensorflow as tf
import numpy as np
with tf.Session():
input1 = tf.constant(1.0, shape=[2, 3])
input2 = tf.constant(np.reshape(np.arange(1.0, 7.0, dtype=np.float32), (2, 3)))
output = tf.add(... | <SYSTEM_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 execution
Step2: Visualization
Step3: Want to use a new library? pip install it. For recipes to import commonly used libraries, re... |
12,105 | <ASSISTANT_TASK:>
Python Code:
import sklearn
from sklearn.datasets import load_iris
iris_data = load_iris()
print(iris_data.keys())
print(iris_data['target_names'])
print(iris_data['feature_names'])
print(type(iris_data['data']))
print(iris_data['data'].shape)
print(iris_data['data'][:5])
print(iris_data['target'])
... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: 1.1 Data is contained in target and data fields
Step2: 1.2 Target array contains Species of flowers
Step3: 2. Create Training and Test sets fr... |
12,106 | <ASSISTANT_TASK:>
Python Code:
# DO NOT EDIT !
from pyesdoc.ipython.model_topic import NotebookOutput
# DO NOT EDIT !
DOC = NotebookOutput('cmip6', 'csiro-bom', 'access-1-0', '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... |
12,107 | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
from pandas import read_csv
from pandas import datetime
from matplotlib import pyplot as plt
from sklearn.metrics import mean_squared_error
from sklearn.preprocessing import MinMaxScaler
from math import sqrt
import numpy as np
def parser(x):
return datetime.strptim... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Persistence Model Forecast
Step2: LSTM訓練データの準備
Step3: データの前処理まとめ
Step4: LSTM
Step5: Persistence ModelのRMSEは136.761なのでそれに比べるとLSTMを用いたRMSEは減少
|
12,108 | <ASSISTANT_TASK:>
Python Code:
import pandas as pd
from bs4 import BeautifulSoup
import re
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.metrics import roc_auc_score,roc_curve
from sklearn.decomposition import TruncatedSVD
from skle... | <SYSTEM_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 dataset
Step2: Notice that 'sentiment' is binary
Step3: Type 'object' is a string for pandas. We shall later convert to number represen... |
12,109 | <ASSISTANT_TASK:>
Python Code:
clicks = Table.read_table("http://stat.columbia.edu/~rachel/datasets/nyt1.csv")
clicks
age_upper_bounds = [18, 25, 35, 45, 55, 65]
def age_range(n):
if n == 0:
return '0'
lower = 1
for upper in age_upper_bounds:
if lower <= n < upper:
return str(lo... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Well. Half a million rows. That would be painful in excel.
Step2: Now we can group the table by Age Range and count how many clicks come from... |
12,110 | <ASSISTANT_TASK:>
Python Code:
import os
SHOGUN_DATA_DIR=os.getenv('SHOGUN_DATA_DIR', '../../../../data')
import shogun as sg
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
def load_file(feat_file,label_file):
feats=sg.create_features(sg.read_csv(feat_file))
labels=sg.create_labels(sg.rea... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Next, we decide the parameters of our Random Forest.
Step2: In the above code snippet, we decided to create a forest using 10 trees in which ea... |
12,111 | <ASSISTANT_TASK:>
Python Code:
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
import os
from os.path import join
path_notebooks = os.path.abspath('.')
path_data = join(path_notebooks, 'data')
from marvin.tools.maps import Maps
# REMOVE FROM NOTEBOOK
filename = '/Users/andrews/hacks/galaxies-mzr/... | <SYSTEM_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 Maps for Galaxy
Step2: Measure Metallicity
Step3: Calculate the necessary line ratio.
Step4: Finally, calculate the metallicity.
Step5: ... |
12,112 | <ASSISTANT_TASK:>
Python Code:
from __future__ import print_function, unicode_literals
from dbpedia_utils import iter_entities_from
from collections import defaultdict, Counter
import pandas as pd
import numpy as np
import json
import gzip
import dbpedia_config
import matplotlib.pyplot as plt
import seaborn as sns
%mat... | <SYSTEM_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 load person data to process only biographies present in our dataset.
Step2: At this point of time you can decide whether you want to ... |
12,113 | <ASSISTANT_TASK:>
Python Code:
# adapted from http://scikit-learn.org/stable/auto_examples/neighbors/plot_classification.html#example-neighbors-plot-classification-py
n_neighbors = 30
# step size in the mesh
# Create color maps
cmap_light = ListedColormap(['#FFAAAA', '#AAFFAA'])
cmap_bold = ListedColormap(['#FF0000', ... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Now let's look at some classification methods.
Step2: Exercise
Step3: Exercise
Step4: Now write a loop that does this using 100 different ra... |
12,114 | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
from matplotlib import pyplot as plt
import numpy as np
from IPython.html.widgets import interact, interactive, fixed
from IPython.display import display
def print_sum(a, b):
print(a + b)
# YOUR CODE HERE
interact(print_sum, a=(-10.0, 10.0, 0.1), b=(-8, 8, 2));
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: Interact basics
Step2: Use the interact function to interact with the print_sum function.
Step3: Write a function named print_string that prin... |
12,115 | <ASSISTANT_TASK:>
Python Code:
% matplotlib inline
import pylab
import numpy as np
import pandas as pd
from hmmlearn.hmm import GaussianHMM
df = pd.read_csv("speed.csv", sep = ",")
df.head(5)
x = df.drop(["row", "corr"], axis = 1)
x["prev"] = pd.factorize(x["prev"])[0]
model = GaussianHMM(n_components=2, n_iter=1000... | <SYSTEM_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: Drop the row number and "corr" so we can focus on the influence of "prev" and "Pacc" on "rt." Also define "prev" as a factor... |
12,116 | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
import os
import sys
sys.path.append(os.path.join('..', '..'))
from data_models.parameters import arl_path
results_dir = arl_path('test_results')
from matplotlib import pylab
pylab.rcParams['figure.figsize'] = (10.0, 10.0)
pylab.rcParams['image.cmap'] = 'rainbow'
from 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: Construct the SKA1-LOW core configuration
Step2: Use Dask
Step3: We create the visibility. This just makes the uvw, time, antenna1, antenna2, ... |
12,117 | <ASSISTANT_TASK:>
Python Code:
import warnings
import matplotlib.pyplot as plt
import pandas
import seaborn
import pycvc
warnings.simplefilter("ignore")
palette = seaborn.color_palette('deep', n_colors=6)
seaborn.set(style='ticks', context='paper', rc={'text.usetex': False})
%matplotlib inline
hydro = pandas.read_csv(... | <SYSTEM_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 Tidy Hydrologic Data
Step2: Split by site name (color) and presence of outflow (row)
Step3: Split by site (row), presence of outflow (col... |
12,118 | <ASSISTANT_TASK:>
Python Code:
from __future__ import print_function
import matplotlib.pyplot as plt
import numpy as np
import os
import sys
import tarfile
from IPython.display import display, Image
from scipy import ndimage
from sklearn.linear_model import LogisticRegression
from six.moves.urllib.request import urlret... | <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: Deep Learning
Step3: Problem 1
Step5: Now let's load the data in a more manageable format. Since, depending on your computer setup you might n... |
12,119 | <ASSISTANT_TASK:>
Python Code:
!(date +%d\ %B\ %G)
%matplotlib inline
import numpy as np
import seaborn as sns
import time
from pyspark import SparkContext
from pyspark import SparkConf
from matplotlib import pyplot as plt
from pyspark.ml.feature import StandardScaler
from pyspark.ml.feature import VectorAssembler
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: Preparation
Step2: In the following cell, adapt the parameters to fit your personal requirements.
Step3: As shown in the output of the cell ab... |
12,120 | <ASSISTANT_TASK:>
Python Code:
import pandas as pd
import numpy as np
import tensorflow as tf
import tflearn
from tflearn.data_utils import to_categorical
reviews = pd.read_csv('reviews.txt', header=None)
labels = pd.read_csv('labels.txt', header=None)
from collections import Counter
total_counts = Counter(word for r... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Preparing the data
Step2: Counting word frequency
Step3: Let's keep the first 10000 most frequent words. As Andrew noted, most of the words in... |
12,121 | <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: Carregar um pandas.DataFrame
Step2: Fazer download do arquivo csv que contém o conjunto de dados do coração.
Step3: Ler o arquivo csv usando p... |
12,122 | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
import matplotlib.pyplot as plt
from scipy.interpolate import interp1d
import numpy as np
std_iso_05 = np.genfromtxt('files/dmestar_00005.0myr_z+0.00_a+0.00_gas07_t010.iso')
std_iso_12 = np.genfromtxt('files/dmestar_00012.0myr_z+0.00_a+0.00_gas07_t010.iso')
std_iso_30 ... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Magnetic isochrones were computed earlier. Details can be found in this notebook entry on a small magnetic stellar grid. I'll focus on those com... |
12,123 | <ASSISTANT_TASK:>
Python Code:
import numpy as np
import matplotlib.pyplot as plt
from smt.surrogate_models import KRG
# defining the training data
xt = np.array([0.0, 1.0, 2.0, 2.5, 4.0])
yt = np.array([0.0, 1.0, 1.5, 1.1, 1.0])
# defining the models
sm_noise_free = KRG() # noise-free Kriging model
sm_noise_fixed = KR... | <SYSTEM_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 2.2
Step2: 3. Heteroscedastic Kriging example
Step3: Example 3.2
|
12,124 | <ASSISTANT_TASK:>
Python Code:
from sklearn.datasets import load_iris
import numpy as np
iris = load_iris()
X = iris.data.astype(np.float32)
y = iris.target
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(
X, y, random_state=37
)
best_acc = 0
best_k = 0
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: Then the goal is to loop over all possible values of $k$. As we do this, we want to keep track of
Step2: Grid search then looks like an outer l... |
12,125 | <ASSISTANT_TASK:>
Python Code:
# iPython notebook magic commands
%load_ext autoreload
%autoreload 2
%matplotlib inline
#General modules
import os
from os.path import join, basename, isdir
from os import makedirs
import pandas as pd
import matplotlib.pyplot as plt
import time
import pickle
# Supervised Modules
from pyne... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Prediction/Classification
Step2: Load Pickled Data
Step3: Run Prediction Analyses
Step4: <p>Run Linear Support Vector Regression with leave o... |
12,126 | <ASSISTANT_TASK:>
Python Code:
# Import a bunch of stuff
import StarData
import HelperFunctions
import Fitters
import Mamajek_Table
import SpectralTypeRelations
import matplotlib.pyplot as plt
import logging
import triangle
from astropy.io import fits
import numpy as np
import sys
import os
%matplotlib inline
logger = ... | <SYSTEM_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 something else
Step2: Fringing. Check the FFT
Step3: There is definitely something there visible in the FFTs. I will fit the fft, and repl... |
12,127 | <ASSISTANT_TASK:>
Python Code:
nperm = 1000
T_obs_bin,clusters_bin,clusters_pb_bin,H0_bin = mne.stats.spatio_temporal_cluster_test(X_bin,threshold=None,n_permutations=nperm,out_type='mask')
T_obs_ste,clusters_ste,clusters_pb_ste,H0_ste = mne.stats.spatio_temporal_cluster_test(X_ste,threshold=None,n_permutations=nperm,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: On récupère les channels trouvés grace a l'analyse de clusters
Step2: One sample ttest FDR corrected (per electrode)
Step3: Tests de 280 a 44... |
12,128 | <ASSISTANT_TASK:>
Python Code:
from IPython.display import Image
import numpy as np
import math
%pylab
%matplotlib inline
Image('../Bell_2003.png')
def bell_mass_to_light(color, band, color_str):
'''Отношение масса светимость вычисляется по калибровке из статьи Bell E. 2003 Table7.'''
coeffs = {'B-V' : {'B' :... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Калибровки Bell et al. 2003
Step2: $$\log_{10}(M/L)=a_{\lambda} + b_{\lambda}\times Color$$
Step3: Самосогласованные калибровки из McGaugh 201... |
12,129 | <ASSISTANT_TASK:>
Python Code:
import numpy as np
import pandas as pd
import pymc3 as pm
from scipy import stats
from scipy import optimize
import matplotlib.pyplot as plt
import seaborn as sns
import re
%matplotlib inline
def plot_traces(trcs, varnames=None):
'''Plot traces with overlaid means and values'''
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: Convenience Functions
Step2: Generate Data
Step4: Since the mean and variance of a Poisson distributed random variable are equal, the sample m... |
12,130 | <ASSISTANT_TASK:>
Python Code:
import numpy as np
a = np.array([[1,2],[3,4]])
pos = [1, 2]
element = np.array([[3, 5], [6, 6]])
pos = np.array(pos) - np.arange(len(element))
a = np.insert(a, pos, element, axis=0)
<END_TASK> | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
|
12,131 | <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: 循环神经网络(RNN)文本生成
Step2: 下载莎士比亚数据集
Step3: 读取数据
Step4: 处理文本
Step5: 现在,每个字符都有一个整数表示值。请注意,我们将字符映射至索引 0 至 len(unique).
Step6: 预测任务
Step7: batch ... |
12,132 | <ASSISTANT_TASK:>
Python Code:
from jyquickhelper import add_notebook_menu
add_notebook_menu()
%matplotlib inline
from pyensae.datasource import download_data
file = download_data("features_bike_chicago.zip")
file
import pandas
features = pandas.read_csv("features_bike_chicago.txt", sep="\t", encoding="utf-8", low_mem... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Les données
Step2: Les données sont agrégrées par tranche de 10 minutes soit 144 période durant la journée et 288 nombre pour les départs et ar... |
12,133 | <ASSISTANT_TASK:>
Python Code:
password = input("Please enter the password: ")
if password=="Beeblebrox":
print("Welcome Zaphod. How improbable of you.")
else:
print("Get lost!")
speed = int(input("Please enter speed in mph: "))
if :
print("You are exceeding the speed limit. Please slow down.")
answer = 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: Study the code you just ran. Hopefully you can see why getting the password right or wrong affects which print function is executed
Step2: Test... |
12,134 | <ASSISTANT_TASK:>
Python Code:
from __future__ import print_function
import re
import os
from scipy.stats import pearsonr
from datetime import datetime
from gensim.models import CoherenceModel
from gensim.corpora.dictionary import Dictionary
base_dir = os.path.join(os.path.expanduser('~'), "workshop/nlp/data/")
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: Download the dataset (movie.zip) and gold standard data (topicsMovie.txt and goldMovie.txt) from the link and plug in the locations below.
Step2... |
12,135 | <ASSISTANT_TASK:>
Python Code:
import numpy as np
import matplotlib.pyplot as plt
from math import pi
import control as ct
def vehicle_update(t, x, u, params={}):
Vehicle dynamics for cruise control system.
Parameters
----------
x : array
System state: car velocity in m/s
u : 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:
Step2: Process Model
Step3: Engine model
Step4: Torque curves for a typical car engine. The graph on the left shows the torque generated by the engin... |
12,136 | <ASSISTANT_TASK:>
Python Code:
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
# Rango de tiempo
tt = np.linspace(0, 1, 100)
# Solución Analítica
def y(t):
return (np.exp(-2*t)*(-3*np.exp(2)+np.exp(4)-np.exp(4*t)+ 3*np.exp(2+4*t)))/(-1+np.exp(4))
yy = y(tt)
# Matriz de diferencias finitas que ... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Los errores de éste método son dos principalmente
Step2: A continuación otro ejemplo de BVP, esta vez note que hay involucrada una función expl... |
12,137 | <ASSISTANT_TASK:>
Python Code:
import pywt
from matplotlib import pyplot
%matplotlib inline
import numpy
from PIL import Image
import urllib.request
import io
import torch
URL = 'https://upload.wikimedia.org/wikipedia/commons/thumb/b/bc/Zuse-Z4-Totale_deutsches-museum.jpg/315px-Zuse-Z4-Totale_deutsches-museum.jpg'
pri... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Let us see what wavelets are available
Step2: For this demo we will use the Biorthogonal 2.2 Wavelets. As we will not properly deal with bounda... |
12,138 | <ASSISTANT_TASK:>
Python Code:
from __future__ import division, print_function
%matplotlib inline
from qinfer import ScoreMixin, SimplePrecessionModel, RandomizedBenchmarkingModel
import numpy as np
import matplotlib.pyplot as plt
try:
plt.style.use('ggplot')
except:
pass
class NumericalSimplePrecessionModel(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: Simple Precession Model Test
Step2: We verify that both models compute the same score by plotting the score for a range of experiment and model... |
12,139 | <ASSISTANT_TASK:>
Python Code:
import SimpleITK as sitk
import registration_utilities as ru
import registration_callbacks as rc
from __future__ import print_function
import matplotlib.pyplot as plt
%matplotlib inline
from ipywidgets import interact, fixed
#utility method that either downloads data from the MIDAS reposi... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Utilities
Step2: Loading Data
Step3: Geting to know your data
Step4: Free Form Deformation
Step5: Perform Registration
Step6: Another optio... |
12,140 | <ASSISTANT_TASK:>
Python Code:
# # TODO: add putty connection too.
# #read SSH connection parameters
# with open('ssh_settings.json') as settings_file:
# settings = json.load(settings_file)
# hostname = settings['hostname']
# username = settings['username']
# password = settings['password']
# local_key_dir = s... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step2: This notebook explores merged craigslist listings/census data and fits some initial models
Step7: Data Preparation
Step8: create variables
Ste... |
12,141 | <ASSISTANT_TASK:>
Python Code:
import pandas as pd
medians_df = pd.read_csv('assets/median_age.csv')
medians_df.head()
medians_df.loc[[0, 1, 2, 5], 'County']
medians_df.iloc[10:15, :4]
medians_df[['Median_age', 'Avg_MonthlyIncome']].head()
from arcgis.features import GeoAccessor, GeoSeriesAccessor
counties_fc_path =... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: We can access individual rows and columns using .loc (with index labels) or .iloc (with indices)
Step2: We can also get just a few columns from... |
12,142 | <ASSISTANT_TASK:>
Python Code:
print('Hello IPython World!')
!pip list
result1 = 1+1
result2 = 2*3
result2
result1
print('2nd = ' + str(result2))
print('1st = ' + str(result1))
print('2nd = ' + str(result2))
print('1st = ' + str(result1))
!ls -alh
!ifconfig
# Import NetworkX library, which is already installed in yo... | <SYSTEM_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 System Command
Step2: Magic!
Step3: Create file manually with %%writefile
Step4: Execute under other interpreters
|
12,143 | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
import tensorflow as tf
import helper
from tensorflow.examples.tutorials.mnist import input_data
print('Getting MNIST Dataset...')
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)
print('Data Extracted.')
# Save the shapes of weights for each layer
layer_... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Neural Network
Step2: Initialize Weights
Step3: As you can see the accuracy is close to guessing for both zeros and ones, around 10%.
Step4: ... |
12,144 | <ASSISTANT_TASK:>
Python Code:
import torch
import torch.nn as nn
import torch.nn.functional as F
from torchvision import datasets, transforms
from torch.autograd import Variable
from collections import OrderedDict
import numpy as np
import matplotlib.pyplot as plt
plt.rcParams['image.cmap'] = 'gray'
%matplotlib inline... | <SYSTEM_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 the data loaders
Step2: Encapsulate training and testing in functions
Step3: Implementing the test procedure
Step4: nn.Module API
... |
12,145 | <ASSISTANT_TASK:>
Python Code:
import george
george.__version__
import numpy as np
import matplotlib.pyplot as plt
from george import kernels
np.random.seed(42)
N = 256
t = np.sort(np.random.uniform(0, 10, N))
theta = np.random.uniform(-np.pi, np.pi, N)
X = np.vstack((t, theta)).T
yerr = np.random.uniform(0.05, 0.25, ... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: It can be useful to model a dataset using a mixture of GPs.
Step2: The physical (oscillatory) component is not obvious in this dataset because ... |
12,146 | <ASSISTANT_TASK:>
Python Code:
train = pd.read_json("train.json")
matplotlib.style.use('ggplot')
cuisine_group = train.groupby('cuisine')
cuisine_group.size().sort_values(ascending=True).plot.barh()
plt.show()
lemmatizer = WordNetLemmatizer()
train = pd.read_json("train.json")
train['ing'] = [' '.join([lemmatizer.lemm... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Italian and mexican categories dominate the recipes dataset. We may want later to take this into account in order to make the problem more bala... |
12,147 | <ASSISTANT_TASK:>
Python Code:
import numpy as np
import mne
from mne.datasets import sample
from mne.preprocessing import compute_proj_ecg, compute_proj_eog
# getting some data ready
data_path = sample.data_path()
raw_fname = data_path + '/MEG/sample/sample_audvis_filt-0-40_raw.fif'
raw = mne.io.read_raw_fif(raw_fname... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Compute SSP projections
Step2: Apply SSP projections
Step3: Yes this was it. Now MNE will apply the projs on demand at any later stage,
Step4:... |
12,148 | <ASSISTANT_TASK:>
Python Code:
doc_skill = buildDocSkillMat(jd_docs, skill_df, folder=SKILL_DIR)
with(open(SKILL_DIR + 'doc_skill.mtx', 'w')) as f:
mmwrite(f, doc_skill)
extracted_skill_df = getSkills4Docs(docs=doc_index['doc'], doc_term=doc_skill, skills=skills)
df = pd.merge(doc_index, extracted_skill_df, left_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: Get skills in each JD
|
12,149 | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
import seaborn as sns
sns.set_context('poster')
moma = pd.read_csv('Artworks.csv', index_col=12, parse_dates=[10])
moma = moma.dropna(subset=['DateAcquired'])
firsts = moma.drop_duplicates('Artist')
... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Then we define a helper function that takes a full name as a string and returns sexmachine's best guess for the gender of the first word in that... |
12,150 | <ASSISTANT_TASK:>
Python Code:
import random
num = [random.randint(0,10) for i in range(1000)]
hist = {}
for i in num:
hist[i] = hist.get(i, 0) + 1
hist
def count1(num):
hist = {}
for i in num:
hist[i] = hist.get(i, 0) + 1
return hist
%timeit count1(num)
def count2(num):
hist = {}
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: Mesurer le temps que cela prend
Step2: Comparons avec une autre implémentation
Step3: Une version plus rapide
Step4: Une dernière avec cyt... |
12,151 | <ASSISTANT_TASK:>
Python Code:
!sudo chown -R jupyter:jupyter /home/jupyter/training-data-analyst
# Ensure the right version of Tensorflow is installed.
!pip freeze | grep tensorflow==2.5
from google.cloud import bigquery
import tensorflow as tf
import numpy as np
import shutil
print(tf.__version__)
CSV_COLUMNS = ['fa... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: <h2> Input </h2>
Step2: <h2> Create features out of input data </h2>
Step3: <h2> Serving input function </h2>
Step4: <h2> tf.estimator.train_... |
12,152 | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
import shutil
import numpy as np
from os import remove
import cPickle as pkl
from os.path import expanduser, exists
import os
import sys
import logging
logging.basicConfig(level=10)
logger = logging.getLogger()
# Add the mlp python src director to the import search path... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: This time we are not going to generate the data but rather use real world annotated training examples.
Step2: At first we want to inspect the c... |
12,153 | <ASSISTANT_TASK:>
Python Code:
from beampy import *
# We first create a new document for our presentation
# Remove quiet=True to see Beampy compiler output
doc = document(quiet=True)
# Then we create a new slide with the title "My first new slide"
with slide('My first slide title'):
# All the slide contents are fun... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Change the position of the text element
Step2: When value of x and y are lower than 1.0, they are by default in percent
Step3: Now we could al... |
12,154 | <ASSISTANT_TASK:>
Python Code:
# For numerical stuff
import pandas as pd
# Plotting
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
%matplotlib inline
plt.rcParams['figure.figsize'] = (7.0, 7.0)
# Some preprocessing utilities
from sklearn.cross_validation import train_test_split # Data splitting... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Load dataset
Step2: Lets print the feature names
Step3: Do a scatter plot
Step4: Get the features and labels
Step5: Split data to training a... |
12,155 | <ASSISTANT_TASK:>
Python Code:
mdest = '../result/random_network/mixture/'
sdest = '../result/random_network/sparse/'
m_f = '%d_%.2f_%.2f_%.2f_%.2f_%.2f_%.2f.pkl'
s_f = '%d_%.2f_%.2f_%.2f.pkl'
colors = cm.rainbow(np.linspace(0, 1, 7))
np.random.shuffle(colors)
colors = itertools.cycle(colors)
def degree_dist_list(graph... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step3: Properties
Step4: Comparision bewteen sparse and mixed graph
Step5: Varying sigma in the sparse part of the mixed graph
Step6: Varying tau in... |
12,156 | <ASSISTANT_TASK:>
Python Code:
def sqrt(n):
"compute square root of n"
PRECISION = 0.00000001 # stop iterating when we converge with this delta
x_0 = 1.0 # pick any old initial value
x_prev = x_0
while True: # Python doesn't have repeat-until loop so fake it
#print(x_prev)
x_new = 0.... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: To test our square root approximation, we can compare it to math.sqrt() and use numpy's isclose to do the comparison.
Step2: As you can see we ... |
12,157 | <ASSISTANT_TASK:>
Python Code:
from folium import plugins
m = folium.Map([45, 3], zoom_start=4)
plugins.ScrollZoomToggler().add_to(m)
m.save(os.path.join('results', 'Plugins_0.html'))
m
import numpy as np
N = 100
data = np.array(
[
np.random.uniform(low=35, high=60, size=N), # Random latitudes in Europe.... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: In this notebook we show a few illustrations of folium's plugin extensions.
Step2: MarkerCluster
Step3: Terminator
Step4: Leaflet.boatmarker
... |
12,158 | <ASSISTANT_TASK:>
Python Code:
# DO NOT EDIT !
from pyesdoc.ipython.model_topic import NotebookOutput
# DO NOT EDIT !
DOC = NotebookOutput('cmip6', 'ncc', 'sandbox-3', '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... |
12,159 | <ASSISTANT_TASK:>
Python Code:
# DO NOT EDIT !
from pyesdoc.ipython.model_topic import NotebookOutput
# DO NOT EDIT !
DOC = NotebookOutput('cmip6', 'inm', 'sandbox-2', 'ocean')
# 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... |
12,160 | <ASSISTANT_TASK:>
Python Code:
from lp_visu import LPVisu
from scipy.optimize import linprog
import numpy as np
A = [[1.0, 0.0], [1.0, 2.0], [2.0, 1.0]]
b = [8.0, 15.0, 18.0]
c = [4.0, 3.0]
x1_bounds = (0, None)
x2_bounds = (0, None)
x1_gui_bounds = (-1, 16)
x2_gui_bounds = (-1, 10)
visu = LPVisu(A, b, 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: Define the problem
Step2: Define the bounds for the two variables x1 and x2, the GUI bounds and create the visualization object (add a "fake" p... |
12,161 | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
import numpy as np
import pandas as pd
import statsmodels.api as sm
import matplotlib.pyplot as plt
# NBER recessions
from pandas_datareader.data import DataReader
from datetime import datetime
usrec = DataReader('USREC', 'fred', start=datetime(1947, 1, 1), end=datetime... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Federal funds rate with switching intercept
Step2: From the summary output, the mean federal funds rate in the first regime (the "low regime") ... |
12,162 | <ASSISTANT_TASK:>
Python Code:
import os
# The Google Cloud Notebook product has specific requirements
IS_GOOGLE_CLOUD_NOTEBOOK = os.path.exists("/opt/deeplearning/metadata/env_version")
# Google Cloud Notebook requires dependencies to be installed with '--user'
USER_FLAG = ""
if IS_GOOGLE_CLOUD_NOTEBOOK:
USER_FLAG... | <SYSTEM_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: Otherwise, set your project ID here.
Step4: Authenticate your Google Cloud account
Step5: ... |
12,163 | <ASSISTANT_TASK:>
Python Code:
from __future__ import division, print_function # Python 3
from sympy import init_printing
init_printing(use_latex='mathjax',use_unicode=False) # Affichage des résultats
for a in range(9):
for a in [1,2,3,4]:
for a in 'bonjour':
for i in liste: # ligne d'en-têt... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Dans ce chapitre et les suivants, nous traitons de la programmation en Python. Les notes ici présentent les grandes lignes et les éléments princ... |
12,164 | <ASSISTANT_TASK:>
Python Code:
import numpy as np
import pandas as pd
from sklearn import linear_model
from sklearn.metrics import mean_squared_error
import matplotlib.pyplot as plt
data = pd.read_csv("../../Data/2014outagesJerry.csv")
data.head()
# Select input/output data
Y_tot = data['Total_outages']
X_tot = 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: Total Outages
Step2: Equipment-caused Outages
Step3: Trees-caused Outages
Step4: Animals-caused Outages
Step5: Lightning-caused Outages
|
12,165 | <ASSISTANT_TASK:>
Python Code:
def pretty_print_review_and_label(i):
print(labels[i] + "\t: " + reviews[i][:70] + "...")
g = open('reviews.txt','r') # What we know!
reviews = list(map(lambda x:x[:-1],g.readlines()))
g.close()
g = open('labels.txt','r') # What we WANT to know!
labels = list(map(lambda x:x[:-1].upper... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Lesson
Step2: Counting all the words
Step3: the most common words have no predictive power
Step4: Hmmm.. it would be more useful to have two ... |
12,166 | <ASSISTANT_TASK:>
Python Code:
import sys
sys.path.insert(0, '..')
import time
import matplotlib.pyplot as plt
%matplotlib notebook
import numpy as np
import scipy.stats
from Configuration import Configuration
from NeuralTract import NeuralTract
conf = Configuration('confNeuralTractSpikes.rmto')
t = np.arange(0.0, co... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: The spike times of all descending commands along the 10000 ms of simulation is shown in Fig. \ref{fig
Step2: The spike times of all descending ... |
12,167 | <ASSISTANT_TASK:>
Python Code:
import os
import mne
sample_data_folder = mne.datasets.sample.data_path()
sample_data_raw_file = os.path.join(sample_data_folder, 'MEG', 'sample',
'sample_audvis_raw.fif')
raw = mne.io.read_raw_fif(sample_data_raw_file, verbose=False)
events = mne.find... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Creating Evoked objects from Epochs
Step2: You may have noticed that MNE informed us that "baseline correction" has been
Step3: Basic visualiz... |
12,168 | <ASSISTANT_TASK:>
Python Code:
import pandas as pd
url = 'data/bank-additional.csv'
bank = pd.read_csv(url, sep=';')
bank.head()
# list all columns (for reference)
bank.columns
<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: Step 2
|
12,169 | <ASSISTANT_TASK:>
Python Code:
df['txcnt_second'] = df['tx_count'].values / df['blockTime'].values
df['avg_gasUsed_t_perblock'] = df.groupby('block_id')['gasUsed_t'].transform('mean')
df['avg_price_perblock'] = df.groupby('block_id')['price_gwei'].transform('mean')
def rolling_avg(window_size):
price = df[['bl... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Merge data with new columns
Step2: Create a label
Step3: Compute the summary statistic mu
Step4: Compute the label, p, given mu
Step5: Look ... |
12,170 | <ASSISTANT_TASK:>
Python Code:
import gensim
import pandas as pd
import smart_open
import random
# read data
dataframe = pd.read_csv('movie_plots.csv')
dataframe
def read_corpus(documents):
for i, plot in enumerate(documents):
yield gensim.models.doc2vec.TaggedDocument(gensim.utils.simple_preprocess(plot, ... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: 1. Visualizing Doc2Vec
Step2: Let's take a look at the training corpus.
Step3: Training the Doc2Vec Model
Step4: Now, we'll save the document... |
12,171 | <ASSISTANT_TASK:>
Python Code:
import os
%%bash
TFX_PKG="tfx==0.22.0"
KFP_PKG="kfp==0.5.1"
pip freeze | grep $TFX_PKG || pip install -Uq $TFX_PKG
pip freeze | grep $KFP_PKG || pip install -Uq $KFP_PKG
PATH=%env PATH
%env PATH={PATH}:/home/jupyter/.local/bin
%%bash
LOCAL_BIN="/home/jupyter/.local/bin"
SKAFFOLD_URI="ht... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Step 1. Environment setup
Step2: You may need to restart the kernel at this point.
Step3: Modify the PATH environment variable so that skaffol... |
12,172 | <ASSISTANT_TASK:>
Python Code:
import tempfile
import girder_client
import numpy as np
from histomicstk.annotations_and_masks.annotation_and_mask_utils import (
delete_annotations_in_slide)
from histomicstk.saliency.cellularity_detection_superpixels import (
Cellularity_detector_superpixels)
import matplotlib.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: Prepwork
Step2: Initialize the cellularity detector
Step3: In this example, and as the default behavior, we use a handful of informative inten... |
12,173 | <ASSISTANT_TASK:>
Python Code:
%%html
%matplotlib inline
import matplotlib
#import pygsp #Uncomment if you have pygsp installed.
import numpy as np
import matplotlib.pylab as plt
import networkx as nx
import pandas as pd
plt.rcParams['figure.figsize'] = (6, 6)
%%html
## Create a graph.
N = 100 # number of nodes.
G = 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: First, simple filtering on a noisy graph signal will be demonstrated. This is based on an example in an article by Nathanael Perraudin et al. (2... |
12,174 | <ASSISTANT_TASK:>
Python Code:
xvals = np.linspace(0, 20, 1000)
mu1 = 5
mu2 = 15
fig, ax = plt.subplots()
ax.plot(xvals, stats.norm.pdf(xvals, loc=mu1, scale=1), label='Model 1')
ax.plot(xvals, stats.norm.pdf(xvals, loc=mu2, scale=1), label='Model 2')
ax.set_xticks([mu1, mu2])
ax.set_yticks([])
ax.set_xticklabels(['$\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: The log-odds ratio, conditioned on the data, between these two models can be written as
|
12,175 | <ASSISTANT_TASK:>
Python Code:
import numpy as np
np.random.seed(1337)
import datetime
from IPython.display import SVG
from keras.datasets import mnist
from keras import activations
from keras.layers import Dense, Input, concatenate, Conv1D, Conv2D, Dropout, MaxPooling1D, MaxPooling2D
from keras.layers import Dense, Fl... | <SYSTEM_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 the purposes of this notebook, a simple model is constructed.
Step2: Model checkpoints can be saved during training. They are usually saved... |
12,176 | <ASSISTANT_TASK:>
Python Code:
# Import Libraries needed
import pandas as pd #dataframe manipulation
import numpy as np #numerical processing of vectors
import matplotlib.pyplot as plt #plotting
%matplotlib inline
#import tensorflow as tf
import sklearn
from sklearn ... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: <h3>Decision Tree Classification of existing Data with Scikit-learn</h3>
Step2: <h3 align='center'>To better have a look at the tree</h3>
|
12,177 | <ASSISTANT_TASK:>
Python Code:
from collections import defaultdict, Counter
import matplotlib.pyplot as plt
%matplotlib inline
plt.rcParams['figure.figsize'] = (8, 8)
girls = ['alice', 'allie', 'bernice', 'brenda', 'clarice', 'cilly']
boys = ['chris', 'christopher', 'arald', 'arnold', 'bob']
[(b, g) for b in boys 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: A grouping pattern, avoiding quadratic time
Step2: the bad way, quadratic time
Step3: there is a better approach avoiding quadratic time, towa... |
12,178 | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
from matplotlib import pyplot as plt
import numpy as np
from IPython.html.widgets import interact, interactive, fixed
from IPython.display import display
def print_sum(a, b):
Print the sum of the arguments a and b.
c=a+b
print (c)
# YOUR CODE HERE
interact... | <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: Interact basics
Step3: Use the interact function to interact with the print_sum function.
Step5: Write a function named print_string that prin... |
12,179 | <ASSISTANT_TASK:>
Python Code:
from __future__ import print_function
import os
import json
import re
import sys
import pandas
from datetime import datetime, timedelta
from time import sleep
from subprocess import check_output
try:
from urllib import urlopen
except:
from urllib.request import urlopen
import ssl
... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step9: Our last main release was 2017-11-03
Step10: The issues are pulled since the last release date of the meta package.
|
12,180 | <ASSISTANT_TASK:>
Python Code:
def nthTerm(N ) :
return(( 2 * N + 3 ) *(2 * N + 3 ) - 2 * N ) ;
n = 4
print(nthTerm(n ) )
<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:
|
12,181 | <ASSISTANT_TASK:>
Python Code:
import tensorflow as tf
# Set up the data loading:
images, labels = ...
# Define the model
with tf.name_scope('conv1_1') as scope:
kernel = tf.Variable(tf.truncated_normal([3, 3, 3, 64], dtype=tf.float32, stddev=1e-1), name='weights')
conv = tf.nn.conv2d(images, kernel, [1, 1, 1, ... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Understanding every line of this model isn't important. The main point to notice is how much space this takes up. Several of the above lines (co... |
12,182 | <ASSISTANT_TASK:>
Python Code:
import numpy as np
import os
import pandas as pd
Série a ser transformada
s = pd.Series(
name="Compras",
index=["Leite", "Ovos", "Carne", "Arroz", "Feijão"],
data=[2, 12, 1, 5, 2]
)
s
Função de Transformação
def fn(x):
return x ** 2 + x - 100
Transformação elemento... | <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: Propagação de Funções
Step5: Elemento a elemento
Step7: DataFrame
Step10: Elemento a elemento
Step14: Linhas e Colunas
Step15: Transformaçõ... |
12,183 | <ASSISTANT_TASK:>
Python Code:
from stix2 import Indicator
indicator = Indicator(name="File hash for malware variant",
pattern_type="stix",
pattern="[file:hashes.md5 = 'd41d8cd98f00b204e9800998ecf8427e']")
print(indicator.serialize(pretty=True))
print(indicator.serialize())
... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: New in 3.0.0
Step2: If you need performance but also need human-readable output, you can pass the indent keyword argument to serialize()
|
12,184 | <ASSISTANT_TASK:>
Python Code:
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import pandas_datareader as pdr
import seaborn
import statsmodels.api as sm
from statsmodels.regression.rolling import RollingOLS
seaborn.set_style("darkgrid")
pd.plotting.register_matplotlib_converters()
%matplotlib 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: pandas-datareader is used to download data from
Step2: The first model estimated is a rolling version of the CAPM that regresses
Step3: We nex... |
12,185 | <ASSISTANT_TASK:>
Python Code:
from pygoose import *
import gc
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import StratifiedKFold
from sklearn.metrics import *
from keras import backend as K
from keras.models import Model, Sequential
from keras.layers import *
from keras.callbacks 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: Config
Step2: Identifier for storing these features on disk and referring to them later.
Step3: Make subsequent NN runs reproducible.
Step4: ... |
12,186 | <ASSISTANT_TASK:>
Python Code:
import math
import random
darths_thrown = 10000
throws = [[random.random(), random.random()] for i in range(darths_thrown)]
in_circle=0
out_circle=0
for throw in throws:
if math.sqrt(throw[0]**2 + throw[1]**2) <= 1:
in_circle +=1
else:
out_circle += 1
pi_estimate ... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: simple way
Step2: now to jazz this up visually
Step3: the ratio of the area of the circle divided by the area of the square gives us pi/4
|
12,187 | <ASSISTANT_TASK:>
Python Code:
sequence = [1, 2, 3, 4, 5]
def square(x):
return x**2
result = list(map(square, sequence))
print(result)
sequence = range(-10, 10)
greater_than_zero = list(filter(lambda x: x > 0, sequence))
print(greater_than_zero)
from functools import reduce
product = reduce((lambda x, y: 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: Filter
Step2: Reduce
|
12,188 | <ASSISTANT_TASK:>
Python Code:
import pandas as pd
data_url = 'https://archive.ics.uci.edu/ml/machine-learning-databases/housing/housing.data'
# this url has no header info, so column names must be specified
colnames = ['CRIM', 'ZN', 'INDUS', 'CHAS', 'NOX', 'RM', 'AGE', 'DIS',
'RAD', 'TAX', 'PTRATIO', 'B', ... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Let's explore some of these variables. It seems like there should definitely be a correlation between several of these variables. For example, I... |
12,189 | <ASSISTANT_TASK:>
Python Code:
y = np.asarray([20, 21, 17, 19, 17, 28])
k = len(y)
p = 1/k
n = y.sum()
n, p
sns.barplot(x=np.arange(1, k+1), y=y);
n, y
with pm.Model() as dice_model:
# initializes the Dirichlet distribution with a uniform prior:
a = np.ones(k)
theta = pm.Dirichlet("theta", a=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: Just looking at a simple bar plot, we suspect that we might not be dealing with a fair die!
Step2: Let's set up a simple model in PyMC3 that n... |
12,190 | <ASSISTANT_TASK:>
Python Code:
firebase = pyrebase.initialize_app(config)
auth = firebase.auth()
uid = ""
password = ""
user = auth.sign_in_with_email_and_password(uid, password)
db = firebase.database() # reference to the database service
def firebaseRefresh():
global user
user = auth.refresh(user['r... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Analyse already evaluated components
|
12,191 | <ASSISTANT_TASK:>
Python Code:
%%capture
# Installing the required libraries:
!pip install matplotlib pandas scikit-learn tensorflow pyarrow tqdm
!pip install google-cloud-bigquery google-cloud-bigquery-storage
!pip install flake8 pycodestyle pycodestyle_magic geopandas
# Python Builtin Libraries
# Third Party Librarie... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Authentication
Step2: Configurations
Step3: Also, let's select the country. In this notebook, we have selected Australia. For a more accurate ... |
12,192 | <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: 正規化
Step2: データセットを準備する
Step3: グループ正規化のチュートリアル
Step4: インスタンス正規化のチュートリアル
Step5: レイヤー正規化のチュートリアル
|
12,193 | <ASSISTANT_TASK:>
Python Code:
import ebisu
defaultModel = (4., 4., 24.) # alpha, beta, and half-life in hours
from datetime import datetime, timedelta
date0 = datetime(2017, 4, 19, 22, 0, 0)
database = [dict(factID=1, model=defaultModel, lastTest=date0),
dict(factID=2, model=defaultModel, lastTest=date0 +... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Ebisu—this is what we’re here to learn about!
Step2: After learning the second fact, at 0900, what does Ebisu expect each fact’s probability of... |
12,194 | <ASSISTANT_TASK:>
Python Code:
import numpy as np
import pandas as pd
import arduino_helpers.hardware.teensy as teensy
from teensy_minimal_rpc.adc_sampler import AdcSampler, analog_reads
from teensy_minimal_rpc import SerialProxy
import teensy_minimal_rpc.ADC as ADC
# Disconnect from existing proxy (if available)
try:
... | <SYSTEM_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
Step2: Example
|
12,195 | <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: Barren plateaus
Step2: Install TensorFlow Quantum
Step3: Now import TensorFlow and the module dependencies
Step5: 1. Summary
Step7: The auth... |
12,196 | <ASSISTANT_TASK:>
Python Code:
# Load Biospytial modules and etc.
%matplotlib inline
import sys
sys.path.append('/apps')
sys.path.append('..')
#sys.path.append('../../spystats')
import django
django.setup()
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
## Use the ggplot style
plt.style.use('ggp... | <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: Algorithm to simulate GMRF with block-circulant Matrix.
Step3: For benchmarking we will perfom a GF simulation.
Step4: comparison
|
12,197 | <ASSISTANT_TASK:>
Python Code:
from nltk.corpus import gutenberg
gutenberg.fileids()
text = ''
for txt in gutenberg.fileids():
if 'chesterton' in txt:
text += gutenberg.raw(txt).lower()
chars = sorted(list(set(text)))
char_indices = dict((c, i) for i, c in enumerate(chars))
indices_char = dict((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: Create the Training set
Step2: One-hot encode
Step3: Create the Model
Step4: Train the Model
Step5: Generate new sequence
|
12,198 | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
import seaborn as sns
import warnings
import numpy as np
import statsmodels.formula.api as smf
import datetime as dt
from pandas_datareader import wb
wb.search('gdp.*capita.*const')[['id','name']]
wb.search('Urban Population')[['id','name']].tail()
indicators = ['NY.... | <SYSTEM_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 on urban bias
Step2: We will use NY.GDP.PCAP.KD for GDP per capita (constant 2010 US$).
Step3: Let's use the ones we like but use a pytho... |
12,199 | <ASSISTANT_TASK:>
Python Code:
def dedupe_pings(rdd):
return rdd.filter(lambda p: p["meta/clientId"] is not None)\
.map(lambda p: (p["meta/documentId"], p))\
.reduceByKey(lambda x, y: x)\
.map(lambda x: x[1])
def transform(ping):
# Should not be None since we filter 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: Transform and sanitize the pings into arrays.
Step2: Create a set of pings from "core" to build a set of core client data. Output the data to C... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.