Unnamed: 0 int64 0 16k | text_prompt stringlengths 149 45.7k | code_prompt stringlengths 67 140k |
|---|---|---|
300 | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Spatiotemporal permutation F-test on full sensor data
Tests for differential evoked responses in at least
one condition using a permutation clustering ... | <ASSISTANT_TASK:>
Python Code:
# Authors: Denis Engemann <denis.engemann@gmail.com>
# Jona Sassenhagen <jona.sassenhagen@gmail.com>
#
# License: BSD (3-clause)
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
import mne
from mne.stats import spatio_temp... |
301 | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Runtime Cythonize in QuTiP
Prepared for EuroSciPy 2019
Alex Pitchford (alex.pitchford@gmail.com)
Two types of time-dependent dynamics solving
'function... | <ASSISTANT_TASK:>
Python Code:
# Imports and utility functions
import time
import numpy as np
import matplotlib.pyplot as plt
from qutip.sesolve import sesolve
from qutip.solver import Options, solver_safe
from qutip import sigmax, sigmay, sigmaz, identity, tensor, basis, Bloch
def timing_val(func):
def wrapper(*ar... |
302 | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
ES-DOC CMIP6 Model Properties - Ocean
MIP Era
Step1: Document Authors
Set document authors
Step2: Document Contributors
Specify document contributors... | <ASSISTANT_TASK:>
Python Code:
# DO NOT EDIT !
from pyesdoc.ipython.model_topic import NotebookOutput
# DO NOT EDIT !
DOC = NotebookOutput('cmip6', 'test-institute-1', 'sandbox-1', 'ocean')
Explanation: ES-DOC CMIP6 Model Properties - Ocean
MIP Era: CMIP6
Institute: TEST-INSTITUTE-1
Source ID: SANDBOX-1
Topic: Oc... |
303 | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Vertex AI Pipelines
Step1: Install the latest GA version of google-cloud-storage library as well.
Step2: Install the latest GA version of google-clou... | <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
Explanation: Vertex AI Pipelines: AutoML Tabular pipelines using google-cloud-... |
304 | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Modeling and Simulation in Python
Chapter 1
Copyright 2020 Allen Downey
License
Step1: The first time you run this on a new installation of Python, it... | <ASSISTANT_TASK:>
Python Code:
try:
import pint
except ImportError:
!pip install pint
import pint
try:
from modsim import *
except ImportError:
!pip install modsimpy
from modsim import *
Explanation: Modeling and Simulation in Python
Chapter 1
Copyright 2020 Allen Downey
License: Creative Common... |
305 | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Homework 6
Due
Step1: An Enum stands for an enumeration, it's a convenient way for you to define lists of things. Typing
Step2: returns a Python repr... | <ASSISTANT_TASK:>
Python Code:
from enum import Enum
class AccountType(Enum):
SAVINGS = 1
CHECKING = 2
Explanation: Homework 6
Due: Tuesday, October 10 at 11:59 PM
Problem 1: Bank Account Revisited
We are going to rewrite the bank account closure problem we had a few assignments ago, only this time developing ... |
306 | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Diagnosing the data issues
Step1: The data you'll be exloring
Step2: Duplicated data
Step3: So this is actually a mask. We can now ask for the data ... | <ASSISTANT_TASK:>
Python Code:
import pandas as pd
import numpy as np
% matplotlib inline
from matplotlib import pyplot as plt
Explanation: Diagnosing the data issues:
End of explanation
data = pd.read_csv('all_data.csv')
data.head(10)
Explanation: The data you'll be exloring:
End of explanation
duplicated_data = dat... |
307 | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Interact Exercise 3
Imports
Step1: Using interact for animation with data
A soliton is a constant velocity wave that maintains its shape as it propaga... | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
from matplotlib import pyplot as plt
import numpy as np
from IPython.html.widgets import interact, interactive, fixed
from IPython.display import display
Explanation: Interact Exercise 3
Imports
End of explanation
from math import sqrt
def soliton(x, t, c, a):
# mak... |
308 | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Reading and writing files
Step1: It says that the file is opened, reminds the filename and indicates that it is in mode 'r', which means 'read'
You ca... | <ASSISTANT_TASK:>
Python Code:
# We can create a file object and store it inside a variable.
# you can see objects as a different type of data
f=open("awanode-farmlab-2017-08-14.txt")
print(f)
Explanation: Reading and writing files
End of explanation
f=open("awanode-farmlab-2017-08-14.txt")
# The read() function reads ... |
309 | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
The author-topic model
Step1: In the following sections we will load the data, pre-process it, train the model, and explore the results using some of ... | <ASSISTANT_TASK:>
Python Code:
!wget -O - 'http://www.cs.nyu.edu/~roweis/data/nips12raw_str602.tgz' > /tmp/nips12raw_str602.tgz
import tarfile
filename = '/tmp/nips12raw_str602.tgz'
tar = tarfile.open(filename, 'r:gz')
for item in tar:
tar.extract(item, path='/tmp')
Explanation: The author-topic model: LDA with met... |
310 | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Модель №2
Вход
Данные
Step1: Загрузка модели word2vec
Step2: Подготовка данных
Step3: Обучение модели
Step4: Результаты
Результаты на тестовой выбо... | <ASSISTANT_TASK:>
Python Code:
reviews_test = pd.read_csv('data/reviews_test.csv', header=0, encoding='utf-8')
reviews_train = pd.read_csv('data/reviews_train.csv', header=0, encoding='utf-8')
X_train_raw = reviews_train.comment
y_train_raw = reviews_train.reting
X_test_raw = reviews_test.comment
y_test_raw = reviews_t... |
311 | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Pipeline
This notebook is from the official Quantopian Guide on Pipelines. Make sure to visit their documentation for many more great resources!
Many t... | <ASSISTANT_TASK:>
Python Code:
from quantopian.pipeline import Pipeline
def make_pipeline():
return Pipeline()
pipe = make_pipeline()
from quantopian.research import run_pipeline
result = run_pipeline(pipe, '2017-01-01', '2017-01-01')
result.head(10)
result.info()
Explanation: Pipeline
This notebook is from the off... |
312 | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Learning Curves and Bias-Variance Tradeoff
In practice, much of the task of machine learning involves selecting algorithms,
parameters, and sets of dat... | <ASSISTANT_TASK:>
Python Code:
%pylab inline
Explanation: Learning Curves and Bias-Variance Tradeoff
In practice, much of the task of machine learning involves selecting algorithms,
parameters, and sets of data to optimize the results of the method. All of these
things can affect the quality of the results, but it’s no... |
313 | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
'rv' Datasets and Options
Setup
Let's first make sure we have the latest version of PHOEBE 2.0 installed. (You can comment out this line if you don't u... | <ASSISTANT_TASK:>
Python Code:
!pip install -I "phoebe>=2.0,<2.1"
Explanation: 'rv' Datasets and Options
Setup
Let's first make sure we have the latest version of PHOEBE 2.0 installed. (You can comment out this line if you don't use pip for your installation or don't want to update to the latest release).
End of explan... |
314 | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Chemicals in Cosmetics - Data Bootcamp Report
Manuela Lopez Giraldo
May 12, 2017
Report Outline
Step1: To extract exact figures for current products, ... | <ASSISTANT_TASK:>
Python Code:
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import datetime as dt
%matplotlib inline
import matplotlib as mpl
import sys
url = 'https://chhs.data.ca.gov/api/views/7kri-yb7t/rows.csv?accessType=DOWNLOAD'
CosmeticsData = pd.read_csv(url)
CosmeticsData.head()
Expla... |
315 | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Start a ipcluster from the Cluster tab in Jupyter or use the command
Step1: Make sure to add the correct path like
Step2: Uncomment the lines for the... | <ASSISTANT_TASK:>
Python Code:
# import os
# from scripts.hpc05 import HPC05Client
# os.environ['SSH_AUTH_SOCK'] = os.path.join(os.path.expanduser('~'), 'ssh-agent.socket')
# cluster = HPC05Client()
from ipyparallel import Client
cluster = Client()
v = cluster[:]
lview = cluster.load_balanced_view()
len(v)
Explanation:... |
316 | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Noise simulation in qsimcirq
<table class="tfo-notebook-buttons" align="left">
<td>
<a target="_blank" href="https
Step1: It is possible to simu... | <ASSISTANT_TASK:>
Python Code:
try:
import cirq
except ImportError:
!pip install cirq --quiet
import cirq
try:
import qsimcirq
except ImportError:
!pip install qsimcirq --quiet
import qsimcirq
Explanation: Noise simulation in qsimcirq
<table class="tfo-notebook-buttons" align="left">
<td>
... |
317 | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
From Eric Veneto, mathematical madmen are on the loose
Step1: How many attacks will happen between the beginning of 2001 and the end of 2099
Step2: W... | <ASSISTANT_TASK:>
Python Code:
import datetime
from collections import Counter
start = datetime.date(2001, 1, 1)
end = datetime.date(2100, 1, 1) - datetime.timedelta(days=1)
d = start
anarchy_dates = []
delta = datetime.timedelta(days=1)
while d <= end:
if d.day * d.month == d.year % 100:
anarchy_dates.appe... |
318 | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
<a href="https
Step1: Looks good! Now we import transformers and download the scripts run_benchmark.py, run_benchmark_tf.py, and plot_csv_file.py whic... | <ASSISTANT_TASK:>
Python Code:
#@title Check available memory of GPU
# Check that we are using 100% of GPU
# memory footprint support libraries/code
!ln -sf /opt/bin/nvidia-smi /usr/bin/nvidia-smi
!pip -q install gputil
!pip -q install psutil
!pip -q install humanize
import psutil
import humanize
import os
import GPUti... |
319 | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
ES-DOC CMIP6 Model Properties - Landice
MIP Era
Step1: Document Authors
Set document authors
Step2: Document Contributors
Specify document contributo... | <ASSISTANT_TASK:>
Python Code:
# DO NOT EDIT !
from pyesdoc.ipython.model_topic import NotebookOutput
# DO NOT EDIT !
DOC = NotebookOutput('cmip6', 'cmcc', 'sandbox-1', 'landice')
Explanation: ES-DOC CMIP6 Model Properties - Landice
MIP Era: CMIP6
Institute: CMCC
Source ID: SANDBOX-1
Topic: Landice
Sub-Topics: Gl... |
320 | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Your first neural network
In this project, you'll build your first neural network and use it to predict daily bike rental ridership. We've provided som... | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
%config InlineBackend.figure_format = 'retina'
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
Explanation: Your first neural network
In this project, you'll build your first neural network and use it to predict daily bike rental ridership. We've ... |
321 | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Introduction
NetworKit provides an easy interface to Gephi that uses the Gephi graph streaming plugin. To be able to use it, install the Graph Streamin... | <ASSISTANT_TASK:>
Python Code:
G = generators.ErdosRenyiGenerator(300, 0.2).generate()
G.addEdge(0, 1) #We want to make sure this specific edge exists, for usage in an example later.
Explanation: Introduction
NetworKit provides an easy interface to Gephi that uses the Gephi graph streaming plugin. To be able to use it,... |
322 | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
OIQ-Exam-Question-1 (Version 2)
Technical exam question from Ordre des ingénieurs du Québec. Obviously meant to be done using moment-distribution, but... | <ASSISTANT_TASK:>
Python Code:
from sympy import *
init_printing(use_latex='mathjax')
from IPython import display
display.SVG('oiq-exam-1.svg')
from sdutil2 import SD, FEF
var('EI theta_a theta_b theta_c theta_d')
Mab,Mba,Vab,Vba = SD(6,EI,theta_a,theta_b) + FEF.p(6,180,4)
Mbc,Mcb,Vbc,Vcb = SD(8,2*EI,theta_b,theta_c) +... |
323 | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Data Hackathon 3.x XGBoost models
Import Libraries
Step1: Load Data
Step2: Define a function for modeling and cross-validation
This function will do ... | <ASSISTANT_TASK:>
Python Code:
import pandas as pd
import numpy as np
import xgboost as xgb
from xgboost.sklearn import XGBClassifier
from sklearn import cross_validation, metrics
from sklearn.grid_search import GridSearchCV
import matplotlib.pylab as plt
%matplotlib inline
from matplotlib.pylab import rcParams
rcParam... |
324 | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
This IPython Notebook illustrates the use of the openmc.mgxs.Library class. The Library class is designed to automate the calculation of multi-group cr... | <ASSISTANT_TASK:>
Python Code:
import math
import pickle
from IPython.display import Image
import matplotlib.pylab as pylab
import numpy as np
import openmc
import openmc.mgxs
from openmc.statepoint import StatePoint
from openmc.summary import Summary
from openmc.source import Source
from openmc.stats import Box
import... |
325 | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Morphological Associative memories
Step1: Now lets add some erosive noise to the image and then lets see the recall | <ASSISTANT_TASK:>
Python Code:
# dependencies
import matplotlib.pyplot as plt
import pickle
import numpy as np
f = open('final_dataset.pickle','rb')
dataset = pickle.load(f)
sample_image = dataset['train_dataset'][0]
sample_label = dataset['train_labels'][0]
print(sample_label)
plt.figure()
plt.imshow(sample_image)
plt... |
326 | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Predicting NBA players positions using Keras
In this notebook we will build a neural net to predict the positions of NBA players using the Keras librar... | <ASSISTANT_TASK:>
Python Code:
%load_ext autoreload
%autoreload 2
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import LabelBinarizer, StandardScaler
from keras.models import Sequential
from keras.layers import Dense, Activation, Dropout
Explanati... |
327 | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
In case of reading training data from file, we illustrate the necessary steps as following
Step1: type I
(get numpy.ndarray from cntk reader)
Step2: ... | <ASSISTANT_TASK:>
Python Code:
import sys, os
import getpass
import numpy as np
mnist_dir = '/home/' + getpass.getuser() + '/repos/cntk/Examples/Image/DataSets/MNIST/'
trn_data_file = mnist_dir + 'Train-28x28_cntk_text.txt'
print (os.path.exists(trn_data_file))
Explanation: In case of reading training data from file, w... |
328 | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Proyecto 2
Zuraya Huizar Cruz
Parte 1
Step1: La imagen original en blanco y negro
La aproximación de grado 10
La aproximación de grado 20
La aproximac... | <ASSISTANT_TASK:>
Python Code:
import matplotlib.pyplot as plt
import numpy as np
from PIL import Image
#Como vamos a trabajar con imagenes blanco y negro, tomamos una imagen a color y la convertimos a BW.
im = Image.open("C:/Users/Zuraya/Pictures/Rossum.jpg", 'r').convert('LA')
mat = np.array(list(im.getdata(band=0)),... |
329 | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Introduction
This is a live IPython notebook. You can write and test code, annotate it with text (including equations $\hat x = \frac{1}{n}\sum_{i=0}^n... | <ASSISTANT_TASK:>
Python Code:
# note that this is a code cell -- you can execute it with Shift-ENTER
%matplotlib inline
Explanation: Introduction
This is a live IPython notebook. You can write and test code, annotate it with text (including equations $\hat x = \frac{1}{n}\sum_{i=0}^n x_i$), plot graphs and start exte... |
330 | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Database-based monthly stats
In this notebook, we'll use a database table to aggregate monthly article quality scores. We'll be using an SQL query to ... | <ASSISTANT_TASK:>
Python Code:
from ipynb.fs.full.article_quality.db_monthly_stats import DBMonthlyStats, dump_aggregation
Explanation: Database-based monthly stats
In this notebook, we'll use a database table to aggregate monthly article quality scores. We'll be using an SQL query to do the aggregation, writing the a... |
331 | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
TME4 FDMS Collaborative Filtering
Florian Toqué & Paul Willot
Step1: Loading the data
Step2: Content example
Step3: Splitting data between train/tes... | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
from random import random
import math
import numpy as np
import copy
from scipy import stats
import matplotlib.pyplot as plt
import pickle as pkl
from scipy.spatial import distance
import seaborn as sns
sns.set_style('darkgrid')
Explanation: TME4 FDMS Collaborative Filt... |
332 | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
TensorFlow - Logistical Regression
The MNIST database (Mixed National Institute of Standards and Technology database) is a large database of handwritte... | <ASSISTANT_TASK:>
Python Code:
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
from pylab import *
from tensorflow.examples.tutorials.mnist import input_data
%matplotlib inline
epochs = 1000
learning_rate = 0.5
Explanation: TensorFlow - Logistical Regression
The MNIST database (Mixed National... |
333 | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Class 9
Step1: Almost everything useful is a function. Python has a ton of other built-in functions!
Along with len, a couple you might have seen are... | <ASSISTANT_TASK:>
Python Code:
len
Explanation: Class 9: Functions
A painful analogy
What do you do when you wake up in the morning?
I don't know about you, but I get ready.
"Obviously," you say, a little too snidely for my liking. You're particular, very detail-oriented, and need more information out of me.
Fine, then... |
334 | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described.
<END_TASK>
<USER_TASK:>
Description:
Return 2^n modulo p (be aware of numerics).
This is how the function will work:
modp(3, 5)
3
This is how the function will work:
modp(1101, 101)
2
... | <ASSISTANT_TASK:>
Python Code:
def modp(n: int, p: int):
ret = 1
for i in range(n):
ret = (2 * ret) % p
return ret
<END_TASK> |
335 | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
DCT-Domain Subsampling
In this notebook, we examine how to subsample an image while in the DCT domain. DCT-domain subsampling is crucial to DCT-domain ... | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
import sys
import y4m
import matplotlib.pyplot as plt
import numpy as np
def decode_y4m_buffer(frame):
W, H = frame.headers['W'], frame.headers['H']
Wdiv2, Hdiv2 = W // 2, H // 2
C, buf = frame.headers['C'], frame.buffer
A, Adiv2, div2 = W * H, Hdiv2 * W... |
336 | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Reflection and Heating
For a comparison between "Horvat" and "Wilson" methods in the "irad_method" parameter, see the tutorial on Lambert Scattering.
S... | <ASSISTANT_TASK:>
Python Code:
#!pip install -I "phoebe>=2.3,<2.4"
Explanation: Reflection and Heating
For a comparison between "Horvat" and "Wilson" methods in the "irad_method" parameter, see the tutorial on Lambert Scattering.
Setup
Let's first make sure we have the latest version of PHOEBE 2.3 installed (uncomment ... |
337 | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Fitting Models Exercise 1
Imports
Step1: Fitting a quadratic curve
For this problem we are going to work with the following model
Step2: First, gener... | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
import scipy.optimize as opt
Explanation: Fitting Models Exercise 1
Imports
End of explanation
a_true = 0.5
b_true = 2.0
c_true = -4.0
Explanation: Fitting a quadratic curve
For this problem we are going to work with th... |
338 | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Outlier Detection with bqplot
In this notebook, we create a class DNA that leverages the new bqplot canvas based HeatMap along with the ipywidgets Rang... | <ASSISTANT_TASK:>
Python Code:
from bqplot import (DateScale, ColorScale, HeatMap,
Figure, LinearScale, OrdinalScale, Axis)
from scipy.stats import percentileofscore
from scipy.interpolate import interp1d
import bqplot.pyplot as plt
from traitlets import List, Float, observe
from ipywidgets import ... |
339 | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Function phasecorr
Synopse
Computes the phase correlation of two images.
g = phasecorr(f,h)
OUTPUT
g
Step1: Examples
Step2: Example 1
Show that the p... | <ASSISTANT_TASK:>
Python Code:
import numpy as np
def phasecorr(f,h):
F = np.fft.fftn(f)
H = np.fft.fftn(h)
T = F * np.conjugate(H)
R = T/np.abs(T)
g = np.fft.ifftn(R)
return g.real
Explanation: Function phasecorr
Synopse
Computes the phase correlation of two images.
g = phasecorr(f,h)
OUTPUT
g:... |
340 | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Chapter 2
Original content created by Cam Davidson-Pilon
Ported to Python 3 and PyMC3 by Max Margenot (@clean_utensils) and Thomas Wiecki (@twiecki) at... | <ASSISTANT_TASK:>
Python Code:
import pymc3 as pm
with pm.Model() as model:
parameter = pm.Exponential("poisson_param", 1.0)
data_generator = pm.Poisson("data_generator", parameter)
Explanation: Chapter 2
Original content created by Cam Davidson-Pilon
Ported to Python 3 and PyMC3 by Max Margenot (@clean_utensil... |
341 | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Tutorial for flexx.ui - creating widgets and user interfaces
Step1: Displaying widgets
Widgets can be inserted into the notebook by making them a cell... | <ASSISTANT_TASK:>
Python Code:
%gui asyncio
from flexx import flx
flx.init_notebook()
Explanation: Tutorial for flexx.ui - creating widgets and user interfaces
End of explanation
b = flx.Button(text='foo')
b
Explanation: Displaying widgets
Widgets can be inserted into the notebook by making them a cell output:
End of e... |
342 | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
San Diego Burrito Analytics
Step1: Load data
Step2: Brief metadata
Step3: What types of burritos have been rated?
Step4: Progress in number of burr... | <ASSISTANT_TASK:>
Python Code:
%config InlineBackend.figure_format = 'retina'
%matplotlib inline
import numpy as np
import scipy as sp
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
sns.set_style("white")
Explanation: San Diego Burrito Analytics: Data characterization
Scott Cole
21 May 2016
T... |
343 | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Probability Distribution Plots
This example shows how to create interactive probability distribution demos using nbinteract.bar method.
Binomial Distri... | <ASSISTANT_TASK:>
Python Code:
# Although this function doesn't appear necessary, the scipy stats functions
# don't explicitly require n and p as args which causes issues with interaction
def binom_pmf(xs, n, p):
return stats.binom.pmf(xs, n, p)
options = {
'xlabel': 'X',
'ylabel': 'probability',
'ylim'... |
344 | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Traffic Sign Classification with Keras
Keras exists to make coding deep neural networks simpler. To demonstrate just how easy it is, you’re going to us... | <ASSISTANT_TASK:>
Python Code:
from urllib.request import urlretrieve
from os.path import isfile
from tqdm import tqdm
class DLProgress(tqdm):
last_block = 0
def hook(self, block_num=1, block_size=1, total_size=None):
self.total = total_size
self.update((block_num - self.last_block) * block_size... |
345 | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Table of Contents
<p><div class="lev1 toc-item"><a href="#Introduction" data-toc-modified-id="Introduction-1"><span class="toc-item-num">1 <... | <ASSISTANT_TASK:>
Python Code:
%load_ext watermark
%watermark -v -m -a "Lilian Besson (Naereen)" -p numpy,numba -g
import numpy as np
Explanation: Table of Contents
<p><div class="lev1 toc-item"><a href="#Introduction" data-toc-modified-id="Introduction-1"><span class="toc-item-num">1 </span>Introduction</a>... |
346 | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Ejercicios Numpy
Ahora es tiempo de aplicar lo aprendido en las lecciones anteriores.
Importar NumPy como np
Crear un arreglo de 10 ceros
Crear un arre... | <ASSISTANT_TASK:>
Python Code:
np.eye(3)
Explanation: Ejercicios Numpy
Ahora es tiempo de aplicar lo aprendido en las lecciones anteriores.
Importar NumPy como np
Crear un arreglo de 10 ceros
Crear un arreglo de 10 unos
Crear un arreglo de 10 cincos
Crear un arreglo con numeros enteros del 10 al 50
Crear un arreglo co... |
347 | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
column explanation
survived
Step1: train_test split
Step2: QDA
Step3: LDA
Step4: solver
svd
Step5: NB
Step6: BernoulliNB 쓸수 없음 => 타겟변수뿐만아니라 독립... | <ASSISTANT_TASK:>
Python Code:
df1 = df.ix[:,0:8]
df1.tail() # 박사님께서 설명을 위해 뒷부분에 컬럼을 채워놓은 것같아서 who 부터 끝까지 잘랐습니다
from sklearn.preprocessing import LabelEncoder
le = LabelEncoder()
df1['sex']= le.fit_transform(df1['sex'])
df1['embarked'] = le.fit_transform(df1['embarked'])
from sklearn.preprocessing import Imputer
imp =... |
348 | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Improving accuracy of models
In the previous example, we constructed scalar models
Once the modes have been found, we can then make use of them to cons... | <ASSISTANT_TASK:>
Python Code:
# setup 2D plotting
%matplotlib inline
from openmodes.ipython import matplotlib_defaults
matplotlib_defaults()
import matplotlib.pyplot as plt
# the numpy library contains useful mathematical functions
import numpy as np
# import useful python libraries
import os.path as osp
# import the... |
349 | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Cell Automata Jupyter Notebook
June 2017
Gustavo A. Patino, based on many of the scripts presented by Dr. Hiroki Sayama
(http
Step1: Model Parameter... | <ASSISTANT_TASK:>
Python Code:
import numpy as np
from matplotlib import pyplot as plt
Explanation: Cell Automata Jupyter Notebook
June 2017
Gustavo A. Patino, based on many of the scripts presented by Dr. Hiroki Sayama
(http://bingweb.binghamton.edu/~sayama/) during the New England Complex Systems
Institute summer c... |
350 | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Guillaume Chaslot (guillaume.chaslot@data.gouv.fr)
Tax Law Simplifier
Tax law is more than 200,000 lines long and opaque.
We believe that with this too... | <ASSISTANT_TASK:>
Python Code:
from compare_simulators import CalculatorComparator
from population_simulator import CerfaPopulationSimulator
from utils import show_histogram
from utils import percent_diff
from utils import scatter_plot
import matplotlib.pyplot as plt
import numpy as np
import random
%matplotlib inline
... |
351 | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
An Intuition for OOP
'OOP' stands for Object Orientated Programming. Today my aim to provide a quick overview of the topic which will help you develop ... | <ASSISTANT_TASK:>
Python Code:
x = "I love cats." # <= x is a string...
print(x.upper()) # converts string to upper case
print(x.replace("c", "b")) # cats? I'm a bat kinda guy myself!
print(x.__add__(x)) # x.__add__(x) is EXACTLY the same as x + x.
print(x.__mul__(3)) # Equivalent to x... |
352 | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Superposition in time with the erfc function
IHE, Delft, 20200106
@T.N.Olsthoorn
See page 56 of the syllabus
Context
Consider a situation where groundw... | <ASSISTANT_TASK:>
Python Code:
import numpy as np
import matplotlib.pyplot as plt
import scipy.special as sp
Explanation: Superposition in time with the erfc function
IHE, Delft, 20200106
@T.N.Olsthoorn
See page 56 of the syllabus
Context
Consider a situation where groundwater is directly subject to varying surface wat... |
353 | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Control de flujo de programas
Bueno, al fin y al cabo llegamos al punto fundamental de la programación. Sin fors o ifs, los programas no son nada más q... | <ASSISTANT_TASK:>
Python Code:
x = -15
if x == 0:
print(x, "es cero")
elif x > 0:
print(x, "es positivo")
elif x < 0:
print(x, "es negativo")
else:
print(x, "es algo que ni idea...")
Explanation: Control de flujo de programas
Bueno, al fin y al cabo llegamos al punto fundamental de la programación. Sin ... |
354 | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Lektion 12
Step1: Matrixexponentiale
Step2: Gekoppelte Pendel
\begin{align}
y'' &= w - y + \cos(2t)\
w'' &= y - 3w
\end{align}
Übersetzt sich in
\beg... | <ASSISTANT_TASK:>
Python Code:
from sympy import *
init_printing()
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
Explanation: Lektion 12
End of explanation
x = Symbol('x', real=True)
A = Matrix(3,3, [x,x,0,0,x,x,0,0,x])
A
A.exp()
Explanation: Matrixexponentiale
End of explanation
A = Matrix(4,4,... |
355 | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
sci-analysis
An easy to use and powerful python-based data exploration and analysis tool
Current Version
2.2 --- Released January 5, 2019
What is sci-a... | <ASSISTANT_TASK:>
Python Code:
import warnings
warnings.filterwarnings("ignore")
import numpy as np
import scipy.stats as st
from sci_analysis import analyze
Explanation: sci-analysis
An easy to use and powerful python-based data exploration and analysis tool
Current Version
2.2 --- Released January 5, 2019
What is sci... |
356 | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
1
2
3
4
5
6
7
马尔可夫链的蒙特卡洛模拟?
8
9
10
11
可以将异或看成是不考虑进位的加法:0 + 0 = 0, 0 + 1 = 1, 1 + 1 = 0
12
13
14
15
16
17
18
19
20
21
22
http
Step1: 23
24
25
26
为什么要除n... | <ASSISTANT_TASK:>
Python Code:
%pylab inline
import numpy as np
points = np.array([[0,0], [1,1], [1,1], [2, 0]])
plt.scatter(points[:, 0])
Explanation: 1
2
3
4
5
6
7
马尔可夫链的蒙特卡洛模拟?
8
9
10
11
可以将异或看成是不考虑进位的加法:0 + 0 = 0, 0 + 1 = 1, 1 + 1 = 0
12
13
14
15
16
17
18
19
20
21
22
http://stats.stackexchange.com/questions/41317/h... |
357 | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Sources of Error
Error can come from many sources when using applying a numerical method
Step1: Truncation Error and Taylor's Theorem
Taylor's Theorem... | <ASSISTANT_TASK:>
Python Code:
f = numpy.exp(1)
f_hat = 2.71
# Error
print "Absolute Error = ", numpy.abs(f - f_hat)
print "Relative Error = ", numpy.abs(f - f_hat) / numpy.abs(f)
# Precision
p = 3
n = numpy.floor(numpy.log10(f_hat)) + 1 - p
print "%s = %s" % (f_hat, numpy.round(10**(-n) * f_hat) * 10**n)
Explanation: ... |
358 |
<SYSTEM_TASK:>
Given the following text problem statement, write Python code to implement the functionality described below in problem statement
<END_TASK>
<USER_TASK:>
Problem:
two different ways to implement categorical cross entropy in TensorFlow
| <ASSISTANT_TASK:>
Python Code::
import tensorflow as tf
from tensorflow.keras.losses import CategoricalCrossentropy
y_true = [[0, 1, 0], [1, 0, 0]]
y_pred = [[0.15, 0.75, 0.1], [0.75, 0.15, 0.1]]
cross_entropy_loss = CategoricalCrossentropy()
print(cross_entropy_loss(y_true, y_pred).numpy())
import tensorflow as tf
fro... |
359 | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Collective intelligence
Step1: Build models
Lookin' good! Let's convert the data into a nice format. We rearrange some columns, check out what the col... | <ASSISTANT_TASK:>
Python Code:
import wget
import pandas as pd
import numpy as np
from sklearn.cross_validation import train_test_split
# Import the dataset
data_url = 'https://raw.githubusercontent.com/nslatysheva/data_science_blogging/master/datasets/wine/winequality-red.csv'
dataset = wget.download(data_url)
dataset... |
360 | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Introduction to Machine Learning
Step1: Problem 1) Introduction to scikit-learn
At the most basic level, scikit-learn makes machine learning extremely... | <ASSISTANT_TASK:>
Python Code:
import numpy as np
import matplotlib.pyplot as plt
%matplotlib notebook
Explanation: Introduction to Machine Learning:
Examples of Unsupervised and Supervised Machine-Learning Algorithms
Version 0.1
Broadly speaking, machine-learning methods constitute a diverse collection of data-driven ... |
361 | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Tip labels
Tip labels are composed simply of text plotted at the tips of the tree, or aligned at the furthest tip of the tree, and can be highly modifi... | <ASSISTANT_TASK:>
Python Code:
import toytree
import toyplot
import numpy as np
Explanation: Tip labels
Tip labels are composed simply of text plotted at the tips of the tree, or aligned at the furthest tip of the tree, and can be highly modified as with any text element. Common examples are presented below.
End of exp... |
362 | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
P3 Creating Customer Segments
In this project you, will analyze a dataset containing annual spending amounts for internal structure, to understand the ... | <ASSISTANT_TASK:>
Python Code:
# Import libraries: NumPy, pandas, matplotlib
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
from matplotlib import rc
# Tell iPython to include plots inline in the notebook
%matplotlib inline
# Set styles for seaborn
%config InlineBackend.... |
363 | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Make Textfile Demo
Demonstrates how to read in the topography or an event and write it out to a text file, as might be needed to read it into ArcGIS, f... | <ASSISTANT_TASK:>
Python Code:
%pylab inline
from __future__ import print_function
import sys, os
from ptha_paths import data_dir, events_dir
Explanation: Make Textfile Demo
Demonstrates how to read in the topography or an event and write it out to a text file, as might be needed to read it into ArcGIS, for example.
En... |
364 | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
1. Princípios
Step1: Outra possibilidade é escrever a função com um sinal de interrogação ao final
Step2: 4. Tipos de dados
Step3: 5. Atribuindo val... | <ASSISTANT_TASK:>
Python Code:
# Comentário de uma linha
# Função:
print('Hello World!')
help(print)
Explanation: 1. Princípios:
Indentation
2. Comentários e ajuda:
End of explanation
3 + 3
# Operações básicas:
print('Soma: ', '3 + 3 = ', 3 + 3)
print('Subtração: ', '3 - 3 = ', 3 - 3)
print('Multiplicação: ', '3 * 3 = ... |
365 | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
8 Advertising on the Web
"adwords" model, search
"collaborative filtering", suggestion
8.1 Issues in On-Line Advertising
8.1.1 Advertising Opportu... | <ASSISTANT_TASK:>
Python Code:
# exerices for section 8.1
Explanation: 8 Advertising on the Web
"adwords" model, search
"collaborative filtering", suggestion
8.1 Issues in On-Line Advertising
8.1.1 Advertising Opportunities
Auto trading sites allow advertisters to post their ads directly on the website.
Disp... |
366 | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: 12 - Introduction to Deep Learning
by Alejandro Correa Bahnsen
version 0.1, May 2016
Part of the class Machine Learning for Security Informatic... | <ASSISTANT_TASK:>
Python Code:
import numpy as np
from load import mnist
X_train, X_test, y_train2, y_test2 = mnist(onehot=True)
y_train = np.argmax(y_train2, axis=1)
y_test = np.argmax(y_test2, axis=1)
X_train[1].reshape((28, 28)).round(2)[:, 4:9].tolist()
from pylab import imshow, show, cm
import matplotlib.pylab as ... |
367 | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
ES-DOC CMIP6 Model Properties - Atmoschem
MIP Era
Step1: Document Authors
Set document authors
Step2: Document Contributors
Specify document contribu... | <ASSISTANT_TASK:>
Python Code:
# DO NOT EDIT !
from pyesdoc.ipython.model_topic import NotebookOutput
# DO NOT EDIT !
DOC = NotebookOutput('cmip6', 'messy-consortium', 'sandbox-1', 'atmoschem')
Explanation: ES-DOC CMIP6 Model Properties - Atmoschem
MIP Era: CMIP6
Institute: MESSY-CONSORTIUM
Source ID: SANDBOX-1
T... |
368 | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Data were munged here.
Step1: <h5>First
Step2: <h3>When did River Grove open, when did the last owners take over, and how many companies have owned t... | <ASSISTANT_TASK:>
Python Code:
import pandas as pd
import numpy as np
from IPython.core.display import display, HTML
display(HTML("<style>.container { width:100% !important; }</style>"))
df = pd.read_csv('../../data/processed/complaints-3-29-scrape.csv')
owners = pd.read_csv('../../data/raw/APD_HistOwner.csv')
Explanat... |
369 | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Exploratory Data Analysis with Python
We will explore the NYC MTA turnstile dataset. These data files are from the New York Subway. It tracks the hourl... | <ASSISTANT_TASK:>
Python Code:
!pip install wget
import os, wget
url_template = "http://web.mta.info/developers/data/nyct/turnstile/turnstile_%s.txt"
for date in ['160206', '160213', '160220', '160227', '160305']:
url = url_template % date
if os.path.isfile('data/turnstile_{}.txt'.format(date)):
print(d... |
370 | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
In this exercise we will decode orientation using data collected for the class.
Step1: Fit a simple classifier using balanced 8-fold crossvalidation
S... | <ASSISTANT_TASK:>
Python Code:
import os,json,glob
import numpy
import nibabel
import sklearn.multiclass
from sklearn.svm import SVC
import sklearn.metrics
import sklearn.cross_validation
import sklearn.preprocessing
import scipy.stats
import random
%matplotlib inline
import matplotlib.pyplot as plt
datadir='orientatio... |
371 | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Notes from David Beazley's Python3 Metaprogramming tutorial (2013)
"ported" to Python 2.7, unless noted otherwise
A Debugging Decorator
Step1: Decorat... | <ASSISTANT_TASK:>
Python Code:
from functools import wraps
def debug(func):
msg = func.__name__
# wraps is used to keep the metadata of the original function
@wraps(func)
def wrapper(*args, **kwargs):
print(msg)
return func(*args, **kwargs)
return wrapper
@debug
def add(x,y):
ret... |
372 | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Tuning a scikit-learn estimator with skopt
Gilles Louppe, July 2016 <br />
Katie Malone, August 2016
Step1: Problem statement
Tuning the hyper-paramet... | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
Explanation: Tuning a scikit-learn estimator with skopt
Gilles Louppe, July 2016 <br />
Katie Malone, August 2016
End of explanation
from sklearn.datasets import load_boston
from sklearn.ensemble import GradientBoosting... |
373 | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Combining SequentialEnsembles with SlicedTrajectoryEnsembles
The ensemble creation features in OpenPathSampling are very powerful, but the ways that so... | <ASSISTANT_TASK:>
Python Code:
from openpathsampling.ensemble import SlicedTrajectoryEnsemble, SequentialEnsemble, AllInXEnsemble, AllOutXEnsemble, LengthEnsemble
from openpathsampling.collectivevariable import FunctionCV
from openpathsampling.volume import CVDefinedVolume
from openpathsampling.engines import Trajector... |
374 | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Spreadsheet widget for the Jupyter Notebook
Installation
To install use pip
Step1: Using the cell function, we can create Cell widgets that are direct... | <ASSISTANT_TASK:>
Python Code:
import ipysheet
sheet = ipysheet.sheet()
sheet
Explanation: Spreadsheet widget for the Jupyter Notebook
Installation
To install use pip:
$ pip install ipysheet
To make it work for Jupyter lab:
$ jupyter labextension ipysheet
If you have notebook 5.2 or below, you also need to execute:
$ j... |
375 | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Point Pattern Windows
Author
Step1: From the summary method we see that the Bounding Rectangle is reported along with the Area of the window for the p... | <ASSISTANT_TASK:>
Python Code:
import pysal.lib as ps
import numpy as np
from pysal.explore.pointpats import PointPattern
f = ps.examples.get_path('vautm17n_points.shp')
fo = ps.io.open(f)
pp_va = PointPattern(np.asarray([pnt for pnt in fo]))
fo.close()
pp_va.summary()
Explanation: Point Pattern Windows
Author: Serge R... |
376 | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Intro to TF-IDF and Doc Clustering
Lynn Cherny, arnicas@gmail
Step1: TF-IDF (Term Frequency, Inverse Document Frequency)
Term Frequency
Step2: What i... | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
# You can ignore the pink warning that appears
import itertools
import math
import nltk
import string
nltk.data.path = ['../nltk_data']
import matplotlib.pyplot as plt
import numpy as np
from scipy.spatial.distance import pdist, squareform
from scipy.cluster.hierarchy i... |
377 | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Preprocessing
Step2: Training LeNet
First, we will train a simple CNN with a single hidden fully connected layer as a classifier.
Step3: Training Ran... | <ASSISTANT_TASK:>
Python Code:
import os
from skimage import io
from skimage.color import rgb2gray
from skimage import transform
from math import ceil
IMGSIZE = (100, 100)
def load_images(folder, scalefactor=(2, 2), labeldict=None):
images = []
labels = []
files = os.listdir(folder)
for file in (f... |
378 | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Plot Trajectories with Pictures
take dimension (e.g. red) that I've trained the nn features to classify and plot sequences in that dimension.
use sequ... | <ASSISTANT_TASK:>
Python Code:
# our lib
from lib.resnet50 import ResNet50
from lib.imagenet_utils import preprocess_input, decode_predictions
#keras
from keras.preprocessing import image
from keras.models import Model
import glob
def preprocess_img(img_path):
img = image.load_img(img_path, target_size=(224, 224))... |
379 | <SYSTEM_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
In this project, you'll classify images from the CIFAR-10 dataset. The dataset consists of airplanes, dogs, cats, and othe... | <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 ... |
380 | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Chapter 3 - Training process and learning rate
In this chapter we will clean up our code and create a logistic classifier class that works much like ma... | <ASSISTANT_TASK:>
Python Code:
# Numpy handles matrix multiplication, see http://www.numpy.org/
import numpy as np
# PyPlot is a matlab like plotting framework, see https://matplotlib.org/api/pyplot_api.html
import matplotlib.pyplot as plt
# This line makes it easier to plot PyPlot graphs in Jupyter Notebooks
%matplotl... |
381 | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Demo for new kwargs-based ncomp
Step1: for btn, sconc is passed as a normal util_3d-compatible argument, no need for the list anymore
Step2: or we pa... | <ASSISTANT_TASK:>
Python Code:
import numpy as np
import flopy
reload(flopy)
from flopy.modflow import *
from flopy.mt3d import *
nlay, nrow, ncol = 3, 10, 10
ml = Modflow("test")
dis = ModflowDis(ml,nlay=nlay, nrow=nrow, ncol=ncol)
Explanation: Demo for new kwargs-based ncomp
End of explanation
mt = Mt3dms(modflowmode... |
382 | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Vertex client library
Step1: Install the latest GA version of google-cloud-storage library as well.
Step2: Restart the kernel
Once you've installed t... | <ASSISTANT_TASK:>
Python Code:
import os
import sys
# Google Cloud Notebook
if os.path.exists("/opt/deeplearning/metadata/env_version"):
USER_FLAG = "--user"
else:
USER_FLAG = ""
! pip3 install -U google-cloud-aiplatform $USER_FLAG
Explanation: Vertex client library: AutoML text multi-label classification model... |
383 | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Homework 10
Step1: Question 2
Step2: Question 3 | <ASSISTANT_TASK:>
Python Code:
import x as ET
tree=ET.parse("example_thermo.xml")
elementroot=tree.getroot()
import sqlite3
import pandas as pd
db = sqlite3.connect('thermo.sqlite')
cursor = db.cursor()
cursor.execute("DROP TABLE IF EXISTS low")
cursor.execute("DROP TABLE IF EXISTS high")
cursor.execute("PRAGMA foreign... |
384 | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Scraping Rate.am
This notebook provides code for scraping rates from rate.am. The rates are provided inside an HTML table, thus pandas.read_html() func... | <ASSISTANT_TASK:>
Python Code:
import pandas as pd
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
browser = webdriver.Chrome()
url = "http://rate.am/en/armenian-dram-exchange-rates/banks/cash"
browser.get(url) #will wait until page is fully loaded
browser.find_element_by_xpath("//label[c... |
385 | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Implementation of a Radix-2 Fast Fourier Transform
Import standard modules
Step3: This assignment is to implement a python-based Fast Fourier Transfor... | <ASSISTANT_TASK:>
Python Code:
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
from IPython.display import HTML
HTML('../style/course.css') #apply general CSS
import cmath
Explanation: Implementation of a Radix-2 Fast Fourier Transform
Import standard modules:
End of explanation
def loop_DFT(x):
... |
386 | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
<h3>TarPipe</h3>
This script creates a .tar.gz of certain folders and allows for easy search of the files backed up.
Currently focus on on motion but ... | <ASSISTANT_TASK:>
Python Code:
import tarfile
import time
import os
import getpass
import paramiko
import arrow
curtime = time.strftime("%d-%b-%Y-%H", time.gmtime())
sshgetdrn = paramiko.SSHClient()
sshgetdrn.set_missing_host_key_policy(paramiko.AutoAddPolicy())
usrg = getpass.getuser()
sshgetdrn.connect('128.199.60.12... |
387 | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
.. _canvas-layout
Step1: If you need greater control over the positioning of the axes within the canvas, or want to add multiple axes to one canvas, i... | <ASSISTANT_TASK:>
Python Code:
import numpy
y = numpy.linspace(0, 1, 20) ** 2
import toyplot
toyplot.plot(y, width=300);
Explanation: .. _canvas-layout:
Canvas Layout
In Toyplot, axes (including :ref:cartesian-axes, :ref:table-axes, and others) are used to map data values into canvas coordinates. The axes range (the a... |
388 | <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: Data Challenge
Files are stored in an S3 bucket. The purpose here is to fully analyze the data and make some predictions.
This workbook was expo... | <ASSISTANT_TASK:>
Python Code:
def convert_list(query_string):
Parse the query string of the url into a dictionary.
Handle special cases:
- There is a single query "error=True" which is rewritten to 1 if True, else 0.
- Parsing the query returns a dictionary of key-value pairs. The value is a list.... |
389 | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
toytree quartet functions (in progress)
Step1: get two random trees
Step2: Plan for counting quartets (Illustrated below)
We will traverse the tree v... | <ASSISTANT_TASK:>
Python Code:
import toytree
import itertools
import numpy as np
Explanation: toytree quartet functions (in progress)
End of explanation
t0 = toytree.rtree.unittree(10, seed=0)
t1 = toytree.rtree.unittree(10, seed=1)
toytree.mtree([t0, t1]).draw(ts='p', height=200);
Explanation: get two random trees
En... |
390 | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
cf. ComputationalPhysics/doc/Programs/LecturePrograms/programs/StatPhys/python/ising2dim.py
Step2: Periodic boundary conditions
Step3: Set up spin ma... | <ASSISTANT_TASK:>
Python Code:
import numpy
import numpy as np
import sys
import math
import matplotlib.pyplot as plt
Explanation: cf. ComputationalPhysics/doc/Programs/LecturePrograms/programs/StatPhys/python/ising2dim.py
End of explanation
def periodic(i,limit,add):
Choose correct matrix index with periodic... |
391 | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Plotting the full vector-valued MNE solution
The source space that is used for the inverse computation defines a set of
dipoles, distributed across the... | <ASSISTANT_TASK:>
Python Code:
# Author: Marijn van Vliet <w.m.vanvliet@gmail.com>
#
# License: BSD-3-Clause
import numpy as np
import mne
from mne.datasets import sample
from mne.minimum_norm import read_inverse_operator, apply_inverse
print(__doc__)
data_path = sample.data_path()
subjects_dir = data_path + '/subjects... |
392 | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Tools - NumPy
NumPy is the fundamental library for scientific computing with Python. NumPy is centered around a powerful N-dimensional array object, an... | <ASSISTANT_TASK:>
Python Code:
from __future__ import division, print_function, unicode_literals
Explanation: Tools - NumPy
NumPy is the fundamental library for scientific computing with Python. NumPy is centered around a powerful N-dimensional array object, and it also contains useful linear algebra, Fourier transform... |
393 | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Notebook snippets, tips and tricks
TODO
Step1: Useful keyboard shortcuts
Enter edit mode
Step2: 3D plots
Step3: Animations
Step4: Interactive plots... | <ASSISTANT_TASK:>
Python Code:
%matplotlib notebook
# As an alternative, one may use: %pylab notebook
# For old Matplotlib and Ipython versions, use the non-interactive version:
# %matplotlib inline or %pylab inline
# To ignore warnings (http://stackoverflow.com/questions/9031783/hide-all-warnings-in-ipython)
import wa... |
394 | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
A Simple Autoencoder
We'll start off by building a simple autoencoder to compress the MNIST dataset. With autoencoders, we pass input data through an e... | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets('MNIST_data', validation_size=0)
Explanation: A Simple Autoencoder
We'll start off by building a simpl... |
395 | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
This notebook is highly inspired from
- LSTM Text Generation
- Lasagne doc about recurrent
Step1: Hyperparameters
The following are hyperparameters, ... | <ASSISTANT_TASK:>
Python Code:
import numpy as np
import theano
import theano.tensor as T
import lasagne
seed = 1
lasagne.random.set_rng(np.random.RandomState(seed))
Explanation: This notebook is highly inspired from
- LSTM Text Generation
- Lasagne doc about recurrent
End of explanation
# Sequence Length
SEQ_LENGTH =... |
396 | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Two extremely well-separated Gaussian clusters. This will be easy--really not even requiring spectral analysis--but it's fine for demo purposes.
Let's ... | <ASSISTANT_TASK:>
Python Code:
# We'll make the number of bins, B
B = 50
plt.figure(0)
plt.hist(X[:, 0], bins = B, normed = True)
plt.title("Dimension 1 ($x$-axis)")
plt.figure(1)
plt.hist(X[:, 1], bins = B, normed = True)
plt.title("Dimension 2 ($y$-axis)")
Explanation: Two extremely well-separated Gaussian clusters. ... |
397 | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Generalized Least Squares
Step1: The Longley dataset is a time series dataset
Step2: Let's assume that the data is heteroskedastic and that we know
... | <ASSISTANT_TASK:>
Python Code:
from __future__ import print_function
import statsmodels.api as sm
import numpy as np
from statsmodels.iolib.table import (SimpleTable, default_txt_fmt)
Explanation: Generalized Least Squares
End of explanation
data = sm.datasets.longley.load()
data.exog = sm.add_constant(data.exog)
print... |
398 | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Crisis Mapping Toolkit Documentation
This document provides a high level overview of how to use the Crisis Mapping Toolkit (CMT). The CMT is a set of ... | <ASSISTANT_TASK:>
Python Code:
import sys
import os
import ee
# This script assumes your authentification credentials are stored as operatoring system
# environment variables.
__MY_SERVICE_ACCOUNT = os.environ.get('MY_SERVICE_ACCOUNT')
__MY_PRIVATE_KEY_FILE = os.environ.get('MY_PRIVATE_KEY_FILE')
# Initialize the Earth... |
399 | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Your first presentation
Import Beampy
To start, you need to import beampy module in your python file.
.. code-block
Step1: Change the position of the ... | <ASSISTANT_TASK:>
Python Code:
from beampy import *
# We first create a new document for our presentation
# Remove quiet=True to see Beampy compiler output
doc = document(quiet=True)
# Then we create a new slide with the title "My first new slide"
with slide('My first slide title'):
# All the slide contents are fun... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.