Unnamed: 0 int64 0 16k | text_prompt stringlengths 110 62.1k | code_prompt stringlengths 37 152k |
|---|---|---|
2,600 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Computation and comparision of the bispectrum and the rotational bispectrum
We show how to compute the bispectrum and the rotational bispectrum, as presented in the paper
Image processing i... | Python Code:
import numpy as np
from numpy import fft
from numpy import linalg as LA
from scipy import ndimage
from scipy import signal
import matplotlib.pyplot as plt
import matplotlib.cm as cm
import os
%matplotlib inline
Explanation: Computation and comparision of the bispectrum and the rotational bispectrum
We show... |
2,601 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
os.path
Writing code to work with files on multiple platforms is easy using the functions included in the os.path module. Even programs not intended to be ported between platforms should use... | Python Code:
import os.path
PATHS = [
'/one/two/three',
'/one/two/three/',
'/',
'.',
'',
]
for path in PATHS:
print('{!r:>17} : {}'.format(path, os.path.split(path)))
for path in PATHS:
print('{!r:>17}:{}'.format(path, os.path.basename(path)))
for path in PATHS:
print('{!r:>17}:{}'.forma... |
2,602 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Data-analyysityöpaja Kajaanin Tiedepäivillä
Mitä data-analyysi on? Data-analyysi tarkoitaa sitä, että datan pohjalta päätellään jotain uutta. Esimerkiksi mittausdatan perusteella voidaan tod... | Python Code:
# Luetaan loitsut, jotka alustavat ympäristön
from pandas import DataFrame, Series, read_csv
from numpy import vstack, round, random
from bokeh.plotting import figure, show, output_notebook, hplot
from bokeh.charts import Bar, Scatter
from bokeh._legacy_charts import HeatMap
from bokeh.palettes import YlOr... |
2,603 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
ES-DOC CMIP6 Model Properties - Atmoschem
MIP Era
Step1: Document Authors
Set document authors
Step2: Document Contributors
Specify document contributors
Step3: Document Publication
Speci... | Python Code:
# DO NOT EDIT !
from pyesdoc.ipython.model_topic import NotebookOutput
# DO NOT EDIT !
DOC = NotebookOutput('cmip6', 'cnrm-cerfacs', 'sandbox-2', 'atmoschem')
Explanation: ES-DOC CMIP6 Model Properties - Atmoschem
MIP Era: CMIP6
Institute: CNRM-CERFACS
Source ID: SANDBOX-2
Topic: Atmoschem
Sub-Topics... |
2,604 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
ModelFree Parser Demo
Arthur G. Palmer, III and Michelle L. Gill
2015/12/06
This IPython notebook demonstartes how to parse various types of ModelFree STAR output files with the library mfou... | Python Code:
import os
# Use sans-serif fonts for plotting
import matplotlib
matplotlib.rcParams[u'font.family'] = [u'sans-serif']
matplotlib.rcParams[u'mathtext.default'] = u'regular'
import matplotlib.pyplot as plt
%matplotlib inline
# %matplotlib notebook # Alternative to `%matplotlib inline` that will make plots in... |
2,605 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Vertex SDK
Step1: Install the latest GA version of google-cloud-storage library as well.
Step2: Restart the kernel
Once you've installed the additional packages, you need to restart the no... | Python Code:
import os
# Google Cloud Notebook
if os.path.exists("/opt/deeplearning/metadata/env_version"):
USER_FLAG = "--user"
else:
USER_FLAG = ""
! pip3 install --upgrade google-cloud-aiplatform $USER_FLAG
Explanation: Vertex SDK: AutoML training image classification model for export to edge
<table align="l... |
2,606 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Gaussian Mixture Model
This is tutorial demonstrates how to marginalize out discrete latent variables in Pyro through the motivating example of a mixture model. We'll focus on the mechanics ... | Python Code:
import os
from collections import defaultdict
import torch
import numpy as np
import scipy.stats
from torch.distributions import constraints
from matplotlib import pyplot
%matplotlib inline
import pyro
import pyro.distributions as dist
from pyro import poutine
from pyro.infer.autoguide import AutoDelta
fro... |
2,607 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Net Surgery
Caffe networks can be transformed to your particular needs by editing the model parameters. The data, diffs, and parameters of a net are all exposed in pycaffe.
Roll up your slee... | Python Code:
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
# Make sure that caffe is on the python path:
caffe_root = '../' # this file is expected to be in {caffe_root}/examples
import sys
sys.path.insert(0, caffe_root + 'python')
import caffe
# configure plotting
plt.rcParams['figure.figsize'... |
2,608 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Regression Week 5
Step1: Load in house sales data
Dataset is from house sales in King County, the region where the city of Seattle, WA is located.
Step2: Create new features
As in Week 2, ... | Python Code:
import graphlab
Explanation: Regression Week 5: Feature Selection and LASSO (Interpretation)
In this notebook, you will use LASSO to select features, building on a pre-implemented solver for LASSO (using GraphLab Create, though you can use other solvers). You will:
* Run LASSO with different L1 penalties.
... |
2,609 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
ES-DOC CMIP6 Model Properties - Ocnbgchem
MIP Era
Step1: Document Authors
Set document authors
Step2: Document Contributors
Specify document contributors
Step3: Document Publication
Speci... | Python Code:
# DO NOT EDIT !
from pyesdoc.ipython.model_topic import NotebookOutput
# DO NOT EDIT !
DOC = NotebookOutput('cmip6', 'mohc', 'sandbox-2', 'ocnbgchem')
Explanation: ES-DOC CMIP6 Model Properties - Ocnbgchem
MIP Era: CMIP6
Institute: MOHC
Source ID: SANDBOX-2
Topic: Ocnbgchem
Sub-Topics: Tracers.
Prop... |
2,610 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Spam Analysis
This notebook will contain the codes and documentations for spam analysis. A report is generated on the analysis in the dropbox paper https
Step1: Spam by Source and User type... | Python Code:
from database import Database
database = Database(
'<host name>',
'<database name>',
'<user name>',
'<password>',
'utf8mb4'
)
Explanation: Spam Analysis
This notebook will contain the codes and documentations for spam analysis. A report is generated on the analysis in the dropbox paper ... |
2,611 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Analyzing Airbnb Prices in New York
Jihyun Kim
Final Project for Data Bootcamp, Fall 2016
What determines each Airbnb's listing price?
Background
Everything in New York is expensive. For fir... | Python Code:
import sys
import pandas as pd
import matplotlib.pyplot as plt
import datetime as dt
import numpy as np
import seaborn as sns
import statistics
import csv
from scipy import stats
from bs4 import BeautifulSoup as bs
import urllib.request
from go... |
2,612 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
1A.soft - Tests unitaires, setup et ingéniérie logicielle
On vérifie toujours qu'un code fonctionne quand on l'écrit mais cela ne veut pas dire qu'il continuera à fonctionner à l'avenir. La ... | Python Code:
from jyquickhelper import add_notebook_menu
add_notebook_menu()
from pyensae.graphhelper import draw_diagram
Explanation: 1A.soft - Tests unitaires, setup et ingéniérie logicielle
On vérifie toujours qu'un code fonctionne quand on l'écrit mais cela ne veut pas dire qu'il continuera à fonctionner à l'avenir... |
2,613 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2021 The TensorFlow Authors.
Step1: Migrate LoggingTensorHook and StopAtStepHook to Keras callbacks
<table class="tfo-notebook-buttons" align="left">
<td>
<a target="_blank"... | 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... |
2,614 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
GDAL command line
Example
Step1: What is this combination of commands?
! this is a jupyter notebook-thing, telling it we're running something on the command line instead of in Python
../scr... | Python Code:
!ogr2ogr ../scratch/deelbekkens_wgs84 -t_srs "EPSG:4326" ../data/deelbekkens/Deelbekken.shp
Explanation: GDAL command line
Example: reprojection
GDAL is a really powerful library for handling GIS data. It provides a number of functionalities to interact with spatial data. As a typical example, take the rep... |
2,615 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Gensim Doc2vec Tutorial on the IMDB Sentiment Dataset
Introduction
In this tutorial, we will learn how to apply Doc2vec using gensim by recreating the results of <a href="https
Step1: The t... | Python Code:
import locale
import glob
import os.path
import requests
import tarfile
import sys
import codecs
import smart_open
dirname = 'aclImdb'
filename = 'aclImdb_v1.tar.gz'
locale.setlocale(locale.LC_ALL, 'C')
if sys.version > '3':
control_chars = [chr(0x85)]
else:
control_chars = [unichr(0x85)]
# Convert... |
2,616 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Working with ECoG data
MNE supports working with more than just MEG and EEG data. Here we show some
of the functions that can be used to facilitate working with
electrocorticography (ECoG) d... | Python Code:
# Authors: Eric Larson <larson.eric.d@gmail.com>
# Chris Holdgraf <choldgraf@gmail.com>
#
# License: BSD (3-clause)
import numpy as np
import matplotlib.pyplot as plt
from scipy.io import loadmat
from mayavi import mlab
import mne
from mne.viz import plot_alignment, snapshot_brain_montage
print(__... |
2,617 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<a href="http
Step1: We can use negative and regular indexing with a list
Step2: Lists can contain strings, floats, and integers. We can nest other lists, and we can also nest tuples and ... | Python Code:
L = ["Michael Jackson" , 10.1,1982]
L
Explanation: <a href="http://cocl.us/topNotebooksPython101Coursera"><img src = "https://ibm.box.com/shared/static/yfe6h4az47ktg2mm9h05wby2n7e8kei3.png" width = 750, align = "center"></a>
<a href="https://www.bigdatauniversity.com"><img src = "https://ibm.box.com/shared... |
2,618 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Plotting Data
Visualizing the metadata is very useful to get a first look at the nature and quality of the run.
First we need a DataFrame with the meta data. You can make one with porekit.ga... | Python Code:
df = pd.read_hdf("../examples/data/ru9_meta.h5", "meta")
Explanation: Plotting Data
Visualizing the metadata is very useful to get a first look at the nature and quality of the run.
First we need a DataFrame with the meta data. You can make one with porekit.gather_metadata once, and then load it later from... |
2,619 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Representation of trajectories
sktracker.trajectories.Trajectories is probably the most important class in sktracker as it represents detected objects and links between them. Trajectories is... | Python Code:
%matplotlib inline
import pandas as pd
import numpy as np
trajs = pd.DataFrame(np.random.random((30, 3)), columns=['x', 'y', 'z'])
trajs['t_stamp'] = np.sort(np.random.choice(range(10), (len(trajs),)))
trajs['label'] = list(range(len(trajs)))
trajs['t'] = trajs['t_stamp'] * 60 # t are in seconds for examp... |
2,620 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Thermochemistry Validation Test
Han, Kehang (hkh12@mit.edu)
This notebook is designed to use a big set of tricyclics for testing the performance of new polycyclics thermo estimator. Currentl... | Python Code:
from rmgpy.data.rmg import RMGDatabase
from rmgpy import settings
from rmgpy.species import Species
from rmgpy.molecule import Group
from rmgpy.rmg.main import RMG
from IPython.display import display
import numpy as np
import os
import pandas as pd
from pymongo import MongoClient
import logging
logging.dis... |
2,621 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Regression
1. Information Generation
Simulation of values to train and test the linear regression model.
Step1: 2. ages_train vs ages_test relationship
Is there a trend we can model ?
Step2... | Python Code:
# importing packages
import numpy
import random
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
# setting ageNetWorthData
def ageNetWorthData():
random.seed(42)
numpy.random.seed(42)
ages = []
for ii in range(100):
ages.append( random.randint(20,65)... |
2,622 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Machine Translation in Python 3 with NLTK
(C) 2017 by Damir Cavar
Version
Step1: We can load a word-level alignment corpus for English and French from the NLTK dataset
Step2: Print out the... | Python Code:
from nltk.corpus import comtrans
Explanation: Machine Translation in Python 3 with NLTK
(C) 2017 by Damir Cavar
Version: 1.0, November 2017
License: Creative Commons Attribution-ShareAlike 4.0 International License (CA BY-SA 4.0)
This is a brief introduction to the Machine Translation components in NLTK.
L... |
2,623 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Standardized Precipitation Index (SPI)
This notebook is inspired by the NCL SPI example.
The Standardized Precipitation Index (SPI) is a probability index that gives a better representation ... | Python Code:
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt # to generate plots
from mpl_toolkits.basemap import Basemap # plot on map projections
import datetime
from netCDF4 import Dataset # http://unidata.github.io/netcdf4-python/
from netCDF4 import netcdftime
from netcdf... |
2,624 | 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="#Genetic-Algorithm" data-toc-modified-id="Genetic-Algorithm-1"><span class="t... | Python Code:
# code for loading the format for the notebook
import os
# path : store the current path to convert back to it later
path = os.getcwd()
os.chdir(os.path.join('..', 'notebook_format'))
from formats import load_style
load_style(plot_style = False)
os.chdir(path)
import numpy as np
import pandas as pd
import ... |
2,625 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
You are currently looking at version 1.1 of this notebook. To download notebooks and datafiles, as well as get help on Jupyter notebooks in the Coursera platform, visit the Jupyter Notebook ... | Python Code:
import pandas as pd
df = pd.read_csv('olympics.csv', index_col=0, skiprows=1)
for col in df.columns:
if col[:2]=='01':
df.rename(columns={col:'Gold'+col[4:]}, inplace=True)
if col[:2]=='02':
df.rename(columns={col:'Silver'+col[4:]}, inplace=True)
if col[:2]=='03':
df.ren... |
2,626 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Content and Objectives
Show effects of asynchronity to IQ signal
QPSK symbols are being pulse-shaped by RRC, distorted in the channel by phase, frequency, and noise and depicted in the compl... | Python Code:
# importing
import numpy as np
from scipy import stats
import matplotlib.pyplot as plt
import matplotlib
# showing figures inline
%matplotlib inline
# plotting options
font = {'size' : 20}
plt.rc('font', **font)
plt.rc('text', usetex=True)
matplotlib.rc('figure', figsize=(18, 6) )
Explanation: Content a... |
2,627 | Given the following text description, write Python code to implement the functionality described.
Description:
You are given a list of integers.
You need to find the largest prime value and return the sum of its digits.
Examples:
For lst = [0,3,2,1,3,5,7,4,5,5,5,2,181,32,4,32,3,2,32,324,4,3] the output shou... | Python Code:
def skjkasdkd(lst):
def isPrime(n):
for i in range(2,int(n**0.5)+1):
if n%i==0:
return False
return True
maxx = 0
i = 0
while i < len(lst):
if(lst[i] > maxx and isPrime(lst[i])):
maxx = lst[i]
i+=1
result = sum... |
2,628 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Creating discrete Bayesian Networks
In this section, we show an example for creating a Bayesian Network in pgmpy from scratch. We use the cancer model (http
Step1: Step 1
Step2: Step 2
Ste... | Python Code:
from IPython.display import Image
Image("images/cancer.png")
Explanation: Creating discrete Bayesian Networks
In this section, we show an example for creating a Bayesian Network in pgmpy from scratch. We use the cancer model (http://www.bnlearn.com/bnrepository/#cancer) for the example. The model structure... |
2,629 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
healpy tutorial
See the Jupyter Notebook version of this tutorial at https
Step1: NSIDE and ordering
Maps are simply numpy arrays, where each array element refers to a location in the sky a... | Python Code:
import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np
import healpy as hp
Explanation: healpy tutorial
See the Jupyter Notebook version of this tutorial at https://github.com/healpy/healpy/blob/master/doc/healpy_tutorial.ipynb
See a executed version of the notebook with embedded plots at ht... |
2,630 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Tranlation Matrix Tutorial
What is it ?
Suppose we are given a setofword pairs and their associated vector representaion ${x_{i},z_{i}}{i=1}^{n}$, where $x{i} \in R^{d_{1}}$ is the distibute... | Python Code:
import os
from gensim import utils
from gensim.models import translation_matrix
from gensim.models import KeyedVectors
Explanation: Tranlation Matrix Tutorial
What is it ?
Suppose we are given a setofword pairs and their associated vector representaion ${x_{i},z_{i}}{i=1}^{n}$, where $x{i} \in R^{d_{1}}$ i... |
2,631 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2020 The TensorFlow Authors.
Step1: BERT Question Answer with TensorFlow Lite Model Maker
<table class="tfo-notebook-buttons" align="left">
<td>
<a target="_blank" href="htt... | 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... |
2,632 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Interact Exercise 5
Imports
Put the standard imports for Matplotlib, Numpy and the IPython widgets in the following cell.
Step1: Interact with SVG display
SVG is a simple way of drawing vec... | Python Code:
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
from IPython.html.widgets import interact, interactive, fixed
from IPython.html import widgets
from IPython.display import display, SVG
Explanation: Interact Exercise 5
Imports
Put the standard imports for Matplotlib, Numpy and the IPyth... |
2,633 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<img src="imgs/tensorflow_head.png" />
Tensorflow
TensorFlow (https
Step1: Meaning
Step2: Data Flow Graph
(IDEA)
_A Machine Learning application is the result of the repeated computation ... | Python Code:
# A simple calculation in Python
x = 1
y = x + 10
print(y)
import tensorflow as tf
# The ~same simple calculation in Tensorflow
x = tf.constant(1, name='x')
y = tf.Variable(x+10, name='y')
print(y)
Explanation: <img src="imgs/tensorflow_head.png" />
Tensorflow
TensorFlow (https://www.tensorflow.org/) is a ... |
2,634 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Linear Regression
Agenda
Introducing the bikeshare dataset
Reading in the data
Visualizing the data
Linear regression basics
Form of linear regression
Building a linear regression model
Usin... | Python Code:
# read the data and set the datetime as the index
import seaborn as sns
import matplotlib.pyplot as plt
%matplotlib inline
plt.rcParams['figure.figsize'] = (8, 6)
plt.rcParams['font.size'] = 14
import pandas as pd
urls = ['../data/KDCA-201601.csv', '../data/KDCA-201602.csv', '../data/KDCA-201603.csv']
fram... |
2,635 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
An Astronomical Application of Machine Learning
Step1: Problem 1) Examine the Training Data
For this problem the training set, i.e. sources with known labels, includes stars and galaxies th... | Python Code:
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
%matplotlib inline
Explanation: An Astronomical Application of Machine Learning:
Separating Stars and Galaxies from SDSS
Version 0.3
By AA Miller 2017 Jan 22
AA Miller 2022 Mar 06 (v0.03)
The problems in the follow... |
2,636 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Coding in Python
Dr. Chris Gwilliams
gwilliamsc@cardiff.ac.uk
Writing in Python
Step1: Types
Python has a type system (variables have types), even if you do not specify it when you declare ... | Python Code:
# Does this make sense without comments?
with open('myfile.csv', 'rb') as opened_csv:
spamreader = csv.reader(csvfile, delimiter=' ', quotechar='|')
for row in spamreader:
print (', '.join(row))
# How about this?
#open csv file in readable format
with open('myfile.csv', 'rbU') as opened_csv... |
2,637 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Perceptually Uniform Color Interpolation
This was a small for fun experiment done on a lazy Saturday. Check the original at https
Step1: Parsing
Step2: Conversion from RGB (assumed sRGB) t... | Python Code:
import re
import colorlover as cl
from IPython.display import HTML
import numpy as np
num_original = 4
num_interpolated = 19
colors = cl.scales[str(num_original).strip()]['qual']['Set1']
HTML(cl.to_html( colors ))
Explanation: Perceptually Uniform Color Interpolation
This was a small for fun experiment don... |
2,638 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Bayesian Optimization
Ever thought about an automatic way to tune hyperparameters of your beloved machine learning algorithm? for example learning rate, weight decay, and drop out probabilit... | Python Code:
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import minimize
from scipy.linalg import det
from scipy.linalg import pinv2 as inv #pinv uses linalg.lstsq algorithm while pinv2 uses SVD
from scipy.stats import norm
%matplotlib inline
%load_ext autoreload
%autoreload 2
%autosave 0
Exp... |
2,639 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Similarity Queries using Annoy Tutorial
This tutorial is about using the (Annoy Approximate Nearest Neighbors Oh Yeah) library for similarity queries with a Word2Vec model built with gensim.... | Python Code:
# pip install watermark
%reload_ext watermark
%watermark -v -m -p gensim,numpy,scipy,psutil,matplotlib
Explanation: Similarity Queries using Annoy Tutorial
This tutorial is about using the (Annoy Approximate Nearest Neighbors Oh Yeah) library for similarity queries with a Word2Vec model built with gensim.
... |
2,640 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
risklearning demo
Most, if not all, operational risk capital models assume the existence of stationary frequency and severity distributions (typically Poisson for frequencies, and a subexpon... | Python Code:
import risklearning.learning_frequency as rlf
reload(rlf)
import pandas as pd
import numpy as np
import scipy.stats as stats
import math
import matplotlib.style
matplotlib.style.use('ggplot')
import ggplot as gg
%matplotlib inline
Explanation: risklearning demo
Most, if not all, operational risk capital mo... |
2,641 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Serialising the Stars
Noodles lets you run jobs remotely and store/retrieve results in case of duplicate jobs or reruns. These features rely on the serialisation (and not unimportant, recons... | Python Code:
from noodles.tutorial import display_text
import pickle
function = pickle.dumps(str.upper)
message = pickle.dumps("Hello, Wold!")
display_text("function: " + str(function))
display_text("message: " + str(message))
pickle.loads(function)(pickle.loads(message))
Explanation: Serialising the Stars
Noodles lets... |
2,642 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Noodles
Easy concurrent programming <s>in</s> using Python
Johan Hidding, Thursday 19-11-2015 @ NLeSC
Step1: But, why?
save time user's time
be flexible
Alternatives
What we discussed
Step2... | Python Code:
from noodles import schedule, run, run_parallel, gather
Explanation: Noodles
Easy concurrent programming <s>in</s> using Python
Johan Hidding, Thursday 19-11-2015 @ NLeSC
End of explanation
@schedule
def add(a, b):
return a+b
@schedule
def sub(a, b):
return a-b
@schedule
def mul(a, b):
return a... |
2,643 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Connecting to Database
Step1: LOGISTIC REGRESSION
Step2: Logistic Regression - Success
Logistic Regression - MULTIPLE
Step3: RANDOM FOREST
Random Forest- MULTIPLE
Step4: Random Forest- S... | Python Code:
import pandas as pd
import numpy as np
terror = pd.read_csv('file.csv', encoding='ISO-8859-1')
cleanedforuse = terror.filter(['imonth', 'iday', 'region','property','propextent','attacktype1','weaptype1','nperps','success','multiple','specificity'])
final = cleanedforuse[~np.isnan(cleanedforuse).any(axis=1)... |
2,644 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Resposta a Degrau
Jupyter Notebook desenvolvido por Gustavo S.S.
Resposta a um degrau de um circuito RC
Quando a fonte CC de um circuito RC for aplicada repentinamente, a fonte de
tensão ou ... | Python Code:
print("Exemplo 7.10")
from sympy import *
m = 10**(-3)
k = 10**3
C = 0.5*m
Vc0 = 24*5*k/(3*k + 5*k) #tensao no capacitor em condicao inicial v0
Vcf = 30 #tensao no capacitor em condicao final
tau = 4*k*C
t = symbols('t')
v = Vcf + (Vc0 - Vcf)*exp(-t/tau)
print("Tensão v(t):",v,"V")
Explanation: Resposta a... |
2,645 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Mass-univariate twoway repeated measures ANOVA on single trial power
This script shows how to conduct a mass-univariate repeated measures
ANOVA. As the model to be fitted assumes two fully c... | Python Code:
# Authors: Denis Engemann <denis.engemann@gmail.com>
# Eric Larson <larson.eric.d@gmail.com>
# Alexandre Gramfort <alexandre.gramfort@telecom-paristech.fr>
#
# License: BSD (3-clause)
import numpy as np
import matplotlib.pyplot as plt
import mne
from mne.time_frequency import tfr_morlet
f... |
2,646 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<a href="https
Step1: We also limit the number of epochs further to 2000 (because we have seen that after that nothing good is going to happen)
Step2: Scores around 80% look good now, ther... | Python Code:
!pip install -q tf-nightly-gpu-2.0-preview
import tensorflow as tf
print(tf.__version__)
import matplotlib.pyplot as plt
import pandas as pd
import tensorflow as tf
import numpy as np
from tensorflow import keras
!curl -O https://raw.githubusercontent.com/DJCordhose/deep-learning-crash-course-notebooks/mas... |
2,647 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2018 The TensorFlow Authors.
Step1: Save and restore models
<table class="tfo-notebook-buttons" align="left">
<td>
<a target="_blank" href="https
Step2: Get an example data... | 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... |
2,648 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
An RNN model for temperature data
This time we will be working with real data
Step1: Hyperparameters
N_FORWARD = 1
Step2: Temperature data
This is what our temperature datasets looks like
... | Python Code:
import math
import sys
import time
import numpy as np
import utils_batching
import utils_args
import tensorflow as tf
from tensorflow.python.lib.io import file_io as gfile
print("Tensorflow version: " + tf.__version__)
from matplotlib import pyplot as plt
import utils_prettystyle
import utils_display
Expla... |
2,649 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Zollinger
https
Step1: pixelogik
https
Step2: ColorThief
https
Step3: OpenCV pixel count
Step4: Back to Zollinger
Step5: OpenCV's kmeans
http
Step6: pyimagesearch
http
Step7: Final St... | Python Code:
def get_colors(img, numcolors=5):
#image = image.resize((resize, resize))
result = img.convert('P', palette=Image.ADAPTIVE, colors=numcolors)
result.putalpha(0)
return result.getcolors()
image = Image.open(images[0])
%time colors = get_colors(image)
colors = get_colors(Image.open(images[0])... |
2,650 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Topics discussed in knesset committees.
Based on transcripts of the knesset committees.<br/>
The work was done in the 'public knowledge workshop' hackathon and won 3rd place prize.
Analyze t... | Python Code:
import pandas as pd
from matplotlib import pyplot as plt
import warnings
warnings.filterwarnings('ignore')
# Normalize the topics' scores
def normalize_scores(scores):
max_i = (0, -1)
second_i = (0, -1)
third_i = (0, -1)
for i in range(len(scores)):
if scores[i] != 0:
if... |
2,651 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<img src="images/csdms_logo.jpg">
Using a BMI
Step1: Import the Cem class, and instantiate it. In Python, a model with a BMI will have no arguments for its constructor. Note that although t... | Python Code:
%matplotlib inline
import numpy as np
Explanation: <img src="images/csdms_logo.jpg">
Using a BMI: Coupling Waves and Coastline Evolution Model
This example explores how to use a BMI implementation to couple the Waves component with the Coastline Evolution Model component.
Links
CEM source code: Look at the... |
2,652 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
DiscreteDP Example
Step2: Here, in the state space we include states that are not reached
due to the constraint that the asset can be serviced at most one per year,
i.e., those pairs of the... | Python Code:
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
import quantecon as qe
from quantecon.markov import DiscreteDP
maxage = 5 # Maximum asset age
repcost = 75 # Replacement cost
mancost = 10 # Maintainance cost
beta = 0.9 # Discount factor
m = 3 # Number of actions; 0: kee... |
2,653 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Don't forget to delete the hdmi_out and hdmi_in when finished
Motion Blur Filter Example
In this notebook, we will demonstrate how to use the motion blur filter. This filter shows that parti... | Python Code:
from pynq.drivers.video import HDMI
from pynq import Bitstream_Part
from pynq.board import Register
from pynq import Overlay
Overlay("demo.bit").download()
Explanation: Don't forget to delete the hdmi_out and hdmi_in when finished
Motion Blur Filter Example
In this notebook, we will demonstrate how to use ... |
2,654 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Protobuf Serialisation
This notebook documents how Acton serialises protobufs.
Protobufs can be serialised and deserialised individually using the built-in methods SerializeToString and Pars... | Python Code:
# Serialising.
with open(path, 'wb') as proto_file:
proto_file.write(proto.SerializeToString())
# Deserialising. (from acton.proto.io)
proto = Proto()
with open(path, 'rb') as proto_file:
proto.ParseFromString(proto_file.read())
Explanation: Protobuf Serialisation
This notebook documents how Acton ... |
2,655 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<H2>A normally distributed random variable</H2>
<P>
Assume $X$ is a random variable which is normally distributed
Step1: <H2>Sum of 2 normally distributed random variables</H2>
<P>
Assume $... | Python Code:
# create a normally distributed random variable with mu and sigma
mu = 28.74
sigma = 8.33 # standard deviation!
rv_X = norm(loc = mu, scale = sigma)
# plot the theoretical and empirical distributions
x = np.linspace(start = rv_X.ppf(0.001), stop = rv_X.ppf(0.999), num = 100)
plt.plot(x, rv_X.pdf(x), color ... |
2,656 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
tridesclous example with olfactory bulb dataset
Step1: DataIO = define datasource and working dir
trideclous provide some datasets than can be downloaded.
Note this dataset contains 3 trial... | Python Code:
%matplotlib inline
import time
import numpy as np
import matplotlib.pyplot as plt
import tridesclous as tdc
from tridesclous import DataIO, CatalogueConstructor, Peeler
Explanation: tridesclous example with olfactory bulb dataset
End of explanation
#download dataset
localdir, filenames, params = tdc.downlo... |
2,657 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
An OrderedDict is a dictionary subclass that remembers the order in which its contents are added.
Step1: A regular dict does not track the insertion order, and iterating over it produces th... | Python Code:
import collections
print('Regular dictionary:')
d = {}
d['a'] = 'A'
d['b'] = 'B'
d['c'] = 'C'
for k, v in d.items():
print(k, v)
print('\nOrderedDict:')
d = collections.OrderedDict()
d['a'] = 'A'
d['b'] = 'B'
d['c'] = 'C'
for k, v in d.items():
print(k, v)
Explanation: An OrderedDict is a dictionar... |
2,658 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
DV360 Report To Sheets
Move existing DV360 report into a Sheets tab.
License
Copyright 2020 Google LLC,
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this f... | Python Code:
!pip install git+https://github.com/google/starthinker
Explanation: DV360 Report To Sheets
Move existing DV360 report into a Sheets tab.
License
Copyright 2020 Google LLC,
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You ma... |
2,659 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: Functions
Storing individual Python commands for re-use is one thing. Creating a function that can be repeatedly applied to different input data is quite another, and of huge importan... | Python Code:
def add(x, y):
Add two numbers
Parameters
----------
x : float
First input
y : float
Second input
Returns
-------
x + y : float
return x + y
add(1, 2)
Explanation: Functions
Storing individual Python commands for re-use is on... |
2,660 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Preprocessing Pipeline
Create a BIDSDataGrabber Node to read data files
Create a IdentityInterface Node to iterate over multiple Subjects
Create following Nodes for preprocessing
Step1: Def... | Python Code:
from bids.grabbids import BIDSLayout
from nipype.interfaces.fsl import (BET, ExtractROI, FAST, FLIRT, ImageMaths,
MCFLIRT, SliceTimer, Threshold,Info, ConvertXFM,MotionOutliers)
from nipype.interfaces.afni import Resample
from nipype.interfaces.io import DataSink
from nip... |
2,661 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Sentiment analysis with TFLearn
In this notebook, we'll continue Andrew Trask's work by building a network for sentiment analysis on the movie review data. Instead of a network written with ... | Python Code:
import pandas as pd
import numpy as np
import tensorflow as tf
import tflearn
from tflearn.data_utils import to_categorical
Explanation: Sentiment analysis with TFLearn
In this notebook, we'll continue Andrew Trask's work by building a network for sentiment analysis on the movie review data. Instead of a n... |
2,662 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Loopless FBA
The goal of this procedure is identification of a thermodynamically consistent flux state without loops, as implied by the name. You can find a more detailed description in the ... | Python Code:
%matplotlib inline
import plot_helper
import cobra.test
from cobra import Reaction, Metabolite, Model
from cobra.flux_analysis.loopless import add_loopless, loopless_solution
from cobra.flux_analysis import pfba
Explanation: Loopless FBA
The goal of this procedure is identification of a thermodynamically c... |
2,663 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Logging results and uploading models to Comet ML
In this example, we train a simple XGBoost model and log the training
results to Comet ML. We also save the resulting model checkpoints
as ar... | Python Code:
!pip install -qU "ray[tune]" sklearn xgboost_ray comet_ml
Explanation: Logging results and uploading models to Comet ML
In this example, we train a simple XGBoost model and log the training
results to Comet ML. We also save the resulting model checkpoints
as artifacts.
Let's start with installing our depen... |
2,664 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Purpose
Provide Thread-Safe FIFO Implementation
multi-producer, multi-consumer queue
Basic FIFO Queue
The Queue class implements a basic first-in, first-out container. Element are added to o... | Python Code:
import queue
q = queue.Queue()
for i in range(5):
q.put(i)
while not q.empty():
print(q.get(), end=' ')
Explanation: Purpose
Provide Thread-Safe FIFO Implementation
multi-producer, multi-consumer queue
Basic FIFO Queue
The Queue class implements a basic first-in, first-out container. Element a... |
2,665 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
CNN HandsOn with Keras
Problem Definition
Recognize handwritten digits
Data
The MNIST database (link) has a database of handwritten digits.
The training set has $60,000$ samples.
The test ... | 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: CNN HandsOn with Keras
Problem Definition
Recognize handwritten digits
Data
The MNIST database (link) has a database of handwritten digits.
The trainin... |
2,666 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Title of Database
Step1: Import and basic data inspection
Step2: The dataframe consists of only positive values and the classes are encoded as strings in the variable with index 24
Step3: ... | Python Code:
# modules
from keras.layers import Input, Dense, Dropout
from keras.models import Model
from keras.datasets import mnist
from keras.models import Sequential, load_model
from keras.optimizers import RMSprop
from keras.callbacks import TensorBoard
from __future__ import print_function
from keras.utils import... |
2,667 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
IPython 3 (jupyter)
Video Toturial
Step1: $$Julia + Python + R = jupyter$$
This is not to indicate that jupyter only supports these languages. But it is a reference to a talk by Fernando Pe... | Python Code:
from IPython.display import Image
Image(filename='kernel.png')
Explanation: IPython 3 (jupyter)
Video Toturial: https://www.youtube.com/user/roshanRush
Jupyter is an web-based interactive development environment. It support multiple programming languages like Julia, Octave, Python and R (In alphabetical or... |
2,668 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Using Variational Autoencoder to Generate Faces
In this example, we are going to use VAE to generate faces. The dataset we are going to use is CelebA. The dataset consists of more than 200K ... | Python Code:
from bigdl.nn.layer import *
from bigdl.nn.criterion import *
from bigdl.optim.optimizer import *
from bigdl.dataset import mnist
import datetime as dt
from glob import glob
import os
import numpy as np
from utils import *
import imageio
image_size = 148
Z_DIM = 128
ENCODER_FILTER_NUM = 32
#download the da... |
2,669 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Getting started with TensorFlow (Graph Mode)
Learning Objectives
- Understand the difference between Tensorflow's two modes
Step1: Graph Execution
Adding Two Tensors
Build the Graph
Unlik... | Python Code:
import tensorflow as tf
print(tf.__version__)
Explanation: Getting started with TensorFlow (Graph Mode)
Learning Objectives
- Understand the difference between Tensorflow's two modes: Eager Execution and Graph Execution
- Get used to deferred execution paradigm: first define a graph then run it in a tf... |
2,670 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Using pretrained GloVe Embedding
Step1: Download data
Step2: With pre-defined and fixed embeddings, we can not be better than just guessing
Step3: Embedding trainable, but still pre-set
S... | Python Code:
# Based on
# https://github.com/fchollet/deep-learning-with-python-notebooks/blob/master/6.1-using-word-embeddings.ipynb
# https://machinelearningmastery.com/develop-word-embeddings-python-gensim/
import warnings
warnings.filterwarnings('ignore')
%matplotlib inline
%pylab inline
import tensorflow as tf
tf.... |
2,671 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
ES-DOC CMIP6 Model Properties - Ocnbgchem
MIP Era
Step1: Document Authors
Set document authors
Step2: Document Contributors
Specify document contributors
Step3: Document Publication
Speci... | Python Code:
# DO NOT EDIT !
from pyesdoc.ipython.model_topic import NotebookOutput
# DO NOT EDIT !
DOC = NotebookOutput('cmip6', 'hammoz-consortium', 'mpiesm-1-2-ham', 'ocnbgchem')
Explanation: ES-DOC CMIP6 Model Properties - Ocnbgchem
MIP Era: CMIP6
Institute: HAMMOZ-CONSORTIUM
Source ID: MPIESM-1-2-HAM
Topic: ... |
2,672 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Stack Overflow Network Analysis
Claas Brüß, Simon Romanski and Maximilian Rünz
NOTE
Step1: 2 Data processing
The data behind this project was provided by Stack Overflow itself. They release... | Python Code:
%matplotlib inline
import os
import networkx as nx
import numpy as np
import matplotlib.pyplot as plt
from scipy import sparse
# Own modules
import DataProcessing as proc
import DataCleaning as clean
import NetworkAnalysis as analysis
import Classification as classification
import NetworkEvolution as evol
... |
2,673 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Nonlinear Classification and Regression with Decision Trees
Decision trees
Decision trees are commonly learned by recursively splitting the set of training
instances into subsets based on th... | Python Code:
# import
import pandas as pd
from sklearn.tree import DecisionTreeClassifier
from sklearn.grid_search import GridSearchCV
from sklearn.metrics import classification_report
from sklearn.model_selection import train_test_split
from sklearn.pipeline import Pipeline
from sklearn.ensemble import RandomForestCla... |
2,674 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Ejercicio
Simplifica los cocientes entre factoriales
Step1: Ejercicio
Calcula las siguientes operaciones | Python Code:
enunciado = list([r'\frac{7!}{6!}',r'\frac{{8!}}{{9!}}',r'\frac{{9!}}{{5!\cdot 4!}}',r'\frac{{m!}}{{(m - 1)!}}', r'\frac{{( {m + 1} )!}}{{( {m - 1} )!}}'])
enunciado
enunciado = list([r'\frac{7!}{6!}',r'\frac{{8!}}{{9!}}',r'\frac{{9!}}{{5!\cdot 4!}}',r'\frac{{m!}}{{(m - 1)!}}', r'\frac{{( {m + 1} )!}}{{( {... |
2,675 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<a href="https
Step1: Solvers
Step2: Undeterdetermined case (expect gradient descent to give sublinear convergence)
Step3: Question for thought | Python Code:
import numpy as np
from numpy.linalg import norm
from matplotlib import pyplot as plt
rng = np.random.default_rng()
Explanation: <a href="https://colab.research.google.com/github/stephenbeckr/convex-optimization-class/blob/master/Demos/ConvergenceRateDemo.ipynb" target="_parent"><img src="https://colab.r... |
2,676 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
NumPy
Step1: Multidimensional array type
Step2: Creating arrays
Step3: See also
Step4: All array creation functions accept an optional dtype argument
Step5: You can use the astype metho... | Python Code:
%matplotlib inline
from matplotlib import pyplot as plt
plt.style.use('ggplot')
Explanation: NumPy: Numerical Arrays for Python
Learning Objectives: Learn how to create, transform and visualize multidimensional data of a single type using Numpy.
NumPy is the foundation for scientific computing and data sc... |
2,677 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Introduction to pyrpl
1) Introduction
The RedPitaya is an affordable FPGA board with fast analog inputs and outputs. This makes it interesting also for quantum optics experiments. The softwa... | Python Code:
import pyrpl
print(pyrpl.__file__)
Explanation: Introduction to pyrpl
1) Introduction
The RedPitaya is an affordable FPGA board with fast analog inputs and outputs. This makes it interesting also for quantum optics experiments. The software package PyRPL (Python RedPitaya Lockbox) is an implementation of m... |
2,678 | Given the following text problem statement, write Python code to implement the functionality described below in problem statement
Problem:
How to batch convert sentence lengths to masks in PyTorch? | Problem:
import numpy as np
import pandas as pd
import torch
lens = load_data()
max_len = max(lens)
mask = torch.arange(max_len).expand(len(lens), max_len) < lens.unsqueeze(1)
mask = mask.type(torch.LongTensor) |
2,679 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Spatial Model fitting in GLS
In this exercise we will fit a linear model using a Spatial structure as covariance matrix.
We will use GLS to get better estimators.
As always we will need to ... | Python Code:
# Load Biospytial modules and etc.
%matplotlib inline
import sys
sys.path.append('/apps')
sys.path.append('..')
sys.path.append('../spystats')
import django
django.setup()
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
## Use the ggplot style
plt.style.use('ggplot')
import tools
Exp... |
2,680 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Numpy and Scipy Tutorial
Numpy and Scipy are the most common Python package for mathematical and numerical routines in precompiled, fast functions. The NumPy package provides basic routines ... | Python Code:
import numpy as np
import scipy as cp
Explanation: Numpy and Scipy Tutorial
Numpy and Scipy are the most common Python package for mathematical and numerical routines in precompiled, fast functions. The NumPy package provides basic routines for manipulating large arrays and matrices of numeric data.
The Sc... |
2,681 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
End-to-end Recommender System with NVIDIA Merlin and Vertex AI.
This notebook shows how to deploy and execute an end-to-end recommender system on Vertex Pipelines using NVIDIA Merlin.
The no... | Python Code:
import os
import json
from datetime import datetime
from google.cloud import aiplatform as vertex_ai
from kfp.v2 import compiler
Explanation: End-to-end Recommender System with NVIDIA Merlin and Vertex AI.
This notebook shows how to deploy and execute an end-to-end recommender system on Vertex Pipelines us... |
2,682 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Derivatives of a TPS
Step1: We start by defining the source and target landmarks. Notice that, in this first example source = target!!!
Step2: The warp can be effectively computed, althoug... | Python Code:
import os
import numpy as np
import scipy.io as sio
import matplotlib.pyplot as plt
from menpo.shape import PointCloud
import menpo.io as mio
from menpofit.transform import DifferentiableThinPlateSplines
Explanation: Derivatives of a TPS
End of explanation
src_landmarks = PointCloud(np.array([[-1, -1],
... |
2,683 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<a href="http
Step1: Describing subsidence due to fault motion
From here, we can think about the subsidence rate of the hangingwall as a function of horizontal extension velocity, $u$. We c... | Python Code:
import numpy as np
import matplotlib.pyplot as plt
alpha0 = 60.0 # fault dip at surface, degrees
z0 = 0.0 # elevation of surface trace
h = 10.0 # detachment depth, km
G0 = np.tan(np.deg2rad(60.0))
x = np.arange(0, 41.0)
z = z0 - h * (1.0 - np.exp(-x * G0 / h))
plt.plot(x, z, "k")
plt.xlabel("Distance (k... |
2,684 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Product of independent complex-circular Gaussian Random Variable
Let $z\sim \mathcal{CN}(0, \sigma^2)$ and if $z = x + {\rm j}y$, both $x$ and $y$ are zero mean Gaussian r.v. with variance $... | Python Code:
# magic
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
# prettyplot stuff
import seaborn as sns
sns.set(style='ticks', palette='Set2')
sns.despine()
mu = 0
sigmasq = 1
sd = np.sqrt(sigmasq)
# Generate complex gaussian r.v. samples
x = np.random.normal(loc = mu, scale = sd/np.sqrt(2),... |
2,685 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Soluciones a los ejercicios propuestos
Nivel básico
1.
Haz un pequeño programa que le pida al usuario introducir dos números ($x_1$ y $x_2$), calcule la siguiente operación y muestre el resu... | Python Code:
x1 = int(input("Introduce un número: "))
x2 = int(input("Y ahora otro: "))
x = (20 * x1 - x2)/(x2 + 3)
print("x =",x)
Explanation: Soluciones a los ejercicios propuestos
Nivel básico
1.
Haz un pequeño programa que le pida al usuario introducir dos números ($x_1$ y $x_2$), calcule la siguiente operación y m... |
2,686 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Sebastian Raschka
back to the matplotlib-gallery at https
Step1: <font size="1.5em">More info about the %watermark extension</font>
Step2: <br>
<br>
Matplotlib Formatting III
Step3: <br>
... | Python Code:
%load_ext watermark
%watermark -u -v -d -p matplotlib,numpy
Explanation: Sebastian Raschka
back to the matplotlib-gallery at https://github.com/rasbt/matplotlib-gallery
End of explanation
%matplotlib inline
Explanation: <font size="1.5em">More info about the %watermark extension</font>
End of explanation
i... |
2,687 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Webscraping with Beautiful Soup
Intro
In this tutorial, we'll be scraping information on the state senators of Illinois, available here, as well as the list of bills each senator has sponsor... | Python Code:
# import required modules
import requests
from bs4 import BeautifulSoup
from datetime import datetime
import time
import re
import sys
Explanation: Webscraping with Beautiful Soup
Intro
In this tutorial, we'll be scraping information on the state senators of Illinois, available here, as well as the list of... |
2,688 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step2: Binary vector generator
Version 1
Type checking
Step5: Binary vector generator
Version 2 - via Itertool
Step9: Accumulator Inputs ##
Step11: Label the data
Step13: Create dataset
... | Python Code:
from scipy.special import comb
import numpy as np
def how_many(max_n = 6, length = 16):
Compute how many different binary vectors of a given length can be formed up to a given number.
If a list is passed, compute the vectors as specified in the list.
if isinstance(max_n, int):
... |
2,689 | 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 11 ... | 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... |
2,690 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Visualizing Supervised Machine Learning
Experiments
Logistic Regression
http
Step1: Loading and exploring our data set
This is a database of customers of an insurance company. Each data poi... | Python Code:
import warnings
warnings.filterwarnings('ignore')
%matplotlib inline
%pylab inline
import matplotlib.pyplot as plt
plt.xkcd()
# if this is true, all images are saved to disk
global_print_flag = False
!mkdir tmp_figures
Explanation: Visualizing Supervised Machine Learning
Experiments
Logistic Regression
htt... |
2,691 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Vertex AI Custom Image Classification Model for Batch Prediction
Overview
In this notebook, you learn how to use the Vertex SDK for Python to train and deploy a custom image classification m... | Python Code:
# Setup your dependencies
import os
# The Google Cloud Notebook product has specific requirements
IS_GOOGLE_CLOUD_NOTEBOOK = os.path.exists("/opt/deeplearning/metadata/env_version")
# Google Cloud Notebook requires dependencies to be installed with '--user'
USER_FLAG = ""
if IS_GOOGLE_CLOUD_NOTEBOOK:
U... |
2,692 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Plotting a resistivity model from ModEM on a basemap
In this example we will plot a resistivity model on a basemap. This example is a bit more complex than previous examples, as, unlike the ... | Python Code:
from mtpy.modeling.modem import Model, Data
from mtpy.utils import gis_tools
import matplotlib.pyplot as plt
from matplotlib import colors
from mpl_toolkits.basemap import Basemap
from shapely.geometry import Polygon
from descartes import PolygonPatch
import numpy as np
Explanation: Plotting a resistivity ... |
2,693 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Predict with Model
View Config
Step1: Predict with Model (CLI)
Step2: Predict with Model under Mini-Load (CLI)
This is a mini load test to provide instant feedback on relative performance.... | Python Code:
%%bash
pio init-model \
--model-server-url http://prediction-python3.community.pipeline.io \
--model-type python3 \
--model-namespace default \
--model-name python3_zscore \
--model-version v1 \
--model-path .
Explanation: Predict with Model
View Config
End of explanation
%%bash
pio predict \
... |
2,694 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Running ProjectQ code on AWS Braket service provided devices
Compiling code for AWS Braket Service
In this tutorial we will see how to run code on some of the devices provided by the Amazon ... | Python Code:
from projectq import MainEngine
from projectq.backends import AWSBraketBackend
from projectq.ops import Measure, H, C, X, All
Explanation: Running ProjectQ code on AWS Braket service provided devices
Compiling code for AWS Braket Service
In this tutorial we will see how to run code on some of the devices p... |
2,695 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Attribution
Step2: For Machine Learning, we are mainly interested in unconstrained minimization of multivariate scalar functions (typically where gradient information is available). In addi... | Python Code:
help(scipy.optimize)
Explanation: Attribution: These examples are taken from the Scipy Tutorial
The scipy.optimize package provides several commonly used optimization algorithms. A detailed listing can be found by:
End of explanation
import numpy as np
from scipy.optimize import minimize
def rosen(x):
... |
2,696 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Portfolio Optimization Using Signals
by Magnus Erik Hvass Pedersen
/ GitHub / Videos on YouTube
Introduction
We are interested in combining multiple stocks into a single investment portfolio... | Python Code:
%matplotlib inline
# Imports from Python packages.
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
from sklearn.preprocessing import MinMaxScaler
# Imports from FinanceOps.
from data_keys import *
from data import load_stock_data, load_index_data
from portfolio import EqualWeights, F... |
2,697 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2019 The TensorFlow Authors.
Step1: 畳み込みニューラルネットワーク (Convolutional Neural Networks)
<table class="tfo-notebook-buttons" align="left">
<td> <a target="_blank" href="https
Ste... | 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... |
2,698 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Boosting to Uniformity
In physical applications frequently we need to achieve uniformity of predictions along some features.
For instance, when testing the existence of new particle, we need... | Python Code:
# downloading data
!wget -O ../data/dalitzdata.root -nc https://github.com/arogozhnikov/hep_ml/blob/data/data_to_download/dalitzdata.root?raw=true
%pylab inline
import pandas, numpy
from sklearn.cross_validation import train_test_split
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble i... |
2,699 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Novel-taxa and simulated community generation
This notebook describes the generation of reference databases for both novel-taxa and simulated community analyses. Novel-taxa analysis is a for... | Python Code:
from tax_credit.framework_functions import \
generate_simulated_datasets, distance_comparison, \
test_cross_validated_sequences, \
test_novel_taxa_datasets
from os.path import expandvars, join
import pandas as pd
%matplotlib inline
project_dir = expandvars("../..")
data_dir = join(project_dir, ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.