Unnamed: 0 int64 0 15.9k | cleaned_code stringlengths 67 124k ⌀ | cleaned_prompt stringlengths 168 30.3k ⌀ |
|---|---|---|
4,700 | <ASSISTANT_TASK:>
Python Code:
from jupyterthemes import get_themes
from jupyterthemes.stylefx import set_nb_theme
themes = get_themes()
set_nb_theme(themes[1])
%load_ext watermark
%watermark -a 'Ethen' -d -t -v -p jupyterthemes
# adjacency list can be efficiently represented as
# a python dictionary, where the nodes ... | <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: Tree Data Structure
Step4: For depth first search, the list of actions to perform upon each visit to a node
|
4,701 | <ASSISTANT_TASK:>
Python Code:
sns.lmplot(x='Attack',y='Defense',hue='Legendary',fit_reg=False,markers=['x','o'],data = pokemon)
plt.show()
sns.heatmap(
pokemon.loc[:, ['HP', 'Attack', 'Sp. Atk', 'Defense', 'Sp. Def', 'Speed']].corr(),
annot=True
)
plt.show()
import pandas as pd
from pandas.plotting import para... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: 非常实用的方法是将Seaborn的分类图分为三类,将分类变量每个级别的每个观察结果显示出来,显示每个观察分布的抽象表示,以及应用统计估计显示的权重趋势和置信区间:
Step2: 1. Facet Grid 2 . Pair Plot
|
4,702 | <ASSISTANT_TASK:>
Python Code:
import cartopy.crs as ccrs
import cartopy.feature as cfeature
import matplotlib.pyplot as plt
import numpy as np
import xarray as xr
import metpy.calc as mpcalc
from metpy.cbook import get_test_data
from metpy.interpolate import cross_section
data = xr.open_dataset(get_test_data('narr_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: Getting the data
Step2: Define start and end points
Step3: Get the cross section, and convert lat/lon to supplementary coordinates
Step4: For... |
4,703 | <ASSISTANT_TASK:>
Python Code:
#!pip install -I "phoebe>=2.4,<2.5"
import phoebe
print(phoebe.multiprocessing_get_nprocs())
phoebe.multiprocessing_off()
print(phoebe.multiprocessing_get_nprocs())
phoebe.multiprocessing_on()
print(phoebe.multiprocessing_get_nprocs())
phoebe.multiprocessing_set_nprocs(2)
print(phoebe... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Accessing/Changing Multiprocessing Settings
Step2: To disable multiprocessing, we can call phoebe.multiprocessing_off.
Step3: To re-enable mul... |
4,704 | <ASSISTANT_TASK:>
Python Code:
import mne
import os.path as op
# Read the info object from an example recording
info = mne.io.read_info(
op.join(mne.datasets.sample.data_path(), 'MEG', 'sample',
'sample_audvis_raw.fif'), verbose=False)
print('Keys in info dictionary:\n', info.keys())
print(info['sfre... | <SYSTEM_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: List all the fields in the info object
Step3: Obtain the sampling rate of the data
Step4: List all information about the first data c... |
4,705 | <ASSISTANT_TASK:>
Python Code:
#!pip install -I "phoebe>=2.3,<2.4"
import phoebe
from phoebe import u # units
import numpy as np
import matplotlib.pyplot as plt
logger = phoebe.logger(clevel='INFO')
b = phoebe.default_binary()
b['incl@orbit'] = 56.789
print(b.save('test.phoebe'))
!head -n 30 test.phoebe
b2 = phoebe... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Saving a Bundle
Step2: To save the Bundle to a file, we can call the save method of the Bundle and pass a filename.
Step3: We can now inspect ... |
4,706 | <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: Load and prepare the data
Step2: Checking out the data
Step3: Dummy variables
Step4: Scaling target variables
Step5: Splitting the data into... |
4,707 | <ASSISTANT_TASK:>
Python Code:
import rebound
sim = rebound.Simulation()
sim.add(m=1.)
print(sim.particles[0])
sim.add(m=1e-3, x=1., vy=1.)
sim.add(m=1e-3, a=2., e=0.1)
sim.status()
sim.integrator = "whfast"
sim.dt = 1e-3
sim.integrate(6.28318530717959, exact_finish_time=0) # 6.28318530717959 is 2*pi
sim.sta... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Next, we create a REBOUND simulation instance. This object encapsulated all the variables and functions that REBOUND has to offer.
Step2: Now, ... |
4,708 | <ASSISTANT_TASK:>
Python Code:
!pip install dm-acme
!pip install dm-acme[reverb]
!pip install dm-acme[tf]
!pip install dm-sonnet
#@title Edit and run
mjkey =
REPLACE THIS LINE WITH YOUR MUJOCO LICENSE KEY
.strip()
mujoco_dir = "$HOME/.mujoco"
# Install OpenGL deps
!apt-get update && apt-get install -y --no-install-re... | <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: MuJoCo
Step4: Machine-locked MuJoCo license.
Step5: RWRL
Step6: RL Unplugged
Step7: Imports
Step8: Data
Step10: Dataset and environment
St... |
4,709 | <ASSISTANT_TASK:>
Python Code:
text1 = "Ethics are built right into the ideals and objectives of the United Nations "
len(text1) # The length of text1
text2 = text1.split(' ') # Return a list of the words in text2, separating by ' '.
len(text2)
text2
[w for w in text2 if len(w) > 3] # Words that are greater than 3 let... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: <br>
Step2: <br>
Step3: Processing free-text
Step4: <br>
Step5: <br>
Step6: <br>
|
4,710 | <ASSISTANT_TASK:>
Python Code:
# Authors: Eric Larson <larson.eric.d@gmail.com>
#
# License: BSD-3-Clause
import os.path as op
import numpy as np
import matplotlib.pyplot as plt
import mne
from mne import find_events, fit_dipole
from mne.datasets import fetch_phantom
from mne.datasets.brainstorm import bst_phantom_elek... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: The data were collected with an Elekta Neuromag VectorView system at 1000 Hz
Step2: Data channel array consisted of 204 MEG planor gradiometers... |
4,711 | <ASSISTANT_TASK:>
Python Code:
from IPython.core.display import display, HTML;from string import Template;
HTML('<script src="//d3js.org/d3.v3.min.js" charset="utf-8"></script>')
css_text2 = '''
#main { float: left; width: 750px;}#sidebar { float: right; width: 100px;}#sequence { width: 600px; height: 70px;}#lege... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Graphic Interpretation
Step2: AIM
Step3: Conclusions
Step4: <a id='num_mod_sev'></a>
Step5: <a id='ua'></a>
Step6: Potential Conlusions
Ste... |
4,712 | <ASSISTANT_TASK:>
Python Code:
# Evaluate this cell to identifiy your form
from dkrz_forms import form_widgets, form_handler, checks
form_infos = form_widgets.show_selection()
# Evaluate this cell to generate your personal form instance
form_info = form_infos[form_widgets.FORMS.value]
sf = form_handler.init_form(form_... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Step 1
Step2: CMOR compliance
Step3: Documentation availability
Step4: Uniqueness of tracking_id and creation_date
Step5: Generic content ch... |
4,713 | <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: Load and prepare the data
Step2: Checking out the data
Step3: Dummy variables
Step4: Scaling target variables
Step5: Splitting the data into... |
4,714 | <ASSISTANT_TASK:>
Python Code:
# importing
import numpy as np
from collections import Counter
def LZ77_encode ( input_sequence, window_length = 10 ):
'''
Implementation of LZ77 encoding
IN: input_sequence ( list or np.array of letters )
OUT: list of 3-tuples with each tuple being (a,b,x) where a 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: Implementation of Lempel-Ziv-77
Step2: Decoding algorithm, just the reconstruction of the string by looking up the data
Step3: Recursive Imple... |
4,715 | <ASSISTANT_TASK:>
Python Code:
import nlp
from nlp import Page, HITS
from nlp import Lexicon, Rules, Grammar, ProbLexicon, ProbRules, ProbGrammar
from nlp import CYK_parse, Chart
from notebook import psource
psource(Lexicon, Rules, Grammar)
lexicon = Lexicon(
Verb = "is | say | are",
Noun = "robot | sheep | 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: CONTENTS
Step2: Let's build a lexicon and a grammar for the above language
Step3: Both the functions return a dictionary with keys the left-ha... |
4,716 | <ASSISTANT_TASK:>
Python Code:
from IPython.display import Image
# Add your filename and uncomment the following line:
#Image(filename='drought.png')
<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: Graphical excellence and integrity
|
4,717 | <ASSISTANT_TASK:>
Python Code:
dx = 1.
x = 1.
while(dx > 1.e-10):
dy = (x+dx)*(x+dx)-x*x
d = dy / dx
print("%6.0e %20.16f %20.16f" % (dx, d, d-2.))
dx = dx / 10.
((1.+0.0001)*(1+0.0001)-1)
dx = 1.
x = 1.
while(dx > 1.e-10):
dy = (x+dx)*(x+dx)-x*x
d = dy / dx
print("%8.5e %20.16f %20.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: Why is it that the sequence does not converge? This is due to the round-off errors in the representation of the floating point numbers. To see t... |
4,718 | <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: 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... |
4,719 | <ASSISTANT_TASK:>
Python Code:
import pandas as pd
import json
from sklearn.ensemble import RandomForestClassifier
from sklearn.externals import joblib
from sklearn.feature_selection import SelectKBest
from sklearn.pipeline import FeatureUnion
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import Labe... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Add code to download the data (in this case, using the publicly hosted data).
Step2: Read in the data
Step3: Load the training census dataset
... |
4,720 | <ASSISTANT_TASK:>
Python Code:
!pip install -q opencv-python
import os
import tensorflow.compat.v2 as tf
import tensorflow_hub as hub
import numpy as np
import cv2
from IPython import display
import math
# Load the model once from TF-Hub.
hub_handle = 'https://tfhub.dev/deepmind/mil-nce/s3d/1'
hub_model = hub.load(hub... | <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: TF-Hub 모델 가져오기
Step4: 텍스트-비디오 검색 시연하기
|
4,721 | <ASSISTANT_TASK:>
Python Code:
x = [51, 65, 56, 19, 11, 49, 81, 59, 45, 73]
max_val = 0
for element in x:
# ... now what?
pass
x = 5
if x < 5:
print("How did this happen?!") # Spoiler alert: this won't happen.
if x == 5:
print("Working as intended.")
x = 5
if x < 5:
print("How did this happ... | <SYSTEM_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 we want to figure out the maximum value, we'll obviously need a loop to check each element of the list (which we know how to do), and a varia... |
4,722 | <ASSISTANT_TASK:>
Python Code:
import matplotlib.pyplot as plt
from numpy import pi, sin, cos, linspace, exp, real, imag, abs, conj, meshgrid, log, log10, angle
from numpy.fft import fft, fftshift, ifft
from mpl_toolkits.mplot3d import axes3d
import BeamOptics as bopt
%matplotlib inline
b=.08*1e-3 # the slit width
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:
Step3: Double-slit model
Step4: Sanity check
Step6: Define a single function to explore the FFT
Step7: This agrees well with Matt's code using symbo... |
4,723 | <ASSISTANT_TASK:>
Python Code:
# Authors: Alexandre Gramfort <alexandre.gramfort@inria.fr>
#
# License: BSD-3-Clause
import numpy as np
import matplotlib.pyplot as plt
import mne
from mne import io
from mne.datasets import sample
print(__doc__)
data_path = sample.data_path()
raw_fname = data_path + '/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: Set parameters
Step2: Show event-related fields images
|
4,724 | <ASSISTANT_TASK:>
Python Code:
from __future__ import division
import gym
import numpy as np
import random
import tensorflow as tf
import matplotlib.pyplot as plt
%matplotlib inline
env = gym.make('FrozenLake-v0')
tf.reset_default_graph()
#These lines establish the feed-forward part of the network used to choose acti... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Load the environment
Step2: The Q-Network Approach
Step3: Training the network
Step4: Some statistics on network performance
Step5: It also ... |
4,725 | <ASSISTANT_TASK:>
Python Code:
# Authors: Denis A. Engemann <denis.engemann@gmail.com>
# Stefan Appelhoff <stefan.appelhoff@mailbox.org>
#
# License: BSD (3-clause)
import os.path as op
import numpy as np
import matplotlib.pyplot as plt
import mne
from mne.datasets import somato
from mne.baseline import rescal... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Set parameters
Step2: We create average power time courses for each frequency band
Step4: Now we can compute the Global Field Power
|
4,726 | <ASSISTANT_TASK:>
Python Code::
from sklearn.svm import SVR
from sklearn.metrics import mean_squared_error, mean_absolute_error
# initliase & fit model
model = SVR(C=1.5, kernel='linear')
model.fit(X_train, y_train)
# make prediction for test data
y_pred = model.predict(X_test)
# evaluate performance
print('RMSE:',mean... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
|
4,727 | <ASSISTANT_TASK:>
Python Code:
#@title Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: 计算梯度
Step2: 安装 TensorFlow Quantum:
Step3: 现在,导入 TensorFlow 和模块依赖项:
Step4: 1. 准备工作
Step5: 以及可观测对象:
Step7: 所用算子为 $⟨Y(\alpha)| X | Y(\alpha)⟩ ... |
4,728 | <ASSISTANT_TASK:>
Python Code:
import ga4gh_client.client as client
c = client.HttpClient("http://1kgenomes.ga4gh.org")
counter = 0
for read_group_set in c.search_read_group_sets(dataset_id="WyIxa2dlbm9tZXMiXQ"):
counter += 1
if counter < 4:
print "Read Group Set: {}".format(read_group_set.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: Search read group sets
Step2: Note
Step3: Note, like in the previous example. Only a selected amount of parameters are selected for illustrati... |
4,729 | <ASSISTANT_TASK:>
Python Code:
import math
if __name__== ' __main __' :
n = 12
print(math . sqrt(n ) )
<END_TASK>
| <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
|
4,730 | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
import chap01soln
resp = chap01soln.ReadFemResp()
import thinkstats2
pmf = thinkstats2.Pmf(resp.numkdhh)
pmf
import thinkplot
thinkplot.Pmf(pmf, label='numkdhh')
thinkplot.Show()
def BiasPmf(pmf, label=''):
Returns the Pmf with oversampling proportional to value.... | <SYSTEM_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... |
4,731 | <ASSISTANT_TASK:>
Python Code:
import numpy as np
import xlrd #With pandas
import matplotlib.pyplot as plt
import pandas as pd
#Exponentiation
print(4 ** 4)
#Types and converstion
mInt = 6
mFloat = .4
mString = "Hey"
mConversion = str(mFloat)
print (mInt, mFloat, mString, mConversion, type(mConversion))
a = "is"
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: Basics
Step2: Lists
Step3: Loop
Step4: Enumerate
Step5: Numpy
Step6: Importing data command
Step7: Importing data array with differents ty... |
4,732 | <ASSISTANT_TASK:>
Python Code:
# Authors: Alexandre Gramfort <alexandre.gramfort@inria.fr>
# Eric Larson <larson.eric.d@gmail.com>
# License: BSD (3-clause)
import os.path as op
import numpy as np
from numpy.random import randn
from scipy import stats as stats
import mne
from mne.epochs import equalize_epoch_c... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Set parameters
Step2: Read epochs for all channels, removing a bad one
Step3: Transform to source space
Step4: Transform to common cortical s... |
4,733 | <ASSISTANT_TASK:>
Python Code:
from IPython.display import YouTubeVideo
# Title: Max Planck Solves the Ultraviolet Catastrophe for Blackbody Radiation | Doc Physics
# Author: Doc Schuster
YouTubeVideo('H-7f-3OAXm0')
%%latex
\begin{aligned}
B_{\lambda}(\lambda, T) = \frac{2hc^2}{\lambda^5} \frac{1}{e^{\frac{hc}{\lambda... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: 3. Equations
Step3: You can also use "line magics" to write LaTeX inline in Markdown cells
Step4: 5. Visualization
|
4,734 | <ASSISTANT_TASK:>
Python Code:
import os, sys
sys.path.append(os.path.abspath('../../main/python'))
from thalesians.tsa.simulation import xtimes, times
for t in xtimes(0, 5): print(t)
xtimes(0, 5)
list(xtimes(0, 5))
times(0, 5)
list(range(0, 5))
ts = []
for t in xtimes(start=1):
ts.append(t)
if len(ts) ==... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: xtimes
Step2: Since xtimes is a generator, the times are computed lazily
Step3: To get hold of them all at once, you need to use something lik... |
4,735 | <ASSISTANT_TASK:>
Python Code:
from pymatgen.ext.matproj import MPRester
from pymatgen.electronic_structure.core import Spin
#This initiliazes the Rest connection to the Materials Project db. Put your own API key if needed.
a = MPRester()
#load the band structure from mp-3748, CuAlO2 from the MP db
bs = a.get_bandstruc... | <SYSTEM_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 print some information about the band structure
Step2: Here, we plot the bs object. By default for an insulator we have en energy limit of c... |
4,736 | <ASSISTANT_TASK:>
Python Code:
from __future__ import print_function
# If our large test file is available, use it. Otherwise, use file generated
# from toy_mstis_2_run.ipynb. This is so the notebook can be used in testing.
import os
test_file = "../toy_mstis_1k_OPS1.nc"
filename = test_file if os.path.isfile(test_fil... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Reaction rates
Step2: The self-rates (the rate of returning the to initial state) are undefined, and return not-a-number.
Step3: We normally l... |
4,737 | <ASSISTANT_TASK:>
Python Code:
% matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
# Generate observations on the interval [0, 1)
x1 = np.random.uniform(low=0.0, high=2.0, size=100)
x2 = np.random.uniform(low=0.0, high=2.0, size=100)
X = np.matrix([x1, x2]).T
# Assign class labels based on the decis... | <SYSTEM_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) Show that in this setting, a support vector machine with a polynomial kernel (with degree greater than 1) or a radial kernel will outperform... |
4,738 | <ASSISTANT_TASK:>
Python Code:
import math as math
def ones_to_words(n):
onesdict = {0: "",
1: "one",
2: "two",
3: "three",
4: "four",
5: "five",
6: "six",
7: "seven",
8: "eight",
9... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Project Euler
Step2: Now write a set of assert tests for your number_to_words function that verifies that it is working as expected.
Step4: No... |
4,739 | <ASSISTANT_TASK:>
Python Code:
from collections import namedtuple
Subscriber = namedtuple("Subscriber", ["addr", "joined"])
sub = Subscriber("jonesy@example.com", "2012-10-19")
sub
sub.addr
sub.joined
len(sub)
addr, joined = sub
addr
joined
def compute_cost(records):
total = 0.0
for rec in records:
to... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: 尽管 namedtuple 的实例看起来像一个普通的类实例,但是它跟元组类型是可交换的,支持所有的普通元组操作,比如索引和解压。 比如:
Step2: 命名元组的一个主要用途是将你的代码从下标操作中解脱出来。 因此,如果你从数据库调用中返回了一个很大的元组列表,通过下标去操作其中的元素... |
4,740 | <ASSISTANT_TASK:>
Python Code:
import torch
import pyro
import pyro.distributions as dist
import pyro.poutine as poutine
from pyro.poutine.runtime import effectful
pyro.set_rng_seed(101)
def scale(guess):
weight = pyro.sample("weight", dist.Normal(guess, 1.0))
return pyro.sample("measurement", dist.Normal(weig... | <SYSTEM_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: This model defines a joint probability distribution over "weight" and "measurement"
Step3: That snippet is short, but stil... |
4,741 | <ASSISTANT_TASK:>
Python Code:
# DO NOT EDIT !
from pyesdoc.ipython.model_topic import NotebookOutput
# DO NOT EDIT !
DOC = NotebookOutput('cmip6', 'nasa-giss', 'giss-e2-1g', 'land')
# Set as follows: DOC.set_author("name", "email")
# TODO - please enter value(s)
# Set as follows: DOC.set_contributor("name", ... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Document Authors
Step2: Document Contributors
Step3: Document Publication
Step4: Document Table of Contents
Step5: 1.2. Model Name
Step6: 1... |
4,742 | <ASSISTANT_TASK:>
Python Code:
import matplotlib.pyplot as plt
%matplotlib inline
X = [0,1,2,3,4]
Fx = [x**2 for x in X]
fig = plt.plot(X,Fx)
plt.show(fig)
fig,axes = plt.subplots(2,2)
F0 = [x**0 for x in X]
F1 = [x**1 for x in X]
F2 = [x**2 for x in X]
F3 = [x**3 for x in X]
axes[0,0].plot(X,F0)
axes[0,1].plot(X,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: Even though we can dispose the Axes how we want inside the figure,
Step2: Another useful way to create grids of plots is by creating a figure a... |
4,743 | <ASSISTANT_TASK:>
Python Code:
# This is a comment
# This is code cell, we execute it pressing also Shift + Intro
print 1+2
a = 5
b = 10
print "a + b = %d" % (a + b)
print "a * b = %d" % (a * b)
%lsmagic
<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: In the notebook we can execute cells with more than one line of code, in the style of matlab or mathematica
Step2: In the menu we can find usef... |
4,744 | <ASSISTANT_TASK:>
Python Code:
import matplotlib.pyplot as plt
import numpy as np
import pickle
%matplotlib inline
def read_weather():
with open('data/weather.pkl', 'rb') as f:
return pickle.load(f)
# The file weather.pkl contains a list of dictionaries
Data = read_weather()
Data[0]
# Implement Q1 part 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: The purpose of the exersise is to manipulate and plot the current weather of a number of European cities. The data has been downloaded from Open... |
4,745 | <ASSISTANT_TASK:>
Python Code:
# Load the sociopatterns network data.
#G = cf.load_sociopatterns_network()
G=nx.read_gpickle('Synthetic Social Network.pkl')
# Let's find out the number of neighbors that individual #7 has.
len(G.neighbors(7))
G.nodes(data=True)
G.edges(data=True)
sorted([(n,G.neighbors(n)) for n in 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: Hubs
Step2: Exercise
Step3: Approach 2
Step4: If you inspect the dictionary closely, you will find that node 51 is the one that has the highe... |
4,746 | <ASSISTANT_TASK:>
Python Code:
sl = s.GetSurfaceDataLayout(0)
print(sl)
arr = np.swapaxes(np.array(s.GetSurfaceData(0).GetDataShorts())[0,0,...],0,2)
print(arr.shape)
vx = (sl.mExtendMaxX-sl.mExtendMinX)/(sl.mSizeX-1)
vy = (sl.mExtendMaxY-sl.mExtendMinY)/(sl.mSizeY-1)
vz = (sl.mExtendMaxZ-sl.mExtendMinZ)/(sl.mSizeZ-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: GetSurfaceData()
Step2: GetSurfaceNormals()
|
4,747 | <ASSISTANT_TASK:>
Python Code:
import numpy as np
import pandas as pd
import holoviews as hv
hv.extension('bokeh', 'matplotlib')
%opts Ellipse [xaxis=None yaxis=None] (color='red' line_width=2)
%opts Box [xaxis=None yaxis=None] (color='blue' line_width=2)
def annotations(angle):
radians = (angle / 180) * np.pi
... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: A simple DynamicMap
Step2: This example uses the concepts introduced in the exploring with containers section. As before, the argument angle i... |
4,748 | <ASSISTANT_TASK:>
Python Code:
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, sof... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Binary Classification
Step2: There should now be an oranges-vs-grapefruit.zip file in the virtual machine for this lab. Let's unzip it so we ca... |
4,749 | <ASSISTANT_TASK:>
Python Code:
### Import libaries
import numpy as np
import cv2
import glob
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import pickle
import time
import background as bg # import background.py
from IPython.display import HTML
%matplotlib inline
### Chessboard Corners
# Prepare ob... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Camera Calibration
Step2: Plots all images, only the ones with the correct grid sizes have corners drawn on them.
Step3: apply the camera cali... |
4,750 | <ASSISTANT_TASK:>
Python Code:
# A bit of setup
import numpy as np
import matplotlib.pyplot as plt
from time import time
%matplotlib inline
plt.rcParams['figure.figsize'] = (10.0, 8.0) # set default size of plots
plt.rcParams['image.interpolation'] = 'nearest'
plt.rcParams['image.cmap'] = 'gray'
# for auto-reloading 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: Load data and model
Step2: TinyImageNet-100-B classes
Step3: Visualize Examples
Step4: Extract features
Step5: kNN with ConvNet features
Ste... |
4,751 | <ASSISTANT_TASK:>
Python Code:
%pylab inline
import pandas as pd
from scipy import stats
import statsmodels.api as sm
import matplotlib.pyplot as plt
import warnings
from itertools import product
def invboxcox(y,lmbda):
if lmbda == 0:
return(np.exp(y))
else:
return(np.exp(np.log(lmbda*y+1)/lmbda))
win... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Проверка стационарности и STL-декомпозиция ряда
Step2: Стабилизация дисперсии
Step3: Стационарность
Step4: Критерий Дики-Фуллера не отвергает... |
4,752 | <ASSISTANT_TASK:>
Python Code:
# These are all the modules we'll be using later. Make sure you can import them
# before proceeding further.
from __future__ import print_function
import numpy as np
import tensorflow as tf
from six.moves import cPickle as pickle
from six.moves import range
pickle_file = 'notMNIST.pickle... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: First reload the data we generated in 1_notmnist.ipynb.
Step2: Reformat into a shape that's more adapted to the models we're going to train
Ste... |
4,753 | <ASSISTANT_TASK:>
Python Code:
import os
os.chdir('~/Codes/DL - Topic Modelling')
from __future__ import print_function, division
import sys
import timeit
from six.moves import cPickle as pickle
import numpy as np
import pandas as pd
import theano
import theano.tensor as T
from lib.deeplearning import deepbeliefnet
# l... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: ------------------------------------------------------------------------------------------------------------------------------------------------... |
4,754 | <ASSISTANT_TASK:>
Python Code:
import matplotlib.pyplot as plt
import numpy as np
import pysra
%matplotlib inline
# Increased figure sizes
plt.rcParams["figure.dpi"] = 120
m = pysra.motion.SourceTheoryRvtMotion(6.0, 30, "wna")
m.calc_fourier_amps()
fig, ax = plt.subplots()
ax.plot(m.freqs, m.fourier_amps)
ax.set(
... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Create a point source theory RVT motion
Step2: Create site profile
Step3: Create the site response calculator
Step4: Specify the output
Step5... |
4,755 | <ASSISTANT_TASK:>
Python Code:
# Meme().display_meme_help()
from eden.util import configure_logging
import logging
configure_logging(logging.getLogger(),verbosity=2)
from utilities import Weblogo
wl = Weblogo(color_scheme='classic')
meme1 = Meme(alphabet="dna", # {ACGT}
gap_in_alphabet=False,
... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: <h3>E-value of each motif</h3>
Step2: <h2>fit_predict() and fit_transform() example</h2>
Step3: <h3>Print motives as lists</h3>
Step4: <h3>Di... |
4,756 | <ASSISTANT_TASK:>
Python Code:
import numpy as np
import pandas as pd
from clustergrammer_widget import *
net = Network(clustergrammer_widget)
net.load_file('rc_two_cats.txt')
net.cluster()
net.widget()
df_genes = net.widget_df()
df_genes.shape
net.load_df(df_genes)
net.cluster()
net.widget()
# generate random matri... | <SYSTEM_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 widget using new API
Step2: Above, we have filtered the matrix to a region of interest using the brush cropping tool. Below we will get ex... |
4,757 | <ASSISTANT_TASK:>
Python Code:
## you can inspect the autosave code to see what it does.
%autosave??
profile_dir = ! ipython locate
profile_dir = profile_dir[0]
profile_dir
import os.path
custom_js_path = os.path.join(profile_dir,'profile_default','static','custom','custom.js')
# my custom js
with open(custom_js_pat... | <SYSTEM_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.js
Step2: and custom js is in
Step3: Note that custom.js is ment to be modified by user, when writing a script, you can define it in a ... |
4,758 | <ASSISTANT_TASK:>
Python Code:
import sys
sys.path.append('..')
import socnet as sn
sn.graph_width = 320
sn.graph_height = 180
g = sn.load_graph('5-kruskal.gml', has_pos=True)
for e in g.edges_iter():
g.edge[e[0]][e[1]]['label'] = g.edge[e[0]][e[1]]['c']
sn.show_graph(g, elab=True)
class Forest(object):
def ... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: A seguir, vamos configurar as propriedades visuais
Step2: Por fim, vamos carregar e visualizar um grafo
Step3: Árvores geradoras mínimas
Step4... |
4,759 | <ASSISTANT_TASK:>
Python Code:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# K is the delivery price agreed upon in the contract
K = 50
# Here we look at various different values that S_T can have
S_T = np.linspace(0, 100, 200)
# Calculate the long and short payoffs
long_payoff = S_T - K
sho... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Derivatives
Step2: This is the long side payoff
Step3: And this is the short side payoff
Step4: For a long position on a forward contract, yo... |
4,760 | <ASSISTANT_TASK:>
Python Code:
print(zeroes[0])
from sklearn.decomposition import PCA
both = [X[i] for i in range(len(y)) if y[i] == 0 or y[i] == 1]
labels = [y_ for y_ in y if y_ == 0 or y_ == 1]
pca = PCA(n_components=3)
Xproj3d = pca.fit_transform(both)
print(Xproj3d[labels.index(0)]) # labels.index(0) gives us 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: How can we visualize the distribution of these points in $\mathbb{R}^{64}$? We need to approximate the relative positions of the points in 1, 2 ... |
4,761 | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
import numpy as np
import scipy.linalg as la
import matplotlib.pyplot as plt
# npoints uniformly randomly distributed points in the interval [0,3]
npnts =100
x = np.random.uniform(0.,3.,npnts)
# set y = mx + b plus random noise of size err
slope = 2.
intercept = 1.
err... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Total Least Squares
Step2: Classical Least Squares
Step3: Total Least Squares
Step4: Now plot and compare the two solutions
|
4,762 | <ASSISTANT_TASK:>
Python Code:
y=np.linspace(-2,3,100)
x=np.exp(y)
plt.plot(x,y)
plt.xlabel('$x$')
plt.ylabel('$y=\ln x$')
plt.show()
plt.semilogx(x,y)
plt.xlabel('$x$')
plt.ylabel('$y=\ln x$')
plt.show()
x=np.logspace(0,10,100)
y=np.log(x)
plt.semilogx(x,y)
plt.semilogx(1/x,-y)
plt.xlabel('$x$')
plt.ylabel('$y=\ln x... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Для графического представления данных часто используется логарифмическая шкала, на которой находищиеся на одном расстоянии точки отличаются в од... |
4,763 | <ASSISTANT_TASK:>
Python Code:
# Run this cell, but please don't change it.
# These lines import the Numpy and Datascience modules.
import numpy as np
from datascience import *
# These lines do some fancy plotting magic
import matplotlib
%matplotlib inline
import matplotlib.pyplot as plt
plt.style.use('fivethirtyeight'... | <SYSTEM_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 Actual Big Bang Theory
Step2: Question 1
Step3: We want to know how long she's been driving, but we forgot to record the time when she lef... |
4,764 | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
from keras.models import Sequential
from keras.layers.core import Dense, Dropout, Activation
from pyspark import SparkContext
from pyspark import SparkConf
from pyspark.ml.feature import StandardScaler
from pyspark.ml... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Spark Configuration and Preparation
Step2: Data Preparation
Step3: After reading the dataset from storage, we will extract several metrics suc... |
4,765 | <ASSISTANT_TASK:>
Python Code:
print(__doc__)
import numpy as np
from sklearn.svm import SVR
import matplotlib.pyplot as plt
X = np.sort(5 * np.random.rand(40, 1), axis=0)
y = np.sin(X).ravel()
y[::5] += 3 * (0.5 - np.random.rand(8))
svr_rbf = SVR(kernel='rbf', C=1e3, gamma=0.1)
svr_lin = SVR(kernel='linear', C=1e3)... | <SYSTEM_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 sample data
Step2: Add noise to targets
Step3: Fit regression model
Step4: look at the results
|
4,766 | <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: Fine-tuning a BERT model with Orbit
Step2: The tf-models-official package contains both the orbit and tensorflow_models modules.
Step3: Setup ... |
4,767 | <ASSISTANT_TASK:>
Python Code:
print("Hello, World!")
print("\N{WAVING HAND SIGN}, \N{EARTH GLOBE ASIA-AUSTRALIA}!")
print("First this line is printed,")
print("and then this one.")
print("This line is missing something."
from client.api.notebook import Notebook
ok = Notebook('Intro.ok')
# Examples of expressions:... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: And this one
Step2: The fundamental building block of Python code is an expression. Cells can contain multiple lines with multiple expressions.... |
4,768 | <ASSISTANT_TASK:>
Python Code:
from IPython.display import display, Latex, Markdown
mark_text = "_Ejemplo_ de **markdown** \nHola mundo"
display(Markdown(mark_text))
fila1 = "|columna 1|columna 2|"
filaalineacion = "|---:|:---:|"
fila2 = "|der|cen|"
display(Markdown(fila1+"\n"+filaalineacion+"\n"+fila2))
latexexp =... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: A continuación usaremos una celda de código en la cual guardaremos una expresión markdown en una variable python para su posterior visualización... |
4,769 | <ASSISTANT_TASK:>
Python Code:
#numerical library
import numpy as np
#plot library
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
from matplotlib.ticker import LinearLocator, FormatStrFormatter
import matplotlib.pyplot as plt
from pprint import pprint
x,y = np.indices([1024,1024])
%timeit (x**2+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: inizialization of the variable
Step2: Guessing the speed gain if this work
Step3: So if this approximation work we can stimate the norm over x... |
4,770 | <ASSISTANT_TASK:>
Python Code:
import numpy as np
from theano import function
raise NotImplementedError("TODO: add any other imports you need")
def make_scalar():
Returns a new Theano scalar.
raise NotImplementedError("TODO: implement this function.")
def log(x):
Returns the logarithm of a 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:
Step3: Theano exercises
Step4: Solution
Step9: Exercise 2
Step10: Solution
Step14: Exercise 3
Step15: Solution
Step17: Exercise 4
Step18: Soluti... |
4,771 | <ASSISTANT_TASK:>
Python Code:
# This Python 3 environment comes with many helpful analytics libraries installed
# It is defined by the kaggle/python docker image: https://github.com/kaggle/docker-python
# For example, here's several helpful packages to load in
from glob import glob
import numpy as np # linear algebra... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Reorganize the data
Step5: Find all the categories of the flowers
Step6: Statistics of flowers
Step7: Observations
Step8: Data Transformatio... |
4,772 | <ASSISTANT_TASK:>
Python Code:
# DO NOT EDIT !
from pyesdoc.ipython.model_topic import NotebookOutput
# DO NOT EDIT !
DOC = NotebookOutput('cmip6', 'cas', 'sandbox-2', 'land')
# Set as follows: DOC.set_author("name", "email")
# TODO - please enter value(s)
# Set as follows: DOC.set_contributor("name", "email"... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Document Authors
Step2: Document Contributors
Step3: Document Publication
Step4: Document Table of Contents
Step5: 1.2. Model Name
Step6: 1... |
4,773 | <ASSISTANT_TASK:>
Python Code:
from jyquickhelper import add_notebook_menu
add_notebook_menu()
from pyquickhelper.helpgen import NbImage
NbImage("images/2048.png", width=200)
import numpy
def create_game():
return numpy.zeros((4,4), dtype=int)
create_game()
import random
def gameover1(game):
arr = game.ravel(... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Exercice 1
Step2: La seconde tire un nombre aléatoire et l'ajoute dans une case vide choisie au hasard s'il en reste. S'il n'en reste plus, le... |
4,774 | <ASSISTANT_TASK:>
Python Code:
from petal_helper import *
import tensorflow as tf
# Detect TPU, return appropriate distribution strategy
try:
tpu = tf.distribute.cluster_resolver.TPUClusterResolver()
print('Running on TPU ', tpu.master())
except ValueError:
tpu = None
if tpu:
tf.config.experimental_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: Distribution Strategy
Step2: TensorFlow will distribute training among the eight TPU cores by creating eight different replicas of your model. ... |
4,775 | <ASSISTANT_TASK:>
Python Code:
from math import sin, exp
def func(x):
return sin(x / 5.) * exp(x / 10.) + 5. * exp(-x / 2.)
import numpy as np
from scipy import linalg
arrCoordinates = np.arange(1., 15.1, 0.1)
arrFunction = np.array([func(coordinate) for coordinate in arrCoordinates])
#многочлен первой степени
arr... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: 1. Сформировать СЛАУ для многочлена первой степени, который должен совпадать с функцией в точках 1 и 15.
Step2: 2. Многочлен второй степени в т... |
4,776 | <ASSISTANT_TASK:>
Python Code:
# DO NOT EDIT !
from pyesdoc.ipython.model_topic import NotebookOutput
# DO NOT EDIT !
DOC = NotebookOutput('cmip6', 'cmcc', 'sandbox-3', 'land')
# Set as follows: DOC.set_author("name", "email")
# TODO - please enter value(s)
# Set as follows: DOC.set_contributor("name", "email... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Document Authors
Step2: Document Contributors
Step3: Document Publication
Step4: Document Table of Contents
Step5: 1.2. Model Name
Step6: 1... |
4,777 | <ASSISTANT_TASK:>
Python Code:
DON'T MODIFY ANYTHING IN THIS CELL
import helper
data_dir = './data/simpsons/moes_tavern_lines.txt'
text = helper.load_data(data_dir)
# Ignore notice, since we don't use it for analysing the data
text = text[81:]
view_sentence_range = (0, 10)
DON'T MODIFY ANYTHING IN THIS CELL
import 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: TV Script Generation
Step3: Explore the Data
Step6: Implement Preprocessing Functions
Step9: Tokenize Punctuation
Step11: Preprocess all the... |
4,778 | <ASSISTANT_TASK:>
Python Code:
# Author: Alan Leggitt <alan.leggitt@ucsf.edu>
#
# License: BSD-3-Clause
import os.path as op
import mne
from mne import setup_source_space, setup_volume_source_space
from mne.datasets import sample
print(__doc__)
data_path = sample.data_path()
subjects_dir = op.join(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: Setup the source spaces
Step2: Plot the positions of each source space
|
4,779 | <ASSISTANT_TASK:>
Python Code:
# Author: Annalisa Pascarella <a.pascarella@iac.cnr.it>
#
# License: BSD (3-clause)
import os.path as op
import matplotlib.pyplot as plt
from nilearn import plotting
import mne
from mne.minimum_norm import make_inverse_operator, apply_inverse
# Set dir
data_path = mne.datasets.sample.data... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Set up our source space.
Step2: We could write the mixed source space with
Step3: Average the source estimates within each label of the cortic... |
4,780 | <ASSISTANT_TASK:>
Python Code:
from lifelines.datasets import load_rossi
rossi = load_rossi()
cph = CoxPHFitter()
cph.fit(rossi, 'week', 'arrest')
cph.print_summary(model="untransformed variables", decimals=3)
cph.check_assumptions(rossi, p_value_threshold=0.05, show_plots=True)
from lifelines.statistics import propo... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Checking assumptions with check_assumptions
Step2: Alternatively, you can use the proportional hazard test outside of check_assumptions
Step3: ... |
4,781 | <ASSISTANT_TASK:>
Python Code:
from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
import edward as ed
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
import numpy as np
import os
import tensorflow as tf
from edward.models import Uniform
fr... | <SYSTEM_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
Step2: Model
Step4: Inference
Step5: Let $p^*(\mathbf{x})$ represent the true data distribution.
Step6: We'll use ADAM as optimizers fo... |
4,782 | <ASSISTANT_TASK:>
Python Code:
PROJECT_DIR = "../../"
use_toy_data = False
LOG_DIR = 'logs' # Tensorboard log directory
if use_toy_data:
batch_size = 8
embedding_dim = 5
cell_size = 32
max_len = 6
else:
batch_size = 64
embedding_dim = 20
cell_size = 128
max_len = 33
use_attention =... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Download data if necessary
Step2: Load and preprocess data
Step3: Create model
Step4: Encoder
Step5: Decoder
Step6: Loss and training opera... |
4,783 | <ASSISTANT_TASK:>
Python Code:
x = 10 # x é um inteiro
print type(x)
x = 1.3 # x é um ponto flutuante
print type(x)
x = "Ola" # x é uma string
print type(x)
x = [1, 5, 10] # x é uma lista
print type(x)
x = 10
for i in range(20):
# Início da repetição For
x = x + 1
if x%2 == 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: (1b) Indentações
Step2: (1c) Funções
Step3: (1d) Tipos Especiais
Step4: (1e) Iteradores
Step5: (1f) Geradores e List Comprehension
Step... |
4,784 | <ASSISTANT_TASK:>
Python Code:
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
size = 18
params = {'legend.fontsize': 'Large',
'axes.labelsize': size,
'axes.titlesize': size,
'xtick.labelsize': size*0.75,
'ytick.labelsize': size*0.75}
plt.rcParams.update(par... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: <font color='teal'> 1. Introduction and purpose of this Notebook </font>
Step3: <font color='olive'>Dogs vs Cats data set</font>
Step8: <font ... |
4,785 | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
import matplotlib
import matplotlib.pyplot as plt
matplotlib.style.use('ggplot')
import chap01soln
resp = chap01soln.ReadFemResp()
resp_numkdhh = resp.numkdhh
resp_numkdhh_vc = resp_numkdhh.value_counts().sort_index()
print resp_numkdhh_vc
resp_numkdhh_pmf_original = 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: 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... |
4,786 | <ASSISTANT_TASK:>
Python Code:
import graphlab as gl
from nltk.stem import *
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 = 'le... | <SYSTEM_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. ... |
4,787 | <ASSISTANT_TASK:>
Python Code:
a = 6
b = 15
if a < b:
m = a
else:
m = b
m
m = a if a < b else b
m
k = 1
while k < 10**9:
print(k)
k = k * 2
k = 1
n = 0
while k < 10**9:
k = k * 2
n = n + 1
print(n)
k = 1
while True:
k = 2*k
print(k)
for i in range(10):
if i == 7:
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: 15 Fonctions def
Step2: Pour un nombre $x\geq1$, trouver l'unique valeur entière $n$ vérifiant $$2^{n−1} < x < 2^n,$$ c’est-à-dire le plus p... |
4,788 | <ASSISTANT_TASK:>
Python Code:
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True, reshape=False)
DO NOT MODIFY THIS CELL
def fully_connected(prev_layer, num_units):
Create a fully connectd layer with the given layer... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step3: Batch Normalization using tf.layers.batch_normalization<a id="example_1"></a>
Step6: We'll use the following function to create convolutional l... |
4,789 | <ASSISTANT_TASK:>
Python Code:
#importing some useful packages
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import numpy as np
import cv2
%matplotlib inline
#reading in an image
image = mpimg.imread('test_images/solidWhiteRight.jpg')
#printing out some stats and plotting
print('This image is:', type... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step8: Some OpenCV functions (beyond those introduced in the lesson) that might be useful for this project are
Step9: Test on Images
Step10: run your... |
4,790 | <ASSISTANT_TASK:>
Python Code:
import Bio.Blast.NCBIWWW as BBNW
import Bio.Seq as BS
import Bio.Alphabet as BA
# BLAST program to use
prog = "blastp"
# database to search against
database = "swissprot"
# query sequence as a Seq object
query = BS.Seq("IRVEGNLRVEYLDDRNTFRHSVVVPYEPPE",
alphabet=BA.IUPAC.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: The NCBI BLAST will accept several query sequences simultaneously. In fact, it is preferred to send all query sequences at once, if possible.
St... |
4,791 | <ASSISTANT_TASK:>
Python Code:
from __future__ import print_function
from cobra import Model, Reaction, Metabolite
# Best practise: SBML compliant IDs
model = Model('example_model')
reaction = Reaction('3OAS140')
reaction.name = '3 oxoacyl acyl carrier protein synthase n C140 '
reaction.subsystem = 'Cell Envelope Biosy... | <SYSTEM_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 to create metabolites as well. If we were using an existing model, we could use Model.get_by_id to get the appropriate Metabolite object... |
4,792 | <ASSISTANT_TASK:>
Python Code:
from pandas import read_csv
srooms_df = read_csv('../data/agaricus-lepiota.data.csv')
from sklearn_pandas import DataFrameMapper
import sklearn
import numpy as np
mappings = ([
('edibility', sklearn.preprocessing.LabelEncoder()),
('odor', sklearn.preprocessing.LabelBinarizer()),
... | <SYSTEM_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 Definition
Step2: Model Compile
Step3: Training
|
4,793 | <ASSISTANT_TASK:>
Python Code:
import os
SHOGUN_DATA_DIR=os.getenv('SHOGUN_DATA_DIR', '../../../data')
import shogun as sg
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
# use scipy for generating samples
from scipy.stats import laplace, norm
def sample_gaussian_vs_laplace(n=220, mu=0.0, sigma2=... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Some Formal Basics (skip if you just want code examples)
Step2: Now how to compare these two sets of samples? Clearly, a t-test would be a bad ... |
4,794 | <ASSISTANT_TASK:>
Python Code:
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
from scipy.signal import argrelmax
fracture_pressure_data = np.loadtxt("data/fracture_pressure_abnormal.csv", delimiter=",")
fracture_pressure, TVD_frac = fracture_pressure_data.T
pore_pressure_data = np.loadtxt("data/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: Turning theory into code
Step2: Step two now involves extending a line up until we hit the fracture pressure. This means we have to interpolate... |
4,795 | <ASSISTANT_TASK:>
Python Code:
import os
import torch
import pyro
import pyro.distributions as dist
from torch.distributions import constraints
from pyro import poutine
from pyro.distributions.util import broadcast_shape
from pyro.infer import Trace_ELBO, JitTrace_ELBO, TraceEnum_ELBO, JitTraceEnum_ELBO, SVI
from pyro.... | <SYSTEM_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: First let's run as usual with an SVI object and Trace_ELBO.
Step3: Next to run with a jit compiled inference, we simply re... |
4,796 | <ASSISTANT_TASK:>
Python Code:
from numpy import concatenate, array
from numpy.random import randn
import os
SHOGUN_DATA_DIR=os.getenv('SHOGUN_DATA_DIR', '../../../data')
num = 200
d1 = concatenate((randn(1,num),10.*randn(1,num)),0)
d2 = concatenate((randn(1,num),10.*randn(1,num)),0)+array([[10.],[0.]])
d3 = concatenat... | <SYSTEM_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 toy data created above consists of 4 gaussian blobs, having 200 points each, centered around the vertices of a rectancle. Let's plot it for ... |
4,797 | <ASSISTANT_TASK:>
Python Code:
# DO NOT EDIT !
from pyesdoc.ipython.model_topic import NotebookOutput
# DO NOT EDIT !
DOC = NotebookOutput('cmip6', 'ec-earth-consortium', 'ec-earth3-veg', 'atmos')
# Set as follows: DOC.set_author("name", "email")
# TODO - please enter value(s)
# Set as follows: DOC.set_contri... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Document Authors
Step2: Document Contributors
Step3: Document Publication
Step4: Document Table of Contents
Step5: 1.2. Model Name
Step6: 1... |
4,798 | <ASSISTANT_TASK:>
Python Code:
import numpy as np
import tensorflow as tf
print("TensorFlow version: ", tf.version.VERSION)
# This will be an int32 tensor by default; see "dtypes" below.
rank_0_tensor = tf.constant(4)
print(rank_0_tensor)
# Let's make this a float tensor.
rank_1_tensor = tf.constant([2.0, 3.0, 4.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: Lab Task 1
Step2: A "vector" or "rank-1" tensor is like a list of values. A vector has 1-axis
Step3: A "matrix" or "rank-2" tensor has 2-axes
... |
4,799 | <ASSISTANT_TASK:>
Python Code:
from IPython.display import Image
Image(url='http://xray.readthedocs.org/en/latest/_images/dataset-diagram.png', embed=True, width=950, height=300)
import numpy as np
import pandas as pd
import xray
temp = 15 + 8 * np.random.randn(2, 2, 3)
VW = 15 + 10 * abs(np.random.randn(2, 2, 3))
pr... | <SYSTEM_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 an example file into a dataset
Step2: This is an example of what our soil moisture data from the radio tower install will look like. Ea... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.