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: IMPORTANT
Step2: Let's keep using the remarkable narratives available from Documenting the American South (http
Step3: back to boolean indexin... | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
import pandas as pd
import matplotlib.pyplot as plt
import textmining_blackboxes as tm
#see if package imported correctly
tm.icantbelieve("butter")
title_info=pd.read_csv('data/na-slave-narratives/data/toc.csv')
#this is the "metadata" of these files--we'll use today
... |
<SYSTEM_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 data into train and test set
Step2: Let us use building 1 for demo purposes
Step3: Let's split data at April 30th
Step4: Visualizing... | <ASSISTANT_TASK:>
Python Code:
from __future__ import print_function, division
import time
from matplotlib import rcParams
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
from six import iteritems
from nilmtk import DataSet, TimeFrame, MeterGroup, HDFDataStore
from nilmtk.disaggregate import Comb... |
<SYSTEM_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'
# Use Floyd's cifar-10 dataset if ... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Fixed orientation
Step2: Let's look at the current estimates using MNE. We'll take the absolute
Step3: Next let's use the default noise normal... | <ASSISTANT_TASK:>
Python Code:
# Author: Eric Larson <larson.eric.d@gmail.com>
#
# License: BSD-3-Clause
import mne
from mne.datasets import sample
from mne.minimum_norm import make_inverse_operator, apply_inverse
print(__doc__)
data_path = sample.data_path()
subjects_dir = data_path + '/subjects'
# Read data (just MEG... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Historical data
Step2: To request hourly data of the last 60 trading days
Step3: Convert the list of bars to a data frame and print the first ... | <ASSISTANT_TASK:>
Python Code:
from ib_insync import *
util.startLoop()
ib = IB()
ib.connect('127.0.0.1', 7497, clientId=14)
contract = Stock('TSLA', 'SMART', 'USD')
ib.reqHeadTimeStamp(contract, whatToShow='TRADES', useRTH=True)
bars = ib.reqHistoricalData(
contract,
endDateTime='',
durationS... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: imports for Python, Pandas
Step2: JSON example, with string
Step3: JSON example, with file
Step4: JSON exercise
Step5: 1. Find the 10 countr... | <ASSISTANT_TASK:>
Python Code:
import pandas as pd
import numpy as np
import json
from pandas.io.json import json_normalize
# define json string
data = [{'state': 'Florida',
'shortname': 'FL',
'info': {'governor': 'Rick Scott'},
'counties': [{'name': 'Dade', 'population': 12345},
... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Vamos a cargar los en Python con pandas. pandas es una biblioteca de Python para trabajar con tablas de datos (llamados DataFrames) de forma cóm... | <ASSISTANT_TASK:>
Python Code:
import urllib.request
urllib.request.urlretrieve("http://www.amstat.org/publications/jse/datasets/cigarettes.dat.txt", "cigarettes.dat")
!wc -l cigarettes.dat
cat cigarettes.dat
import pandas as pd
df = pd.read_csv("cigarettes.dat", delim_whitespace=True, header=None,
na... |
<SYSTEM_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 Solve an optimization problem
Step2: 2 Define your own objective function
Step3: Likewise, you can implement your owns solvers and accelerat... | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
from pyunlocbox import functions, solvers
plt.rcParams['figure.figsize'] = (17, 5)
f1 = functions.norm_l2(y=[4, 5, 6, 7])
f2 = functions.dummy()
solver = solvers.forward_backward()
ret = solvers.solve([f1, f2], [0., 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:
Step3: Plot functions
Step5: Objective function
Step6: The "Differential Evolution" (DE) algorithm
Step7: Performances analysis
| <ASSISTANT_TASK:>
Python Code:
# Init matplotlib
%matplotlib inline
import matplotlib
matplotlib.rcParams['figure.figsize'] = (8, 8)
from mpl_toolkits.mplot3d import axes3d
import matplotlib.colors as colors
import numpy as np
import warnings
from scipy import optimize
def plot_contour_2d_solution_space(func,
... |
<SYSTEM_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 need a Google Cloud link to our data to load the data using a TPU.
Step2: Load the data
Step3: Let's count how many healthy/normal chest X-... | <ASSISTANT_TASK:>
Python Code:
import re
import os
import random
import numpy as np
import pandas as pd
import tensorflow as tf
import matplotlib.pyplot as plt
try:
tpu = tf.distribute.cluster_resolver.TPUClusterResolver.connect()
print("Device:", tpu.master())
strategy = tf.distribute.TPUStrategy(tpu)
exce... |
<SYSTEM_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 XANES object from Materials Project website downloaded spectrum file (tsv)
Step2: Initiate XANES object from XAS Data Interchange (XDI... | <ASSISTANT_TASK:>
Python Code:
Fe2O3_spectrum_dataframe = pd.read_pickle('Fe2O3_computational_spectrum.pkl')
Fe2O3_spectrum_dataframe
spectrum_energy = Fe2O3_spectrum_dataframe['x_axis_energy_55eV'].values[0]
spectrum_mu = Fe2O3_spectrum_dataframe['interp_spectrum_55eV'].values[0]
Fe2O3_XANES_object1 = XANES(spectrum_e... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Computing the eigenvalues and the eigenvectors
Step2: The @ operator stands, in this context, for matrix multiplication.
Step3: Modal Response... | <ASSISTANT_TASK:>
Python Code:
k0, m0 = 1.0, 1.0 # ideally, dimensional units...
w20 = k0/m0
w0 = np.sqrt(w20)
k1, k2 = 2*k0, 3*k0
m1, m2 = 2*m0, 4*m0
M = np.array(((m1, 0), ( 0, m2)))
K = np.array(((k1+k2, -k2), (-k2, k2)))
p = np.array(( 0.0, 1.0)); w = 2.0*w0
print_mat(M, pre='\\boldsymbol{M}=m\\,', fmt='%d')
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: Represent each number using a one-hot where the index of the one represents the digit value
Step2: Load the MNIST training and testing images
S... | <ASSISTANT_TASK:>
Python Code:
import matplotlib.pyplot as plt
%matplotlib inline
import nengo
import numpy as np
import scipy.ndimage
import matplotlib.animation as animation
from matplotlib import pylab
from PIL import Image
import nengo.spa as spa
import cPickle
import random
from nengo_extras.data import load_mnist... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Universal Sentence Encoder
Step2: More detailed information about installing Tensorflow can be found at https
Step3: Semantic Textual Similari... | <ASSISTANT_TASK:>
Python Code:
# Copyright 2018 The TensorFlow Hub Authors. All Rights Reserved.
#
# 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
#
# http://www.apache.org/licenses/LICENSE... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Generate Summary Statistics for the Entire Dataset
Step2: Generate Summary Statistics for Object Type Columns
Step3: Get the Mode of the Entir... | <ASSISTANT_TASK:>
Python Code:
# Import the libraries we need
import pandas as pd
# Import the dataset from the CSV file
accidents_data_file = '/Users/robert.dempsey/Dropbox/Private/Art of Skill Hacking/' \
'Books/Python Business Intelligence Cookbook/Data/Stats19-Data1979-2004/Accidents7904.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: It seems profitable to define a function that computes the sum
Step2: Discussion
| <ASSISTANT_TASK:>
Python Code:
import numpy as np
import matplotlib.pyplot as plt
from scipy.special import erfc
def sInf(p, kD, b, x):
'''Return steady state head change due to fixed recharge p starting at t=0'''
return p / (2 * kD) * (b**2 - x**2)
def sDiff(p, x, b, S, kD, t):
'''Return difference betwee... |
<SYSTEM_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 grab any part of the datetime object you want
Step2: Pandas with Datetime Index
| <ASSISTANT_TASK:>
Python Code:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from datetime import datetime
# To illustrate the order of arguments
my_year = 2017
my_month = 1
my_day = 2
my_hour = 13
my_minute = 30
my_second = 15
# January 2nd, 2017
my_date = datetime(my_year,my_month, my_day)
# ... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Motivating Random Forests
Step2: The binary splitting makes this extremely efficient.
Step3: We have some convenience functions in the reposit... | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
from scipy import stats
plt.style.use('seaborn')
import fig_code
fig_code.plot_example_decision_tree()
from sklearn.datasets import make_blobs
X, y = make_blobs(n_samples=300, centers=4,
random_state... |
<SYSTEM_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 driving code starts here
Step2: A slightly more interesting demo
Step3: Driving code
Step4: A generator-coroutine that receives values
St... | <ASSISTANT_TASK:>
Python Code:
import types
@types.coroutine
def gen():
yield 42
async def delegating():
await gen()
coro = delegating()
coro
coro.send(None)
# coro.send(None) # --> StopIteration
@types.coroutine
def gen123():
return (i for i in range(1, 4))
async def delegating():
await gen123()
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: AOS frames
Step2: Virtual channel 1
Step3: We need to sort the data, since the different files we've loaded up are not in chronological order.... | <ASSISTANT_TASK:>
Python Code:
def load_frames(path):
frame_size = 220
frames = np.fromfile(path, dtype = 'uint8')
frames = frames[:frames.size//frame_size*frame_size].reshape((-1, frame_size))
return frames
frames = load_frames('ATA_2021-09-18/ce5_frames.u8')
aos = [CE5_AOSFrame.parse(f) for f in fram... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: B
Step2: C
| <ASSISTANT_TASK:>
Python Code:
try:
dot_product
except:
assert False
else:
assert True
import numpy as np
np.random.seed(56985)
x = np.random.random(48)
y = np.random.random(48)
np.testing.assert_allclose(14.012537210130272, dot_product(x, y))
x = np.random.random(48)
y = np.random.random(49)
assert dot_pro... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: When we typed help(), we were greeted with a message and some instructions, followed by the help prompt. At the prompt, we entered keywords and ... | <ASSISTANT_TASK:>
Python Code:
__builtins__? # ipython help on object (module) __builtins__
__builtins__?? # should also show code if present (not built in)
help(__builtins__) # extended help (python)
help() # type keywords below to see keywords and quit to quit
#help('modules') # there is an error in my Ipython impl... |
<SYSTEM_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 statement
Step2: As long as your Python session is active, you can access all the optimization results via the res object.
Step3: And ... | <ASSISTANT_TASK:>
Python Code:
import numpy as np
np.random.seed(777)
from skopt import gp_minimize
noise_level = 0.1
def obj_fun(x, noise_level=noise_level):
return np.sin(5 * x[0]) * (1 - np.tanh(x[0] ** 2)) + np.random.randn() * noise_level
res = gp_minimize(obj_fun, # the function to minimize
... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Metric
Step2: The metric that did not work.
| <ASSISTANT_TASK:>
Python Code:
import numpy as np
import subprocess
import os
from os.path import join as opj
import re
import nibabel as nib
# paths = np.genfromtxt('/home1/varunk/results_again_again/anat_file_paths.txt', dtype='str') #Didn't work
# paths = np.genfromtxt('/home1/varunk/results_again_again/skullstrip_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: Using the Globus SDK
Step2: The Research Data Portal function
Step3: We use the Globus SDK function operation_mkdir to create a directory (in ... | <ASSISTANT_TASK:>
Python Code:
from globus_sdk import AuthClient, TransferClient, AccessTokenAuthorizer, NativeAppAuthClient, TransferData
CLIENT_ID = '2f9482c4-67b3-4783-bac7-12b37d6f8966'
client = NativeAppAuthClient(CLIENT_ID)
client.oauth2_start_flow()
authorize_url = client.oauth2_get_authorize_url()
print('Please... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: First we'll load the text file and convert it into integers for our network to use. Here I'm creating a couple dictionaries to convert the chara... | <ASSISTANT_TASK:>
Python Code:
import time
from collections import namedtuple
import numpy as np
import tensorflow as tf
with open('anna.txt', 'r') as f:
text=f.read()
vocab = set(text)
vocab_to_int = {c: i for i, c in enumerate(vocab)}
int_to_vocab = dict(enumerate(vocab))
encoded = np.array([vocab_to_int[c] for ... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Other magics
| <ASSISTANT_TASK:>
Python Code:
%load_ext ipython_unittest
def add(x, y):
return x + y
%%unittest
assert add(1, 1) == 2
assert add(1, 2) == 3
assert add(2, 2) == 4
%load_ext ipython_unittest
def fizzbuzz():
pass
%%unittest -p 1
assert fizzbuzz() == 0
import unittest
import sys
class JupyterTest(unittest.TestCase... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Utilities
Step2: Loading Data
Step3: Getting to know your data
Step4: Free Form Deformation
Step5: Perform Registration
Step6: Another opti... | <ASSISTANT_TASK:>
Python Code:
import SimpleITK as sitk
import registration_utilities as ru
import registration_callbacks as rc
%matplotlib inline
import matplotlib.pyplot as plt
from ipywidgets import interact, fixed
# utility method that either downloads data from the Girder repository or
# if already downloaded retu... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Storing Arrays
Step2: Schema validation
Step3: Data Sharing
Step4: Streaming Data
Step5: Explosive Storage
Step6: Data Provenance
Step7: C... | <ASSISTANT_TASK:>
Python Code:
mkdir -p hello_world
from asdf import AsdfFile
# Make the tree structure, and create a AsdfFile from it.
tree = {'hello': 'world'}
ff = AsdfFile(tree)
ff.write_to("hello_world/test.asdf")
# You can also make the AsdfFile first, and modify its tree directly:
ff = AsdfFile()
ff.tree['hello'... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: 만약 부동소수점을 사용하는 경우에는 무한대를 표현하기 위한 np.inf와 정의할 수 없는 숫자를 나타내는 np.nan 을 사용할 수 있다.
Step2: The irrational number e is also known as Euler’s number. I... | <ASSISTANT_TASK:>
Python Code:
x = np.array([1, 2, 3])
x.dtype
x = np.array([1, 2, 3])
x.dtype #2.7과 3버전의 차이인가?
np.exp(-np.inf)
-np.inf
np.exp(1)
np.array([1, 0]) / np.array([0, 0])
np.array([1, 0]) / np.array([0, 0])
x = np.array([1, 2, 3])
x
a = np.zeros(5)
a
b = np.zeros((5, 2), dtype="f8")
b
c = 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:
Step3: A sabesp disponibiliza dados para consulta neste endereço, mas não faço idéia de como pegar os dados com o python...
Step4: OK. Tudo certo. Ba... | <ASSISTANT_TASK:>
Python Code:
from IPython.display import display, Image
## eis a imagem da notícia
infograficoG1 = Image('reservatorios1403.jpg')
display(infograficoG1)
import urllib.request
req = urllib.request.urlopen("https://sabesp-api.herokuapp.com/").read().decode()
import json
data = json.loads(req)
import da... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: scikit-learn 4-step modeling pattern
Step 1
Step2: Step 2
Step3: Name of the object does not matter
Step4: Step 3
Step5: Step 4
Step6: Retu... | <ASSISTANT_TASK:>
Python Code:
# import load_iris function from datasets module
from sklearn.datasets import load_iris
# save "bunch" object containing iris dataset and its attributes
iris = load_iris()
# store feature matrix in "X"
X = iris.data
# store response vector in "y"
y = iris.target
# print the shapes of X 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: Tutorial on Multi Armed Bandits in TF-Agents
Step2: Imports
Step7: Introduction
Step8: The above interim abstract class implements PyEnvironm... | <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: To reiterate the previous method, let's run the built-in merge collision resolution method
Step2: We can see above that two particles merged in... | <ASSISTANT_TASK:>
Python Code:
import rebound
import numpy as np
import matplotlib.pyplot as plt
def setupSimulation():
''' Setup the 3-Body scenario'''
sim = rebound.Simulation()
sim.integrator = "ias15" # IAS15 is the default integrator, so we don't need this line
sim.add(m=1.)
sim.add(m=1e-3, a=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: Restart the kernel before proceeding further (On the Notebook menu - Kernel - Restart Kernel).
Step2: Re-train our model with trips_last_5min f... | <ASSISTANT_TASK:>
Python Code:
!pip install --upgrade apache-beam[gcp]
import os
import shutil
import numpy as np
import tensorflow as tf
from google import api_core
from google.cloud import aiplatform, bigquery
from google.protobuf import json_format
from google.protobuf.struct_pb2 import Value
from matplotlib 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: We create a rectangular mesh using the builtin Firedrake mesh utility.
Step2: We can use the built in plot function of firedrake to visualise ... | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
import matplotlib
import matplotlib.pyplot as plt
from thetis import *
lx = 40e3
ly = 2e3
nx = 25
ny = 2
mesh2d = RectangleMesh(nx, ny, lx, ly)
fig, ax = plt.subplots(figsize=(12,1))
triplot(mesh2d, axes=ax);
P1_2d = FunctionSpace(mesh2d, 'CG', 1)
bathymetry_2d = Fun... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Summary functions
Step2: This method generates a high-level summary of the attributes of the given column. It is type-aware, meaning that its o... | <ASSISTANT_TASK:>
Python Code:
#$HIDE_INPUT$
import pandas as pd
pd.set_option('max_rows', 5)
import numpy as np
reviews = pd.read_csv("../input/wine-reviews/winemag-data-130k-v2.csv", index_col=0)
reviews
reviews.points.describe()
reviews.taster_name.describe()
reviews.points.mean()
reviews.taster_name.unique()
r... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: 2. Set Configuration
Step2: 3. Enter BigQuery Query To Table Recipe Parameters
Step3: 4. Execute BigQuery Query To Table
| <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_write':'service', # Credentials used for wri... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Goals
| <ASSISTANT_TASK:>
Python Code:
from sklearn import datasets
import matplotlib.pyplot as plt
bost = datasets.load_boston()
fig = plt.figure(figsize=(15, 10))
for i in range(0, 12):
ax = fig.add_subplot(3, 4, i + 1)
ax.set_xlabel(bost.feature_names[i])
xs, ys = bost.data[:, i], bost.target
plt.scatter(xs,... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Franke function
Step2: Setting up the training data
Step3: Setting up the model
Step4: The model training is similar to training a standard G... | <ASSISTANT_TASK:>
Python Code:
import torch
import gpytorch
import math
from matplotlib import cm
from matplotlib import pyplot as plt
import numpy as np
%matplotlib inline
%load_ext autoreload
%autoreload 2
def franke(X, Y):
term1 = .75*torch.exp(-((9*X - 2).pow(2) + (9*Y - 2).pow(2))/4)
term2 = .75*torch.exp... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Get metadata for the symbols below.
Step2: Get metadata for all symbols in the cache directory
| <ASSISTANT_TASK:>
Python Code:
import pandas as pd
import pinkfish as pf
# format price data
pd.options.display.float_format = '{:0.2f}'.format
# increase display of dataframe rows
pd.set_option('display.max_rows', 1000)
df = pf.get_symbol_metadata(symbols=['msft', 'orcl', 'tsla'])
df.sort_values('num_years', ascendin... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Generate independent samples from this distribution and plot them
Step2: Use adaptive covariance MCMC to sample from this (un-normalised) pdf.
... | <ASSISTANT_TASK:>
Python Code:
import pints
import pints.toy
import numpy as np
import matplotlib.pyplot as plt
# Create log pdf (default is 2-dimensional with r0=10 and sigma=1)
log_pdf = pints.toy.AnnulusLogPDF()
# Contour plot of pdf
num_points = 100
x = np.linspace(-15, 15, num_points)
y = np.linspace(-15, 15, num_... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: MappingInfo objects
Step2: To view the mappings MappingInfo objects provide the
Step3: MappingInfo objects are needed to load data into IntDa... | <ASSISTANT_TASK:>
Python Code:
# You might have to set the path to run this notebook directly from ipython notebook
import sys
my_path_to_modules = "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/"
sys.path.append(my_path_to_modules)
from pergola import mapping
# load mapping file
mappi... |
<SYSTEM_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: D... | <ASSISTANT_TASK:>
Python Code:
%load_ext watermark
%watermark -a "Sebastian Raschka" -u -d -p numpy,pandas,matplotlib,sklearn
# Use the IPython/jupyter feature to show images inline with the notebook
# output rather than have images popup.
from IPython.display import Image
%matplotlib inline
# Sample csv
import pand... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Install the latest GA version of google-cloud-storage library as well.
Step2: Install the latest GA version of google-cloud-pipeline-components... | <ASSISTANT_TASK:>
Python Code:
import os
# Google Cloud Notebook
if os.path.exists("/opt/deeplearning/metadata/env_version"):
USER_FLAG = "--user"
else:
USER_FLAG = ""
! pip3 install --upgrade google-cloud-aiplatform[full] $USER_FLAG
! pip3 install -U google-cloud-storage $USER_FLAG
! pip3 install $USER kfp 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: Given Physical Data
Step2: From simple integeration, we can easily solve the diffrential equation and the solution will be -
Step3: Building ... | <ASSISTANT_TASK:>
Python Code:
!pip install --pre deepchem[jax]
import numpy as np
import functools
try:
import jax
import jax.numpy as jnp
import haiku as hk
import optax
from deepchem.models import PINNModel, JaxModel
from deepchem.data import NumpyDataset
from deepchem.models.optimizers import Adam
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: Change the headers
Step2: NODES
Step3: -----------------------------
Step4: Import script - LOAD CSV?? - STOPPED HERE
Step5: Original Blockc... | <ASSISTANT_TASK:>
Python Code:
import errno
import os
import shutil
import zipfile
import numpy as np
import pandas as pd
# In[22]:
# TARGETDIR = '../btc/graphs_njp.zip'
# In[23]:
# with open(doc, "rb") as zipsrc:
# zfile = zipfile.ZipFile(zipsrc)
# for member in zfile.infolist():
# target_path = os.path... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Credentials for Azure Python SDK
Step2: IPython filters the subscription ID and tenant ID using awk command and stores into sid and tid variabl... | <ASSISTANT_TASK:>
Python Code:
!yes|azure login
!azure account show
sid_tid = !azure account show|awk -F ':' '/ID/{ print $3}'
sid = sid_tid[0]
tid = sid_tid[1]
out=!azure ad sp create --name simpleazure
cid = out[6].split(":")[1].lstrip()
newout="\n".join(out)
print(newout)
password=""
!azure ad sp set -p $passwor... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: By definition, a Graph is a collection of nodes (vertices) along with
Step2: add a list of nodes,
Step3: or add any iterable container of node... | <ASSISTANT_TASK:>
Python Code:
import networkx as nx
G = nx.Graph()
G.add_node(1)
G.add_nodes_from([2, 3])
H = nx.path_graph(10)
G.add_nodes_from(H)
H.edges()
G.add_node(H)
G.add_edge(1, 2)
e = (2, 3)
G.add_edge(*e) # unpack edge tuple*
G.add_edges_from([(1, 2), (1, 3)])
G.add_edges_from(H.edges())
G.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: Load and prepare the data
Step2: Checking out the data
Step3: Dummy variables
Step4: Scaling target variables
Step5: Splitting the data into... | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
%config InlineBackend.figure_format = 'retina'
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
data_path = 'Bike-Sharing-Dataset/hour.csv'
rides = pd.read_csv(data_path)
rides.head()
rides[:24*10].plot(x='dteday', y='cnt')
dummy_fields = ['seas... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: ANALYSIS
Step2: FOOD BIGRAMS
Step3: CLEANING, PROCESSING THE DATA
Step4: EXTRA CODE
| <ASSISTANT_TASK:>
Python Code:
class HandleGZippedJSON:
def __init__(self, url):
self.url = url
self.json_data = None
def run(self):
request = urllib2.Request(self.url)
request.add_header('Accept-encoding', 'gzip')
opener = urllib2.build_opener()
f = opener.open... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: From equations to code in a few lines of Python
Step2: Functions and data
Step3: Ok, let's create a function $f(x, y)$ and look at the data De... | <ASSISTANT_TASK:>
Python Code:
from devito import *
grid = Grid(shape=(5, 6), extent=(1., 1.))
grid
print(Function.__doc__)
f = Function(name='f', grid=grid)
f
f.data
g = TimeFunction(name='g', grid=grid)
g
g.shape
g.dt
g.dt.evaluate
g.forward
g.backward
g.forward.dt
g.forward.dy
from examples.cfd import 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: Load Iris Dataset
Step2: Make Iris Dataset Imbalanced
Step3: Downsample Majority Class To Match Minority Class
| <ASSISTANT_TASK:>
Python Code:
# Load libraries
import numpy as np
from sklearn.datasets import load_iris
# Load iris data
iris = load_iris()
# Create feature matrix
X = iris.data
# Create target vector
y = iris.target
# Remove first 40 observations
X = X[40:,:]
y = y[40:]
# Create binary target vector indicating if ... |
<SYSTEM_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', 'mohc', 'sandbox-3', 'toplevel')
# Set as follows: DOC.set_author("name", "email")
# TODO - please enter value(s)
# Set as follows: DOC.set_contributor("name", "e... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: For creating other marks (like scatter, pie, bars, etc.), only step 3 needs to be changed. Lets look a simple example to create a bar chart
Step... | <ASSISTANT_TASK:>
Python Code:
from bqplot import (LinearScale, Axis, Figure, OrdinalScale,
LinearScale, Bars, Lines, Scatter)
# first, let's create two vectors x and y to plot using a Lines mark
import numpy as np
x = np.linspace(-10, 10, 100)
y = np.sin(x)
# 1. Create the scales
xs = LinearScale(... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Derivative of Divergences as a function of $\mu_q$
Step2: Finding the Zeros of the Derivatives
Step3: Examining the Divergences as a function ... | <ASSISTANT_TASK:>
Python Code:
a = -0.7
j_vals = []
kl_vals = []
mus = np.linspace(0,1,100)
for mu in mus:
j_vals.append(J(mu,p_sig,a)[0])
kl_vals.append(KL(mu,p_sig)[0])
fig = plt.figure(figsize=(15,5))
p_vals = p(mus)
plt.plot(mus, p_vals/p_vals.max(), label="$p(x)$")
#plt.plot(mus, j_vals/np.max(np.abs(j_val... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: 从 sklearn.datasets 这个库中导入 fetch_20newsgroups 模块
Step2: 整个数据集包含了 2257 个这样的文档。 我们需要用这 2257 条数据来训练我们的模型, 让它变得智能起来。
Step3: X_train_counts 的维度, 包含了... | <ASSISTANT_TASK:>
Python Code:
import logging
logging.basicConfig()
from sklearn.datasets import fetch_20newsgroups
categories = ['alt.atheism', 'soc.religion.christian','comp.graphics', 'sci.med']
twenty_train = fetch_20newsgroups(subset='train', categories=categories, shuffle=True, random_state=42)
print len(twenty_... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Next, obtain the county-level predictor, uranium, by combining two variables.
Step2: Use the merge method to combine home- and county-level inf... | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns; sns.set_context('notebook')
# Import radon data
srrs2 = pd.read_csv('../data/srrs2.dat')
srrs2.columns = srrs2.columns.map(str.strip)
srrs_mn = srrs2[srrs2.state=='MN']
srrs_m... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Custom generator without __init__ method
Step2: Explicitly setting the name of generated items
Step3: The generated sequence is the same as ab... | <ASSISTANT_TASK:>
Python Code:
import tohu
from tohu.v4.primitive_generators import *
from tohu.v4.derived_generators import *
from tohu.v4.dispatch_generators import *
from tohu.v4.custom_generator import *
from tohu.v4.utils import print_generated_sequence, make_dummy_tuples
print(f'Tohu version: {tohu.__version__}')... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Next, let's import the Boston housing prices dataset. This is included with the scikit-learn library, so we can import it directly from there. T... | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
import math
import random
import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd
from sklearn.datasets import load_boston
import numpy as np
import tensorflow as tf
sns.set(style="ticks", color_codes=True)
#load data from scikit-learn library
dataset... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Computation of Sensitivity Kernels by 2D acoustic FD modelling
Step2: As always, we start with the definition of the basic modelling parameters... | <ASSISTANT_TASK:>
Python Code:
# Execute this cell to load the notebook's style sheet, then ignore it
from IPython.core.display import HTML
css_file = '../../style/custom.css'
HTML(open(css_file, "r").read())
# Import Libraries
# ----------------
import numpy as np
from numba import jit
import matplotlib
import matpl... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step2: We start by implementing the right-hand-side of the evolution
Step4: We see that this doesn't give us the update term at the edges of the domai... | <ASSISTANT_TASK:>
Python Code:
import numpy
from matplotlib import pyplot
%matplotlib notebook
def RHS(U, dx):
RHS term.
Parameters
----------
U : array
contains [phi, phi_t, phi_x] at each point
dx : double
grid spacing
Returns
-------
dUdt ... |
<SYSTEM_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 find the top 30 closest points to objective point in a set of 40000 tuples. The graph below shows
Step2: 2. VPTREE on timeseries
Step3:... | <ASSISTANT_TASK:>
Python Code:
def find_similar_pt():
rn = lambda: random.randint(0, 10000)
aset = [(rn(), rn()) for i in range(40000)]
q = (rn(), rn())
rad = 9990
distance = lambda a, b: math.sqrt(sum([((x-y)**2) for x, y in zip(a, b)]))
s = time.time()
print("creating vptree...")
root ... |
<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 pandas as pd
df = pd.DataFrame({'Name': ['Name1', 'Name2', 'Name3'],
'2001': [2, 1, 0],
'2002': [5, 4, 5],
'2003': [0, 2, 0],
'2004': [0, 0, 0],
'2005': [4, 4, 0],
'200... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Heteroskedasticity
Step2: Testing for Heteroskedasticity
Step3: Correcting for Heteroskedasticity
Step4: Serial correlation of errors
Step5: ... | <ASSISTANT_TASK:>
Python Code:
# Import all the libraries we'll be using
import numpy as np
import statsmodels.api as sm
from statsmodels import regression, stats
import statsmodels
import matplotlib.pyplot as plt
residuals = np.random.normal(0, 1, 100)
_, pvalue, _, _ = statsmodels.stats.stattools.jarque_bera(residual... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: List files
Step2: Plot an image
Step3: Image metadata
| <ASSISTANT_TASK:>
Python Code:
%%capture
!python -m pip install abraia
import os
if not os.getenv('ABRAIA_KEY'):
#@markdown <a href="https://abraia.me/console/settings" target="_blank">Get your ABRAIA_KEY</a>
abraia_key = '' #@param {type: "string"}
%env ABRAIA_KEY=$abraia_key
from abraia import Abraia
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: Start submission procedure
Step2: please provide information on the contact person for this CORDEX data submission request
Step3: Requested ge... | <ASSISTANT_TASK:>
Python Code:
from dkrz_forms import form_widgets
form_widgets.show_status('form-submission')
MY_LAST_NAME = "ki" # e.gl MY_LAST_NAME = "schulz"
#-------------------------------------------------
from dkrz_forms import form_handler, form_widgets, checks
form_info = form_widgets.check_pwd(MY_LAST_NA... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Retrieving training and test data
Step2: Visualize the training data
Step3: Building the network
Step4: Training the network
Step5: Testing
| <ASSISTANT_TASK:>
Python Code:
# Import Numpy, TensorFlow, TFLearn, and MNIST data
import numpy as np
import tensorflow as tf
import tflearn
import tflearn.datasets.mnist as mnist
# Retrieve the training and test data
trainX, trainY, testX, testY = mnist.load_data(one_hot=True)
# Visualizing the data
import matplotli... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Define model name of your model and the location of MODFLOW executable. All MODFLOW files and output will be stored in the subdirectory defined ... | <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: Graphe aléatoire - matrice d'adjacence aléatoire
Step2: En le visualisant...
Step3: Vocabulaire lié aux graphes
Step4: D'après les remarques ... | <ASSISTANT_TASK:>
Python Code:
from jyquickhelper import add_notebook_menu
add_notebook_menu()
%matplotlib inline
import numpy
mat = numpy.random.random((15, 15))
mat = mat + mat.T
adja = (mat >= 1.4).astype(int)
for i in range(adja.shape[0]):
adja[i ,i] = 0
adja
import networkx
import matplotlib.pyplot as plt
fi... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Associated is dependant variable. Both can't happen at the same time
Step2: To calculate the percentiles
Step3: Pnorm ranges
Step4: Standard ... | <ASSISTANT_TASK:>
Python Code:
%load_ext rpy2.ipython
%%R
mean = 1500
sd = 300
d = 1800
(d-mean)/sd
%%R
mean = 1500
sd = 300
point = 2100
LT = T
pnorm(point,mean=mean,sd=sd,lower.tail=LT)
%%R
mean = 1500
sd = 300
percentile = 0.4
LT = T
qnorm(percentile,mean=mean,sd=sd,lower.tail=LT)
%%R
mean = 70
sd = 3.3
lower = 6... |
<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: Character counting and entropy
Step4: The entropy is a quantiative measure of the disorder of a probability distribution. It is used extensivel... | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
from matplotlib import pyplot as plt
import numpy as np
from IPython.html.widgets import interact
def char_probs(s):
Find the probabilities of the unique characters in the string s.
Parameters
----------
s : str
A string of characters.
... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: <!--setupplotcode{import seaborn as sns
Step2: from the command prompt where you can access your python installation.
Step3: Olympic Marathon ... | <ASSISTANT_TASK:>
Python Code:
import urllib.request
urllib.request.urlretrieve('https://raw.githubusercontent.com/lawrennd/talks/gh-pages/mlai.py','mlai.py')
urllib.request.urlretrieve('https://raw.githubusercontent.com/lawrennd/talks/gh-pages/teaching_plots.py','teaching_plots.py')
urllib.request.urlretrieve('https:/... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Run the default solution on dev
Step2: Evaluate the default output
| <ASSISTANT_TASK:>
Python Code:
from default import *
import os
lexsub = LexSub(os.path.join('data','glove.6B.100d.magnitude'))
output = []
with open(os.path.join('data','input','dev.txt')) as f:
for line in f:
fields = line.strip().split('\t')
output.append(" ".join(lexsub.substitutes(int(fields[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: Load relevant data
Step2: Create XP designs
Step3: Standardize wavefiles
Step4: Get MFCC and F1F2 figure for each wavefile
Step5: Define dis... | <ASSISTANT_TASK:>
Python Code:
# Requirements:
# - sox + soundfile + our vowel_discri package
# - ABXpy.distances (could be made independent from ABXpy)
import soundfile
import os
import os.path as path
import pandas as pd
import numpy as np
import seaborn
from ast import literal_eval as make_tuple
import wave
impor... |
<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: Exercises about Numpy
Step5: This notebook reviews some of the Python modules that make it possible to work with data structures in an easy an ... | <ASSISTANT_TASK:>
Python Code:
# Import some libraries that will be necessary for working with data and displaying plots
import numpy as np
import hashlib
# Test functions
def hashstr(str1):
Implements the secure hash of a string
return hashlib.sha1(str1).hexdigest()
def test_arrayequal(x1, x2, err_msg, ok_msg=... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: First we import all the scattering parameters of the capacitor simulated at different positions. S-parameters are imported as skrf networks in a... | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
import skrf as rf
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
rf.stylely()
capas = rf.read_all('S_Matrices/', f_unit='MHz')
capas_set = rf.NetworkSet(capas)
f_band = '35-65MHz'
f = capas_set[0].f
omega = 2*np.pi*f
D_cylinders... |
<SYSTEM_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: NOTE
Step4: Calculating the solution
Step5: Plot
Step6: Print the variables in BOUT++ format
| <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: Veamos la gráfica...
Step2: Otra manera de hacer lo anterior
Step3: El converso del teorema anterior no es cierto.
Step4: 2. Criterio de la s... | <ASSISTANT_TASK:>
Python Code:
# Librería de cálculo simbólico
import sympy as sym
# Para imprimir en formato TeX
from sympy import init_printing; init_printing(use_latex='mathjax')
sym.var('x', real = True)
f = x**2
f
df = sym.diff(f, x)
df
x_c = sym.solve(df, x)
x_c[0]
import numpy as np
import matplotlib.pyplot as ... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: 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: <table class="tfo-notebook-buttons" align="left">
Step2: Download the dataset
Step3: This dataset produces Portuguese/English sentence pairs
S... | <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: 如何卸载一个包
| <ASSISTANT_TASK:>
Python Code:
import graphlab as gl
from IPython.display import display
from IPython.display import Image
gl.canvas.set_target('ipynb')
%matplotlib inline
import matplotlib.pyplot as plt
plt.plot(2, 2)
plt.text(2, 2, '汉字', fontsize = 300)
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: PlateCarree
Step2: set the central longitude to $180^\circ$
Step3: AzimuthalEquidistant
Step4: LambertCylindrical
Step5: Mercator
Step6: Mi... | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
import matplotlib.pyplot as plt
import cartopy.crs as ccrs
plt.figure(figsize=(12, 12))
ax = plt.axes(projection=ccrs.PlateCarree())
ax.coastlines(resolution='110m')
ax.stock_img()
ax.gridlines();
plt.figure(figsize=(12, 12))
ax = plt.axes(projection=ccrs.PlateCarree(... |
<SYSTEM_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, load the data. Loading may take some time.
Step2: Part 1
Step3: A Map is a collection of regions and other features such as points and ... | <ASSISTANT_TASK:>
Python Code:
# Run this cell, but please don't change it.
import numpy as np
import math
from datascience import *
# These lines set up the plotting functionality and formatting.
import matplotlib
matplotlib.use('Agg', warn=False)
%matplotlib inline
import matplotlib.pyplot as plots
plots.style.use('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: Face Generation
Step3: Explore the Data
Step5: CelebA
Step7: Preprocess the Data
Step10: Input
Step13: Discriminator
Step16: Generator
Ste... | <ASSISTANT_TASK:>
Python Code:
data_dir = './data'
# FloydHub - Use with data ID "R5KrjnANiKVhLWAkpXhNBe"
data_dir = '/input'
DON'T MODIFY ANYTHING IN THIS CELL
import helper
helper.download_extract('mnist', data_dir)
helper.download_extract('celeba', data_dir)
show_n_images = 25
DON'T MODIFY ANYTHING IN THIS CELL
%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: Load Dataset
Step2: Create Train and Test Data [from categories-medical and automobiles]
Step3: Explore the data
Step4: Pre-process Data
Ste... | <ASSISTANT_TASK:>
Python Code:
import re
from time import time
import string
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from pprint import pprint
#Sklearn Imports
from sklearn import metrics
from sklearn.datasets import fetch_20newsgroups
from sklearn import preprocessing
from sklearn.pipeli... |
<SYSTEM_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
Step2: Geolocation APIs have hourly limits, so this was originally run using a cron job nightly to build up a large map of locations to... | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
import time
import pylab
import numpy as np
import pandas as pd
import pycupid.locations
people = pd.read_json('/Users/ajmendez/data/okcupid/random.json')
print('Scraping archive found {:,d} random people'.format(len(people)))
locations = people['location'].astype(unic... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Ok, we get his id now, now we have to get his match history. Let's find all his matches in 2016 season and team builder draft 5v5 rank queue.
St... | <ASSISTANT_TASK:>
Python Code:
from lolcrawler_util import read_key, get_summoner_info
api_key = read_key()
name = 'Doublelift'
summoner = get_summoner_info(api_key, name)
usr_id = summoner[name.lower()]['id']
print usr_id
from lolcrawler_util import get_matchlist_by_summoner
matchlist = get_matchlist_by_summoner(usr_... |
<SYSTEM_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 often use $\boldsymbol{X}$ to represent a dataset of input vectors. The $i^{th}$ input vector in $X$ is notated $X_i$, though often times whe... | <ASSISTANT_TASK:>
Python Code:
from __future__ import print_function
%matplotlib inline
from sklearn.datasets import load_digits
from matplotlib import pyplot as plt
import numpy as np
np.random.seed(42) # for reproducibility
digits = load_digits()
X = digits.data
y = digits.target
zeroes = [X[i] for i in range(len(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: Short Introduction to Python and Jupyter
Step2: Task #3 [10%]
Step3: Plotting
Step4: Task #4 [10%]
Step5: Data structures
Step6: Accessing ... | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
import sys
print('Python version:')
print(sys.version)
print('Numpy version:')
print(np.__version__)
import sklearn
print('Sklearn version:')
print(sklearn.__version__)
#This is a code cell
#Jupyter allows you to run ... |
<SYSTEM_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: (1b) Sparse vectors
Step3: (1c) OHE features as sparse vectors
Step5: (1d) Define a OHE function
Step6: (1e) Apply OHE to a... | <ASSISTANT_TASK:>
Python Code:
labVersion = 'cs190_week4_v_1_3'
# Data for manual OHE
# Note: the first data point does not include any value for the optional third feature
sampleOne = [(0, 'mouse'), (1, 'black')]
sampleTwo = [(0, 'cat'), (1, 'tabby'), (2, 'mouse')]
sampleThree = [(0, 'bear'), (1, 'black'), (2, 'salm... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: What's a graph?
Step2: Graphs are everywhere these days!
Step4: ipython-gremlin
| <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
%load_ext gremlin
import asyncio
import aiogremlin
import networkx as nx
g = nx.scale_free_graph(10)
nx.draw_networkx(g)
@asyncio.coroutine
def stream(gc):
results = []
resp = yield from gc.submit("x + x", bindings={"x": 1})
while True:
result = yi... |
<SYSTEM_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 vectors of users
Step2: getAllUserVectorData
Step3: Correlation Matrix
Step4: List of users and their sessions
Step5: List of sessions ... | <ASSISTANT_TASK:>
Python Code:
%run "../Functions/1. Google form analysis.ipynb"
%run "../Functions/4. User comparison.ipynb"
#getAllResponders()
setAnswerTemporalities(gform)
# small sample
#allData = getAllUserVectorData( getAllUsers( rmdf152 )[:10] )
# complete set
#allData = getAllUserVectorData( getAllUsers( rmd... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: GitHub Authorization
Step2: Basic API request
Step3: Issues in an organization's repos
| <ASSISTANT_TASK:>
Python Code:
import github3
import json
from os.path import join
import pprint
import requests
from urllib.parse import urljoin
TOKEN=''
gh = github3.login(token=TOKEN)
type(gh)
url = 'https://api.github.com/orgs/jupyterhub/repos'
response = requests.get(url)
if response.status_code != 200:
# Th... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Check that the loaded data are consistent with what we expect
Step2: To begin with, let's write a function that returns the algebraic distance ... | <ASSISTANT_TASK:>
Python Code:
import numpy as np
import matplotlib.pyplot as plt #We might need this
#First, let us load the data
#Catalog from HSC
cat_hsc = np.loadtxt('./Catalog_HSC.csv')
x_hsc = cat_hsc[:,0]
y_hsc = cat_hsc[:,1]
#Catalog from HST
cat_hst = np.loadtxt('./Catalog_HST.csv')
x_hst = cat_hst[:,0]
y_hs... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: "MOSFET" toy model
Step2: The next one is slightly modified
Step3: The following function also needs to be modified slightly
Step4: Let's put... | <ASSISTANT_TASK:>
Python Code:
import numpy as np
import kwant
%run matplotlib_setup.ipy
from matplotlib import pyplot
lat = kwant.lattice.square()
def make_lead_x(W=10, t=1):
syst = kwant.Builder(kwant.TranslationalSymmetry([-1, 0]))
syst[(lat(0, y) for y in range(W))] = 4 * t
syst[lat.neighbors()] = -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: Full disclaimer
Step3: 2.2. Clean your data
Step4: 2.3. Share your data
Step6: 2.4. Study your data
Step7: 2.5. Split your data in train and... | <ASSISTANT_TASK:>
Python Code:
from configparser import ConfigParser
from os.path import join
from os import pardir
config = ConfigParser()
config.read(join(pardir,'src','credentials.ini'))
APP_KEY = config['twitter']['app_key']
APP_SECRET = config['twitter']['app_secret']
OAUTH_TOKEN = config['twitter']['oauth_token'... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Download and preprocess data
Step2: In the following cell, replace your-cloud-project with the name of your GCP project.
Step3: Model version ... | <ASSISTANT_TASK:>
Python Code:
import json
import numpy as np
import pandas as pd
import xgboost as xgb
import tensorflow as tf
from sklearn.utils import shuffle
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
from google.cloud import bigquery
from google.colab import au... |
<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Get Data
Step2: Standardize Data
Step3: Create Inner Cross Validation (For Parameter Tuning)
Step4: The code below isn't necessary for parame... | <ASSISTANT_TASK:>
Python Code:
# Load required packages
from sklearn import datasets
from sklearn.model_selection import GridSearchCV, cross_val_score
from sklearn.preprocessing import StandardScaler
import numpy as np
from sklearn.svm import SVC
# Load the data
dataset = datasets.load_breast_cancer()
# Create X 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: Do a simple wet/dry classification
Step2: Derive a constant baseline
Step3: Or derive a linear baseline
Step4: Compare the results from const... | <ASSISTANT_TASK:>
Python Code:
cml = pycml.io.examples.read_one_cml()
# Remove artifacts and plot data
cml.process.quality_control.set_to_nan_if('tx', '>=', 100)
cml.process.quality_control.set_to_nan_if('rx', '==', -99.9)
cml.plot_data(['tx', 'rx', 'txrx']);
cml.process.wet_dry.std_dev(window_length=30, threshold=0.8... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.