text_prompt stringlengths 168 30.3k | code_prompt stringlengths 67 124k |
|---|---|
<SYSTEM_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 demonstrate the OTP, we can decrypt the CTs by XOR'ing with the key (k)
Step2: The assignment asks us to examine what happens when we a spac... | <ASSISTANT_TASK:>
Python Code:
m1 = "hello world!!".encode('hex')
m2 = "other message".encode('hex')
key = "secretkey123!".encode('hex')
print 'm1: {}\nm2: {}\nkey: {}'.format(m1, m2, key)
print len(m1), len(m2), len(key)
ct1 = hex(int(m1, 16) ^ int(key, 16))[2:-1]
ct2 = hex(int(m2, 16) ^ int(key, 16))[2:-1]
print 'ct1... |
<SYSTEM_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 loaded automatically by the following configuration in "~/.ipython/profile_default/ipython_config.py"
Step2: After loading the extens... | <ASSISTANT_TASK:>
Python Code:
%load_ext pandas_td.ipython
c = get_config()
c.InteractiveShellApp.extensions = [
'pandas_td.ipython',
]
%td_databases
%td_tables sample
%td_jobs
%td_use sample_datasets
nasdaq
%%td_presto
select count(1) cnt
from nasdaq
%%td_presto -o df
select count(1) cnt
from nasdaq
df
%%... |
<SYSTEM_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 use the same dataset from the last Lab.
Step2: Note that the labels should not be used in the k-means algorithm. It is only used here as ... | <ASSISTANT_TASK:>
Python Code:
import numpy as np
import pandas as pd
import seaborn as sns
%matplotlib inline
df = pd.read_csv ('http://vuduc.org/cse6040/logreg_points_train.csv')
df.head()
sns.lmplot(data=df, x="x_1", y="x_2", hue="label", fit_reg=False,)
points = df.as_matrix (['x_1', 'x_2'])
labels = df['label'].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: Introduction
Step2: Why not just smooth things with a simple linear filter?
Step3: Spike noise
Step4: Signal dropout
Step5: Maybe we need a ... | <ASSISTANT_TASK:>
Python Code:
# import the things we need
from __future__ import print_function, division
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
import pykalman
import ipywidgets
import IPython
import matplotlib, matplotlib.colors
matplotlib.rcParams['figure.figsize'] = (14.0, 8.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:
| <ASSISTANT_TASK:>
Python Code:
import numpy as np
import pandas as pd
import sklearn
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.svm import LinearSVC
corpus, y = load_data()
assert type(corpus) == list
assert type(y) == list
vectorizer = TfidfVectorizer()
X = vectorizer.fit_transform(corpus... |
<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: FQE vs OpenFermion vs Cirq
Step3: The first example we will perform is diagonal Coulomb evolution on the Hartree-Fock state. The diagonal Coul... | <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: TensorFlow Lite Model Analyzer
Step2: Basic usage with MobileNetV3Large Keras model
Step3: Check GPU delegate compatibility
Step4: Case 2
| <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: Part 1
Step2: Part 2
Step3: Part 3
Step4: The Gaussian Kernel between x1 = [1; 2; 1], x2 = [0; 4; -1], sigma = 2 should be about 0.324652.
St... | <ASSISTANT_TASK:>
Python Code:
import numpy as np
import matplotlib.pyplot as plt
import scipy.io
import sklearn.svm
%matplotlib inline
ex6data1 = scipy.io.loadmat('ex6data1.mat')
X = ex6data1['X']
y = ex6data1['y'][:, 0]
def plot_data(X, y, ax=None):
if ax == None:
fig, ax = plt.subplots(figsize=(7,5))
... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Language Translation
Step3: Explore the Data
Step6: Implement Preprocessing Function
Step8: Preprocess all the data and save it
Step10: Chec... | <ASSISTANT_TASK:>
Python Code:
DON'T MODIFY ANYTHING IN THIS CELL
import helper
import problem_unittests as tests
source_path = 'data/small_vocab_en'
target_path = 'data/small_vocab_fr'
source_text = helper.load_data(source_path)
target_text = helper.load_data(target_path)
view_sentence_range = (0, 10)
DON'T MODIFY AN... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: The transitions are coded in terms of state to state transitions. The columns and rows represent the states 0, 1, and 2. The following transitio... | <ASSISTANT_TASK:>
Python Code:
from numpy import array
a = array([
[1, 1, 0],
[1, 0, 0],
[0, 0, 0]
])
b = array([
[0, 1, 0],
[0, 1, 0],
[0, 0, 0]
])
c = array([
[0, 0, 0],
[0, 0, 1],
[0, 0, 0]
])
init = array([
[1, 0, 0]
])
final = array([
[0],
[0],
[1]
])
init.... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Here we get hold of the lines list from the OrbitPlotter.plot method this is a list of lines. The first is the orbit line. The second is the cur... | <ASSISTANT_TASK:>
Python Code:
from astropy.time import Time
import matplotlib.pyplot as plt
plt.ion()
import poliastro.plotting as plotting
from poliastro.bodies import Earth, Mars, Jupiter, Sun
from poliastro.twobody import Orbit
epoch = Time("2018-08-17 12:05:50", scale="tdb")
plotter = plotting.OrbitPlotter()
plott... |
<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: Hildebrand Diagram
Step5: Discrete Ripple Gait
Step9: Continous Ripple Gait
Step10: Gait Plot
Step11: Now the code below runs the for all 4 ... | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
from __future__ import print_function
from __future__ import division
import matplotlib.pyplot as plt
import numpy as np
from numpy.linalg import norm
from math import sin, cos, pi, sqrt
from math import radians as d2r
# def printFoot(i, newpos):
# if i == 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: Données
Step2: Géolocalisation des circonscription
Step3: Géolocation des bureaux de vote
Step4: Ce qui suit explique la façon dont j'ai cons... | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
from jyquickhelper import add_notebook_menu
add_notebook_menu()
from actuariat_python.data import elections_legislatives_bureau_vote
tour = elections_legislatives_bureau_vote(source='xd')
tour["T2"].sort_values(["Code département", "N° de circonscription Lg"]).head()
... |
<SYSTEM_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 recompute the PR data used by this notebook run the
Step2: Create Leakage Table
Step3: Average leakage coefficient
Step4: Conclusions
Ste... | <ASSISTANT_TASK:>
Python Code:
#bsearch_ph_sel = 'all-ph'
#bsearch_ph_sel = 'Dex'
bsearch_ph_sel = 'DexDem'
data_file = 'results/usALEX-5samples-PR-raw-%s.csv' % bsearch_ph_sel
from __future__ import division
import numpy as np
import pandas as pd
from IPython.display import display
import matplotlib.pyplot as plt
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: 2. Set Configuration
Step2: 3. Enter Email Fetch Recipe Parameters
Step3: 4. Execute Email Fetch
| <ASSISTANT_TASK:>
Python Code:
!pip install git+https://github.com/google/starthinker
from starthinker.util.configuration import Configuration
CONFIG = Configuration(
project="",
client={},
service={},
user="/content/user.json",
verbose=True
)
FIELDS = {
'auth_read':'user', # Credentials used for reading... |
<SYSTEM_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 tutorial we'll crop and resample the raw data to a manageable size
Step2: To create fixed length epochs, we simply call the function a... | <ASSISTANT_TASK:>
Python Code:
import os
import numpy as np
import matplotlib.pyplot as plt
import mne
from mne.preprocessing import compute_proj_ecg
sample_data_folder = mne.datasets.sample.data_path()
sample_data_raw_file = os.path.join(sample_data_folder, 'MEG', 'sample',
'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: Image Classification
Step2: Explore the Data
Step5: Implement Preprocess Functions
Step8: One-hot encode
Step10: Randomize Data
Step12: Che... | <ASSISTANT_TASK:>
Python Code:
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
from urllib.request import urlretrieve
from os.path import isfile, isdir
from tqdm import tqdm
import problem_unittests as tests
import tarfile
cifar10_dataset_folder_path = 'cifar-10-batches-py'
class DLProgress(tqdm):
last_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: Problem 1b
Step2: Problem 1c
Step3: Problem 1d
Step4: Problem 2) A Brief Review of Fourier Analysis
Step5: The common Fourier pairs are espe... | <ASSISTANT_TASK:>
Python Code:
def gen_periodic_data(x, period=1, amplitude=1, phase=0, noise=0):
'''Generate periodic data given the function inputs
y = A*sin(2*pi*x/p - phase) + noise
Parameters
----------
x : array-like
input values to evaluate the array
period : float ... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Python has special syntax for catching an arbitary number of parameters. For regular parameters it is a variable with one asterisk * and for key... | <ASSISTANT_TASK:>
Python Code:
def my_function(arg_one, arg_two, optional_1=6, optional_2="seven"):
return " ".join([str(arg_one), str(arg_two), str(optional_1), str(optional_2)])
print(my_function("a", "b"))
print(my_function("a", "b", optional_2="eight"))
#go ahead and try out different components
def count_args... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Date/Time data handling
Step2: In addition to datetime there are simpler objects for date and time information only, respectively.
Step3: Havi... | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from datetime import datetime
now = datetime.now()
now
now.day
now.weekday()
from datetime import date, time
time(3, 24)
date(1970, 9, 3)
my_age = now - datetime(1970, 9, 3)
my_age
my_age.days/365... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: We'll set some hard coded values up front. These should really get read from the environment but I'm lazy at the moment.
Step2: Try connecting ... | <ASSISTANT_TASK:>
Python Code:
import json
import base64
import os
import hashlib
from pprint import pprint # for debug
from jupyter_client.ioloop import IOLoopKernelManager
from tornado.httpclient import AsyncHTTPClient, HTTPClient
SLACK_URL = 'https://hooks.slack.com/services/XXXXXX/XXXXXX/XXXXXXX'
SLACK_TOKEN = 'XX... |
<SYSTEM_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: Закономерность очевидна - всегда присутствует горизонталь (... | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
from string import ascii_uppercase as alphabet
def get_board(board_size):
x, y = np.meshgrid(range(board_size), range(board_size))
board = np.empty(shape=(board_size, board_size), dtype='uint8')
text_colors ... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Sample road traffic data in CSV format can be downloaded here (for the sake of this example, dataset is included in the repository).
Step2: Spl... | <ASSISTANT_TASK:>
Python Code:
from fbprophet import Prophet
import pandas as pd
%matplotlib notebook
import matplotlib
date_parse = lambda date: pd.datetime.strptime(date, '%Y-%m-%d')
time_series = pd.read_csv("solarhringsumferd-a-talningarsto.csv", header=0, names=['ds', 'y'], usecols=[0, 1],
... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Model
Step2: Predict
Step3: Data Processing
Step4: Voxelize Mesh
Step5: Sample SDF
| <ASSISTANT_TASK:>
Python Code:
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
import os
import sys
from pathlib import Path
%load_ext autoreload
%autoreload 2
from DeepSDF import DeepSDF
# model config
deep_sdf_config = {
"nb_layers": 8,
"latent_dim": 1,
"inner... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: 2. Defining a margin such that there is 10% whitespace inside the axes around the drawn line. (Hint
Step2: 3. Setting a 10% margin on the axes ... | <ASSISTANT_TASK:>
Python Code:
import matplotlib.pyplot as plt
ax = plt.axes()
line1, = ax.plot([0, 1, 2, 1.5], [3, 1, 2, 4])
ax.set_xlim(0.5, 2)
ax.set_ylim(1, 5)
plt.show()
ax = plt.axes()
line1, = ax.plot([0, 1, 2, 1.5], [3, 1, 2, 4])
ax.margins(0.1)
plt.show()
ax = plt.axes()
line1, = ax.plot([0, 1, 2, 1.5], [3, ... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: <span id="clustering_notebook_plat_prod">Choose Platform and Product ▴</span>
Step2: Choose product and platform
Step3: <span id="cluste... | <ASSISTANT_TASK:>
Python Code:
import sys
import os
sys.path.append(os.environ.get('NOTEBOOK_ROOT'))
%matplotlib inline
import matplotlib.pyplot as plt
import datacube
import datetime as dt
import xarray as xr
import numpy as np
from utils.data_cube_utilities.data_access_api import DataAccessApi
from utils.data_cube_... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: GIF animation of latent space during training
Step2: to create a gif
| <ASSISTANT_TASK:>
Python Code:
from __future__ import print_function
import numpy as np
import time
import matplotlib.pyplot as plt
import tensorflow as tf
import sys
sys.path.append('..')
import models.VAE as vae
import os
from io import BytesIO
import PIL.Image
import scipy.misc
import scipy.io
from IPython.display 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: Extract features
Step2: There's easier ways that we can do this though. revscoring.Feature overloads simple mathematical operators to allow yo... | <ASSISTANT_TASK:>
Python Code:
import sys
sys.path.append("/usr/local/lib/python3.4/dist-packages/")
sys.path.append("/usr/local/lib/python3.4/dist-packages/revscoring/")
sys.path.append("/usr/local/lib/python3.4/dist-packages/more_itertools/")
sys.path.append("/usr/local/lib/python3.4/dist-packages/deltas/")
!sudo pip... |
<SYSTEM_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: Project 1
Step3: Transforming Text into Numbers
Step4: Project 2
Step5: Project 3
| <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: The Spectral Galerkin method
Step2: Jie Shen's bases with Dirichlet bcs
Step3: Shen's bases with Neumann $u'(\pm 1) = 0$
Step4: Shen's biharm... | <ASSISTANT_TASK:>
Python Code:
from shenfun import *
print('hello world')
from shenfun import *
N = 8
C = FunctionSpace(N, 'Chebyshev', quad='GC', domain=[-2, 2])
L = FunctionSpace(N, 'Legendre')
x, w = C.points_and_weights()
print(L.points_and_weights())
C0 = FunctionSpace(N, 'Chebyshev', bc=(0, 0))
L0 = FunctionSpa... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Exercises
Step2: 2) Make it easier to find Mitzie!
| <ASSISTANT_TASK:>
Python Code:
# Set up feedback system
from learntools.core import binder
binder.bind(globals())
from learntools.sql_advanced.ex4 import *
print("Setup Complete")
# Fill in your answer
query_to_optimize = ____
# Check your answer
q_1.check()
# Lines below will give you a hint or solution code
#_COMMEN... |
<SYSTEM_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 the image is just a numpy array (matrix) that can be indexed like any other array. The np.flipup function ("flip up-down") was used so that ... | <ASSISTANT_TASK:>
Python Code:
from astropy.io import fits as fits
fitsimage=fits.open('filename.fits')
image=np.flipud(fitsimage[0].data)
import matplotlib.pyplot as plt
plt.imshow(image)
plt.show()
<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: Estadística Descriptiva
Step2: Ejemplito
| <ASSISTANT_TASK:>
Python Code:
import os
import pandas as pd
import pandas_profiling as pd_profiling
import altair as alt
def read_field_type(x):
'''
Para facilitar la lectura de los dataframes con los tipos de columna correspondientes.
'''
if x in ['String']:
return str
elif x in ['Integer'... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Reading shape & records
Step2: Metadata
Step3: Read zip codes
Step4: Shapely Union - Works
Step5: OSGEO Unions - Doesn't work
| <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
import shapefile
from functools import reduce
from mpl_toolkits.basemap import Basemap
import matplotlib.pyplot as plt
import numpy as np
sf = shapefile.Reader("Data/cb_2015_us_zcta510_500k/cb_2015_us_zcta510_500k")
def find_max_and_min(shape_records):
points = map(... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: 1144 K fuel and graphite
Step2: Summary
Step3: msre_homogeneous
Step4: 2/27/17
Step5: Above value perfectly matches one-group nubar
Step6: ... | <ASSISTANT_TASK:>
Python Code:
k_nom = 1.0545
k_f_1144 = 1.04149
fuel_reactivity = (k_f_1144 - k_nom) / k_nom / 400
print(fuel_reactivity)
k_f_g_1144 = 1.02315
total_reactivity = (k_f_g_1144 - k_nom) / k_nom / 400
print(total_reactivity)
graph_reactivity = total_reactivity - fuel_reactivity
print(graph_reactivity)
fro... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: load data
Step2: set some model hyper-parameters
Step3: Zero-Augmentation
Step4: build encoder
Step5: build decoder
Step6: build models
Ste... | <ASSISTANT_TASK:>
Python Code:
import numpy as np
import time
import h5py
import keras
import matplotlib.pyplot as plt
import sys
from keras.layers import (Input, Dense, Lambda, Flatten, Reshape, BatchNormalization, Activation,
Dropout, Conv1D, UpSampling1D, MaxPooling1D, ZeroPadding1D, Leaky... |
<SYSTEM_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: BQPlot
Step3: Quantile cuts
| <ASSISTANT_TASK:>
Python Code:
from IPython.lib.display import YouTubeVideo
YouTubeVideo("FytuB8nFHPQ", width=400, height=300)
from __future__ import absolute_import, division, print_function
%matplotlib inline
import matplotlib.pyplot as plt
import seaborn as sns
sns.set_context('poster')
sns.set_style('whitegrid')
#... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Contents
Step2: The Stanford English Colors in Context corpus (SCC) is included in the data distribution for this course. If you store the data... | <ASSISTANT_TASK:>
Python Code:
__author__ = "Christopher Potts"
__version__ = "CS224u, Stanford, Spring 2022"
from colors import ColorsCorpusReader
import os
import pandas as pd
from sklearn.model_selection import train_test_split
import torch
from torch_color_describer import (
ContextualColorDescriber, create_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: 1. Load the LAS file with lasio
Step2: That's it! But the object itself doesn't tell us much — it's really just a container
Step3: 2. Look at ... | <ASSISTANT_TASK:>
Python Code:
import welly
ls ../data/*.LAS
import lasio
l = lasio.read('../data/P-129.LAS') # Line 1.
l
l.header['Well'] # Line 2.
l.header['Parameter']['EKB']
l.data
l.curves.GR # Line 3.
l['GR'] # Line 4.
import matplotlib.pyplot as plt
plt.figure(figsize=(15,3))
plt.plot(l['DEPT'], l['G... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: We also have a Python file containing implementations for several functions that will be used during the course of this assignment.
Step2: Load... | <ASSISTANT_TASK:>
Python Code:
import graphlab
'''Check GraphLab Create version'''
from distutils.version import StrictVersion
assert (StrictVersion(graphlab.version) >= StrictVersion('1.8.5')), 'GraphLab Create must be version 1.8.5 or later.'
from em_utilities import *
wiki = graphlab.SFrame('people_wiki.gl/').head... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
| <ASSISTANT_TASK:>
Python Code:
def fact(n ) :
if n == 1 or n == 0 :
return 1
else :
return n * fact(n - 1 )
def findValue(n , r , a ) :
k =(a - 1 ) // fact(n )
answer = k
for i in range(1 , n + 1 ) :
answer = answer *(n + r - i )
answer = answer + 1
return answer
N = 1
A = 2
R = 3
... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Material Properties
Step2: Slab Geometry Width and Discretization
Step3: Generation of Leakage Matrix
Step4: Algorithm
| <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
D = 0.9
nusigf = 0.70
siga = 0.066
#Lx = np.pi*((nusigf-siga)/D)**(-0.5)
Lx = 15.0
N = 55;
h = Lx/(N-1)
x = np.zeros(N)
for i in range(N-1):
x[i+1] = x[i] + h
L = np.zeros((N,N))
A = np.zeros((N,N))
M = np.zeros(... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Load data
Step2: Plot the raw PSD
Step3: Plot a cleaned PSD
Step4: Alternative functions for PSDs
| <ASSISTANT_TASK:>
Python Code:
# Authors: Alexandre Gramfort <alexandre.gramfort@inria.fr>
# Martin Luessi <mluessi@nmr.mgh.harvard.edu>
# Eric Larson <larson.eric.d@gmail.com>
# License: BSD (3-clause)
import numpy as np
import matplotlib.pyplot as plt
import mne
from mne import io, read_proj, read_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: To always time execution of a function, just add the decorator to its definition...
Step2: ...and whenever the function is run it will print th... | <ASSISTANT_TASK:>
Python Code:
import time
def time_usage(func):
def wrapper(*args, **kwargs):
beg_ts = time.time ()
func(*args, **kwargs)
end_ts = time.time ()
print("elapsed time: %f" % (end_ts - beg_ts))
return wrapper
@time_usage
def test():
for i in range(0, 100000):
... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: <p style="font-family
Step2: <p style="font-family
Step3: <p style="font-family
Step4: Use array slicing to get a subarray consisting of the ... | <ASSISTANT_TASK:>
Python Code:
import numpy as np
an_array = np.array([3, 33, 333]) # Create a rank 1 array
print(type(an_array)) # The type of an ndarray is: "<class 'numpy.ndarray'>"
import numpy as np
my_array = np.array([2, 22, 456])
print(type(my_array))
# test the shape of the array we just created,... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Recap
Step2: Using the filtering and reductions operations we have seen in the previous notebooks, we could do something like
Step3: Pandas do... | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
try:
import seaborn
except ImportError:
pass
pd.options.display.max_rows = 10
df = pd.DataFrame({'key':['A','B','C','A','B','C','A','B','C'],
'data': [0, 5, 10, 5, 10, 15,... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Initialize
Step2: Define the variables
Step3: Define the function to take the derivative of
Step4: Calculating the solution
Step5: Plot
Step... | <ASSISTANT_TASK:>
Python Code:
%matplotlib notebook
from sympy import init_printing
from sympy import S
from sympy import sin, cos, tanh, exp, pi, sqrt
from boutdata.mms import x, y, z, t
from boutdata.mms import DDX
import os, sys
# If we add to sys.path, then it must be an absolute path
common_dir = os.path.abspath('... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Load data
Step2: RandomForestClassifier
Step3: Hiperparameter optimization
Step4: Use of RandomizedSearchCV
| <ASSISTANT_TASK:>
Python Code:
from __future__ import print_function
from sklearn import __version__ as sklearn_version
print('Sklearn version:', sklearn_version)
from sklearn import datasets
digits = datasets.load_digits()
print(digits.DESCR)
print(digits.data)
print(digits.target)
#Randomize and separate train & tes... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
| <ASSISTANT_TASK:>
Python Code:
import numpy as np
data = np.array([4, 2, 5, 6, 7, 5, 4, 3, 5, 7])
bin_size = 3
bin_data_max = data[:(data.size // bin_size) * bin_size].reshape(-1, bin_size).max(axis=1)
<END_TASK> |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Getting the data ready for work
Step2: Testing bicalib
Step3: Comparing results with the report file (bicalib.rep)
Step4: Note
Step5: expect... | <ASSISTANT_TASK:>
Python Code:
#general imports
import matplotlib.pyplot as plt
import pygslib
import numpy as np
import pandas as pd
#make the plots inline
%matplotlib inline
#get the data in gslib format into a pandas Dataframe
cluster= pygslib.gslib.read_gslib_file('../data/cluster.dat')
ydata = pygslib.gs... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Make a PMF of <tt>numkdhh</tt>, the number of children under 18 in the respondent's household.
Step2: Display the PMF.
Step4: Define <tt>BiasP... | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
import chap01soln
import thinkstats2
import thinkplot
import nsfg
import numpy as np
import pandas as pd
resp = chap01soln.ReadFemResp()
fem = nsfg.ReadFemPreg()
pmf = thinkstats2.Pmf(resp.numkdhh, label='unbiased')
first = fem[fem.birthord == 1]
other = fem[fem.birtho... |
<SYSTEM_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. Gráficos del Pay Off de opciones Call y Put europeas
Step2: 2. Gráficos de estrategias
Step3: Vende en $\$1$ una opción de compra a tres me... | <ASSISTANT_TASK:>
Python Code:
#importar los paquetes que se van a usar
import pandas as pd
import pandas_datareader.data as web
import numpy as np
import datetime
from datetime import datetime
import scipy.stats as stats
import matplotlib.pyplot as plt
import seaborn as sns
%matplotlib inline
#algunas opciones para Py... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Variables en Python
Step2: <br />
Step3: El valor True se corresponde con el valor entero 1, mientras que el el valor False se corresponde con... | <ASSISTANT_TASK:>
Python Code:
print(2 ** 6)
print(-3)
print(2 * 6)
print(6 / 2)
print(14 % 3)
print(2 + 6)
print(6 - 2)
# Operación especial que realiza la división y solo muestra el valor entero (sin decimales)
print(14 // 3)
# Primero se ejecuta la elevación del número 2 seis veces (64) y luego se le suma 7
print(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: Plot the source estimate
Step2: Plot the activation in the direction of maximal power for this data
Step3: The normal is very similar
Step4: ... | <ASSISTANT_TASK:>
Python Code:
# Author: Marijn van Vliet <w.m.vanvliet@gmail.com>
#
# License: BSD-3-Clause
import numpy as np
import mne
from mne.datasets import sample
from mne.minimum_norm import read_inverse_operator, apply_inverse
print(__doc__)
data_path = sample.data_path()
subjects_dir = data_path + '/subjects... |
<SYSTEM_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 problem
Step2: Find if there's null values
Step3: NaN values will be filled with the mean of the feature they belong. It's a good way to... | <ASSISTANT_TASK:>
Python Code:
import numpy as np
import pandas as pd
#load the files
train = pd.read_csv('input/train.csv')
test = pd.read_csv('input/test.csv')
data = pd.concat([train, test])
#size of training dataset
train_samples = train.shape[0]
#print some of them
data.head()
# remove the Id feature, because is 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: If you already have an H2O cluster running that you'd like to connect to (for example, in a multi-node Hadoop environment), then you can specify... | <ASSISTANT_TASK:>
Python Code:
import h2o
# Start an H2O Cluster on your local machine
h2o.init()
# This will not actually do anything since it's a fake IP address
# h2o.init(ip="123.45.67.89", port=54321)
csv_url = "https://h2o-public-test-data.s3.amazonaws.com/smalldata/wisc/wisc-diag-breast-cancer-shuffled.csv"
da... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Now load my face into the thingie!
Step2: Join the data.
Step3: Training logistic regression
Step4: Fit and save final model
| <ASSISTANT_TASK:>
Python Code:
faceshape = (80,80)
ws = []
hs = []
data = []
for (path, label) in labelled_paths:
im = cv2.imread(path, 0)
faces = face_cascade.detectMultiScale(im, 1.3, 5)
if faces == ():
#print 'missed a face'
continue
else:
(x,y,w,h) = faces.tolist()[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: Loading pickle files
Step2: Sample training images with labels
Step3: Sample test images with labels
Step4: The class distribution is pretty ... | <ASSISTANT_TASK:>
Python Code:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import pickle
plt.style.use('fivethirtyeight')
# plt.rcParams['font.family'] = 'serif'
plt.rcParams['font.serif'] = 'Helvetica'
plt.rcParams['font.monospace'] = 'Consolas'
plt.rcParams['font.size'... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Parameters
Step3: Setup dataset and model
Step4: Model parameters
Step5: Training loop
| <ASSISTANT_TASK:>
Python Code:
%pip --quiet install objax
import math
import random
import numpy as np
import tensorflow_datasets as tfds
import objax
from objax.zoo.wide_resnet import WideResNet
base_learning_rate = 0.1 # Learning rate
lr_decay_epochs = 30 # How often to decay learning rate
lr_decay_factor = 0.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: Load data from CSV files
Step2: Data merging
Step3: Let's explore some data
Step4: 'angle bracket' search term is not contained in the body. ... | <ASSISTANT_TASK:>
Python Code:
import graphlab as gl
train = gl.SFrame.read_csv("../data/train.csv")
test = gl.SFrame.read_csv("../data/test.csv")
desc = gl.SFrame.read_csv("../data/product_descriptions.csv")
# merge train with description
train = train.join(desc, on = 'product_uid', how = 'left')
# merge test with 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: 2. Join data to identify common water samples
Step2: Next. check how much of the data downloaded by Salar is already in the database.
Step3: S... | <ASSISTANT_TASK:>
Python Code:
# Read data
in_xls = (r'C:\Data\James_Work\Staff\Heleen_d_W\ICP_Waters\TOC_Trends_Analysis_2015'
r'\Swedish_Ca_Data\Missing_Data_25_Swedish_Sites.xlsx')
smhi_df = pd.read_excel(in_xls, sheetname='salar_data')
resa_df = pd.read_excel(in_xls, sheetname='from_resa_10-02-2017')
# Ge... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Trouvons une méthode pour communiquer.
Step2: Super, alors, on va décréter que
Step3: Tu as raté? c'est pas grâve, recommmence, essaies ces li... | <ASSISTANT_TASK:>
Python Code:
from poppy.creatures import PoppyTorso
poppy=PoppyTorso(simulator='vrep')
# oui
for i in range(0,3):
poppy.head_y.goto_position(15,0.5,wait=True)
poppy.head_y.goto_position(-15,0.5,wait=True)
print i
poppy.head_y.goto_position(-15,0.1,wait=True)
import time
position_start = 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: Example 1
Step2: Example 2
Step3: The resulting hill is taller (due to the higher uplift rate) and no longer has uniform convexity.
| <ASSISTANT_TASK:>
Python Code:
import numpy as np
import matplotlib.pyplot as plt
from landlab import RasterModelGrid
from landlab.components import TaylorNonLinearDiffuser
# define parameters
L = 50.0 # distance from base to ridgeline, m
dx = 2.0 # node spacing, m
D = 0.01 # diffusion-like coefficient, m2/y
U = 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: Document Authors
Step2: Document Contributors
Step3: Document Publication
Step4: Document Table of Contents
Step5: 1.2. Model Name
Step6: 1... | <ASSISTANT_TASK:>
Python Code:
# DO NOT EDIT !
from pyesdoc.ipython.model_topic import NotebookOutput
# DO NOT EDIT !
DOC = NotebookOutput('cmip6', 'bnu', 'sandbox-2', 'atmos')
# 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: Now we import some modules we use and add the PyPhysim to the python path.
Step2: Now we set the transmit parameters and load the simulation re... | <ASSISTANT_TASK:>
Python Code:
%pylab inline
import sys
sys.path.append("/home/darlan/cvs_files/pyphysim")
# xxxxxxxxxx Import Statements xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
from pyphysim.simulations.core import SimulationRunner, SimulationParameters, SimulationResults, Result
from pyphysim.comm import modula... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Fit a line to a toy 2D problem.
Step2: MNIST
Step3: Multilayer convolutional network
Step4: The intuition is correct. In mathematics, $\frac{... | <ASSISTANT_TASK:>
Python Code:
%load_ext autoreload
%autoreload 2
%matplotlib inline
#%config InlineBackend.figure_format = 'svg'
#%config InlineBackend.figure_format = 'pdf'
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import scipy.stats as stats
import tensorflow as tf
# font options
font = {
... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Make a table showing the number of respondents in each cycle
Step2: Check for missing values in agemarry
Step3: Estimate the hazard function f... | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
import pandas as pd
import numpy as np
import seaborn as sns
import math
import matplotlib.pyplot as plt
from matplotlib import pylab
from scipy.interpolate import interp1d
from scipy.misc import derivative
import thinkstats2
import thinkplot
from thinkstats2 import Cdf... |
<SYSTEM_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 X and y
Step2: Exercise 5.1
Step3: Exercise 5.2
Step4: Exercise 5.3
Step5: Exercise 5.4
Step6: Exercise 5.5
| <ASSISTANT_TASK:>
Python Code:
import pandas as pd
url = 'https://raw.githubusercontent.com/justmarkham/DAT8/master/data/titanic.csv'
titanic = pd.read_csv(url, index_col='PassengerId')
titanic.head()
feature_cols = ['Pclass', 'Parch']
X = titanic[feature_cols]
Y = titanic.Survived
import numpy as np
# Insert code he... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Berechnung wesentlicher Metriken für Größe und Nutzungsgrad
Step2: Vorbereitung Verbindung zu technischen Schulden
Step3: Änderungshäufigkeit ... | <ASSISTANT_TASK:>
Python Code:
import pandas as pd
coverage = pd.read_csv("../dataset/jacoco_production_coverage_spring_petclinic.csv")
coverage.head()
coverage['lines'] = coverage.LINE_MISSED + coverage.LINE_COVERED
coverage['covered'] = coverage.LINE_COVERED / coverage.lines
coverage.head()
coverage['fqn'] = covera... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Constants / Parameters
Step2: Interpolation and cleanup
Step3: Deduplication
Step4: Outlier removal
Step5: "by-hand" fixes for particular da... | <ASSISTANT_TASK:>
Python Code:
# boilerplate includes
import sys
import os
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
#from mpl_toolkits.mplot3d import Axes3D
import pandas as pd
import seaborn as sns
import datetime
import scipy.interpolate
# import re
from IPython.display import displ... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: You can access elements of the sequence in the same way as for strings (but remember, Python counts from zero!)
Step2: The Seq object has a .co... | <ASSISTANT_TASK:>
Python Code:
from Bio.Seq import Seq
my_seq = Seq("GATCG")
for index, letter in enumerate(my_seq):
print("%i %s" % (index, letter))
print(len(my_seq))
print(my_seq[0]) #first letter
print(my_seq[2]) #third letter
print(my_seq[-1]) #last letter
print("AAAA".count("AA"))
print(Seq("AAAA").count("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: Import relevant stingray libraries.
Step2: Initializing
Step3: For ease of analysis, define a simple delta impulse response with width 1. Here... | <ASSISTANT_TASK:>
Python Code:
import numpy as np
from matplotlib import pyplot as plt
%matplotlib inline
from stingray import Lightcurve, Crossspectrum, sampledata
from stingray.simulator import simulator, models
var = sampledata.sample_data()
# Beware: set tstart here, or nothing will work!
sim = simulator.Simulato... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Variables
Step2: Simple data types
Step3: Arithmetic operations
Step4: Lists
Step5: Dictionnaries
Step6: Sets
Step7: Tuples
Step8: String... | <ASSISTANT_TASK:>
Python Code:
print('Hello from python!') # to print some text, enclose it between quotation marks - single
print("I'm here today!") # or double
print(34) # print an integer
print(2 + 4) # print the result of an arithmetic operation
print("The answer is", 42) # 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: Au lieu d'imprimer l'objet numpy, on peut voir sa représentation directement
Step2: Créons une deuxième liste ainsi qu'une liste de listes
Step... | <ASSISTANT_TASK:>
Python Code:
import numpy as np # Presque tous les programmeurs utilisent l'abbréviation np
ma_liste = [1, 2, 3, 4, 5]
array1 = np.array(ma_liste)
print("ma liste:", ma_liste)
print("objet numpy: ", array1)
array1
ma_liste2 = [10, 20, 30, 40, 50]
mes_listes = [ma_liste, ma_liste2]
print("mes listes... |
<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: Where Am I?
Step5: Commit and Deploy New Tensorflow AI Model
Step6: Airflow Workflow Deploys New Model through Github Post-Commit Webhook to T... | <ASSISTANT_TASK:>
Python Code:
import numpy as np
import os
import tensorflow as tf
from tensorflow.contrib.session_bundle import exporter
import time
# make things wide
from IPython.core.display import display, HTML
display(HTML("<style>.container { width:100% !important; }</style>"))
from IPython.display import clear... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: After importing Essentia library, let's import other numerical and plotting tools
Step2: Define the parameters of the STFT workflow
Step3: Spe... | <ASSISTANT_TASK:>
Python Code:
# import essentia in streaming mode
import essentia
import essentia.streaming as es
# import matplotlib for plotting
import matplotlib.pyplot as plt
import numpy as np
# algorithm parameters
params = { 'frameSize': 2048, 'hopSize': 512, 'startFromZero': False, 'sampleRate': 44100, \
... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Basics of MapReduce
Step2: Quiz
Step3: Mapper
Step4: Reducer
Step5: Quiz
| <ASSISTANT_TASK:>
Python Code:
from IPython.display import HTML
HTML('<iframe width="846" height="476" src="https://www.youtube.com/embed/KdSqUjFWzdY" frameborder="0" allowfullscreen></iframe>')
from IPython.display import HTML
HTML('<iframe width="960" height="540" src="https://www.youtube.com/embed/gYiwszKaCoQ" frame... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Categorical Variables
Step2: Exercises
| <ASSISTANT_TASK:>
Python Code:
import numpy as np
import matplotlib.pyplot as plt
% matplotlib inline
from sklearn.datasets import load_boston
boston = load_boston()
from sklearn.model_selection import train_test_split
X, y = boston.data, boston.target
X_train, X_test, y_train, y_test = train_test_split(
X, y, rand... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Visualize the Pixel Weights
Step2: Ffrom these two examples the calculations with the same gradients produces the same pixel weights The clumpe... | <ASSISTANT_TASK:>
Python Code:
import numpy as np
import matplotlib.pyplot as plt
from eniric.atmosphere import Atmosphere
from eniric.legacy import mask_clumping, RVprec_calc_masked
from scripts.phoenix_precision import convolve_and_resample
from eniric.snr_normalization import snr_constant_band
from eniric.precision ... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Set parameters
Step2: Infer parameters
Step3: Define sample object
Step4: Calculate the uncertainties of the multiple scattering calculations... | <ASSISTANT_TASK:>
Python Code:
# standard imports
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
import os
import time
import seaborn as sns
# import package
import infer_structcol as ifs
nwalkers = 14 # number of walkers to step through different parameters
nst... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Collect the data
Step2: Build adjacency matrix
Step3: Spectral Clustering
Step4: Analysis of the clustering
| <ASSISTANT_TASK:>
Python Code:
import pandas as pd
import numpy as np
import os
import matplotlib.pyplot as plt
import sklearn
import sklearn.ensemble
from sklearn.metrics import silhouette_score
from sklearn.cluster import KMeans
import csv
path = '../../datas/nlp_results/'
voting_df = pd.read_csv(path+'voting_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: Document Authors
Step2: Document Contributors
Step3: Document Publication
Step4: Document Table of Contents
Step5: 1.2. Model Name
Step6: 2... | <ASSISTANT_TASK:>
Python Code:
# DO NOT EDIT !
from pyesdoc.ipython.model_topic import NotebookOutput
# DO NOT EDIT !
DOC = NotebookOutput('cmip6', 'cmcc', 'cmcc-cm2-hr5', 'seaice')
# 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: Using the wrapper
Step2: Quiz
Step3: Most Common Weight
Step4: Height vs Weight
Step5: Barchart
Step6: Wages
Step7: Wage Barchart
Step8: ... | <ASSISTANT_TASK:>
Python Code:
%%writefile plotting.py
from matplotlib import pyplot
from numpy import arange
import bisect
def scatterplot(x,y):
pyplot.plot(x,y,'b.')
pyplot.xlim(min(x)-1,max(x)+1)
pyplot.ylim(min(y)-1,max(y)+1)
pyplot.show()
def barplot(labels,data):
pos=arange(len(data))
pypl... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Splitting the data into validation and train + One Hot Encoding the labels + data augumentation
Step2: Recizing the images into appropriate dim... | <ASSISTANT_TASK:>
Python Code:
def reducex(X, y, reduce_classes=None, reduce_percent=.2):
# import pdb; pdb.set_trace()
idxs = []
if reduce_classes:
for c in reduce_classes:
try:
idxs += list(np.where(y == c)[0])
except IndexError:
continue
... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: scipy.optimize.fsolve
| <ASSISTANT_TASK:>
Python Code:
from IPython.display import display
import pandas as pd
# data
data = pd.DataFrame([
[10, 300],
[20, 200],
[30, 100],
[40, 400]
], columns=['QTY', 'UNIT.V'],
index=['A', 'B', 'C', 'D'])
display(data)
def gain(unit_v, qty):
return unit_v*qty*0.1
data['GAIN']... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Check that we are using the GPU
Step2: Model
Step3: Base Model arquitecture
Step4: Complete model with FCN Classifier on top
Step5: Set the ... | <ASSISTANT_TASK:>
Python Code:
IMAGE_SIZE = (299,299) # The dimensions to which all images found will be resized.
BATCH_SIZE = 16
NUMBER_EPOCHS = 8
TENSORBOARD_DIRECTORY = "../logs/simple_model/tensorboard"
TRAIN_DIRECTORY = "../data/train/"
VALID_DIRECTORY = "../data/valid/"
WEIGHTS_DIRECTORY = "../weights/"
TEST_DIRE... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Inputs
Step2: Computation
Step3: Plot of the reflectance spectrum at $\lambda$ = 804 nm
Step4: Plot of the local fields at $\lambda=804$ nm a... | <ASSISTANT_TASK:>
Python Code:
# libraries
import numpy as np # numpy
import sys # sys to add py_matrix to the path
# matplotlib inline plots
import matplotlib.pylab as plt
%matplotlib inline
# adding py_matrix parent folder to python path
sys.path.append('../../')
import py_matrix as pm # importing py... |
<SYSTEM_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 data
Step2: Initialize the analysis object
Step3: Call run
Step4: Show the full tree with bootstrap supports
Step5: Show the majority-... | <ASSISTANT_TASK:>
Python Code:
# conda install ipyrad -c bioconda
# conda install tetrad -c eaton-lab -c conda-forge
import ipyrad.analysis as ipa
import toytree
# the path to your sequence data in HDF5 format
data = "/home/deren/Documents/virentes-reference/analysis-ipyrad/ref_min4_outfiles/ref_min4.snps.hdf5"
# ini... |
<SYSTEM_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. Release year
Step2: Are our movie embeddings sensitive to year?
Step3: 2. Average rating
Step4: Again, is there a global pattern to the d... | <ASSISTANT_TASK:>
Python Code:
import os
import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
import matplotlib as mpl
from learntools.core import binder; binder.bind(globals())
from learntools.embeddings.ex4_tsne import *
#_RM_
input_dir = '.'
#_UNCOMMENT_
#input_dir = '../input/visualizing-embe... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Notice that by default a line plot is drawn, and a light grid is included. All of this can be changed, however
Step2: Similarly, for a DataFram... | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
# Set some Pandas options
pd.set_option('display.notebook_repr_html', False)
pd.set_option('display.max_columns', 20)
pd.set_option('display.max_rows', 25)
normals = pd.Series(np.random.normal(size=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: To run your saved file go to the IPython window and at the prompt type
Step2: There are a lot of magic commands, most of which we don't need ri... | <ASSISTANT_TASK:>
Python Code:
# This code tests that your Python installation worked.
# It generates a png image file that you should e-mail
# to the address shown on the plot
import scipy as sp
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
import platform
import socket
# If you are a studen... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Additional columns
Step2: Preparation for temporalities
Step3: Displays all unique answers to every question
Step4: List of answers
Step5: D... | <ASSISTANT_TASK:>
Python Code:
%run "../Utilities/Preparation.ipynb"
processGFormEN = not ('gformEN' in globals())
if processGFormEN:
# tz='Europe/Berlin' time
dateparseGForm = lambda x: pd.Timestamp(x.split(' GMT')[0], tz='Europe/Berlin').tz_convert('utc')
if processGFormEN:
csvEncoding = 'utf-8'
gform... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: As always, let's do imports and initialize a logger and a new Bundle. See Building a System for more details.
Step2: Now let's add a mesh data... | <ASSISTANT_TASK:>
Python Code:
!pip install -I "phoebe>=2.1,<2.2"
%matplotlib inline
import phoebe
from phoebe import u # units
import numpy as np
import matplotlib.pyplot as plt
logger = phoebe.logger()
b = phoebe.default_binary()
b.add_dataset('mesh', times=np.linspace(0,1,11), dataset='mesh01')
print b['requiv@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: To use the scikit-learn interface, we'll need to define our model
Step2: Because the larch.Model object is an estimator, if offers a fit
Step3:... | <ASSISTANT_TASK:>
Python Code:
# TEST
from pytest import approx
import numpy as np
import larch
import pandas as pd
from larch import PX, P, X
from larch.data_warehouse import example_file
df = pd.read_csv(example_file("MTCwork.csv.gz"))
df.set_index(['casenum','altnum'], inplace=True, drop=False)
m = larch.Model()
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:
Step3: Utility functions
Step4: Loading Data
Step5: Initial Alignment
Step6: Look at the transformation, what type is it?
Step7: Final registration... | <ASSISTANT_TASK:>
Python Code:
import SimpleITK as sitk
# Utility method that either downloads data from the network or
# if already downloaded returns the file name for reading from disk (cached data).
from downloaddata import fetch_data as fdata
# Always write output to a separate directory, we don't want to pollute ... |
<SYSTEM_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 want to create a decision tree from the above training dataset. The first step for that is to encode the data into numeric values and bind th... | <ASSISTANT_TASK:>
Python Code:
import os
import numpy as np
import shogun as sg
import matplotlib.pyplot as plt
%matplotlib inline
SHOGUN_DATA_DIR=os.getenv('SHOGUN_DATA_DIR', '../../../../data')
# training data
train_income=['Low','Medium','Low','High','Low','High','Medium','Medium','High','Low','Medium',
'Medium','Hi... |
<SYSTEM_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 and Authorisation
Step3: Post this step, we will have full access to twitter api's
Step10: Streaming with tweepy
Step13: Drawb... | <ASSISTANT_TASK:>
Python Code:
import logging # python logging module
# basic format for logging
logFormat = "%(asctime)s - [%(levelname)s] (%(funcName)s:%(lineno)d) %(message)s"
# logs will be stored in tweepy.log
logging.basicConfig(filename='tweepy.log', level=logging.INFO,
format=logFormat, date... |
<SYSTEM_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 Data
Step2: To merge these two lists together we will use the zip function.
Step3: We are basically done creating the data set. We now ... | <ASSISTANT_TASK:>
Python Code:
import pandas as pd
# The inital set of baby names and bith rates
names = ['Bob','Jessica','Mary','John','Mel']
births = [968, 155, 77, 578, 973]
BabyDataSet = zip(names,births)
BabyDataSet
df = pd.DataFrame(data = BabyDataSet, columns=['Names', 'Births'])
df
df.to_csv('births1880.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: While this would work for defining a single molecule or very small system, this would not be efficient for large systems. Instead, the clone an... | <ASSISTANT_TASK:>
Python Code:
import mbuild as mb
class MonoLJ(mb.Compound):
def __init__(self):
super(MonoLJ, self).__init__()
lj_particle1 = mb.Particle(name='LJ', pos=[0, 0, 0])
self.add(lj_particle1)
lj_particle2 = mb.Particle(name='LJ', pos=[1, 0, 0])
self.add(lj_partic... |
<SYSTEM_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 beginning we need to instantiate two objects in the main file to run the program -
Step2: Those type " " names later become dictionari... | <ASSISTANT_TASK:>
Python Code:
# %load sflow.py
# [SublimeLinter pep8-max-line-length:300]
# -*- coding: utf-8 -*-
# -------------------------------------------------------------------------
#
# MAIN
#
# -------------------------------------------------------------------------
if __name__ == '__main__':
from src.e... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.