Unnamed: 0 int64 0 15.9k | cleaned_code stringlengths 67 124k ⌀ | cleaned_prompt stringlengths 168 30.3k ⌀ |
|---|---|---|
4,400 | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
import pandas as pd
import pandas.io.data as web
import matplotlib.pyplot as plt
import numpy as np
import datetime as dt
file_path = "/Users/Jennifer/Desktop/Freshmen Spring Semester/Data_Bootcamp/PROJECT/Obesity Project/basicstats.xls"
df = pd.read_excel(file_path)
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: The Data Set
Step2: On average, 63.86% of children are in the range considered to be a healthy weight.
Step3: The following chart shows the pe... |
4,401 | <ASSISTANT_TASK:>
Python Code:
import numpy as np
import pandas as pd
import scipy.stats as stats
import matplotlib.pyplot as plt
import math
import cvxpy
def get_markowitz_weights(mu, Sigma, gamma=1, max_position=1.0, max_leverage=1.0, short=False):
w = cvxpy.Variable(len(Sigma))
g = cvxpy.Parameter(sign='pos... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Helper Functions
Step2: Exercise 1
Step3: b. $1 Bets
Step4: Exercise 2
Step5: b. Equally Weighted Portfolio
Step6: c. Market Weighted Portf... |
4,402 | <ASSISTANT_TASK:>
Python Code:
# Versão da Linguagem Python
from platform import python_version
print('Versão da Linguagem Python Usada Neste Jupyter Notebook:', python_version())
class Grid(object):
def find_path(self, matrix):
# Implemente aqui sua solução
%%writefile missao3.py
from nose.tools import 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: Missão
Step2: Teste da Solução
|
4,403 | <ASSISTANT_TASK:>
Python Code:
import scipy as sp
import scipy.stats as stats
import matplotlib.pyplot as plt
from numpy.random import normal
%pylab inline
def h(x, w): return w[1] * x + w[0]
def quadratic_loss(y, hx):
return (y - hx)**2
def error(h, X, y):
err = 0
for xi, yi in zip(X, y):
er... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Sadržaj
Step2: (2) Funkcija gubitka (i njoj odgovarajuća funkcija pogreške)
Step3: Funkcija koja generira podatke (i koju zapravo želimo nauči... |
4,404 | <ASSISTANT_TASK:>
Python Code:
import sys, os
sys.path.insert(0, "/Users/kaestner/git/lib/lib")
sys.path.insert(0, "/Users/kaestner/git/scripts/python/")
if 'LD_LIBRARY_PATH' not in os.environ:
os.environ['LD_LIBRARY_PATH'] = '/Users/kaestner/git/lib/lib'
# os.execv(sys.argv[0], sys.argv)
import numpy as np
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: Create a reconstructor object
Step2: Reconstruction workflow
Step3: The wood data
Step4: Preprocessing
Step5: Prepare and run the back-proje... |
4,405 | <ASSISTANT_TASK:>
Python Code:
import pandas
import numpy as np
from sklearn.cross_validation import train_test_split
from sklearn.cluster import KMeans
from pprint import pprint
TITANIC_TRAIN = 'train.csv'
TITANIC_TEST = 'test.csv'
# t_df refers to titanic_dataframe
t_df = pandas.read_csv(TITANIC_TRAIN, header=0)
t_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: Selection of Features
Step2: Cleaning Data
Step6: Experiment Heueristics (Design)
Step7: Representation
Step8: Experiment
Step9: The K-Mean... |
4,406 | <ASSISTANT_TASK:>
Python Code:
# from sklearn.datasets import fetch_20newsgroups
from sklearn.datasets import load_files
# categories = ['alt.atheism', 'soc.religion.christian', 'comp.graphics', 'sci.med']
# all_of_it = fetch_20newsgroups(subset='train', categories=categories, shuffle=True, random_state=42)
all_of_it =... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Dividing the training and test data into 80-20 ratio(Roughly).
Step2: Some details about the dataset
Step3: How the files look like
Step4: Sa... |
4,407 | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
# here the usual imports. If any of the imports fails,
# make sure that pynoddy is installed
# properly, ideally with 'python setup.py develop'
# or 'python setup.py install'
import sys, os
import matplotlib.pyplot as plt
import numpy as np
# adjust some settings 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: Initiate experiment with this input file
Step2: Before we start to draw random realisations of the model, we should first store the base state ... |
4,408 | <ASSISTANT_TASK:>
Python Code:
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
%matplotlib inline
from statsmodels.tsa.exponential_smoothing.ets import ETSModel
plt.rcParams['figure.figsize'] = (12, 8)
oildata = [
111.0091, 130.8284, 141.2871, 154.2278,
162.7409, 192.1665, 240.7997, 304.... | <SYSTEM_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 exponential smoothing
Step2: The plot above shows annual oil production in Saudi Arabia in million tonnes. The data are taken from the R... |
4,409 | <ASSISTANT_TASK:>
Python Code:
%matplotlib notebook
from matplotlib import pylab as plt
from numpy import sin, cos, pi, matrix, random, linalg, asarray
from scipy.linalg import pinv
from __future__ import division
from math import atan2
from IPython import display
from ipywidgets import interact, fixed
def trans(x, 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: Coordinate Transformation
Step2: Parameters of robot arm
Step3: Forward Kinematics
Step4: Inverse Kinematics
|
4,410 | <ASSISTANT_TASK:>
Python Code:
%%bash
cd /tmp
rm -rf playground
git clone https://github.com/crystalzhaizhai/playground.git
%%bash
cd /tmp/playground
git pull origin mybranch1
ls
%%bash
cd /tmp/playground
git status
%%bash
cd /tmp/playground
git reset --hard origin/master
ls
%%bash
cd /tmp/playground
git status
%%bash... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Problem 2
Step2: Problem 3
Step3: Problem 4
Step4: Problem 5
|
4,411 | <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() # bag of... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: 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... |
4,412 | <ASSISTANT_TASK:>
Python Code:
%pylab inline
import keras
import numpy as np
t = np.arange(50).reshape(1, -1)
x = np.sin(2*np.pi/50*t)
print(x.shape)
plot(t[0], x[0]);
from keras.models import Sequential
from keras.layers import containers
from keras.layers.core import Dense, AutoEncoder
encoder = containers.Sequenti... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Input signal. Single training example.
Step2: Simple autoencoder of four layers
Step3: The model fits the data quite nicely.
Step4: The model... |
4,413 | <ASSISTANT_TASK:>
Python Code:
import numpy as np
import os
import tensorflow as tf
from ppo.history import *
from ppo.models import *
from ppo.trainer import Trainer
from unityagents import *
### General parameters
max_steps = 5e5 # Set maximum number of steps to run environment.
run_path = "ppo" # The sub-directory ... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Hyperparameters
Step2: Load the environment
Step3: Train the Agent(s)
Step4: Export the trained Tensorflow graph
|
4,414 | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
import matplotlib.pyplot as plt
from jyquickhelper import add_notebook_menu
add_notebook_menu()
from actuariat_python.data import population_france_year
population = population_france_year()
df = population
df.head(n=3)
hommes = df["hommes"]
femmes = df["femmes"]
somme... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Exercice 1
Step2: Je reprends ici le code exposé à Damien Vergnaud's Homepage en l'adaptant un peu avec les fonctions de matplotlib via l'inte... |
4,415 | <ASSISTANT_TASK:>
Python Code:
## EXAMPLE: Get all images from experiment 11.
xp_11_images = all_data_images.filter(xp_id=156)
## EXAMPLE: Get all images from CJRs 140, 158, and 161.
selected_cjrs_images = all_data_images.filter(cjr_id__in=[140,158,161])
## EXAMPLE: Get all images from experiments 11 and 94.
selected_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: Store Priorities - DON'T FORGET TO DO THIS - This is what actually queues the images to be tagged
Step2: This can take some time.
Step3: Clear... |
4,416 | <ASSISTANT_TASK:>
Python Code:
def create_matrix(size):
mat = np.zeros((size, size))
for i in range(size):
for j in range (size):
mat[i, j] = i * j
return mat
create_matrix(4)
mat = create_matrix(20)
plt.imshow(mat)
plt.colorbar() # Adds a colorbar to the plot to aid in interpretation.
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: In the plot above each cell of the matrix corresponds to one of the coloured grids, with the colour indicating the cell value.
Step2: It's poss... |
4,417 | <ASSISTANT_TASK:>
Python Code:
import pandas as pd
import pandas as pd
import numpy as np
ndarray = np.array(['a','b','c','d'])
serie = pd.Series(ndarray)
print(serie)
dog_data=[
['Pedro','Doberman',3],\
['Clementine','Golden Retriever',8],\
['Norah','Great Dane',6],\
['Mabel','Austrailian Shepherd',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: Pandas is well suited for many different kinds of data
Step2: Create a data frame
Step3: Previewing the data frame
Step4: DataFrame.tail(n=5)... |
4,418 | <ASSISTANT_TASK:>
Python Code:
import pandas as pd
df = pd.DataFrame({'A': ['Good & bad', 'BB', 'CC', 'DD', 'Good & bad'], 'B': range(5), 'C': ['Good & bad'] * 5})
def g(df):
return df.replace('&','&', regex=True)
df = g(df.copy())
<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:
|
4,419 | <ASSISTANT_TASK:>
Python Code:
# DO NOT EDIT !
from pyesdoc.ipython.model_topic import NotebookOutput
# DO NOT EDIT !
DOC = NotebookOutput('cmip6', 'dwd', 'mpi-esm-1-2-hr', 'ocnbgchem')
# 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... |
4,420 | <ASSISTANT_TASK:>
Python Code:
# 1. Input model parameters
parameters = pd.Series()
parameters['rhoa'] = .9
parameters['sigma'] = 0.001
print(parameters)
# 2. Define a function that evaluates the equilibrium conditions
def equilibrium_equations(variables_forward,variables_current,parameters):
# Parameters
... | <SYSTEM_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
Step2: The previous step constructs a log-linear approximation of the model and then solves for the endogenous variables as functions... |
4,421 | <ASSISTANT_TASK:>
Python Code:
#Importamos las librerías utilizadas
import numpy as np
import pandas as pd
import seaborn as sns
#Mostramos las versiones usadas de cada librerías
print ("Numpy v{}".format(np.__version__))
print ("Pandas v{}".format(pd.__version__))
print ("Seaborn v{}".format(sns.__version__))
#Abrimos... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Representamos ambos diámetro y la velocidad de la tractora en la misma gráfica
Step2: En el boxplot, se ve como la mayoría de los datos están p... |
4,422 | <ASSISTANT_TASK:>
Python Code:
def pretty_print_review_and_label(i):
print(labels[i] + "\t:\t" + reviews[i][:80] + "...")
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].uppe... | <SYSTEM_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: Lesson
Step3: Project 1
Step4: We'll create three Counter objects, one for words from postive reviews, one for words from negativ... |
4,423 | <ASSISTANT_TASK:>
Python Code:
from sympy import isprime
print(isprime.__doc__[:180])
first_number = 6_00_00_00_00
last_number = 7_99_99_99_99
# test rapide
#last_number = first_number + 20
all_numbers = range(first_number, last_number + 1)
def count_prime_numbers_in_range(some_range):
count = 0
for number in ... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Réponse
Step2: Conclusion
Step3: Et donc, on peut calculer la part de nombres premiers parmi les numéros de téléphones mobiles français.
|
4,424 | <ASSISTANT_TASK:>
Python Code:
def fix_status(current_value):
if current_value == -2: return 'no_consumption'
elif current_value == -1: return 'paid_full'
elif current_value == 0: return 'revolving'
elif current_value in [1,2]: return 'delay_2_mths'
elif current_value in [3,4,5,6,7,8,9]: return 'del... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: one hot encoding where needed
Step2: can we do better by training a different model by subpopulation?
Step3: young people (age<=30)
Step4: so... |
4,425 | <ASSISTANT_TASK:>
Python Code:
# here we define a function that we can call to execute our simulation under
# a variety of different alternative scenarios
import scipy as sp
import numpy as np
import matplotlib.pyplot as pl
import pandas as pd
import shap
%config InlineBackend.figure_format = 'retina'
def run_credit_ex... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: <!--## Scenario A
Step2: Now we can use SHAP to decompose the model output among each of the model's input features and then compute the demogr... |
4,426 | <ASSISTANT_TASK:>
Python Code:
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
def gen_complex_chirp(fs=44100, pad_frac=.01, time_s=1):
f0= -fs / (2. * (1 + pad_frac))
f1= fs / (2. *(1 + pad_frac))
t1 = time_s
beta = (f1 - f0) / float(t1)
t = np.arange(0, t1, t1/ float(fs))
... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Filtering
Step2: We can see that the chirp has been filtered. Now you may be saying "I thought this was a low pass filter, but it took the cent... |
4,427 | <ASSISTANT_TASK:>
Python Code:
metaphors_url = 'http://metacorps.io/static/viomet-snapshot-project-df.csv'
project_df = get_project_data_frame(metaphors_url)
print(project_df.columns)
from viomet_9_10_17 import fit_all_networks
import pandas as pd
date_range = pd.date_range('2016-9-1', '2016-11-30', freq='D')
# uncomm... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Fitting excited state models to each network and all networks
Step2: Visualize model fits overlaid on timeseries data
Step3: Trump, Clinton as... |
4,428 | <ASSISTANT_TASK:>
Python Code:
data_in_shape = (3, 5, 2, 2)
L = ZeroPadding3D(padding=(1, 1, 1), data_format='channels_last')
layer_0 = Input(shape=data_in_shape)
layer_1 = L(layer_0)
model = Model(inputs=layer_0, outputs=layer_1)
# set weights to random (use seed for reproducibility)
np.random.seed(260)
data_in = 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: [convolutional.ZeroPadding3D.1] padding (1,1,1) on 3x5x2x2 input, data_format='channels_first'
Step2: [convolutional.ZeroPadding3D.2] padding (... |
4,429 | <ASSISTANT_TASK:>
Python Code:
import pandas as pd
# get titanic training file as a DataFrame
titanic = pd.read_csv("../datasets/titanic_train.csv")
titanic.shape
# preview the data
titanic.head()
titanic.describe()
titanic.info()
ports = pd.get_dummies(titanic.Embarked , prefix='Embarked')
ports.head()
titanic = 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: Variable Description
Step2: Not all features are numeric
Step3: 2. Process the Data
Step4: Now the feature Embarked (a category) has been tra... |
4,430 | <ASSISTANT_TASK:>
Python Code:
# Import the required packages
import numpy as np
import pandas as pd
import matplotlib
import matplotlib.pyplot as plt
import scipy
import math
import random
import string
random.seed(123)
# Display plots inline
%matplotlib inline
# Define plot's default figure size
matplotlib.rcParams[... | <SYSTEM_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 start building our NN's building blocks.
Step2: Our NN class
Step3: Let's visualize and observe the resultset
Step4: Create Neural netw... |
4,431 | <ASSISTANT_TASK:>
Python Code:
# Authors: Hari Bharadwaj <hari@nmr.mgh.harvard.edu>
# Denis Engemann <denis.engemann@gmail.com>
# Chris Holdgraf <choldgraf@berkeley.edu>
#
# License: BSD-3-Clause
import numpy as np
from matplotlib import pyplot as plt
from mne import create_info, EpochsArray
from mne.... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Simulate data
Step2: Calculate a time-frequency representation (TFR)
Step3: (1) Least smoothing (most variance/background fluctuations).
Step4... |
4,432 | <ASSISTANT_TASK:>
Python Code:
# download image from github: -q quiet mode; -N overwrite on the next download
!wget -q -N https://github.com/robertoalotufo/ia898/raw/830a0f5f6e6a1ddd459127631bf9c0c750bf1f58/data/cameraman.tif
!wget -q -N https://github.com/robertoalotufo/ia898/raw/830a0f5f6e6a1ddd459127631bf9c0c750bf1f... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Introdução ao NumPy - Redução de eixo
Step2: A título de curiosidade, em processamento paralelo, fazer este tipo de operação, que acumula um
S... |
4,433 | <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: Dogs vs Cats Image Classification Without Image Augmentation
Step2: Data Loading
Step3: The dataset we have downloaded has the following direc... |
4,434 | <ASSISTANT_TASK:>
Python Code:
from Bio import SeqIO
counter = 0
for seq in SeqIO.parse('../data/proteome.faa', 'fasta'):
counter += 1
counter
%matplotlib inline
import matplotlib.pyplot as plt
sizes = []
for seq in SeqIO.parse('../data/proteome.faa', 'fasta'):
sizes.append(len(seq))
plt.hist(sizes, ... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Can you plot the distribution of protein sizes in the data/proteome.faa file?
Step2: Can you count the number of CDS sequences in the data/ecol... |
4,435 | <ASSISTANT_TASK:>
Python Code:
import absl
import os
import tempfile
import time
import pandas as pd
import tensorflow as tf
import tensorflow_data_validation as tfdv
import tensorflow_model_analysis as tfma
import tensorflow_transform as tft
import tfx
from pprint import pprint
from tensorflow_metadata.proto.v0 import... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Note
Step2: If the versions above do not match, update your packages in the current Jupyter kernel below. The default %pip package installation... |
4,436 | <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()
for idx,... | <SYSTEM_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... |
4,437 | <ASSISTANT_TASK:>
Python Code:
import os
import mne
from mne.preprocessing import (ICA, create_eog_epochs, create_ecg_epochs,
corrmap)
sample_data_folder = mne.datasets.sample.data_path()
sample_data_raw_file = os.path.join(sample_data_folder, 'MEG', 'sample',
... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: <div class="alert alert-info"><h4>Note</h4><p>Before applying ICA (or any artifact repair strategy), be sure to observe
Step2: We can get a sum... |
4,438 | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
import numpy as np
from matplotlib import style
import matplotlib.pyplot as plt
style.use('ggplot')
def diurnal_tide(t, K1amp, K1phase, O1amp, O1phase, randamp):
out = K1amp * np.sin(2 * np.pi * t / 23.9344 - K1phase)
out += O1amp * np.sin(2 * np.pi * t / 25.819... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Semi-diurnal
Step2: Diurnal
|
4,439 | <ASSISTANT_TASK:>
Python Code:
reactions = [
# (coeff, r_stoich, net_stoich)
('k1', {'A': 1}, {'B': 1, 'A': -1}),
('k2', {'B': 1, 'C': 1}, {'A': 1, 'B': -1}),
('k3', {'B': 2}, {'B': -1, 'C': 1})
]
names = 'A B C'.split()
%load_ext scipy2017codegen.exercise
%exercise exercise_symbolic.py
sym.init_prin... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Exercise
Step2: Use either the %exercise or %load magic to get the exercise / solution respectively
Step3: To complete the above exercise you ... |
4,440 | <ASSISTANT_TASK:>
Python Code:
import mne
from mne.datasets import sample
data_path = sample.data_path()
raw_fname = data_path + '/MEG/sample/sample_audvis_filt-0-40_raw.fif'
event_fname = data_path + '/MEG/sample/sample_audvis_filt-0-40_raw-eve.fif'
# these data already have an EEG average reference
raw = mne.io.read... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Setup for reading the raw data
Step2: Let's restrict the data to the EEG channels
Step3: By looking at the measurement info you will see that ... |
4,441 | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
from __future__ import print_function
from __future__ import division
import numpy as np
from sympy import symbols, sin, cos, pi, simplify
from math import radians as d2r
from math import degrees as r2d
from math import atan2, sqrt, acos, fabs
t1, t2, t3 = symbols('t1 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: The following class follows the traditional DH convention. Where
Step2: The parameters are
Step3: Inverse Kinematics
Step5: Loading
|
4,442 | <ASSISTANT_TASK:>
Python Code:
week = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']
for weekday in week:
print("Today is ",weekday)
for i in range(len(week)):
print("This is the value of the index, ", i)
weekday = week[i] #once we have the index we can obtain the correspon... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: The following for structure cycles over the elements of the list
Step2: Alternatively we loop over the indices of the list
Step3: Third possib... |
4,443 | <ASSISTANT_TASK:>
Python Code:
import toytree
import toyplot
import numpy as np
## A tree with edge lengths
newick = "((apple:2,orange:4):2,(((tomato:2,eggplant:1):2,pepper:3):1,tomatillo:2):1);"
tre = toytree.tree(newick)
## show tip labels
tre.draw();
## hide tip labels
tre.draw(tip_labels=False);
## enter a new li... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Hide/Show tip labels
Step2: Modify tip labels
Step3: Color tip labels
Step4: Aligning tip labels
Step5: Styling edges on aligned tip trees
|
4,444 | <ASSISTANT_TASK:>
Python Code:
import graphlab
sales = graphlab.SFrame('kc_house_data.gl/')
train_data,test_data = sales.random_split(.8,seed=0)
# Let's compute the mean of the House Prices in King County in 2 different ways.
prices = sales['price'] # extract the price column of the sales SFrame -- this is now an SA... | <SYSTEM_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 house sales data
Step2: Split data into training and testing
Step3: Useful SFrame summary functions
Step4: As we see we get the same ans... |
4,445 | <ASSISTANT_TASK:>
Python Code:
# uncomment the following line to install/upgrade the PixieDust library
# ! pip install pixiedust --user --upgrade
import pixiedust
from pixiedust.display.app import *
@PixieApp
class HelloWorldPixieApp:
@route()
def main(self):
return
<input pd_options="click... | <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: Hello World
Step5: <hr>
|
4,446 | <ASSISTANT_TASK:>
Python Code:
# Import some libraries
import numpy as np
import math
from test_helper import Test
# Define data file
ratingsFilename = 'u.data'
# Read data with spark
rawRatings = sc.textFile(ratingsFilename)
# Check file format
print rawRatings.take(10)
##############################################... | <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: Formatting the data
Step3: 2. Format your data
Step4: Creating training and test rating matrices
Step6: Baseline recommender
Step7: 2. Compu... |
4,447 | <ASSISTANT_TASK:>
Python Code:
from pygoose import *
import os
import sys
from scipy.sparse import csr_matrix, dok_matrix
from sklearn.decomposition import TruncatedSVD
from sklearn.metrics.pairwise import cosine_distances, euclidean_distances, manhattan_distances
project = kg.Project.discover()
feature_list_id = '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: Config
Step2: Identifier for storing these features on disk and referring to them later.
Step3: Number of SVD components.
Step4: Make subsequ... |
4,448 | <ASSISTANT_TASK:>
Python Code:
# We need libffi-dev to launch the Dataflow pipeline.
!apt-get -qq install libffi-dev
# Clone the python-docs-samples respository.
!git clone https://github.com/GoogleCloudPlatform/python-docs-samples.git
# Navigate to the sample code directory.
%cd python-docs-samples/people-and-planet-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: 🛎️ [DON’T PANIC] It’s safe to ignore the warnings.
Step2: ✏️ Entering project details
Step3: Click the run button ▶️ for the cells above.
Ste... |
4,449 | <ASSISTANT_TASK:>
Python Code:
import numpy as np
A = np.array([[1,2,3]]); print(A)
B = np.array([[1,2,3],[4,5,6],[7,8,9]]); print(B)
C = np.zeros((2,1)); print(C)
D = np.ones((1,3)); print(D)
E = np.random.randn(3,3); print(E)
print(B)
B[0] #first row
B[:,0] #first column
B[0,0]
B[2,2]
B[:,0]
print(B.dtype)
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: Create Basic Arrays
Step2: Array Indexing
Step3: Array Attributes
Step4: Array Methods
Step5: Array Calcuations
Step6: Array Arithmetic
|
4,450 | <ASSISTANT_TASK:>
Python Code:
import numpy as np
import scipy as sp
from scipy import integrate,stats
def bekkers(x, a, m, d):
p = a*np.exp((-1*(x**(1/3) - m)**2)/(2*d**2))*x**(-2/3)
return(p)
range_start = 1
range_end = 10
estimated_a, estimated_m, estimated_d = 1,1,1
sample_data = [1.5,1.6,1.8,2.1,2.2,3.3,4,... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
|
4,451 | <ASSISTANT_TASK:>
Python Code:
import pandas as pd
import requests
from urllib.parse import quote
from artist_api import *
artists_df = pd.read_csv('artists.dat', sep='\t', header=0, index_col=0, skipinitialspace=True)
artists_df.head()
artists_df['mbid'] = artists_df.apply(parse_artists, axis=1)
artists_df_mbid = pd... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: The artist dataset contains ids, Artist names, Artist url, and Artist pictureURL.
Step2: In this notebook we extract the unique mbid code ident... |
4,452 | <ASSISTANT_TASK:>
Python Code:
from sklearn.datasets import make_regression
from sklearn.cross_validation import train_test_split
X, y, true_coefficient = make_regression(n_samples=80, n_features=30, n_informative=10, noise=100, coef=True, random_state=5)
X_train, X_test, y_train, y_test = train_test_split(X, y, random... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Linear Regression
Step2: Ridge Regression (L2 penalty)
Step3: Lasso (L1 penalty)
Step4: Linear models for classification
Step5: Multi-Class ... |
4,453 | <ASSISTANT_TASK:>
Python Code:
import scipy.optimize
import numpy as np
np.random.seed(42)
a = np.random.rand(3,5)
x_true = np.array([10, 13, 5, 8, 40])
y = a.dot(x_true ** 2)
x0 = np.array([2, 3, 1, 4, 20])
def residual_ans(x, a, y):
s = ((y - a.dot(x**2))**2).sum()
return s
out = scipy.optimize.minimize(resid... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
|
4,454 | <ASSISTANT_TASK:>
Python Code:
import numpy as np
from keras import layers
from keras import optimizers
from keras.layers import Input, Dense, Activation, ZeroPadding2D, BatchNormalization, Flatten, Conv2D
from keras.layers import AveragePooling2D, MaxPooling2D, Dropout, GlobalMaxPooling2D, GlobalAveragePooling2D
from ... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Note
Step3: Details of the "Happy" dataset
Step4: You have now built a function to describe your model. To train and test this model, there ar... |
4,455 | <ASSISTANT_TASK:>
Python Code:
# Install tflearn
import os
os.system("sudo pip install tflearn")
import numpy as np
import pandas as pd
import copy
from matplotlib import pyplot as plt
%matplotlib inline
# Temporarily load from np arrays
chi_photos_np = np.load('chi_photos_np_0.03_compress.npy')
lars_photos_np = np.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: Feature Building
Step2: Scaling Inputs
Step3: Reshaping 3D Array To 4D Array
Step4: Putting It All Together
Step5: Preparing Labels
Step6: ... |
4,456 | <ASSISTANT_TASK:>
Python Code:
import os
import sys
import matplotlib.pyplot as plt
import numpy as np
import imageio
import pandas as pd
import seaborn as sns
sns.set(style='ticks')
sys.path.append('../scripts/')
import bicorr as bicorr
import bicorr_e as bicorr_e
import bicorr_plot as bicorr_plot
import bicorr_sums 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: Load some data
Step2: Specify energy range
Step3: singles_hist_e_n.npz
Step4: Load bhp_nn_e for all pairs
Step5: Set up det_df columns and s... |
4,457 | <ASSISTANT_TASK:>
Python Code:
import nltk
import pandas as pd
import numpy as np
data = pd.read_csv("original_train_data.csv", header = None,delimiter = "\t", quoting=3,names = ["Polarity","TextFeed"])
#Data Visualization
data.head()
data_positive = data.loc[data["Polarity"]==1]
data_negative = data.loc[data["Polarit... | <SYSTEM_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 Preparation
Step2: Data pre-processing - text analytics to create a corpus
Step3: The below implementation produces a sparse representati... |
4,458 | <ASSISTANT_TASK:>
Python Code:
import pandas as pd
df = pd.read_csv('ner_dataset.csv.gz', compression='gzip', encoding='ISO-8859-1')
df.info()
df.T
df = df.fillna(method='ffill')
df.info()
df.T
df['Sentence #'].nunique(), df.Word.nunique(), df.POS.nunique(), df.Tag.nunique()
df.Tag.value_counts()
def word2features(se... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: We have 47959 sentences that contain 35178 unique words.
Step2: Conditional Random Fields
Step3: Prepare Train and Test Datasets
Step4: Build... |
4,459 | <ASSISTANT_TASK:>
Python Code:
from IPython.display import IFrame
IFrame('http://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data', width=300, height=200)
# import load_iris function from datasets module
from sklearn.datasets import load_iris
# save "bunch" object containing iris dataset and its attrib... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Machine learning on the iris dataset
Step2: Machine learning terminology
Step3: Each value we are predicting is the response (also known as
St... |
4,460 | <ASSISTANT_TASK:>
Python Code:
from bedrock.client.client import BedrockAPI
import requests
import pandas
import pprint
SERVER = "http://localhost:81/"
api = BedrockAPI(SERVER)
resp = api.ingest("opals.spreadsheet.Spreadsheet.Spreadsheet")
if resp.json():
print("Spreadsheet Opal Installed!")
else:
print("Spre... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Test Connection to Bedrock Server
Step2: Check for Spreadsheet Opal
Step3: Check for logit2 Opal
Step4: Check for select-from-dataframe Opal
... |
4,461 | <ASSISTANT_TASK:>
Python Code:
import sys
import os
sys.path.insert(0, '/usr/hdp/2.6.0.3-8/spark2/python')
sys.path.insert(0, '/usr/hdp/2.6.0.3-8/spark2/python/lib/py4j-0.10.4-src.zip')
os.environ['SPARK_HOME'] = '/usr/hdp/2.6.0.3-8/spark2/'
os.environ['SPARK_CONF_DIR'] = '/etc/hadoop/synced_conf/spark2/'
os.environ['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: Airlines Data
Step2: You can interact with a DataFrame via SQLContext using SQL statements by registerting the DataFrame as a table
Step3: How... |
4,462 | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
import networkx as nx
import matplotlib.pyplot as plt
import random
G = nx.Graph()
G.add_edge(0,5)
n = 15
labels={0:"0",5:"5"}
for i in range(0,30):
a,b = random.randint(0,n),random.randint(0,n)
G.add_edge(b,a)
labels[a]=str(a)
labels[b]=str(b)
pos=nx.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: On suppose qu'on a un graphe $G(V,E)$ pour lequel on cherche à déterminer la distance de tous les noeuds à un noeud précis du graphe. Si calcule... |
4,463 | <ASSISTANT_TASK:>
Python Code:
%load_ext watermark
%watermark -a '' -u -d -v -p numpy,matplotlib,theano,keras
from IPython.display import Image
%matplotlib inline
import theano
from theano import tensor as T
import numpy as np
# define expression
# which can be visualized as a graph
x1 = T.scalar()
w1 = T.scalar()
w0... | <SYSTEM_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 use of watermark is optional. You can install this IPython extension via "pip install watermark". For more information, please see
Step2: B... |
4,464 | <ASSISTANT_TASK:>
Python Code:
X = np.array([[-1.0, -1.0], [-1.2, -1.4], [1, -0.5], [-3.4, -2.2], [1.1, 1.2], [-2.1, -0.2]])
y = np.array([1, 1, 1, 2, 2, 2])
x_new = [0, 0]
plt.scatter(X[y==1, 0], X[y==1, 1], s=100, c='r')
plt.scatter(X[y==2, 0], X[y==2, 1], s=100, c='b')
plt.scatter(x_new[0], x_new[1], s=100, c='g')
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: 다수결 모형이 개별 모형보다 더 나은 성능을 보이는 이유는 다음 실험에서도 확인 할 수 있다.
Step2: 배깅
Step3: 랜덤 포레스트
Step4: 랜덤 포레스트의 장점 중 하나는 각 독립 변수의 중요도(feature importance)를 계산할 ... |
4,465 | <ASSISTANT_TASK:>
Python Code:
import gmpy2
from gmpy2 import sqrt as rt2
from gmpy2 import mpfr
gmpy2.get_context().precision=200
root2 = rt2(mpfr(2))
root3 = rt2(mpfr(3))
root5 = rt2(mpfr(5))
ø = (root5 + 1)/2
ø_down = ø ** -1
ø_up = ø
E_vol = (15 * root2 * ø_down ** 3)/120 # a little more than 1/24, volume of T modu... | <SYSTEM_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 lets import the tetravolume.py module, which in turn has dependencies, to get these volumes directly, based on edge lengths. I'll use the e... |
4,466 | <ASSISTANT_TASK:>
Python Code:
data_sets = input_data.read_data_sets(FLAGS.train_dir, FLAGS.fake_data)
images_placeholder = tf.placeholder(tf.float32, shape=(batch_size,
mnist.IMAGE_PIXELS))
labels_placeholder = tf.placeholder(tf.int32, shape=(batch_size))
with 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: 注意:fake_data标记是用于单元测试的,读者可以不必理会。
Step2: 在训练循环(training loop)的后续步骤中,传入的整个图像和标签数据集会被切片,以符合每一个操作所设置的batch_size值,占位符操作将会填补以符合这个batch_size值。然后使用feed... |
4,467 | <ASSISTANT_TASK:>
Python Code:
import numpy as np
from time import time
from operator import itemgetter
from scipy.stats import randint as sp_randint
from sklearn.grid_search import GridSearchCV, RandomizedSearchCV
from sklearn.datasets import load_digits
from sklearn.ensemble import RandomForestClassifier
iris = load... | <SYSTEM_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, we'll load up the iris data set, an example data set from scikit-learn that has various measurements of different species of i... |
4,468 | <ASSISTANT_TASK:>
Python Code:
import steps.model as smodel
import steps.geom as stetmesh
import steps.utilities.meshio as smeshio
import steps.rng as srng
import steps.solver as solvmod
import pylab
import math
# Number of iterations; plotting dt; sim endtime:
NITER = 10
# The data collection time increment (s)
DT = ... | <SYSTEM_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 set some simulation constants
Step2: Model specification
Step3: Geometry specification
Step4: Then we create a compartment comprising all ... |
4,469 | <ASSISTANT_TASK:>
Python Code:
import data_science.j_utils as j_utils
import data_science.lendingclub.dataprep_and_modeling.modeling_utils.data_prep_new as data_prep
import dir_constants as dc
from sklearn.externals import joblib
import torch
import torch.nn as nn
import torch.optim as optim
from torch.autograd import ... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: DO NOT FORGET TO DROP ISSUE_D AFTER PREPPING
Step2: Until I figure out a good imputation method (e.g. bayes PCA), just drop columns with null s... |
4,470 | <ASSISTANT_TASK:>
Python Code:
2 + 3
2*3
2**3
sin(pi)
from math import sin, pi
sin(pi)
a = 10
a
# ESCRIBE TU CODIGO AQUI
raise NotImplementedError
# ESCRIBE TU CODIGO AQUI
raise NotImplementedError
from nose.tools import assert_equal
assert_equal(_, c)
print("Sin errores")
A = [2, 4, 8, 10]
A
A*2
f = lambda x: x... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Sin embargo no existen funciones trigonométricas cargadas por default. Para esto tenemos que importarlas de la libreria math
Step2: Variables
S... |
4,471 | <ASSISTANT_TASK:>
Python Code:
!pip install xarray netCDF4 geopy
#setup widgets
import ipywidgets as widgets
w = widgets.Dropdown(
options=['Melbourne', 'Sydney', 'Canberra', 'Brisbane', 'Adelaide', 'Hobart', 'Perth', 'Darwin'],
description='Capital city:',
disabled=False,
)
arrYears = [str(i) for i in ran... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Setup widgets to select city and year
Step2: Setup xarray
Step3: Use geopy to get the lat-long coordinates for the selected city
Step4: Use c... |
4,472 | <ASSISTANT_TASK:>
Python Code:
from __future__ import print_function
import math
import random
from pycsa import CoupledAnnealer
try:
xrange
except NameError:
xrange = range
cities = {
'New York City': (40.72, 74.00),
'Los Angeles': (34.05, 118.25),
'Chicago': (41.88, 87.63),
'Houston': (29.77,... | <SYSTEM_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 create a set of cities to use for TSP.
Step3: Now's lets define the function to calculate distances between cities
Step6: Next we have t... |
4,473 | <ASSISTANT_TASK:>
Python Code:
import numpy as np
import faps as fp
import matplotlib.pylab as plt
import pandas as pd
from time import time, localtime, asctime
print("Created using FAPS version {}.".format(fp.__version__))
np.random.seed(37)
allele_freqs = np.random.uniform(0.2, 0.5, 50)
adults = fp.make_parents(10, ... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Before committing to the time and cost of genotyping samples for a paternity study, it is always sensible to run simulations to test the likely ... |
4,474 | <ASSISTANT_TASK:>
Python Code:
import matplotlib.pyplot as plt
import numpy as np
import xarray as xr
%load_ext autoreload
%autoreload 2
fig, axarr = plt.subplots(ncols=2, nrows=2)
# plot the same signal scaled and shifted or both
axarr.flat[0].plot(np.random.rand(10))
axarr.flat[1].plot((np.random.rand(10)*5)-16)
axar... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: These are hard to compare with regard to their amplitude.
Step2: Now we can clearly see the different amplitude.
Step3: Thats pretty cool (xa... |
4,475 | <ASSISTANT_TASK:>
Python Code::
from PIL import Image
import numpy as np
import matplotlib.pyplot as plt
from scipy.signal import convolve2d
image = Image.open('image.jpg')
gray = np.mean(image, axis = 2)
h_x = [[1,0,-1], [2,0,-2], [1,0,-1]]
h_y = [[1,2,1], [0,0,0], [-1,-2,-1]]
g_x = convolve2d(gray, h_x)
g_y = convolv... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
|
4,476 | <ASSISTANT_TASK:>
Python Code:
import os
from os.path import isdir, join
from pathlib import Path
import pandas as pd
from tqdm import tqdm
# Math
import numpy as np
import scipy.stats
from scipy.fftpack import fft
from scipy import signal
from scipy.io import wavfile
import librosa
import librosa.display
from scipy im... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Recompute
Step2: Feature Extraction
Step3: Pipeline for a small number of audio files
Step4: After selecting 2 words we normalize their valu... |
4,477 | <ASSISTANT_TASK:>
Python Code:
## You can use Python as a calculator:
5*7 #This is a comment and does not affect your code.
#You can have as many as you want.
#Comments help explain your code to others and yourself.
#No worries.
5+7
5-7
5/7
a = 10
b = 7
print(a)
print(b)
print(a*b , a+b, a/b)
a = 5
b = 7
print(a*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: Unfortunately, the output of your calculations won't be saved anywhere, so you can't use them later in your code.
Step2: You can also write ov... |
4,478 | <ASSISTANT_TASK:>
Python Code:
# install published dev version
# !pip install cirq~=0.4.0.dev
# install directly from HEAD:
!pip install git+https://github.com/quantumlib/Cirq.git@8c59dd97f8880ac5a70c39affa64d5024a2364d0
import cirq
import numpy as np
import matplotlib.pyplot as plt
print(cirq.google.Foxtail)
a = cir... | <SYSTEM_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 verify that Cirq is installed in your environment, try to import cirq and print out a diagram of the Foxtail device. It should produce a 2x11... |
4,479 | <ASSISTANT_TASK:>
Python Code:
from IPython.display import Image
Image("images/monty.png")
from pgmpy.models import BayesianNetwork
from pgmpy.factors.discrete import TabularCPD
# Defining the network structure
model = BayesianNetwork([("C", "H"), ("P", "H")])
# Defining the CPDs:
cpd_c = TabularCPD("C", 3, [[0.33], [... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: with the following CPDs
|
4,480 | <ASSISTANT_TASK:>
Python Code:
import tensorflow as tf
import numpy as np
import shutil
print(tf.__version__)
!gsutil cp gs://cloud-training-demos/taxifare/traffic/small/*.csv .
!ls -l *.csv
CSV_COLUMN_NAMES = ["fare_amount","dayofweek","hourofday","pickuplon","pickuplat",\
"dropofflon","dropoffla... | <SYSTEM_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 raw data
Step2: Train and Evaluate input functions
Step3: Feature Engineering
Step4: Feature Engineering
Step5: Gather list of feature ... |
4,481 | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
from scipy.integrate import odeint
from IPython.html.widgets import interact, fixed
def lorentz_derivs(yvec, t, sigma, rho, beta):
Compute the the derivatives for the Lorentz system at yvec(t).
x = yvec[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:
Step2: Lorenz system
Step4: Write a function solve_lorenz that solves the Lorenz system above for a particular initial condition $[x(0),y(0),z(0)]$. Y... |
4,482 | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
import numpy as np
import idx2numpy
import pyflann
import mnist
import matplotlib.pyplot as plt
train_image_labels = idx2numpy.convert_from_file('train-labels-idx1-ubyte')
train_images = idx2numpy.convert_from_file('train-images-idx3-ubyte')
test_image_labels = idx2nump... | <SYSTEM_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 first step is to build the index.
Step2: Let's take a look at our test data. Plotting routines can be found on GitHub.
Step3: Let us try a... |
4,483 | <ASSISTANT_TASK:>
Python Code:
# DO NOT EDIT !
from pyesdoc.ipython.model_topic import NotebookOutput
# DO NOT EDIT !
DOC = NotebookOutput('cmip6', 'ec-earth-consortium', 'ec-earth3-veg', 'seaice')
# Set as follows: DOC.set_author("name", "email")
# TODO - please enter value(s)
# Set as follows: DOC.set_contr... | <SYSTEM_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... |
4,484 | <ASSISTANT_TASK:>
Python Code:
from astropy import time
from poliastro.twobody.orbit import Orbit
from poliastro.bodies import Earth
from poliastro.frames import Planes
from poliastro.plotting import StaticOrbitPlotter
eros = Orbit.from_sbdb("Eros")
eros.plot(label="Eros");
ganymed = Orbit.from_sbdb("1036") # Ganyme... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Small Body Database (SBDB)
Step2: You can also search by IAU number or SPK-ID (there is a faster neows.orbit_from_spk_id() function in that cas... |
4,485 | <ASSISTANT_TASK:>
Python Code:
# YOUR CODE HERE
raise NotImplementedError()
assert True # leave this to grade the import statements
# YOUR CODE HERE
raise NotImplementedError()
assert True # leave this to grade the image display
# YOUR CODE HERE
raise NotImplementedError()
assert True # leave this here to grade the q... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Basic rich display
Step2: Use the HTML object to display HTML in the notebook that reproduces the table of Quarks on this page. This will requi... |
4,486 | <ASSISTANT_TASK:>
Python Code:
# This tells matplotlib not to try opening a new window for each plot.
%matplotlib inline
# General libraries.
import re
import numpy as np
import matplotlib.pyplot as plt
# SK-learn libraries for learning.
from sklearn.pipeline import Pipeline
from sklearn.neighbors import KNeighborsClas... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Load the data, stripping out metadata so that we learn classifiers that only use textual features. By default, newsgroups data is split into tra... |
4,487 | <ASSISTANT_TASK:>
Python Code:
from eden.io.gspan import load
pos_graphs = list(load('data/bursi.pos.gspan'))
neg_graphs = list(load('data/bursi.neg.gspan'))
graphs = pos_graphs + neg_graphs
y = [1]*len(pos_graphs) + [-1]*len(neg_graphs)
import numpy as np
y = np.array(y)
%%time
from eden.graph import vectorize
X = ve... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: EDeN exports a vectorize function that converts a list of graphs in input to a data matrix in output.
Step2: Several predictive algorithms from... |
4,488 | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
import os
import sys
import platform
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
import flopy
print(sys.version)
print('numpy version: {}'.format(np.__version__))
print('matplotlib version: {}'.format(mpl.__version__))
print('flopy versio... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Model parameters
Step2: Create and run the MODFLOW-USG model
Step3: Read the simulated MODFLOW-USG model results
Step4: Plot MODFLOW-USG resu... |
4,489 | <ASSISTANT_TASK:>
Python Code:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import sqlite3
%matplotlib inline
# Connect to the MIMIC database
conn = sqlite3.connect('data/mimicdata.sqlite')
# Create our test query
test_query =
SELECT subject_id, hadm_id, admittime, dischtime, admission_type,... | <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: Connect to the database
Step4: Load the chartevents data
Step5: Review the patient's heart rate
Step6: In a similar way, we can select rows f... |
4,490 | <ASSISTANT_TASK:>
Python Code:
import os
import tempfile
import tensorflow as tf
import tensorflow_data_validation as tfdv
import time
from apache_beam.options.pipeline_options import PipelineOptions, GoogleCloudOptions, StandardOptions, SetupOptions, DebugOptions, WorkerOptions
from google.protobuf import text_format
... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Set the GCS locations of datasets used during the lab
Step2: Set the local path to the lab's folder.
Step3: Configure GCP project, region, and... |
4,491 | <ASSISTANT_TASK:>
Python Code:
# Load libraries
from sklearn import datasets
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.metrics import classification_report
# Load data
iris = datasets.load_iris()
# Create feature matrix
X = iris.data
# Create ... | <SYSTEM_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 Iris Flower Data
Step2: Create Training And Test Sets
Step3: Train A Logistic Regression Model
Step4: Generate Report
|
4,492 | <ASSISTANT_TASK:>
Python Code:
from datetime import datetime, timedelta
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
%matplotlib inline
sns.set_context('notebook')
def fourier_basis(x, degree, half_period):
Returns a 2-d array of fourier basis.
A = np.ones((x.siz... | <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: Implementation
Step6: CCL4 NY4 data
Step8: The values in the time axis are given in decimal years. We first need to express them as real date ... |
4,493 | <ASSISTANT_TASK:>
Python Code:
import numpy as np
import pandas as pd
from scipy.sparse.linalg import svds
from sklearn.metrics import mean_squared_error
import matplotlib.pyplot as plt
from jlab import load_test_data
X_train = pd.read_csv('MLchallenge2_training.csv')
X_test = load_test_data('test_in.csv')
X = (pd.conc... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Hooray, we did it
Step3: Make a recommender class, a la sklearn
Step4: Tune the one hyperparameter we have
Step5: Optimal performance at k=7
... |
4,494 | <ASSISTANT_TASK:>
Python Code:
import os
import os.path as op
from urllib.request import urlretrieve
from pathlib import Path
URL = "https://github.com/m2dsupsdlclass/lectures-labs/releases/download/totallylookslike/dataset_totally.zip"
FILENAME = "dataset_totally.zip"
if not op.exists(FILENAME):
print('Downloading... | <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: We will use mostly TensorFlow functions to open and process images
Step4: To generate the list of negative images, let's randomize the list of ... |
4,495 | <ASSISTANT_TASK:>
Python Code:
from spirack import SPI_rack, S5k_module, version
import numpy as np
from scipy import signal
import matplotlib.pyplot as plt
%matplotlib notebook
#assert version.__version__ >= '0.1.4', 'spirack version needs to be >= 0.1.4'
print("SPI-rack Code Version: " + version.__version__)
spi = 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: Open SPI rack connection and unlock (necessary after bootup of the controller module).
Step2: Create new S5k module object at correct address a... |
4,496 | <ASSISTANT_TASK:>
Python Code:
## Constants used by this program
CONSONANTS = "bcdfghjklmnpqrstvwyz"
VOWELS = "aeiou"
def convert_pin(pin):
##FIXME: Replace the rest with your code
pass
# %load test_foo.py
from nose.tools import assert_equal
class Testconvert_pin(object):
def test_convert_pin(self):
... | <SYSTEM_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
|
4,497 | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
my_matrix = np.array([[1,3,5],[2,5,1],[2,3,8]])
print(my_matrix)
my_matrix.mean() # mean of the whole matrix
my_matrix.mean(axis=0) # mean of the columns
my_matrix.mean(axis=0)[0] # mean of the 0th column
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: Working with images in python is essentially a visual way of working with 2-d arrays (matrices)
Step2: All of the normal numpy commands work wi... |
4,498 | <ASSISTANT_TASK:>
Python Code:
import nltk
from nltk import corpus
# nltk.download()
# print(dir(corpus))
# corp = corpus.gutenberg
files = corpus.gutenberg.fileids()
print(files)
# NOTE: This is only needed to open NLTK's downloads manager!
# nltk.download()
# Get our source corpora from gutenberg in nltk.
emma_sents ... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Label Samples
|
4,499 | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
import matplotlib.pyplot as plt
n = 19
print("Каждая цифра представлена матрицей формы ", digits.data[n, :].shape)
digit = 255 - digits.data[n, :].reshape(8, 8)
plt.imshow(digit, cmap='gray', interpolation='none')
plt.title("This is " + str(digits.target[n]))
plt.show(... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Чтобы отобразить её на экране, нужно применить метод reshape. Целевая форма — $8 \times 8$.
Step2: Возьмем один из методов прошлой лекции... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.