Unnamed: 0 int64 0 16k | text_prompt stringlengths 110 62.1k | code_prompt stringlengths 37 152k |
|---|---|---|
3,900 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
This notebook is intended to show how to use pandas, and sql alchemy to upload data into DB2-switch.
Install using pip or any other package manager pandas, sqlalchemy and pg8000. The later o... | Python Code:
import pandas as pd
from sqlalchemy import create_engine
Explanation: This notebook is intended to show how to use pandas, and sql alchemy to upload data into DB2-switch.
Install using pip or any other package manager pandas, sqlalchemy and pg8000. The later one is the driver to connect to the db.
End of e... |
3,901 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Matrix Factorization via Singular Value Decomposition
Matrix factorization is the breaking down of one matrix in a product of multiple matrices. It's extremely well studied in mathematics, a... | Python Code:
import pandas as pd
import numpy as np
r_cols = ['user_id', 'movie_id', 'rating']
m_cols = ['movie_id', 'title', 'genres']
ratings_df = pd.read_csv('ratings.dat',sep='::', names=r_cols, engine='python', usecols=range(3), dtype = int)
movies_df = pd.read_csv('movies.dat', sep='::', names=m_cols, engine='pyt... |
3,902 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
In this notebook I´ll create functions for easing the development of geostatistical models using the GPFlow (James H, et.al )the library for modelling gaussian processes in Tensor Flow (Goog... | Python Code:
run ../../../../traversals/tests.py
Explanation: In this notebook I´ll create functions for easing the development of geostatistical models using the GPFlow (James H, et.al )the library for modelling gaussian processes in Tensor Flow (Google) (Great Library, btw).
Requirements
Inputs
Design Matrix X compos... |
3,903 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Evaluation of a force sensor
Andrés Marrugo, PhD
Universidad Tecnológica de Bolívar
A force sensor (FSR) is evaluated experimentally. To do so, the resistance of the sensor is measured fo... | Python Code:
import matplotlib.pyplot as plt
import numpy as np
%matplotlib inline
F = np.array([50,100,150,200,250,300,350,400,450,500,550,600,650])
R = np.array([500,256.4,169.5,144.9,125,100,95.2,78.1,71.4,65.8,59.9,60,55.9])
plt.plot(R,F,'*')
plt.ylabel('R [Omega]')
plt.xlabel('Force [N]')
plt.show()
Explanation: E... |
3,904 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Anyway, under a gigabyte. So, nothing to worry about even if we have 24 cores.
Step1: Interesting... the S&P 500 ETF
Step2: Doing some compute
We'll use a "big" table to get some sense of ... | Python Code:
# But what symbol is that?
max_sym = None
max_rows = 0
for sym, rows in rec_counts.items():
if rows > max_rows:
max_rows = rows
max_sym = sym
max_sym, max_rows
Explanation: Anyway, under a gigabyte. So, nothing to worry about even if we have 24 cores.
End of explanation
# Most symbols a... |
3,905 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Symbulate Documentation
Markov Processes
<a id='mc'></a>
Random processes are typically collections of dependent random variables, but allowing arbitrary associations between values at diffe... | Python Code:
from symbulate import *
%matplotlib inline
Explanation: Symbulate Documentation
Markov Processes
<a id='mc'></a>
Random processes are typically collections of dependent random variables, but allowing arbitrary associations between values at different points in time makes analysis intractable. Markov proce... |
3,906 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Building an RNN in PyTorch
In this notebook, I'll construct a character-level RNN with PyTorch. If you are unfamiliar with character-level RNNs, check out this great article by Andrej Karpat... | Python Code:
import numpy as np
import torch
from torch import nn
import torch.nn.functional as F
from torch.autograd import Variable
with open('anna.txt', 'r') as f:
text = f.read()
Explanation: Building an RNN in PyTorch
In this notebook, I'll construct a character-level RNN with PyTorch. If you are unfamiliar wi... |
3,907 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2019 The TensorFlow Authors.
Step1: Save and load a model using a distribution strategy
<table class="tfo-notebook-buttons" align="left">
<td>
<a target="_blank" href="https... | 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... |
3,908 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Histogram
By Evgenia "Jenny" Nitishinskaya and Delaney Granizo-Mackenzie
Notebook released under the Creative Commons Attribution 4.0 License.
A histogram displays a frequency distribution u... | Python Code:
import numpy as np
import matplotlib.pyplot as plt
# Get returns data for S&P 500
start = '2014-01-01'
end = '2015-01-01'
spy = get_pricing('SPY', fields='price', start_date=start, end_date=end).pct_change()[1:]
# Plot a histogram using 20 bins
fig = plt.figure(figsize = (16, 7))
_, bins, _ = plt.hist(spy,... |
3,909 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Text retrieval
This guide will introduce techniques for organizing text data. It will show how to analyze a large corpus of text, extracting feature vectors for individual documents, in orde... | Python Code:
import os
Explanation: Text retrieval
This guide will introduce techniques for organizing text data. It will show how to analyze a large corpus of text, extracting feature vectors for individual documents, in order to be able to retrieve documents with similar content.
scipy and scikit-learn are required t... |
3,910 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Likelihood Analysis with Python
The python likelihood tools are a very powerful set of analysis tools that expand upon the command line tools provided with the Fermi Science Tools package. N... | Python Code:
!mkdir working
import urllib
url_base = "https://fermi.gsfc.nasa.gov/ssc/data/analysis/scitools/data/pyLikelihood/"
datafiles = ["L1504241622054B65347F25_PH00.fits",
"L1504241622054B65347F25_PH01.fits",
"L1504241622054B65347F25_SC00.fits",]
for datafile in datafiles:
urllib.u... |
3,911 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
1. Análise de Sentimentos
1. Objetivo
O objetivo da análise de sentimentos e classificação de textos é determinar o valor subjetivo de um documento de texto. Aqui trabalharemos apenas com um... | Python Code:
import pandas
imdb = pandas.read_csv('data/imdb_labelled.txt', sep="\t", names=["sentences", "polarity"])
yelp = pandas.read_csv('data/yelp_labelled.txt', sep="\t", names=["sentences", "polarity"])
amazon = pandas.read_csv('data/amazon_cells_labelled.txt', sep="\t", names=["sentences", "polarity"])
big = p... |
3,912 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Load Data
Step1: The CIFAR-10 data-set is about 163 MB and will be downloaded automatically if it is not located in the given path.
Step2: Load the class-names.
Step3: Load the training-s... | Python Code:
import cifar10
Explanation: Load Data
End of explanation
cifar10.maybe_download_and_extract()
Explanation: The CIFAR-10 data-set is about 163 MB and will be downloaded automatically if it is not located in the given path.
End of explanation
class_names = cifar10.load_class_names()
class_names
Explanation: ... |
3,913 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Generate a synthetic 1PL/2PL IRT model and sample an interaction history from it
Step1: Verify that models.OneParameterLogisticModel can recover parameters. We would only expect this to be ... | Python Code:
num_students = 2000
num_assessments = 3000
num_ixns_per_student = 1000
USING_2PL = False # False => using 1PL
proficiencies = np.random.normal(0, 1, num_students)
difficulties = np.random.normal(0, 1, num_assessments)
if USING_2PL:
discriminabilities = np.random.normal(0, 1, num_assessments)
else:
... |
3,914 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Accuracy vs Mag DEIMOS Spec Test Set
In this notebook we examine the accuracy as a function of magnitude for sources with spectroscopic classifications from DEIMOS COSMOS survey. The DEIMOS ... | Python Code:
import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
%matplotlib inline
_df = pd.read_table('DEIMOS/deimos_10K_March2018/deimos.tbl', header=None)
arr = np.empty((len(_df), len(_df.iloc[0][0].split())), dtype='<U50')
for i in range(len(_df)):
i_row = [k for k in _df.iloc[i][0].s... |
3,915 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Deep Inverse Regression with Yelp reviews
In this note we'll use gensim to turn the Word2Vec machinery into a document classifier, as in Document Classification by Inversion of Distributed L... | Python Code:
# ### uncomment below if you want...
# ## ... copious amounts of logging info
# import logging
# logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)
# rootLogger = logging.getLogger()
# rootLogger.setLevel(logging.INFO)
# ## ... or auto-reload of gensim during develo... |
3,916 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
CMSIS-DSP Python package example
Installing and importing the needed packages
The following command may take some time to execute
Step1: Creating the signal
Conversion functions to use CMS... | Python Code:
!pip install cmsisdsp
import numpy as np
import cmsisdsp as dsp
import cmsisdsp.fixedpoint as f
import matplotlib.pyplot as plt
from ipywidgets import interact, interactive, fixed, interact_manual,FloatSlider
import ipywidgets as widgets
Explanation: CMSIS-DSP Python package example
Installing and importin... |
3,917 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Flow Distribution for the Two Treatment Trains
Problem Definition
The two 60 L/s trains need proper flow control. They need a flow control system to split the plant flow evenly between the t... | Python Code:
from aide_design.play import *
from IPython.display import display
pipe.ID_sch40 = np.vectorize(pipe.ID_sch40)
pipe.ID_sch40 = np.vectorize(pipe.ID_sch40)
################## Constants #################
flow_branch = 60 *u.L/u.s
flow_full = flow_branch * 2
nd_pipe_train_4 = 4 *u.inch
sdr_pipe =... |
3,918 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
mpl_toolkits
In addition to the core library of matplotlib, there are a few additional utilities that are set apart from matplotlib proper for some reason or another, but are often shipped w... | Python Code:
from mpl_toolkits.mplot3d import Axes3D, axes3d
fig, ax = plt.subplots(1, 1, subplot_kw={'projection': '3d'})
X, Y, Z = axes3d.get_test_data(0.05)
ax.plot_wireframe(X, Y, Z, rstride=10, cstride=10)
plt.show()
Explanation: mpl_toolkits
In addition to the core library of matplotlib, there are a few additiona... |
3,919 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Fish detection
In this notebook we address the problem of detecting and cropping the fishes from the data images. This is a problem of computer vision that has no easy solution. We considere... | Python Code:
import os
import glob
import time
from SimpleCV import *
import scipy
import numpy as np
import tensorflow as tf
import collections
import matplotlib.pyplot as plt
import cv2
import imutils
from skimage.transform import pyramid_gaussian
import argparse
import cv2
from scipy import ndimage
from scipy.ndimag... |
3,920 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Defining inputs
Need to define some heterogenous factors of production...
Step1: Note that we are shifting the distributions of worker skill and firm productivity to the right by 1.0 in ord... | Python Code:
# define some workers skill
x, loc1, mu1, sigma1 = sym.var('x, loc1, mu1, sigma1')
skill_cdf = 0.5 + 0.5 * sym.erf((sym.log(x - loc1) - mu1) / sym.sqrt(2 * sigma1**2))
skill_params = {'loc1': 1e0, 'mu1': 0.0, 'sigma1': 1.0}
workers = pyam.Input(var=x,
cdf=skill_cdf,
... |
3,921 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step2: OT for image color adaptation
This example presents a way of transferring colors between two image
with Optimal Transport as introduced in [6]
[6] Ferradans, S., Papadakis, N., Peyre,... | Python Code:
# Authors: Remi Flamary <remi.flamary@unice.fr>
# Stanislas Chambon <stan.chambon@gmail.com>
#
# License: MIT License
import numpy as np
from scipy import ndimage
import matplotlib.pylab as pl
import ot
r = np.random.RandomState(42)
def im2mat(I):
Converts and image to matrix (one pixel per li... |
3,922 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Ch. 6 - Minibatch Gradient Descent
Before you head of into the challenge, there is one more topic we need to cover
Step1: Now we will generate a dataset with 10,000 examples. This should be... | Python Code:
# Package imports
# Matplotlib is a matlab like plotting library
import matplotlib
import matplotlib.pyplot as plt
# Numpy handles matrix operations
import numpy as np
# SciKitLearn is a useful machine learning utilities library
import sklearn
# The sklearn dataset module helps generating datasets
import s... |
3,923 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Homework 10 Key
CHE 116
Step1: The $p$-value is 0.46, so the data is likely normal
2.2 Answer
The null hypothesis is that $\hat{\alpha} = 0$. Since we're testing against the null hpyothesis... | Python Code:
import scipy.stats as ss
ss.shapiro([-26.6,-24.0, -20.9, -25.8, -24.3, -22.6, -23.0, -26.8, -26.5, -23.6, -20.0, -23.1, -22.4, -22.5])
Explanation: Homework 10 Key
CHE 116: Numerical Methods and Statistics
Prof. Andrew White
Version 1 (3/30/2016)
0. Revise a Problem (15 Bonus Points on HW 7)
Revist a probl... |
3,924 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Logit Transform and Normalize Methylation Data
Step1: Prepare Data for Association Tests
The association tests take a while to run in serial so we do them in a map-reduce type format
The ... | Python Code:
df = df_hiv.ix[:, pred_c.index]
dd = logit_adj(df)
m = dd.ix[:, ti(duration == 'Control')].mean(1)
s = dd.ix[:, ti(duration == 'Control')].std(1)
df_norm = dd.subtract(m, axis=0).divide(s, axis=0)
df_norm = df_norm.clip(-7,7)
df_norm.shape
Explanation: Logit Transform and Normalize Methylation Data
End of ... |
3,925 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: This notebook gives intuition about the basics of Bayesian inference. This first example is borrowed from Cam Davidson-Pilon's online book, Probabilistic Programming & Bayesian Method... | Python Code:
%matplotlib inline
from IPython.core.pylabtools import figsize
import numpy as np
import numpy
from matplotlib import pyplot as plt
figsize(11, 9)
import scipy.stats as stats
dist = stats.beta
n_trials = [0, 1, 2, 3, 4, 5, 8, 15, 50, 500]
data = stats.bernoulli.rvs(0.5, size=n_trials[-1])
x = np.linspace(0... |
3,926 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
A simple example of generating playlist by multilable learning
Step1: Data loading
Load playlists.
Step2: Load song_id --> track_id mapping
Step3: Load song tags, build track_id --> tag m... | Python Code:
%matplotlib inline
import os, sys, time
import pickle as pkl
import numpy as np
import pandas as pd
import sklearn as sk
from sklearn.linear_model import LogisticRegression
import matplotlib.pyplot as plt
import seaborn as sns
data_dir = 'data'
faotm = os.path.join(data_dir, 'aotm-2011/aotm-2011-subset.pkl... |
3,927 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: Image Captioning with RNNs
In this exercise you will implement a vanilla recurrent neural networks and use them it to train a model that can generate novel captions for images.
Step2:... | Python Code:
# As usual, a bit of setup
from __future__ import print_function
import time, os, json
import numpy as np
import matplotlib.pyplot as plt
from cs231n.gradient_check import eval_numerical_gradient, eval_numerical_gradient_array
from cs231n.rnn_layers import *
from cs231n.captioning_solver import CaptioningS... |
3,928 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
EXP 2-HighOrder
In this experiment we generate 1000 high-order sequences each comprising 10 SDRs. The process of generating these sequences is as follows
Step1: Feed sequences to the TM
Ste... | Python Code:
import numpy as np
import random
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from nupic.bindings.algorithms import TemporalMemory as TM
from htmresearch.support.neural_correlations_utils import *
uintType = "uint32"
random.seed(1)
symbolsPerSequence = 10
numSequences = 1000... |
3,929 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Scale heights for typical atmospheric soundings
Plot McClatchey's US Standard Atmospheres
There are five different average profiles for the tropics, subarctic summer, subarctic winter, midla... | Python Code:
from matplotlib import pyplot as plt
import matplotlib.ticker as ticks
import urllib
import numpy as np
from a301utils.a301_readfile import download
import h5py
filename='std_soundings.h5'
download(filename)
Explanation: Scale heights for typical atmospheric soundings
Plot McClatchey's US Standard Atmosphe... |
3,930 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<center>
<h1> ILI286 - Computación Científica II </h1>
<h2> Ecuaciones Diferenciales Parciales
Step1: <div id='intro' />
Introducción
En el siguiente notebook se estudia la resoluc... | Python Code:
import numpy as np
from mpl_toolkits.mplot3d import axes3d
from matplotlib import pyplot as plt
from ipywidgets import interact
from ipywidgets import IntSlider
import sympy as sym
import matplotlib as mpl
mpl.rcParams['font.size'] = 14
mpl.rcParams['axes.labelsize'] = 20
mpl.rcParams['xtick.labelsize'] = ... |
3,931 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<a href="https
Step1: FlatMap
<script type="text/javascript">
localStorage.setItem('language', 'language-py')
</script>
<table align="left" style="margin-right
Step2: Examples
In the follo... | Python Code:
#@title Licensed under the Apache License, Version 2.0 (the "License")
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this fi... |
3,932 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Comparing Spots in PHOEBE 2 vs PHOEBE Legacy
Setup
Let's first make sure we have the latest version of PHOEBE 2.2 installed. (You can comment out this line if you don't use pip for your inst... | Python Code:
!pip install -I "phoebe>=2.2,<2.3"
Explanation: Comparing Spots in PHOEBE 2 vs PHOEBE Legacy
Setup
Let's first make sure we have the latest version of PHOEBE 2.2 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 expla... |
3,933 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Getting started with mpl-probscale
Installation
mpl-probscale is developed on Python 3.6. It is also tested on Python 3.4, 3.5, and even 2.7 (for the time being).
From conda
Official release... | Python Code:
%matplotlib inline
import warnings
warnings.simplefilter('ignore')
import numpy
from matplotlib import pyplot
from scipy import stats
import seaborn
clear_bkgd = {'axes.facecolor':'none', 'figure.facecolor':'none'}
seaborn.set(style='ticks', context='talk', color_codes=True, rc=clear_bkgd)
Explanation: Get... |
3,934 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2020 The TensorFlow Authors.
Step1: Effective Tensorflow 2
<table class="tfo-notebook-buttons" align="left">
<td>
<a target="_blank" href="https
Step2: Recommendations for ... | 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... |
3,935 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Avengers Data
You can also see this notebook rendered on github
Step1: Filter out the bad years
Since the data was collected from a community site, where most of the contributions came from... | Python Code:
import pandas as pd
avengers = pd.read_csv("avengers.csv")
avengers.head(5)
Explanation: Avengers Data
You can also see this notebook rendered on github: https://github.com/eggie5/ipython-notebooks/blob/master/avengers/Avengers.ipynb
Life and Death of the Avengers
The Avengers are a well-known and widely l... |
3,936 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Generate a left cerebellum volume source space
Generate a volume source space of the left cerebellum and plot its vertices
relative to the left cortical surface source space and the FreeSurf... | Python Code:
# Author: Alan Leggitt <alan.leggitt@ucsf.edu>
#
# License: BSD (3-clause)
import mne
from mne import setup_source_space, setup_volume_source_space
from mne.datasets import sample
print(__doc__)
data_path = sample.data_path()
subjects_dir = data_path + '/subjects'
subject = 'sample'
aseg_fname = subjects_d... |
3,937 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Head model and forward computation
The aim of this tutorial is to be a getting started for forward computation.
For more extensive details and presentation of the general concepts for forwar... | Python Code:
import os.path as op
import mne
from mne.datasets import sample
data_path = sample.data_path()
# the raw file containing the channel location + types
sample_dir = op.join(data_path, 'MEG', 'sample',)
raw_fname = op.join(sample_dir, 'sample_audvis_raw.fif')
# The paths to Freesurfer reconstructions
subjects... |
3,938 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<center>
<h1> Scientific Programming in Python </h1>
<h2> Topic 4
Step4: En esta actividad implementaremos una conocida métrica para medir disimilitud entre conjuntos
Step8: Paso ... | Python Code:
import numba
import numpy as np
import numexpr as ne
import matplotlib.pyplot as plt
Explanation: <center>
<h1> Scientific Programming in Python </h1>
<h2> Topic 4: Just in Time Compilation: Numba and NumExpr </h2>
</center>
Notebook created by Martín Villanueva - martin.villanueva@usm.cl - DI UT... |
3,939 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Persistent homology
This demo explains how to use Dionysus for persistent homology computation. First necessary imports.
Step1: We will compute persistent homology of a 2-simplex (triangle)... | Python Code:
from dionysus import Simplex, Filtration, StaticPersistence, \
vertex_cmp, data_cmp, data_dim_cmp, \
DynamicPersistenceChains
from math import sqrt
Explanation: Persistent homology
This demo explains how to use Dionysus for persistent homology computation. First ne... |
3,940 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Time the functions
This notebooks measures the runtime of each functionality.
Step1: Binarization
Step2: Binary detection
Step3: MSER detection
Step4: Conclusion
The tophat operation (fo... | Python Code:
import numpy as np
import cv2
import sys
import os
sys.path.insert(0, os.path.abspath('..'))
import salientregions as sr
import cProfile
%pylab inline
#Load the image
path_to_image = 'images/graffiti.jpg'
img = cv2.imread(path_to_image)
sr.show_image(img)
%%timeit
#Time: creation of the detector
det = sr.S... |
3,941 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Lesson 1
Create Data - We begin by creating our own data set for analysis. This prevents the end user reading this tutorial from having to download any files to replicate the results below. ... | Python Code:
# Import all libraries needed for the tutorial
# General syntax to import specific functions in a library:
##from (library) import (specific library function)
from pandas import DataFrame, read_csv
# General syntax to import a library but no functions:
##import (library) as (give the library a nickname/a... |
3,942 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
AveragePooling1D
[pooling.AveragePooling1D.0] input 6x6, pool_size=2, strides=None, padding='valid'
Step1: [pooling.AveragePooling1D.1] input 6x6, pool_size=2, strides=1, padding='valid'
St... | Python Code:
data_in_shape = (6, 6)
L = AveragePooling1D(pool_size=2, strides=None, padding='valid')
layer_0 = Input(shape=data_in_shape)
layer_1 = L(layer_0)
model = Model(inputs=layer_0, outputs=layer_1)
# set weights to random (use seed for reproducibility)
np.random.seed(250)
data_in = 2 * np.random.random(data_in_... |
3,943 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Keras for Text Classification
Learning Objectives
Learn how to create a text classification datasets using BigQuery.
Learn how to tokenize and integerize a corpus of text for training in Ker... | Python Code:
import os
from google.cloud import bigquery
import pandas as pd
%load_ext google.cloud.bigquery
Explanation: Keras for Text Classification
Learning Objectives
Learn how to create a text classification datasets using BigQuery.
Learn how to tokenize and integerize a corpus of text for training in Keras.
Lear... |
3,944 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2020 The TensorFlow Authors.
Step1: Text generation with an RNN
<table class="tfo-notebook-buttons" align="left">
<td>
<a target="_blank" href="https
Step2: Download the Sh... | 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... |
3,945 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
ES-DOC CMIP6 Model Properties - Seaice
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', 'awi', 'awi-cm-1-0-hr', 'seaice')
Explanation: ES-DOC CMIP6 Model Properties - Seaice
MIP Era: CMIP6
Institute: AWI
Source ID: AWI-CM-1-0-HR
Topic: Seaice
Sub-Topics: Dynamics, Thermod... |
3,946 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
[WIP] From Climatology Test to Anomaly Detection
Objective
Step1: Synthetic data
Let's create some synthetic data to illustrate some concepts.
Step3: How does this dataset look like?
Step4... | Python Code:
from bokeh.io import output_notebook, show
from bokeh.plotting import figure
import numpy as np
from scipy import stats
import cotede
output_notebook()
Explanation: [WIP] From Climatology Test to Anomaly Detection
Objective:
Explain the concept of the Anomaly Detection approach to quality control
Create a ... |
3,947 | 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... |
3,948 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Precursors
Step1: SNP activity difference compute
Analyzing noncoding variation associated with disease is a major application of Basenji. I now offer several tools to enable that analysis.... | Python Code:
if not os.path.isfile('data/hg19.ml.fa'):
subprocess.call('curl -o data/hg19.ml.fa https://storage.googleapis.com/basenji_tutorial_data/hg19.ml.fa', shell=True)
subprocess.call('curl -o data/hg19.ml.fa.fai https://storage.googleapis.com/basenji_tutorial_data/hg19.ml.fa.fai', shell=True) ... |
3,949 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Hello World!
Un-attributed images in the presentation are author's own creation. To use them, check the attributions here
Step1: Hmm.. DFs look similar to SQL Tables, don't they?
<span styl... | Python Code:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
#so that we can view the graphs inside the notebook
df = pd.read_csv("wine.csv")
df.head(3)
Explanation: Hello World!
Un-attributed images in the presentation are author's own creation. To use them, check the attri... |
3,950 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Procedural Python and Unit Tests
In this section, our main goal will be to outline how to go from the kind of trial-and-error exploratory data analysis we explored this morning, into a nice,... | Python Code:
import this
Explanation: Procedural Python and Unit Tests
In this section, our main goal will be to outline how to go from the kind of trial-and-error exploratory data analysis we explored this morning, into a nice, linear, reproducible analysis.
End of explanation
URL = "https://s3.amazonaws.com/pronto-da... |
3,951 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
PMOD TC1 Sensor demonstration
This demonstration shows how to use the PmodTC1. You will also see how to plot a graph using matplotlib.
The PmodTC1 is required.
The thermocouple sensor is ini... | Python Code:
from pynq import Overlay
Overlay("base.bit").download()
from pynq.iop import Pmod_TC1
from pynq.iop import PMODB
# TC1 sensor is on PMODB
my_tc1 = Pmod_TC1(PMODB)
r = my_tc1.read()
print('Raw Register Value: %08x hex' % r)
print('Ref Junction Temp: %.4f' % my_tc1.reg_to_ref(r))
print('Thermocouple Temp: ... |
3,952 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
sPlot
This notebook is devoted to explanation what is sPlot and how to use hep_ml.splot.
If you prefer explanation without code, find it here
sPlot is a way to reconstruct features of mixtur... | Python Code:
%matplotlib inline
import numpy
from matplotlib import pyplot as plt
plt.rcParams['figure.figsize'] = [15, 6]
size = 10000
sig_data = numpy.random.normal(-1, 1, size=size)
bck_data = numpy.random.normal(1, 1, size=size)
Explanation: sPlot
This notebook is devoted to explanation what is sPlot and how to use... |
3,953 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Sumário
Funções de Ativação
Funções Auxiliares
Funções de Custo
Inicialização de Pesos
Regularização
Learning Rate Decay
Batch Normalization
Batch Generator
Implementação
Testes da Implement... | Python Code:
import numpy as np
import _pickle as pkl
import matplotlib.pyplot as plt
from sklearn.datasets import load_iris
from sklearn.datasets.samples_generator import make_blobs, make_circles, make_moons, make_classification
from sklearn.metrics import accuracy_score
from sklearn.preprocessing import MinMaxScaler,... |
3,954 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Notebook arguments
measurement_id (int)
Step1: Selecting a data file
Step2: Data load and Burst search
Load and process the data
Step3: Compute background and burst search
Step4: Let's t... | Python Code:
import time
from pathlib import Path
import pandas as pd
from scipy.stats import linregress
from scipy import optimize
from IPython.display import display
from fretbursts import *
sns = init_notebook(fs=14)
import lmfit; lmfit.__version__
import phconvert; phconvert.__version__
Explanation: Notebook argume... |
3,955 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<p><font size="6"><b>CASE - Observation data</b></font></p>
© 2021, Joris Van den Bossche and Stijn Van Hoey (jorisvandenbo... | Python Code:
%matplotlib inline
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
plt.style.use('seaborn-whitegrid')
Explanation: <p><font size="6"><b>CASE - Observation data</b></font></p>
© 2021, Joris Van den Bossche and Stijn Van Hoey (jorisv... |
3,956 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Executing Code
In this notebook we'll look at some of the issues surrounding executing
code in the notebook.
Backtraces
When you interrupt a computation, or if an exception is raised but not... | Python Code:
def f(x):
return 1.0 / x
def g(x):
return x - 1.0
f(g(1.0))
Explanation: Executing Code
In this notebook we'll look at some of the issues surrounding executing
code in the notebook.
Backtraces
When you interrupt a computation, or if an exception is raised but not
caught, you will see a backtrace of... |
3,957 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<h1>Table of Contents<span class="tocSkip"></span></h1>
<div class="toc"><ul class="toc-item"><li><span><a href="#Gradient-Boosted-Tree-Inferencing" data-toc-modified-id="Gradient-Boosted-Tr... | Python Code:
# 1. magic to print version
# 2. magic so that the notebook will reload external python modules
%matplotlib inline
%load_ext watermark
%load_ext autoreload
%autoreload 2
import os
import numpy as np
import pandas as pd
import m2cgen as m2c
import sklearn.datasets as datasets
from xgboost import XGBClassifi... |
3,958 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Handling Event Data
by
Step1: Let's inspect the small event log.
The first line (i.e., row) specifies the name of each column (i.e., event attribute).
Observe that, in the data table descri... | Python Code:
import pandas as pd
df = pd.read_csv('data/running_example.csv', sep=';')
df
Explanation: Handling Event Data
by: Sebastiaan J. van Zelst
Process mining exploits Event Logs to generate knowledge of a process.
A wide variety of information systems, e.g., SAP, ORACLE, SalesForce, etc., allow us to extract, i... |
3,959 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Pandas 4
Step1: <a id=want></a>
The want operator
We need to know what we're trying to do -- what we want the data to look like. We say we apply the want operator.
Some problems we've ru... | Python Code:
import sys # system module
import pandas as pd # data package
import matplotlib.pyplot as plt # graphics module
import datetime as dt # date and time module
import numpy as np # foundation for Pandas
%matplotlib ... |
3,960 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Using pre-trained word embeddings in a Keras model
Based on https
Step1: Preparing the Embedding layer
Step2: Training a 1D convnet | Python Code:
from __future__ import print_function
import os
import sys
import numpy as np
from keras.preprocessing.text import Tokenizer
from keras.preprocessing.sequence import pad_sequences
from keras.utils import to_categorical
from keras.layers import Dense, Input, GlobalMaxPooling1D
from keras.layers import Conv1... |
3,961 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<h1>On Galerkin approximations for the QG equations</h1>
<h2>Supplementary material for subsection on the $\beta-$Eady model</h2>
<h3>Wave structure for Charney mode</h3>
<p></p>
</h3>Cesar ... | Python Code:
from __future__ import division
import numpy as np
from numpy import pi, sqrt,cos
import matplotlib.pyplot as plt
plt.rcParams.update({'font.size': 25, 'legend.handlelength' : 1.25})
%matplotlib inline
import seaborn as sns
#sns.set(style="darkgrid")
sns.set_context("paper", font_scale=5, rc={"lines.linew... |
3,962 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
output
Step1: I. prepare mapping_PDalpha file
calculate average PD alpha diversity at highest rarefaction 5870
Step2: Add PD alpha diversity into mapping file
Step3: output mapping file w... | Python Code:
import pandas as pd
import numpy as np
import statsmodels.formula.api as smf
from statsmodels.compat import lzip
import statsmodels.stats.api as sms
import statsmodels.api as sm
import matplotlib.pyplot as plt
import seaborn as sns
%matplotlib inline
Explanation: output: 'mapping_PDalpha.txt'(mapping file ... |
3,963 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Learn the standard library to at least know what's there
itertools and collections have very useful features
chain
product
permutations
combinations
izip
Step2: Challenge (Easy)
Write a fun... | Python Code:
%matplotlib inline
%config InlineBackend.figure_format='retina'
import matplotlib.pyplot as plt
import seaborn as sns
sns.set_context('talk')
sns.set_style('darkgrid')
plt.rcParams['figure.figsize'] = 12, 8 # plotsize
import numpy as np
import pandas as pd
# plot residuals
from itertools import groupby ... |
3,964 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
ES-DOC CMIP6 Model Properties - Atmos
MIP Era
Step1: Document Authors
Set document authors
Step2: Document Contributors
Specify document contributors
Step3: Document Publication
Specify d... | Python Code:
# DO NOT EDIT !
from pyesdoc.ipython.model_topic import NotebookOutput
# DO NOT EDIT !
DOC = NotebookOutput('cmip6', 'csir-csiro', 'vresm-1-0', 'atmos')
Explanation: ES-DOC CMIP6 Model Properties - Atmos
MIP Era: CMIP6
Institute: CSIR-CSIRO
Source ID: VRESM-1-0
Topic: Atmos
Sub-Topics: Dynamical Core... |
3,965 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Building communities
micom will construct communities from a specification via a Pandas DataFrame. Here, the DataFrame needs at least two columns
Step1: As we see this specification contain... | Python Code:
from micom.data import test_taxonomy
taxonomy = test_taxonomy()
taxonomy
Explanation: Building communities
micom will construct communities from a specification via a Pandas DataFrame. Here, the DataFrame needs at least two columns: "id" and "file" which specify the ID of the organism/tissue and a file con... |
3,966 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
ES-DOC CMIP6 Model Properties - Atmos
MIP Era
Step1: Document Authors
Set document authors
Step2: Document Contributors
Specify document contributors
Step3: Document Publication
Specify d... | Python Code:
# DO NOT EDIT !
from pyesdoc.ipython.model_topic import NotebookOutput
# DO NOT EDIT !
DOC = NotebookOutput('cmip6', 'inm', 'sandbox-3', 'atmos')
Explanation: ES-DOC CMIP6 Model Properties - Atmos
MIP Era: CMIP6
Institute: INM
Source ID: SANDBOX-3
Topic: Atmos
Sub-Topics: Dynamical Core, Radiation, T... |
3,967 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Annotate movement artifacts and reestimate dev_head_t
Periods, where the participant moved considerably, are contaminated by low
amplitude artifacts. When averaging the magnetic fields, the ... | Python Code:
# Authors: Adonay Nunes <adonay.s.nunes@gmail.com>
# Luke Bloy <luke.bloy@gmail.com>
# License: BSD (3-clause)
import os.path as op
import mne
from mne.datasets.brainstorm import bst_auditory
from mne.io import read_raw_ctf
from mne.preprocessing import annotate_movement, compute_average_dev_head_... |
3,968 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Semi graphic displays and charsets
Some text or semi graphic displays included in stemgraphic.
imports
Step1: Loading some data
Step2: Heatmaps
These are stem-and-leaf heatmaps as introduc... | Python Code:
import pandas as pd
from stemgraphic.num import text_heatmap, heatmatrix, text_hist, text_dot, stem_tally, stem_text
from stemgraphic.helpers import available_charsets
Explanation: Semi graphic displays and charsets
Some text or semi graphic displays included in stemgraphic.
imports
End of explanation
df =... |
3,969 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Monte Carlo Simulations
Calculating Pi
Step1: Calculating an integral
Step2: Drawing random numbers
Numpy has tons of random number functions.
See https
Step3: Hit-miss
Now let draw from ... | Python Code:
def random_number_plusminus1(n):
return 2*np.random.random(n) - 1
x, y = random_number_plusminus1((2,1000))
plt.scatter(x, y)
plt.show()
area_of_square = 2*2
ratio_of_dart_inside = np.mean(x**2 + y**2 < 1)
pi_estimate = area_of_square * ratio_of_dart_inside
print(pi_estimate, np.pi)
x, y = random_numbe... |
3,970 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Calculer x**n le plus rapidement possible
Step1: Enoncé
Comme $n$ est entier, la façon la plus simple est de calculer $xx...*x$ mais existe-t-il plus rapide que cela ?
Solution
L'idée de dé... | Python Code:
from jyquickhelper import add_notebook_menu
add_notebook_menu()
Explanation: Calculer x**n le plus rapidement possible
End of explanation
def puissance2k(x,k):
while k > 0 :
x *= x
k -= 1
return x
for i in range(0,4) :
print ( "2^(2^{0})=2^{1}={2}".format( i, 2**i, puissance2k (... |
3,971 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2019 The TensorFlow Authors.
Step1: 텍스트 생성을 위한 Federated Learning
<table class="tfo-notebook-buttons" align="left">
<td> <a target="_blank" href="https
Step2: 사전 훈련된 모델 로드하... | 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... |
3,972 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
We have some data providing the results of 30 coin tosses. We would like to estimate how fair the coin is, i.e. what is the probability of getting heads (1).
Step1: We build a probabilistic... | Python Code:
data = [1,0,1,0,0,1,1,1,0,0,1,1,1,0,1,1,1,0,0,1,1,0,1,1,0,1,1,0,1,1]
print(len(data))
Explanation: We have some data providing the results of 30 coin tosses. We would like to estimate how fair the coin is, i.e. what is the probability of getting heads (1).
End of explanation
fig_size=[]
fig_size.append(15)... |
3,973 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Catchy feature extraction
Outline
This notebook shows how to compute features for a set of presegmented audiofiles.
Extracting catchy features from a folder of such files involves three step... | Python Code:
audio_dir = '../Cogitch/Audio/Eurovision/'
euro_dict = utils.dataset_from_dir(audio_dir)
Explanation: Catchy feature extraction
Outline
This notebook shows how to compute features for a set of presegmented audiofiles.
Extracting catchy features from a folder of such files involves three steps:
1. Base feat... |
3,974 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: TV Script Generation
In this project, you'll generate your own Simpsons TV scripts using RNNs. You'll be using part of the Simpsons dataset of scripts from 27 seasons. The Neural Ne... | Python Code:
DON'T MODIFY ANYTHING IN THIS CELL
import helper
data_dir = './data/simpsons/moes_tavern_lines.txt'
text = helper.load_data(data_dir)
# Ignore notice, since we don't use it for analysing the data
text = text[81:]
Explanation: TV Script Generation
In this project, you'll generate your own Simpsons TV script... |
3,975 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Initialization
Step1: Algorithm
Step2: Save coefs (X) and Y, along with tests (to know what each row refers to) to work with it later
Step3: What without NEs
Step4: SGD
Step5: Simple tr... | Python Code:
folder = os.path.join('..', 'data')
newsbreaker.init(os.path.join(folder, 'topic_model'), 'topic_model.pkl', 'vocab.txt')
entries = load_entries(folder)
entries_dict = defaultdict(list)
for entry in entries:
entries_dict[entry.feed].append(entry)
client = MongoClient()
db = client.newstagger
Explanatio... |
3,976 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: Unsupervised dimensionality reduction using a 1 Hidden-layer perceptron where label == ground truth
For NLP, we can say somewhat say that word2vec and autoencoders are similiar.
Dimen... | Python Code:
import os
from random import randint
from collections import Counter
os.environ['TF_CPP_MIN_LOG_LEVEL']='2'
import numpy as np
import tensorflow as tf
corpus = "the quick brown fox jumped over the lazy dog from the quick tall fox".split()
test_corpus = "the quick brown fox jumped over the lazy dog from the... |
3,977 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Introduction
This IPython notebook illustrates how to performing matching with a ML matcher. In particular we show examples with a decision tree matcher, but the same principles apply to all... | Python Code:
# Import py_entitymatching package
import py_entitymatching as em
import os
import pandas as pd
Explanation: Introduction
This IPython notebook illustrates how to performing matching with a ML matcher. In particular we show examples with a decision tree matcher, but the same principles apply to all of the ... |
3,978 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Aufgabe 3
Step1: First we load the iris data from task 1 and split it into training and validation set.
Step2: Then we specify our parameter space and performance metric.
Step3: Next we r... | Python Code:
# imports
import pandas
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.cross_validation import train_test_split
from sklearn.neighbors import KNeighborsClassifier
from sklearn.grid_search import GridSearchCV
Explanation: Aufgabe 3: Cross Validation and Grid Search
We ... |
3,979 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
DCT-based Transform Coding of Images
This code is provided as supplementary material of the lecture Quellencodierung.
This code illustrates
* Show basis functions of the DCT
Step1: Function... | Python Code:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
from itertools import chain
from scipy import fftpack
import scipy as sp
from ipywidgets import interactive, HBox, Label
import ipywidgets as widgets
%matplotlib inline
Explanation: DCT-based Transform Coding of Images
This... |
3,980 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<h1>Data's messy - clean it up!</h1>
Data cleaning is a critical process for improving data quality and ultimately the accuracy of machine learning model output. In this notebook we show how... | Python Code:
import os
import graphlab as gl
Explanation: <h1>Data's messy - clean it up!</h1>
Data cleaning is a critical process for improving data quality and ultimately the accuracy of machine learning model output. In this notebook we show how the GraphLab Create Data Matching toolkit can be used to get your data ... |
3,981 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Nipype Quickstart
This is a very quick non-imaging introduction to Nipype workflows. For a more comprehensive introduction, check the next section of the tutorial.
Existing documentation
Vi... | Python Code:
import os
from nipype import Workflow, Node, Function
Explanation: Nipype Quickstart
This is a very quick non-imaging introduction to Nipype workflows. For a more comprehensive introduction, check the next section of the tutorial.
Existing documentation
Visualizing the evolution of Nipype
This notebook is... |
3,982 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Think Bayes
This notebook presents example code and exercise solutions for Think Bayes.
Copyright 2018 Allen B. Downey
MIT License
Step3: The World Cup Problem, Part One
In the 2014 FIFA Wo... | Python Code:
# Configure Jupyter so figures appear in the notebook
%matplotlib inline
# Configure Jupyter to display the assigned value after an assignment
%config InteractiveShell.ast_node_interactivity='last_expr_or_assign'
# import classes from thinkbayes2
from thinkbayes2 import Pmf, Cdf, Suite
import thinkbayes2
i... |
3,983 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Phylogenetic generalized least squares model fit for quartet data
Manuscript
Step1: We're gonna be running R code as well, so we need the following
Step3: To run parallel Python code using... | Python Code:
## import Python libraries
from scipy.optimize import fminbound
import numpy as np
import pandas as pd
import itertools
import ete3
import rpy2
import copy
import glob
import gzip
import os
Explanation: Phylogenetic generalized least squares model fit for quartet data
Manuscript: "Misconceptions on Missing... |
3,984 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Polynomials
Some of the equations we've looked at so far include expressions that are actually polynomials; but what is a polynomial, and why should you care?
A polynomial is an algebraic ex... | Python Code:
from random import randint
x = randint(1,100)
(x**3 + 2*x**3 - 3*x - x + 8 - 3) == (3*x**3 - 4*x + 5)
Explanation: Polynomials
Some of the equations we've looked at so far include expressions that are actually polynomials; but what is a polynomial, and why should you care?
A polynomial is an algebraic expr... |
3,985 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Scrapy 3
Step1: As you can see the very first (and brutal) approach can be adding the URLs one-by-one to the start_urls list. The good news is that all URLs are quite similar
Step2: The sa... | Python Code:
# -*- coding: utf-8 -*-
import scrapy
class QuoteSpider(scrapy.Spider):
name = "quote"
allowed_domains = ["quotes.toscrape.com"]
start_urls = ['http://quotes.toscrape.com/page/1/',
'http://quotes.toscrape.com/page/2/']
def parse(self, response):
for quote in respon... |
3,986 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Build a DNN using the Keras Functional API
Learning objectives
Review how to read in CSV file data using tf.data.
Specify input, hidden, and output layers in the DNN architecture.
Review and... | Python Code:
import os, json, math
import numpy as np
import shutil
import tensorflow as tf
print("TensorFlow version: ",tf.version.VERSION)
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' # SET TF ERROR LOG VERBOSITY
Explanation: Build a DNN using the Keras Functional API
Learning objectives
Review how to read in CSV file da... |
3,987 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Algorithms Exercise 3
Imports
Step2: Character counting and entropy
Write a function char_probs that takes a string and computes the probabilities of each character in the string
Step4: Th... | Python Code:
%matplotlib inline
from matplotlib import pyplot as plt
import numpy as np
from IPython.html.widgets import interact
Explanation: Algorithms Exercise 3
Imports
End of explanation
def char_probs(s):
Find the probabilities of the unique characters in the string s.
Parameters
----------
s... |
3,988 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Planet Analytics API Tutorial
Summary Statistics
Step1: 2. Post a stats job request
a) Check API Connection
Note
Step2: b) Select your subscription
The analytics stats API enables you to c... | Python Code:
!pip install hvplot
import os
import requests
import json
import pprint
import time
import pandas as pd
import holoviews as hv
import hvplot.pandas
from bokeh.models.formatters import DatetimeTickFormatter
from collections import defaultdict
Explanation: Planet Analytics API Tutorial
Summary Statistics: Sh... |
3,989 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Rich Output
In Python, objects can declare their textual representation using the __repr__ method. IPython expands on this idea and allows objects to declare other, rich representations inc... | Python Code:
from IPython.display import display
Explanation: Rich Output
In Python, objects can declare their textual representation using the __repr__ method. IPython expands on this idea and allows objects to declare other, rich representations including:
HTML
JSON
PNG
JPEG
SVG
LaTeX
A single object can declare som... |
3,990 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
6. ADI forward modeling of disks
Author
Step1: In the following box we import all the VIP routines that will be used in this tutorial.
The path to some routines has changed between versions... | Python Code:
%matplotlib inline
from hciplot import plot_frames, plot_cubes
from matplotlib.pyplot import *
from matplotlib import pyplot as plt
import numpy as np
from packaging import version
Explanation: 6. ADI forward modeling of disks
Author: Julien Milli
Last update: 23/03/2022
Suitable for VIP v1.0.0 onwards.
Ta... |
3,991 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step2: Markdown 2 Reportlab
Markdown
Here we create some lorem ipsum markdown text for testing
Step3: ReportLab
import the necessary functions one by one
Step8: The ReportFactory class cre... | Python Code:
from IPython.display import HTML
import markdown as md
l = LOREM ipsum dolor sit amet, _consectetur_ adipiscing elit. Praesent dignissim orci a leo dapibus semper eget sed
sem. Pellentesque tellus nisl, condimentum nec libero id, __cursus consequat__ lectus. Ut quis nulla laoreet, efficitur
metus sit ame... |
3,992 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2018 The TensorFlow Authors.
Step1: Get Started with TensorFlow 1.x
<table class="tfo-notebook-buttons" align="left">
<td>
<a target="_blank" href="https
Step2: Load and pr... | 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... |
3,993 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Use Word2Vec in gensim to train a word embedding model using the content from NIPS papers.
Step1: Gensim word2vec
https
Step2: Train a word2vec model
Step3: Create a representation of eac... | Python Code:
%load_ext autoreload
%autoreload 2
%matplotlib inline
#%config InlineBackend.figure_format = 'svg'
#config InlineBackend.figure_format = 'pdf'
from IPython.core.display import HTML
import gensim as gen
import gensim.models.word2vec as w2v
import matplotlib.pyplot as plt
from nltk.tokenize import Whitespace... |
3,994 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Si in FCC Ni
Based on data in hdl.handle.net/11115/239, "Data Citation
Step1: Create an FCC Ni crystal.
Step2: Next, we construct our diffuser. For this problem, our thermodynamic range is... | Python Code:
import sys
sys.path.append('../')
import numpy as np
import matplotlib.pyplot as plt
plt.style.use('seaborn-whitegrid')
%matplotlib inline
import onsager.crystal as crystal
import onsager.OnsagerCalc as onsager
from scipy.constants import physical_constants
kB = physical_constants['Boltzmann constant in eV... |
3,995 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Tailored constraints, variables and objectives
Thanks to the use of symbolic expressions via the optlang mathematical modeling package, it is relatively straight-forward to add new variables... | Python Code:
import cobra.test
model = cobra.test.create_test_model('textbook')
same_flux = model.problem.Constraint(
model.reactions.FBA.flux_expression - model.reactions.NH4t.flux_expression,
lb=0,
ub=0)
model.add_cons_vars(same_flux)
Explanation: Tailored constraints, variables and objectives
Thanks to t... |
3,996 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Building a dashboard to plan a marketing campaign leveraging CARTO Data Observatory
Combining different data sources to identify some patterns or understand some behavior in a specific locat... | Python Code:
import geopandas as gpd
import pandas as pd
from cartoframes.auth import set_default_credentials
from cartoframes.data.services import Isolines
from cartoframes.data.observatory import *
from cartoframes.viz import *
from shapely.geometry import box
pd.set_option('display.max_columns', None)
Explanation: B... |
3,997 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Grade
Step1: If you get an error stating that database "homework2" does not exist, make sure that you followed the instructions above exactly. If necessary, drop the database you created (w... | Python Code:
import pg8000
conn = pg8000.connect(database="homework2")
Explanation: Grade: 5 / 6 -- search "TA-COMMENT" to check out a note on the last question!
Homework 2: Working with SQL (Data and Databases 2016)
This homework assignment takes the form of an IPython Notebook. There are a number of exercises below, ... |
3,998 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Javascript extension for a notebook
Play with Javascript extensions.
Step1: We install extensions in case it was not done before
Step2: We check the list of installed extensions (from IPyt... | Python Code:
from pyquickhelper.ipythonhelper import install_notebook_extension, get_installed_notebook_extension
Explanation: Javascript extension for a notebook
Play with Javascript extensions.
End of explanation
install_notebook_extension()
Explanation: We install extensions in case it was not done before:
End of ex... |
3,999 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
COSC Learning Lab
03_interface_properties.py
Related Scripts
Step1: Implementation
Step2: Execution
Step3: HTTP | Python Code:
help('learning_lab.03_interface_properties')
Explanation: COSC Learning Lab
03_interface_properties.py
Related Scripts:
* 03_interface_configuration.py
Table of Contents
Table of Contents
Documentation
Implementation
Execution
HTTP
Documentation
End of explanation
from importlib import import_module
script... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.