Unnamed: 0 int64 0 16k | text_prompt stringlengths 110 62.1k | code_prompt stringlengths 37 152k |
|---|---|---|
7,600 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
ABC calibration of $I_\text{Kur}$ in Courtemanche model to original dataset.
Note the term $I_\text{sus}$ for sustained outward Potassium current is used throughout the notebook.
Step1: Ini... | Python Code:
import os, tempfile
import logging
import matplotlib as mpl
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
from ionchannelABC import theoretical_population_size
from ionchannelABC import IonChannelDistance, EfficientMultivariateNormalTransition, IonChannelAcceptor
from ionchannelA... |
7,601 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Application
Step1: Load and Subset on Individual Contributors
Step2: What proportion of contributons were by blacks, whites, Hispanics, and Asians?
Step3: What proportion of the donors we... | Python Code:
import pandas as pd
df = pd.read_csv('/opt/names/fec_contrib/contribDB_2000.csv', nrows=100)
df.columns
from ethnicolr import census_ln
Explanation: Application: 2000/2010 Political Campaign Contributions by Race
Using ethnicolr, we look to answer three basic questions:
<ol>
<li>What proportion of contribu... |
7,602 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Relax and hold steady
Many problems in physics have no time dependence, yet are rich with physical meaning
Step1: To visualize 2D data, we can use pyplot.imshow(), but a 3D plot can sometim... | Python Code:
from matplotlib import pyplot
import numpy
%matplotlib inline
from matplotlib import rcParams
rcParams['font.family'] = 'serif'
rcParams['font.size'] = 16
Explanation: Relax and hold steady
Many problems in physics have no time dependence, yet are rich with physical meaning: the gravitational field produce... |
7,603 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Building a song recommender
Fire up GraphLab Create
Step1: Load music data
Step2: Explore data
Music data shows how many times a user listened to a song, as well as the details of the song... | Python Code:
import graphlab
Explanation: Building a song recommender
Fire up GraphLab Create
End of explanation
song_data = graphlab.SFrame('song_data.gl/')
Explanation: Load music data
End of explanation
song_data.head()
Explanation: Explore data
Music data shows how many times a user listened to a song, as well as t... |
7,604 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Análisis de los datos obtenidos
Uso de ipython para el análsis y muestra de los datos obtenidos durante la producción.Se implementa un regulador experto. Los datos analizados son del día 13 ... | Python Code:
#Importamos las librerías utilizadas
import numpy as np
import pandas as pd
import seaborn as sns
#Mostramos las versiones usadas de cada librerías
print ("Numpy v{}".format(np.__version__))
print ("Pandas v{}".format(pd.__version__))
print ("Seaborn v{}".format(sns.__version__))
#Abrimos el fichero csv co... |
7,605 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Machine Learning Engineer Nanodegree
Model Evaluation & Validation
Project
Step1: Data Exploration
In this first section of this project, you will make a cursory investigation about the Bos... | Python Code:
# Import libraries necessary for this project
import numpy as np
import pandas as pd
from sklearn.cross_validation import ShuffleSplit
# Import supplementary visualizations code visuals.py
import visuals as vs
# Pretty display for notebooks
%matplotlib inline
# Load the Boston housing dataset
data = pd.rea... |
7,606 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step7: Chapter 4 Linear Algebra
Vectors
Step9: Matrices | Python Code:
height = [70, # inches,
170, # pounds,
40] # years
grades = [95, # exam1,
80, # exam2,
75, # exam3,
62] # exam4
def vector_add(v, w):
'''adds corresponding elements'''
return [v_i + w_i
for v_i, w_i in zip(v, w)]
def vector_substract(v... |
7,607 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Generate a functional label from source estimates
Threshold source estimates and produce a functional label. The label
is typically the region of interest that contains high values.
Here we ... | Python Code:
# Author: Luke Bloy <luke.bloy@gmail.com>
# Alex Gramfort <alexandre.gramfort@inria.fr>
# License: BSD (3-clause)
import numpy as np
import matplotlib.pyplot as plt
import mne
from mne.minimum_norm import read_inverse_operator, apply_inverse
from mne.datasets import sample
print(__doc__)
data_path ... |
7,608 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Test environment setup
Step1: Create a new RTA workload generator object
The wlgen
Step2: Workload Generation Examples
Single periodic task
An RTApp workload is defined by specifying a kin... | Python Code:
# Let's use the local host as a target
te = TestEnv(
target_conf={
"platform": 'host',
"username": 'put_here_your_username'
})
Explanation: Test environment setup
End of explanation
# Create a new RTApp workload generator
rtapp = RTA(
target=te.target, # Target execution on... |
7,609 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
This code generates a Fourier transform of a specified shape as outlined in Timmer and Koenig 1995 (A&A vol 300 p 707-710), and plots it and its corresponding time series. The user can speci... | Python Code:
import numpy as np
from scipy import fftpack
import matplotlib.pyplot as plt
from matplotlib.ticker import MultipleLocator
import matplotlib.font_manager as font_manager
import itertools
## Shows the plots inline, instead of in a separate window:
%matplotlib inline
## Sets the font size for plotting
font_p... |
7,610 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
map(func)
Retorna um novo RDD formado pela passagem de cada elemento do RDD de origem através de uma da função func.
Exemplo
Step1: filter(func)
Retorna um novo RDD formado pela seleção daq... | Python Code:
data = sc.parallelize(range(1, 11))
def duplicar(x): return x*x
# data é um rdd
res = data.map( duplicar )
print (res.collect())
Explanation: map(func)
Retorna um novo RDD formado pela passagem de cada elemento do RDD de origem através de uma da função func.
Exemplo:
End of explanation
data = sc.paralleliz... |
7,611 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Using third-party Native Libraries
Sometimes, the functionality you need is only available in third-party native libraries. These libraries can still be used from within Pythran, using Pythr... | Python Code:
import pythran
%load_ext pythran.magic
%%pythran
#pythran export pythran_cbrt(float64(float64), float64)
def pythran_cbrt(libm_cbrt, val):
return libm_cbrt(val)
Explanation: Using third-party Native Libraries
Sometimes, the functionality you need is only available in third-party native libraries. Thes... |
7,612 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
The Lorenz Differential Equations
Before we start, we import some preliminary libraries. We will also import (below) the accompanying lorenz.py file, which contains the actual solver and plo... | Python Code:
%matplotlib inline
from ipywidgets import interactive, fixed
Explanation: The Lorenz Differential Equations
Before we start, we import some preliminary libraries. We will also import (below) the accompanying lorenz.py file, which contains the actual solver and plotting routine.
End of explanation
from lore... |
7,613 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
To understand what CUDA is and why it is important, I read
this article. It is a subtle plug for their services, but it aligns well with all that I have so far heard about GPUs in data scie... | Python Code:
from theano import function, config, shared, sandbox
import theano.tensor as T
import numpy
import time
vlen = 10 * 30 * 768 # 10 x #cores x # threads per core
iters = 1000
rng = numpy.random.RandomState(22)
x = shared(numpy.asarray(rng.rand(vlen), config.floatX))
f = function([], T.exp(x))
print(f.maker.... |
7,614 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
采用Spark处理OpenStreetMap的osm文件。
Spark DataFrame参考
Step1: 配置环境SparkConf和创建SparkContext运行环境对象。
Step2: 显示Spark的配置信息。
Step3: Spark的文本RDD操作。
按照文本方式读取osm的json格式文件,将JSON字符串转为dict对象。
Step4: 从RDD中按... | Python Code:
from pprint import *
import pyspark
from pyspark import SparkConf, SparkContext
sc = None
print(pyspark.status)
Explanation: 采用Spark处理OpenStreetMap的osm文件。
Spark DataFrame参考: https://spark.apache.org/docs/1.3.0/sql-programming-guide.html#interoperating-with-rdds
by openthings@163.com,2016-4-23. Lic... |
7,615 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Exercise 1
We proceed building the alogrithm for testing the accuracy of the numerical derivative
Step1: a)
Step2: We can see that until $h = 10^7$ the trend is that the absolute error dim... | Python Code:
def f(x):
return np.exp(np.sin(x))
def df(x):
return f(x) * np.cos(x)
def absolute_err(f, df, h):
g = (f(h) - f(0)) / h
return np.abs(df(0) - g)
hs = 10. ** -np.arange(15)
epsilons = np.empty(15)
for i, h in enumerate(hs):
epsilons[i] = absolute_err(f, df, h)
Explanation: Exercise 1
We... |
7,616 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Convolutional Autoencoder
Sticking with the MNIST dataset, let's improve our autoencoder's performance using convolutional layers. Again, loading modules and the data.
Step1: Network Archit... | 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)
img = mnist.train.images[2]
plt.imshow(img.reshape((28, 28)), cmap='Greys_r')
Explanati... |
7,617 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Pythonのコードをセル内に書いて実行することができます
Step1: このようにPythonをインタラクティブに動作させるだけでなく、GCPの各種サービスとシームレスに連携できることがDatalabの大きな利点となります。
DatalabからBigQueryを呼び出す
bqというマジックコマンドを使う
Step2: BigQueryコマンドの結果をPythonのオブジェ... | Python Code:
# このセルにカーソルを当ててCtrl+Enter もしくは Shift+Enterを押すと'hello world'と出力することができます
print('hello world')
# 各種制御構文、クラスや関数なども含めて通常のプログラミングと同じように動作させることができます
for i in range(10):
print(i)
# 変数の定義はセル内だけでなく、ノートブック全体がスコープとなり、通常のPythonと同じような扱いとなります
x = 10
# xは10なので、10+20となります
y = x + 20
print(y)
Explanation: Pythonのコードをセル... |
7,618 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Ensemble Design Pattern
Stacking is an Ensemble method which combines the outputs of a collection of models to make a prediction. The initial models, which are typically of different model t... | Python Code:
import os
import pandas as pd
import tensorflow as tf
from tensorflow import keras
from tensorflow import feature_column as fc
from tensorflow.keras import layers, models, Model
df = pd.read_csv("./data/babyweight_train.csv")
df.head()
Explanation: Ensemble Design Pattern
Stacking is an Ensemble method whi... |
7,619 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Anna KaRNNa
In this notebook, we'll build a character-wise RNN trained on Anna Karenina, one of my all-time favorite books. It'll be able to generate new text based on the text from the book... | Python Code:
import time
from collections import namedtuple
import numpy as np
import tensorflow as tf
Explanation: Anna KaRNNa
In this notebook, we'll build a character-wise RNN trained on Anna Karenina, one of my all-time favorite books. It'll be able to generate new text based on the text from the book.
This network... |
7,620 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Simulating a Yo-Yo
Modeling and Simulation in Python
Copyright 2021 Allen Downey
License
Step1: Yo-yo
Suppose you are holding a yo-yo with a length of string wound around its axle, and you ... | Python Code:
# install Pint if necessary
try:
import pint
except ImportError:
!pip install pint
# download modsim.py if necessary
from os.path import exists
filename = 'modsim.py'
if not exists(filename):
from urllib.request import urlretrieve
url = 'https://raw.githubusercontent.com/AllenDowney/ModSim/... |
7,621 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Earth Engine REST API Quickstart
This is a demonstration notebook for using the Earth Engine REST API. See the complete guide for more information
Step1: Define service account credentials... | Python Code:
# INSERT YOUR PROJECT HERE
PROJECT = 'your-project'
!gcloud auth login --project {PROJECT}
Explanation: Earth Engine REST API Quickstart
This is a demonstration notebook for using the Earth Engine REST API. See the complete guide for more information: https://developers.google.com/earth-engine/reference/Q... |
7,622 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Prepare Notebook
To run this code, written at the very end of Chapter 3, you need a working empty database.
To move the project into a valid state, please use the command git chapter [chapte... | Python Code:
from datetime import date
from organizer.models import Tag, Startup, NewsLink
from blog.models import Post
Explanation: Prepare Notebook
To run this code, written at the very end of Chapter 3, you need a working empty database.
To move the project into a valid state, please use the command git chapter [cha... |
7,623 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Calibrations
This notebook demonstrates how to calibrate real and reciprocal space coordinates of scanning electron diffraction data. Calibrations include correcting the diffraction pattern ... | Python Code:
%matplotlib inline
import numpy as np
import pyxem as pxm
import hyperspy.api as hs
from pyxem.libraries.calibration_library import CalibrationDataLibrary
from pyxem.generators.calibration_generator import CalibrationGenerator
Explanation: Calibrations
This notebook demonstrates how to calibrate real and r... |
7,624 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
ES-DOC CMIP6 Model Properties - Aerosol
MIP Era
Step1: Document Authors
Set document authors
Step2: Document Contributors
Specify document contributors
Step3: Document Publication
Specify... | Python Code:
# DO NOT EDIT !
from pyesdoc.ipython.model_topic import NotebookOutput
# DO NOT EDIT !
DOC = NotebookOutput('cmip6', 'nuist', 'sandbox-3', 'aerosol')
Explanation: ES-DOC CMIP6 Model Properties - Aerosol
MIP Era: CMIP6
Institute: NUIST
Source ID: SANDBOX-3
Topic: Aerosol
Sub-Topics: Transport, Emissio... |
7,625 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Markov switching autoregression models
This notebook provides an example of the use of Markov switching models in Statsmodels to replicate a number of results presented in Kim and Nelson (19... | Python Code:
%matplotlib inline
import numpy as np
import pandas as pd
import statsmodels.api as sm
import matplotlib.pyplot as plt
import requests
from io import BytesIO
# NBER recessions
from pandas_datareader.data import DataReader
from datetime import datetime
usrec = DataReader('USREC', 'fred', start=datetime(1947... |
7,626 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Consumer Choice and Intertemporal Choice
We setup and solve a very simple generic one-period consumer choice problem over two goods. We later specialize to the case of intertemporal trade o... | Python Code:
consume_plot()
Explanation: Consumer Choice and Intertemporal Choice
We setup and solve a very simple generic one-period consumer choice problem over two goods. We later specialize to the case of intertemporal trade over two periods and choice over lotteries. The consumer is assumed to have time-consiste... |
7,627 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Choose subject ID
Step1: Load data
Step2: Cell below opens an html report in a web-browser
Step3: Exclude ICA components
To exclude/include an ICA component click on mne_browse window | Python Code:
name_sel = widgets.Select(
description='Subject ID:',
options=subject_ids
)
display(name_sel)
cond_sel = widgets.RadioButtons(
description='Condition:',
options=sessions,
)
display(cond_sel)
%%capture
if cond_sel.value == sessions[0]:
session = sessions[0]
elif cond_sel.value == session... |
7,628 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
3.1. Spark DataFrames & Pandas Plotting - Python
Create Dataproc Cluster with Jupyter
This notebook is designed to be run on Google Cloud Dataproc.
Follow the links below for instructions on... | Python Code:
!scala -version
Explanation: 3.1. Spark DataFrames & Pandas Plotting - Python
Create Dataproc Cluster with Jupyter
This notebook is designed to be run on Google Cloud Dataproc.
Follow the links below for instructions on how to create a Dataproc Cluster with the Juypter component installed.
Tutorial - Insta... |
7,629 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Synthetic Data
Developed by Stijn Klop and Mark Bakker
This Notebook contains a number of examples and tests with synthetic data. The purpose of this notebook is to demonstrate the noise mod... | Python Code:
import numpy as np
import matplotlib.pyplot as plt
from scipy.special import gammainc, gammaincinv
import pandas as pd
import pastas as ps
ps.show_versions()
Explanation: Synthetic Data
Developed by Stijn Klop and Mark Bakker
This Notebook contains a number of examples and tests with synthetic data. The pu... |
7,630 | Given the following text description, write Python code to implement the functionality described below step by step
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 encoder that makes a compressed represen... | 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 simple autoencoder to c... |
7,631 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Processing the open food databse to extract a dataset to use for the visualization.
Step1: Working from the full database, because the usda_imports_filtered.csv file in the shared drive doe... | Python Code:
import pandas as pd
import numpy as np
import re
from scipy import sparse as sparse
# SK-learn libraries for feature extraction from text.
from sklearn.feature_extraction.text import *
data_dir = "/Users/seddont/Dropbox/Tom/MIDS/W209_work/Tom_project/"
code_dir = "/Users/seddont/Dropbox/Tom/MIDS/W209_work/... |
7,632 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Evolution d'indicateurs dans les communes
Step1: Jointure entre 2 fichiers
Step2: Il y a bien les colonnes "status", "mean_altitude", "superficie", "is_metropole" et "metropole_name"
Nom... | Python Code:
commune_metropole = pd.read_csv('data/commune_metropole.csv', encoding='utf-8')
commune_metropole.shape
commune_metropole.head()
insee = pd.read_csv('data/insee.csv',
sep=";", # séparateur du fichier
dtype={'COM' : np.dtype(str)}, # On force la ... |
7,633 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Basic MEG and EEG data processing
MNE-Python reimplements most of MNE-C's (the original MNE command line utils)
functionality and offers transparent scripting.
On top of that it extends MNE-... | Python Code:
import mne
Explanation: Basic MEG and EEG data processing
MNE-Python reimplements most of MNE-C's (the original MNE command line utils)
functionality and offers transparent scripting.
On top of that it extends MNE-C's functionality considerably
(customize events, compute contrasts, group statistics, time-f... |
7,634 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Run Average Time Experiment
Step1: Average Time excluding PQT Time
This is equivalent to running the algorithms using a PQT generated on the current points.
Step2: Average Time including P... | Python Code:
splice_avg_times, plg_avg_times, asplice_avg_times, pqt_avg_times = \
compute_avg_times(n_pairs_li, n_reps, gen_pd_edges, p_hat, verbose=True)
Explanation: Run Average Time Experiment
End of explanation
fig, ax = plt.subplots()
ax.set_yscale('log')
ax.plot(n_pairs_li, splice_avg_times, color='b', linestyle... |
7,635 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Prerequisites (downloading tensorflow_models and checkpoints)
Checkpoint based inference
Frozen inference
Prerequisites (downloading tensorflow_models and checkpoints)
Step1: Checkpoint bas... | Python Code:
!git clone https://github.com/tensorflow/models
from __future__ import print_function
from IPython import display
checkpoint_name = 'mobilenet_v2_1.0_224' #@param
url = 'https://storage.googleapis.com/mobilenet_v2/checkpoints/' + checkpoint_name + '.tgz'
print('Downloading from ', url)
!wget {url}
print('... |
7,636 | Given the following text problem statement, write Python code to implement the functionality described below in problem statement
Problem:
I am trying to convert a MATLAB code in Python. I don't know how to initialize an empty matrix in Python. | Problem:
import numpy as np
result = np.array([]) |
7,637 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<img src="../../img/logo_white_bkg_small.png" align="left" />
Worksheet 3
Step1: Exercise 1
Step2: Exercise 2
Step3: Exercise 3
Step4: Exercise 4
Step5: Part 1
Step6: Part 2
Step7: P... | Python Code:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
plt.style.use('ggplot')
%pylab inline
data = pd.read_csv( '../../data/dailybots.csv' )
#Look at a summary of the data
data.describe()
Explanation: <img src="../../img/logo_white_bkg_small.png" align="left" />
Worksheet 3: EDA Workshee... |
7,638 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
ES-DOC CMIP6 Model Properties - Toplevel
MIP Era
Step1: Document Authors
Set document authors
Step2: Document Contributors
Specify document contributors
Step3: Document Publication
Specif... | Python Code:
# DO NOT EDIT !
from pyesdoc.ipython.model_topic import NotebookOutput
# DO NOT EDIT !
DOC = NotebookOutput('cmip6', 'fio-ronm', 'sandbox-1', 'toplevel')
Explanation: ES-DOC CMIP6 Model Properties - Toplevel
MIP Era: CMIP6
Institute: FIO-RONM
Source ID: SANDBOX-1
Sub-Topics: Radiative Forcings.
Prop... |
7,639 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Demonstration of the topic coherence pipeline in Gensim
Introduction
We will be using the u_mass and c_v coherence for two different LDA models
Step1: Set up corpus
As stated in table 2 fro... | Python Code:
from __future__ import print_function
import os
import logging
import json
import warnings
try:
raise ImportError
import pyLDAvis.gensim
CAN_VISUALIZE = True
pyLDAvis.enable_notebook()
from IPython.display import display
except ImportError:
ValueError("SKIP: please install pyLDAvis"... |
7,640 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Chaos Theory and the Logistic Map
In this tutorial, we will see how to implement Geoff Boeing's
excellent blog post on Chaos Theory and the Logistic
Map using
our newly release library,
Holo... | Python Code:
import numpy as np
import holoviews as hv
from holoviews import Dimension
hv.notebook_extension()
Explanation: Chaos Theory and the Logistic Map
In this tutorial, we will see how to implement Geoff Boeing's
excellent blog post on Chaos Theory and the Logistic
Map using
our newly release library,
HoloViews.... |
7,641 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
... and so we begin
Critical information
First steps
Order of the day
Learn to use Jupyter / iPython Notebook
Get familiar with basic Python
Start with Spyder, a traditional editor
Fundament... | Python Code:
import datetime
print(datetime.date.today())
Explanation: ... and so we begin
Critical information
First steps
Order of the day
Learn to use Jupyter / iPython Notebook
Get familiar with basic Python
Start with Spyder, a traditional editor
Fundamental Python-in-Science skills
What is Jupyter
(previously iPy... |
7,642 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Obtain all the data for the Master students, starting from 2007. Compute how many months it took each master student to complete their master, for those that completed it. Partition the data... | Python Code:
# Requests : make http requests to websites
import requests
# BeautifulSoup : parser to manipulate easily html content
from bs4 import BeautifulSoup
# Regular expressions
import re
# Aren't pandas awesome ?
import pandas as pd
Explanation: Obtain all the data for the Master students, starting from 2007. Co... |
7,643 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Advanced Pandas
Step1: <a id=movielens></a>
MovieLens data
The data comes as a zip file that contains several csv's. We get the details from the README inside. (It's written in Markdown, ... | Python Code:
%matplotlib inline
import pandas as pd # data package
import matplotlib.pyplot as plt # graphics
import datetime as dt # date tools, used to note current date
# these are new
import os # operating system tools (check files)
import requests, io # ... |
7,644 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Introduction to SimpleITKv4 Registration <a href="https
Step1: Utility functions
A number of utility callback functions for image display and for plotting the similarity metric during regis... | Python Code:
import SimpleITK as sitk
# Utility method that either downloads data from the Girder repository or
# if already downloaded returns the file name for reading from disk (cached data).
%run update_path_to_download_script
from downloaddata import fetch_data as fdata
# Always write output to a separate director... |
7,645 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
KMeans Clustering
K = 5
Step1: Bisecting K-Means
Step2: Cutting the tree structure
Cut the tree to get a clustering with a new n_cluster
bkm.cut(n_clusters=4)
It returns a tuple | Python Code:
km = pyclust.KMeans(n_clusters=5)
km.fit(df.iloc[:,0:2].values)
print(km.centers_)
plot_scatter(df.iloc[:,0:2].values, labels=km.labels_, title="Scatter Plot: K-Means")
Explanation: KMeans Clustering
K = 5
End of explanation
bkm = pyclust.BisectKMeans(n_clusters=5)
bkm.fit(df.iloc[:,0:2].values)
print(bkm... |
7,646 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
XMAP plotter
Helping hands
http
Step1: Definitions
Step2: Setup
Figure sizes controller
Step3: Column type definition
Step4: Read XMAP
http
Step7: Add length column
Step8: More stats
S... | Python Code:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
#import matplotlib as plt
#plt.use('TkAgg')
import operator
import re
from collections import defaultdict
import pylab
pylab.show()
%pylab inline
Explanation: XMAP plotter
Helping hands
http://nbviewer.ipython.org/github/herrfz/dat... |
7,647 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Python Identifiers aka Variables
In Python, variable names are kind of tags/pointers to the memory location which hosts the data. We can also think of it as a labeled container that can stor... | Python Code:
current_month = "MAY"
print(current_month)
Explanation: Python Identifiers aka Variables
In Python, variable names are kind of tags/pointers to the memory location which hosts the data. We can also think of it as a labeled container that can store a single value. That single value can be of practically any... |
7,648 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Excersises
1.
Implemet softmax. Softmax is a vector-vector function such that
$$
x_i \mapsto \frac{\exp(x_i)}{\sum_{j=1}^n \exp(x_j)}
$$
Avoid using for loops, use vectorization. The solutio... | Python Code:
def softmax(X):
X = numpy.array(X)
Y = numpy.exp(X)
return Y/Y.sum()
print(softmax([-1,0,1]))
Explanation: Excersises
1.
Implemet softmax. Softmax is a vector-vector function such that
$$
x_i \mapsto \frac{\exp(x_i)}{\sum_{j=1}^n \exp(x_j)}
$$
Avoid using for loops, use vectorization. The solut... |
7,649 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Trip S&S
Maps for https
Step1: 1. Map
Step2: 2. Profile
Route drawn in Google Maps and converted in http | Python Code:
import numpy as np
from scipy.interpolate import interp1d
import travelmaps2 as tm
from matplotlib import pyplot as plt
tm.setup(dpi=200)
Explanation: Trip S&S
Maps for https://mexico.werthmuller.org/besucherreisen/simon.
End of explanation
fig_x = tm.plt.figure(figsize=(tm.cm2in([11, 6])))
# Locations
MDF... |
7,650 | Given the following text description, write Python code to implement the functionality described.
Description:
Count quadruples ( i , j , k , l ) in an array such that i < j < k < l and arr [ i ] = arr [ k ] and arr [ j ] = arr [ l ]
Function to count total number of required tuples ; Initialize unordered map ; Find th... | Python Code:
def countTuples(arr , N ) :
ans = 0
val = 0
freq = { }
for j in range(N - 2 ) :
val = 0
for l in range(j + 1 , N ) :
if(arr[j ] == arr[l ] ) :
ans += val
if arr[l ] in freq :
val += freq[arr[l ] ]
freq[arr[j ] ] = freq . get(arr[j ] , 0 ) + 1
return ans
if __name__=... |
7,651 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Spectrum
Colour is defined as the characteristic of visual perception that can be described by attributes of hue, brightness (or lightness) and colourfulness (or saturation or chroma).
When ... | Python Code:
%matplotlib inline
import colour
from colour.plotting import *
colour.filter_warnings(True, False)
colour_plotting_defaults()
# Plotting the visible spectrum.
visible_spectrum_plot()
Explanation: Spectrum
Colour is defined as the characteristic of visual perception that can be described by attributes of hu... |
7,652 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
This tutorial shows various methods of reusing your Python code. The follow up tutorial on packaging code will explore ways to make code reusable by others.
Step1: Step 0
Step2: To make th... | Python Code:
import numpy as np
import matplotlib.pyplot as plt
Explanation: This tutorial shows various methods of reusing your Python code. The follow up tutorial on packaging code will explore ways to make code reusable by others.
End of explanation
def go_figure():
figure, axes = plt.subplots(2, 2, figsize=(10,... |
7,653 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Correlation Functions
Contents
Two-Time Correlation Functions
Steady State Correlation Functions
Emission Spectrum
Non-Steady State Correlation Function
Step1: <a id='twotime'></a>
Two-Time... | Python Code:
%matplotlib inline
import numpy as np
from pylab import *
from qutip import *
Explanation: Correlation Functions
Contents
Two-Time Correlation Functions
Steady State Correlation Functions
Emission Spectrum
Non-Steady State Correlation Function
End of explanation
times = np.linspace(0,10.0,200)
a = destroy(... |
7,654 | Given the following text description, write Python code to implement the functionality described below step by step
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: Now define a count_letters(n) that return... | Python Code:
def number_to_words(n):
Given a number n between 1-1000 inclusive return a list of words for the number.
dic_1s == ["one", 'two','three','four','five''six','seven','eight','nine']
dic_10s == ['ten','twenty', 'thirty','fourty','fifty', 'sixty','seveny','eighty','ninety']
1000 == "one t... |
7,655 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
DKRZ data ingest workflow information update
(Disclaimer
Step1: demo examples - step by step
The following examples can be adopted to the data managers needs by e.g. creating targeted jupyt... | Python Code:
# import necessary packages
from dkrz_forms import form_handler, utils, wflow_handler, checks
from datetime import datetime
from pprint import pprint
Explanation: DKRZ data ingest workflow information update
(Disclaimer: This demo notebook is for data managers only !)
Updating information with respect to t... |
7,656 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<center>
<img src="../img/ods_stickers.jpg">
Открытый курс по машинному обучению. Сессия № 2
</center>
Автор материала
Step1: Считываем обучающую выборку.
Step2: Выкинем признак Cabin, а п... | Python Code:
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
%matplotlib inline
Explanation: <center>
<img src="../img/ods_stickers.jpg">
Открытый курс по машинному обучению. Сессия № 2
</center>
Автор материала: программист-исследователь Mail.ru Group, старший преподаватель... |
7,657 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Compute MxNE with time-frequency sparse prior
The TF-MxNE solver is a distributed inverse method (like dSPM or sLORETA)
that promotes focal (sparse) sources (such as dipole fitting technique... | Python Code:
# Author: Alexandre Gramfort <alexandre.gramfort@inria.fr>
# Daniel Strohmeier <daniel.strohmeier@tu-ilmenau.de>
#
# License: BSD-3-Clause
import numpy as np
import mne
from mne.datasets import sample
from mne.minimum_norm import make_inverse_operator, apply_inverse
from mne.inverse_sparse import t... |
7,658 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
This notebook investigates the test power vs. the number of test locations J in an incremental way. Specifically, we conjectured that the test power using $\mathcal{T}$, the set of $J$ locat... | Python Code:
%load_ext autoreload
%autoreload 2
%matplotlib inline
#%config InlineBackend.figure_format = 'svg'
#%config InlineBackend.figure_format = 'pdf'
import freqopttest.util as util
import freqopttest.data as data
import freqopttest.ex.exglobal as exglo
import freqopttest.kernel as kernel
import freqopttest.tst ... |
7,659 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
SQLAlchemy
What is it?
Object-Relational Mapper -- A technique that connects the objects of an application to tables in an RDB
multi-level -- can interact with DBs as multiple levels of abst... | Python Code:
import os,sys,getpass,datetime
from sqlalchemy import Column, ForeignKey, Integer, String, Float, DateTime
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
Base = declarative_base()
c... |
7,660 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Tecnologías NoSQL -- Tutorial en JISBD 2017
Toda la información de este tutorial está disponible en https
Step1: http
Step2: Creamos una base de datos presentations
Step3: Y la colección ... | Python Code:
%load extra/utils/functions.py
ds(1,2)
ds(3)
yoda(u"Una guerra SQL vs. NoSQL no debes empezar")
Explanation: Tecnologías NoSQL -- Tutorial en JISBD 2017
Toda la información de este tutorial está disponible en https://github.com/dsevilla/jisbd17-nosql.
Diego Sevilla Ruiz, dsevilla@um.es.
End of explanation
... |
7,661 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Simple RNN Encode-Decoder for Translation
Learning Objectives
1. Learn how to create a tf.data.Dataset for seq2seq problems
1. Learn how to train an encoder-decoder model in Keras
1. Learn h... | Python Code:
import os
import pickle
import sys
import nltk
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
import tensorflow as tf
from tensorflow.keras.layers import (
Dense,
Embedding,
GRU,
Input,
)
from tensorflow.keras.models import (
load_model,
... |
7,662 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Lab #0 - jupyter notebook autograder test
Copyright 2016 © document created by TeamLab.Gachon@gmail.com
Introduction
많이 달라긴 프로그래밍 환경에 놀란 것도 잠시, 첫 번째 Lab을 수행해보자. 첫 번째 랩은 전혀 어렵지 않다. 단지 Linux환경... | Python Code:
import gachon_autograder_client as g_autograder
EMAIL = "#YOUR_EMAIL"
PASSWORD = "#YOUR_PASSWORD"
ASSIGNMENT_NAME = "nb_test"
g_autograder.get_assignment(EMAIL, PASSWORD, ASSIGNMENT_NAME)
Explanation: Lab #0 - jupyter notebook autograder test
Copyright 2016 © document created by TeamLab.Gachon@gmail.com
In... |
7,663 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Interactive Image Processing with Numba and Bokeh
This demo shows off how interactive image processing can be done in the notebook, using Numba for numerics, Bokeh for plotting, and Ipython ... | Python Code:
from __future__ import print_function, division
from timeit import default_timer as timer
from bokeh.plotting import figure, show, output_notebook
from bokeh.models import GlyphRenderer, LinearColorMapper
from numba import jit, njit
from IPython.html.widgets import interact
import numpy as np
import scipy.... |
7,664 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Usage
Step1: Setting up the Pulsar object
enterprise uses a specific Pulsar object to store all of the relevant pulsar information (i.e. TOAs, residuals, error bars, flags, etc) from the ti... | Python Code:
% matplotlib inline
%config InlineBackend.figure_format = 'retina'
from __future__ import division
import numpy as np
import matplotlib.pyplot as plt
from enterprise.pulsar import Pulsar
import enterprise.signals.parameter as parameter
from enterprise.signals import utils
from enterprise.signals import sig... |
7,665 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Encoder-Decoder Analysis
Model Architecture
Step1: Perplexity on Each Dataset
Step2: Loss vs. Epoch
Step3: Perplexity vs. Epoch
Step4: Generations
Step5: BLEU Analysis
Step6: N-pairs B... | Python Code:
report_file = '/Users/bking/IdeaProjects/LanguageModelRNN/experiment_results/encdec_noing10_bow_200_512_04dra/encdec_noing10_bow_200_512_04dra.json'
log_file = '/Users/bking/IdeaProjects/LanguageModelRNN/experiment_results/encdec_noing10_bow_200_512_04dra/encdec_noing10_bow_200_512_04dra_logs.json'
import ... |
7,666 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<a href='http
Step1: Exploring the Format of the Data
Step2: Setting up Vocabulary of All Words
Step3: Vectorizing the Data
Step4:
Step5: Functionalize Vectorization
Step6: Creating t... | Python Code:
import pickle
import numpy as np
with open("train_qa.txt", "rb") as fp: # Unpickling
train_data = pickle.load(fp)
with open("test_qa.txt", "rb") as fp: # Unpickling
test_data = pickle.load(fp)
Explanation: <a href='http://www.pieriandata.com'> <img src='../Pierian_Data_Logo.png' /></a>
Questi... |
7,667 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Fitting Spatial Extension of IC443
This tutorial demonstrates how to perform a measurement of spatial extension with the extension method in the fermipy package. This tutorial assumes that ... | Python Code:
%matplotlib inline
import os
import matplotlib.pyplot as plt
import matplotlib
import numpy as np
from fermipy.gtanalysis import GTAnalysis
from fermipy.plotting import ROIPlotter
Explanation: Fitting Spatial Extension of IC443
This tutorial demonstrates how to perform a measurement of spatial extension wi... |
7,668 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Sensitivity of enrichment analysis to quality trimming
In this sheet we explore how trimming the gene-age data by various quality measures affects enrichment analysis of gene ontology and ot... | Python Code:
import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
%matplotlib inline
Explanation: Sensitivity of enrichment analysis to quality trimming
In this sheet we explore how trimming the gene-age data by various quality measures affects enrichment analysis of gene ontology and other terms... |
7,669 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Self-Driving Car Engineer Nanodegree
Deep Learning
Project
Step1: Step 1
Step2: Include an exploratory visualization of the dataset
Visualize the German Traffic Signs Dataset using the pic... | Python Code:
# Load pickled data
import pickle
# TODO: Fill this in based on where you saved the training and testing data
training_file = r'C:\Users\VINOD\Google Drive\SDCND\CarND-Traffic-Sign-Classifier-Project\pickled_data\train.p'
validation_file = r'C:\Users\VINOD\Google Drive\SDCND\CarND-Traffic-Sign-Classifier-P... |
7,670 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Introduction
The competition is to predict the highest future returns for stocks that are actually traded on the Japan Exchange Group, Inc.
In this notebook, we will work with jpx_tokyo_mark... | Python Code:
# check gpu env with torch
import torch
print(torch.__version__) # 查看torch当前版本号
print(torch.version.cuda) # 编译当前版本的torch使用的cuda版本号
print("is_cuda_available:", torch.cuda.is_available()) # 查看当前cuda是否可用于当前版本的Torch,如果输出
print('gpu count:', torch.cuda.device_count())
# 查看指定GPU的容量、名称
device = "cuda:0"
print(... |
7,671 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Machine Learning 101++ in Python
Created by
Step1: 2. Linear Regression
Linear Regression assumes a linear relationship between 2 variables.
As an example we'll consider the historical pag... | Python Code:
import numpy as np
import matplotlib.pyplot as plt
plt.rcParams["figure.figsize"] = (13.0, 8.0)
%matplotlib inline
import pickle
import sklearn
import sklearn.linear_model
import sklearn.preprocessing
import sklearn.gaussian_process
import sklearn.ensemble
Explanation: Machine Learning 101++ in Python
Crea... |
7,672 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Finite-Time Air-Fuel Otto Cycles in Python
Octane Cycle Example
Module import
After installing this module, it should import normally as
Step1: Case setup and solution
1. Engine
To setup a ... | Python Code:
import FTAF
FTAF.__version__
import math
import numpy
import matplotlib
import matplotlib.pylab as plt
%matplotlib inline
Explanation: Finite-Time Air-Fuel Otto Cycles in Python
Octane Cycle Example
Module import
After installing this module, it should import normally as:
End of explanation
# Reciprocating... |
7,673 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Estimating School Location Choice
This notebook illustrates how to re-estimate a single model component for ActivitySim. This process
includes running ActivitySim in estimation mode to rea... | Python Code:
import larch # !conda install larch #for estimation
import pandas as pd
import numpy as np
import yaml
import larch.util.excel
import os
Explanation: Estimating School Location Choice
This notebook illustrates how to re-estimate a single model component for ActivitySim. This process
includes running Ac... |
7,674 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
MNIST Dataset
Also known as digits if you're familiar with sklearn
Step1: Basic data analysis on the dataset
Step2: Display Images
Let's now display some of the images and see how they loo... | Python Code:
import numpy as np
import keras
from keras.datasets import mnist
# Load the datasets
(X_train, y_train), (X_test, y_test) = mnist.load_data()
Explanation: MNIST Dataset
Also known as digits if you're familiar with sklearn:
```python
from sklearn.datasets import digits
```
Problem Definition
Recognize handw... |
7,675 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
spaCy Tutorial
(C) 2019-2020 by Damir Cavar
Version
Step1: We can load the English NLP pipeline in the following way
Step2: Tokenization
Step3: Part-of-Speech Tagging
We can tokenize and ... | Python Code:
import spacy
Explanation: spaCy Tutorial
(C) 2019-2020 by Damir Cavar
Version: 1.4, February 2020
Download: This and various other Jupyter notebooks are available from my GitHub repo.
This is a tutorial related to the L665 course on Machine Learning for NLP focusing on Deep Learning, Spring 2018 at Indiana... |
7,676 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Linear Support Vector Machines
Classification Loss vs. Hinge Loss vs. Huberized Hinge Loss vs. Square Hinge Loss
Step1: Analytic Expressions
Let $X \in R^{n \times d+1}$ and $y = (y_1,...,y... | Python Code:
%matplotlib nbagg
import matplotlib.pyplot as plt
plt.clf()
plt.cla()
import numpy as np
ax = plt.subplot(1,1,1)
x_plot=np.linspace(-2,2,1000)
y_plot1=x_plot.copy()
y_plot1[x_plot < 0]=1
y_plot1[x_plot == 0]=0
y_plot1[x_plot > 0]=0
plot1 = ax.plot(x_plot,y_plot1, label='Classification Loss')
y_plot2=np.max... |
7,677 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
This is an iPython Notebook!
Step1: Basics
All you need to know about Python is here
Step2: You can assign several variables at once
Step3: There is no "begin-end"! You use indentation to... | Python Code:
# you can mix text and code in one place and
# run code from a Web browser
Explanation: This is an iPython Notebook!
End of explanation
a = 10
a
Explanation: Basics
All you need to know about Python is here:
You don't need to specify type of a variable
End of explanation
a, b = 1, 2
a, b
b, a = a, b
a, b
E... |
7,678 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Grove ADC Example
This example shows how to use the Grove ADC.
A Grove I2C ADC (v1.2) and PYNQ Grove Adapter are required. An analog input is also required. In this example, the Grove slide ... | Python Code:
from pynq.overlays.base import BaseOverlay
base = BaseOverlay("base.bit")
from pynq.lib.pmod import Grove_ADC
from pynq.lib.pmod import PMOD_GROVE_G4
grove_adc = Grove_ADC(base.PMODA,PMOD_GROVE_G4)
print("{} V".format(round(grove_adc.read(),4)))
Explanation: Grove ADC Example
This example shows how to use... |
7,679 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2020 The TensorFlow Authors.
Step1: Listwise ranking
<table class="tfo-notebook-buttons" align="left">
<td>
<a target="_blank" href="https
Step2: We can then import all the... | 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 writing, software
# dist... |
7,680 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
深入MNIST
TensorFlow是一个非常强大的用来做大规模数值计算的库。其所擅长的任务之一就是实现以及训练深度神经网络。
在本教程中,我们将学到构建一个TensorFlow模型的基本步骤,并将通过这些步骤为MNIST构建一个深度卷积神经网络。
这个教程假设你已经熟悉神经网络和MNIST数据集。如果你尚未了解,请查看新手指南。
关于本教程
本教程首先解释了mnist_sof... | Python Code:
import input_data
mnist = input_data.read_data_sets('MNIST_data', one_hot=True)
Explanation: 深入MNIST
TensorFlow是一个非常强大的用来做大规模数值计算的库。其所擅长的任务之一就是实现以及训练深度神经网络。
在本教程中,我们将学到构建一个TensorFlow模型的基本步骤,并将通过这些步骤为MNIST构建一个深度卷积神经网络。
这个教程假设你已经熟悉神经网络和MNIST数据集。如果你尚未了解,请查看新手指南。
关于本教程
本教程首先解释了mnist_softmax.py中的代码 —— 一个简单的Tens... |
7,681 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Rand 2011 Bayesian Analysis
This notebook outlines how to begin the duplication the analysis of the Rand et al. 2011 study "Dynamic social networks promote cooperation in experiments with hu... | Python Code:
from bedrock.client.client import BedrockAPI
Explanation: Rand 2011 Bayesian Analysis
This notebook outlines how to begin the duplication the analysis of the Rand et al. 2011 study "Dynamic social networks promote cooperation in experiments with humans" Link to Paper
This notebook focuses on using a Bayesi... |
7,682 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Title
Step1: Create Data
Step2: View Table
Step3: Delete Column
Step4: View Table | Python Code:
# Ignore
%load_ext sql
%sql sqlite://
%config SqlMagic.feedback = False
Explanation: Title: Add A Column
Slug: add_a_column
Summary: Add a column in a table in SQL.
Date: 2016-05-01 12:00
Category: SQL
Tags: Basics
Authors: Chris Albon
Note: This tutorial was written using Catherine Devlin's SQL in Jupy... |
7,683 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
TPOT tutorial on the Titanic dataset
The Titanic machine learning competition on Kaggle is one of the most popular beginner's competitions on the platform. We will use that competition here ... | Python Code:
# Import required libraries
from tpot import TPOTClassifier
from sklearn.model_selection import train_test_split
import pandas as pd
import numpy as np
# Load the data
titanic = pd.read_csv('data/titanic_train.csv')
titanic.head(5)
Explanation: TPOT tutorial on the Titanic dataset
The Titanic machine lear... |
7,684 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Audio using the Base Overlay
The PYNQ-Z1 board contains an integrated MIC, and line out connected to a 3.5mm jack. Both these interfaces are connected to the FPGA fabric of the Zynq® chip. T... | Python Code:
from pynq.drivers import Audio
audio = Audio()
Explanation: Audio using the Base Overlay
The PYNQ-Z1 board contains an integrated MIC, and line out connected to a 3.5mm jack. Both these interfaces are connected to the FPGA fabric of the Zynq® chip. The Microphone has a PDM interface, and the line out is a ... |
7,685 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: MarkDown input
WARNING
Step2: Create HTML document
Save notebook before creating doc
Make sure to update the notebook name if necessary
selected_cells is the list of cells that will ... | Python Code:
# path_img1 = 'data/svgclock.svg'
# path_img2 = 'data/example2.jpg'
# path_img3 = 'data/example4.png'
path_img1 = 'http://upload.wikimedia.org/wikipedia/commons/f/fd/Ghostscript_Tiger.svg'
path_img2 = 'http://upload.wikimedia.org/wikipedia/commons/thumb/3/3e/Einstein_1921_by_F_Schmutzer_-_restoration.jpg/2... |
7,686 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Compute source power using DICS beamfomer
Compute a Dynamic Imaging of Coherent Sources (DICS) filter from single trial
activity to estimate source power for two frequencies of interest.
The... | Python Code:
# Author: Roman Goj <roman.goj@gmail.com>
# Denis Engemann <denis.engemann@gmail.com>
#
# License: BSD (3-clause)
import mne
from mne.datasets import sample
from mne.time_frequency import compute_epochs_csd
from mne.beamformer import dics_source_power
print(__doc__)
data_path = sample.data_path()
r... |
7,687 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
The following is adapted from Visualizing TensorFlow Graphs in Jupyter Notebooks
And excuted in
bash
docker run -it -p 8888
Step1: Run the follwing
Step2:
Step3:
Step8:
Step9: The fo... | Python Code:
import tensorflow as tf
g = tf.Graph()
with g.as_default():
a = tf.placeholder(tf.float32, name="a")
b = tf.placeholder(tf.float32, name="b")
c = a + b
[node.name for node in g.as_graph_def().node]
g.as_graph_def().node[2].input
%%bash
export DEBIAN_FRONTEND=noninteractive
apt-get update
apt-ge... |
7,688 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
2
Step1: 3
Step2: 4
Step3: 5
Step4: 7
Step5: 8
Step6: 9
Step7: 10 | Python Code:
# The story is stored in the file "story.txt".
f = open("story.txt", "r")
story = f.read()
print(story)
Explanation: 2: Reading the file in
Instructions
The story is stored in the "story.txt" file. Open the file and read the contents into the story variable.
Answer
End of explanation
# We can split strings... |
7,689 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
TOC Thematic Report - February 2019 (Part 2
Step1: 2. Calculate annual trends
Step2: 1. 1990 to 2016
Step3: There are lots of warnings printed above, but the main one of interest is
Step4... | Python Code:
# Select projects
prj_grid = nivapy.da.select_resa_projects(eng)
prj_grid
prj_df = prj_grid.get_selected_df()
print (len(prj_df))
prj_df
# Get stations
stn_df = nivapy.da.select_resa_project_stations(prj_df, eng)
print(len(stn_df))
stn_df.head()
# Map
nivapy.spatial.quickmap(stn_df, popup='station_code')
E... |
7,690 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Spatial Data Processing with PySAL & Pandas
PySAL has two simple ways to read in data. But, first, you need to get the path from where your notebook is running on your computer to the place ... | Python Code:
!pwd
Explanation: Spatial Data Processing with PySAL & Pandas
PySAL has two simple ways to read in data. But, first, you need to get the path from where your notebook is running on your computer to the place the data is. For example, to find where the notebook is running:
End of explanation
dbf_path = ps.e... |
7,691 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
26 May 2016
I trained a simple fp_linear network (FingerprintLayer -> Linear Regression) to learn how to count the sum of all of the nodes. This was a sanity check before progressing further... | Python Code:
import pickle as pkl
from pprint import pprint
def open_wb(path):
with open(path, 'rb') as f:
wb = pkl.load(f)
return wb
wb = open_wb('../experiments/wbs/fp_linear-cf.score_sum-5000_iters-10_wb.pkl')
pprint(wb)
Explanation: 26 May 2016
I trained a simple fp_linear network (FingerprintL... |
7,692 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Report04 - Nathan Yee
This notebook contains report04 for computational baysian statistics fall 2016
MIT License
Step1: Parking meter theft
From DASL(http
Step2: Next, we need to normalize... | Python Code:
from __future__ import print_function, division
% matplotlib inline
import warnings
warnings.filterwarnings('ignore')
import math
import numpy as np
from thinkbayes2 import Pmf, Cdf, Suite, Joint, EvalNormalPdf, MakeNormalPmf, MakeMixture
import thinkplot
import matplotlib.pyplot as plt
import pandas as pd... |
7,693 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Pipeline Tutorial with HeteroSecureBoost
install
Pipeline is distributed along with fate_client.
bash
pip install fate_client
To use Pipeline, we need to first specify which FATE Flow Servic... | Python Code:
!pipeline --help
Explanation: Pipeline Tutorial with HeteroSecureBoost
install
Pipeline is distributed along with fate_client.
bash
pip install fate_client
To use Pipeline, we need to first specify which FATE Flow Service to connect to. Once fate_client installed, one can find an cmd enterpoint name pipeli... |
7,694 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Interact Exercise 01
Import
Step1: Interact basics
Write a print_sum function that prints the sum of its arguments a and b.
Step2: Use the interact function to interact with the print_sum ... | 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 01
Import
End of explanation
def print_sum(a=0.0, b=0):
print(a+b)
Explanation: Interact basics
Wri... |
7,695 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Required inputs for Akita are
Step1: Download a few Micro-C datasets, processed using distiller (https
Step2: Write out these cooler files and labels to a samples table.
Step3: Next, we w... | Python Code:
import json
import os
import shutil
import subprocess
if not os.path.isfile('./data/hg38.ml.fa'):
print('downloading hg38.ml.fa')
subprocess.call('curl -o ./data/hg38.ml.fa.gz https://storage.googleapis.com/basenji_barnyard/hg38.ml.fa.gz', shell=True)
subprocess.call('gunzip ./data/hg38.ml.fa.g... |
7,696 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Analysis of neonatal ventilator alarms
Author
Step1: Import modules containing own functions
Step2: List and set the working directory and the directories to write out data
Step3: List of... | Python Code:
import IPython
import pandas as pd
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
import os
import sys
import pickle
import scipy as sp
from scipy import stats
from pandas import Series, DataFrame
from datetime import datetime, timedelta
%matplotlib inline
matplotlib.style.use('classi... |
7,697 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Linear time series analysis - AR/MA models
Lorenzo Biasi (3529646), Julius Vernie (3502879)
Task 1. AR(p) models.
1.1
Step1: We can see that simulating the data as an AR(1) model is not eff... | Python Code:
import numpy as np
import matplotlib.pyplot as plt
import scipy.io as sio
from sklearn import datasets, linear_model
%matplotlib inline
def set_data(p, x):
temp = x.flatten()
n = len(temp[p:])
x_T = temp[p:].reshape((n, 1))
X_p = np.ones((n, p + 1))
for i in range(1, p + 1):
X_p... |
7,698 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Zpracování rotačních spekter $N_2(C\,^3\Pi_g\rightarrow B\,^3\Pi_u)$
V atmosférických výbojích často pozorujeme záření molekuly dusíky v důsledku přechodu $N_2(C\,^3\Pi_g\rightarrow B\,^3\Pi... | Python Code:
#kod v teto bunce neni soucasti lekce,
#presto ho ale netajime
import massiveOES
import matplotlib.pyplot as plt
%matplotlib inline
from matplotlib import colors as mcolors
colors = dict(mcolors.BASE_COLORS, **mcolors.CSS4_COLORS)
N2 = massiveOES.SpecDB('N2CB.db')
spec_cold = N2.get_spectrum(Trot=300, Tvib... |
7,699 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
By default Prophet fits additive seasonalities, meaning the effect of the seasonality is added to the trend to get the forecast. This time series of the number of air passengers is an exampl... | Python Code:
%%R -w 10 -h 6 -u in
df <- read.csv('../examples/example_air_passengers.csv')
m <- prophet(df)
future <- make_future_dataframe(m, 50, freq = 'm')
forecast <- predict(m, future)
plot(m, forecast)
df = pd.read_csv('../examples/example_air_passengers.csv')
m = Prophet()
m.fit(df)
future = m.make_future_datafr... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.