Unnamed: 0 int64 0 16k | text_prompt stringlengths 110 62.1k | code_prompt stringlengths 37 152k |
|---|---|---|
7,500 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
H2O Tutorial
Author
Step1: Enable inline plotting in the Jupyter Notebook
Step2: Intro to H2O Data Munging
Read csv data into H2O. This loads the data into the H2O column compressed, in-me... | Python Code:
import pandas as pd
import numpy
from numpy.random import choice
from sklearn.datasets import load_boston
import h2o
h2o.init()
# transfer the boston data from pandas to H2O
boston_data = load_boston()
X = pd.DataFrame(data=boston_data.data, columns=boston_data.feature_names)
X["Median_value"] = boston_dat... |
7,501 | Given the following text problem statement, write Python code to implement the functionality described below in problem statement
Problem:
Is there any way for me to preserve punctuation marks of !, ?, " and ' from my text documents using text CountVectorizer parameters in scikit-learn? | Problem:
import numpy as np
import pandas as pd
from sklearn.feature_extraction.text import CountVectorizer
text = load_data()
vent = CountVectorizer(token_pattern=r"(?u)\b\w\w+\b|!|\?|\"|\'")
transformed_text = vent.fit_transform([text]) |
7,502 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
A full-fledged scraper
Import our modules or packages that we will need to scrape a website, including requests and bs4 and csv
Step1: Make a request to the webpage url that we are scraping... | Python Code:
import requests
from bs4 import BeautifulSoup
import csv
Explanation: A full-fledged scraper
Import our modules or packages that we will need to scrape a website, including requests and bs4 and csv
End of explanation
r = requests.get('https://s3-us-west-2.amazonaws.com/nicar-2015/Weekly+Rankings+-+Weekend+... |
7,503 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
By deploying or using this software you agree to comply with the AI Hub Terms of Service and the Google APIs Terms of Service. To the extent of a direct conflict of terms, the AI Hub Terms o... | Python Code:
PROJECT_ID = "[your-project-id]" #@param {type:"string"}
! gcloud config set project $PROJECT_ID
Explanation: By deploying or using this software you agree to comply with the AI Hub Terms of Service and the Google APIs Terms of Service. To the extent of a direct conflict of terms, the AI Hub Terms of Servi... |
7,504 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Variable Coefficient Poisson
Derive the form of a test variable-coefficient elliptic equation with periodic boundary conditions for testing the variable-coefficient multigrid solver.
We want... | Python Code:
%pylab inline
from sympy import init_session
init_session()
alpha = 2.0 + cos(2*pi*x)*cos(2*pi*y)
phi = sin(2*pi*x)*sin(2*pi*y)
Explanation: Variable Coefficient Poisson
Derive the form of a test variable-coefficient elliptic equation with periodic boundary conditions for testing the variable-coefficient m... |
7,505 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Tests overlaying rule 18 values on top of spacetime diagram
Step1: Tests overlaying inferred states on top of rule 18 spacetime diagram | Python Code:
overlay_test(rule_18.get_spacetime(),rule_18.get_spacetime(),t_max=20, x_max=20, text_color='red')
overlay_test(rule_18.get_spacetime(),rule_18.get_spacetime(),t_max=20, x_max=20, colors=plt.cm.Set2, text_color='black')
overlay_test(rule_18.get_spacetime(),rule_18.get_spacetime(),t_max=20, x_max=20, colorb... |
7,506 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Exercise from Think Stats, 2nd Edition (thinkstats2.com)<br>
Allen Downey
Read the female respondent file.
Step1: Make a PMF of <tt>numkdhh</tt>, the number of children under 18 in the resp... | Python Code:
%matplotlib inline
import chap01soln
resp = chap01soln.ReadFemResp()
Explanation: Exercise from Think Stats, 2nd Edition (thinkstats2.com)<br>
Allen Downey
Read the female respondent file.
End of explanation
import thinkstats2 as ts
children_PMF = ts.Pmf(resp.numkdhh)
Explanation: Make a PMF of <tt>numkdhh... |
7,507 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Repairing artifacts with SSP
This tutorial covers the basics of signal-space projection (SSP) and shows
how SSP can be used for artifact repair; extended examples illustrate use
of SSP for e... | Python Code:
import os
import numpy as np
import matplotlib.pyplot as plt
import mne
from mne.preprocessing import (create_eog_epochs, create_ecg_epochs,
compute_proj_ecg, compute_proj_eog)
Explanation: Repairing artifacts with SSP
This tutorial covers the basics of signal-space projectio... |
7,508 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Transient Fickian Diffusion
The package OpenPNM allows for the simulation of many transport phenomena in porous media such as Stokes flow, Fickian diffusion, advection-diffusion, transport o... | Python Code:
import numpy as np
import openpnm as op
%config InlineBackend.figure_formats = ['svg']
np.random.seed(10)
%matplotlib inline
np.set_printoptions(precision=5)
Explanation: Transient Fickian Diffusion
The package OpenPNM allows for the simulation of many transport phenomena in porous media such as Stokes flo... |
7,509 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
How to forecast time series in BigQuery ML
This notebook accompanies the article
How to do time series forecasting in BigQuery
Install library and extensions if needed
You don't need to do t... | Python Code:
#!pip install google-cloud-bigquery
%load_ext google.cloud.bigquery
Explanation: How to forecast time series in BigQuery ML
This notebook accompanies the article
How to do time series forecasting in BigQuery
Install library and extensions if needed
You don't need to do this if you use AI Platform Notebooks... |
7,510 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Machine Learning Using Python by ARCC
What is Machine Learning?
Machine Learning is the subfield of computer science, which is defined by Arthur Samuel as "Giving computers the ability to le... | Python Code:
#NumPy is the fundamental package for scientific computing with Python
import numpy as np
# Matplotlib is a Python 2D plotting library
import matplotlib.pyplot as plt
#Number of data points
n=50
x=np.random.randn(n)
y=np.random.randn(n)
#Create a figure and a set of subplots
fig, ax = plt.subplots()
#Find... |
7,511 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Excercises Electric Machinery Fundamentals
Chapter 1
Problem 1-18
Step1: Description
Assume that the voltage applied to a load is $\vec{V} = 208\,V\angle -30^\circ$ and the current flowing ... | Python Code:
%pylab notebook
Explanation: Excercises Electric Machinery Fundamentals
Chapter 1
Problem 1-18
End of explanation
V = 208.0 * exp(-1j*30/180*pi) # [V]
I = 2.0 * exp( 1j*20/180*pi) # [A]
Explanation: Description
Assume that the voltage applied to a load is $\vec{V} = 208\,V\angle -30^\circ$ and the curr... |
7,512 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Source alignment and coordinate frames
The aim of this tutorial is to show how to visually assess that the data are
well aligned in space for computing the forward solution, and understand
t... | Python Code:
import os.path as op
import numpy as np
from mayavi import mlab
import mne
from mne.datasets import sample
print(__doc__)
data_path = sample.data_path()
subjects_dir = op.join(data_path, 'subjects')
raw_fname = op.join(data_path, 'MEG', 'sample', 'sample_audvis_raw.fif')
trans_fname = op.join(data_path, 'M... |
7,513 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
ES-DOC CMIP6 Model Properties - Ocean
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', 'bnu', 'sandbox-1', 'ocean')
Explanation: ES-DOC CMIP6 Model Properties - Ocean
MIP Era: CMIP6
Institute: BNU
Source ID: SANDBOX-1
Topic: Ocean
Sub-Topics: Timestepping Framework, Adve... |
7,514 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
An IPython notebook that explores the relationship(correlation) between betweenness centrality and community membership of a number of mailing-lists in a given time period.
Step1: The follo... | Python Code:
%matplotlib inline
from bigbang.archive import Archive
import bigbang.parse as parse
import bigbang.analysis.graph as graph
import bigbang.ingress.mailman as mailman
import bigbang.analysis.process as process
import networkx as nx
import matplotlib.pyplot as plt
import pandas as pd
from pprint import pprin... |
7,515 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
In TBtrans and TranSiesta one is capable of performing real space transport calculations by using real space self-energies (see here).
Currently the real space self-energy calculation has to... | Python Code:
graphene = sisl.geom.graphene(orthogonal=True)
# Graphene tight-binding parameters
on, nn = 0, -2.7
H_minimal = sisl.Hamiltonian(graphene)
H_minimal.construct([[0.1, 1.44], [on, nn]])
Explanation: In TBtrans and TranSiesta one is capable of performing real space transport calculations by using real space s... |
7,516 | Given the following text problem statement, write Python code to implement the functionality described below in problem statement
Problem:
How does one convert a left-tailed p-value to a z_score from the Z-distribution (standard normal distribution, Gaussian distribution)? I have yet to find the magical function in Sci... | Problem:
import numpy as np
import scipy.stats
p_values = [0.1, 0.225, 0.5, 0.75, 0.925, 0.95]
z_scores = scipy.stats.norm.ppf(p_values) |
7,517 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<h1 align="center">TensorFlow Neural Network Lab</h1>
<img src="image/notmnist.png">
In this lab, you'll use all the tools you learned from Introduction to TensorFlow to label images of Engl... | Python Code:
import hashlib
import os
import pickle
from urllib.request import urlretrieve
import numpy as np
from PIL import Image
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import LabelBinarizer
from sklearn.utils import resample
from tqdm import tqdm
from zipfile import ZipFile
p... |
7,518 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Sample code to test features of 'NumPy', 'Matplotlib' and 'Scipy'
Importing includes
Step1: Testing variable assignment and operations in python
Step2: Extra
Step3: Simple Linear Regressi... | Python Code:
%matplotlib inline
%pylab inline
from __future__ import print_function
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import theano
import numpy as np
from theano import tensor as T
from numpy.linalg import inv
Explanation: Sample code to test features of 'NumPy', 'Matplotlib' and... |
7,519 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright Jana Schaich Borg/Attribution-NonCommercial 4.0 International (CC BY-NC 4.0)
MySQL Exercise 3
Step1: 1. Use AS to change the titles of the columns in your output
The AS clause all... | Python Code:
%load_ext sql
%sql mysql://studentuser:studentpw@mysqlserver/dognitiondb
%sql USE dognitiondb
%config SqlMagic.displaylimit=25
Explanation: Copyright Jana Schaich Borg/Attribution-NonCommercial 4.0 International (CC BY-NC 4.0)
MySQL Exercise 3: Formatting Selected Data
In this lesson, we are going to learn... |
7,520 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
A Network Tour of Data Science, EPFL 2016
Project
Step1: Load the data from *.csv file
The first step is to load the data from the .csv file. <br> The format of the csv line is<br>
class{0... | Python Code:
import random
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
import csv
import scipy.misc
import time
import collections
import os
import utils as ut
import importlib
import copy
importlib.reload(ut)
# This is a bit of magic to make matplotlib figures appear inline in the notebo... |
7,521 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
SAM Registry Hive Handle Request
Metadata
| | |
|
Step1: Download & Process Mordor Dataset
Step2: Analytic I
Monitor for any handle requested for the SAM registry hive... | Python Code:
from openhunt.mordorutils import *
spark = get_spark()
Explanation: SAM Registry Hive Handle Request
Metadata
| | |
|:------------------|:---|
| collaborators | ['@Cyb3rWard0g', '@Cyb3rPandaH'] |
| creation date | 2019/07/25 |
| modification date | 2020/09/20 |
| playbook relat... |
7,522 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
dataset
We generate a dataset, y and a sub-sampled version y_sub
Step1: Regularisation
We wish to solve problems that involve the term | Python Code:
# pull a dataset and make it 1D for now
url='https://upload.wikimedia.org/wikipedia/en/0/04/TCF_centre.jpg'
im = np.array(Image.open(urllib.request.urlopen(url)).convert("L")).astype(float)
#
y = im/im.max()
plt.imshow(y,cmap='gray')
plt.colorbar()
# sub-sample
# how many samples to mask?
nmask = int(y.si... |
7,523 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
This is functionally similar to the the other notebook. All the operations here have been vectorized. This results in much much faster code, but is also much unreadable. The vectorization al... | Python Code:
import numpy as np
Explanation: This is functionally similar to the the other notebook. All the operations here have been vectorized. This results in much much faster code, but is also much unreadable. The vectorization also necessitated the replacement of the Gauss-Seidel smoother with under-relaxed Jacob... |
7,524 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: Nikola
Static site generator
Features
It’s just a bunch of HTML files and assets.
Incremental builds/rebuild using doit, so Nikola is fast.
Multilingual
Extensible
Friendly CLI
Multip... | Python Code:
from nbconvert.exporters import HTMLExporter
...
def _compile_string(self, nb_json):
Export notebooks as HTML strings.
self._req_missing_ipynb()
c = Config(self.site.config['IPYNB_CONFIG'])
c.update(get_default_jupyter_config())
exportHtml = HTMLExporter(config=c)
body, _ = exportHt... |
7,525 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Chapter 1 Introduction
Step1: History | Python Code:
show_image('fig1_5.png', figsize=[12, 10])
show_image('fig1_4.png', figsize=[10, 8])
Explanation: Chapter 1 Introduction
End of explanation
show_image('fig1_11.png', figsize=[10, 8])
Explanation: History:
distributed representation
back-propagation
long short-term memory (LSTM) network: used for many seque... |
7,526 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
===============================================================
Model selection with Probabilistic PCA and Factor Analysis (FA)
==============================================================... | Python Code:
# Authors: Alexandre Gramfort
# Denis A. Engemann
# License: BSD 3 clause
import numpy as np
import matplotlib.pyplot as plt
from scipy import linalg
from sklearn.decomposition import PCA, FactorAnalysis
from sklearn.covariance import ShrunkCovariance, LedoitWolf
from sklearn.model_selection impor... |
7,527 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Analysing PPG signals from smart rings
There's a range of Smart Rings that recently hit the market. Among other things they also record PPG signals on the finger, so let's dive into how to a... | Python Code:
#Let's import some packages first
import numpy as np
import matplotlib.pyplot as plt
import heartpy as hp
sample_rate = 32
#load the example file
data = hp.get_data('ring_data.csv')
Explanation: Analysing PPG signals from smart rings
There's a range of Smart Rings that recently hit the market. Among other ... |
7,528 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Target Connectivity
Configurable logging system
All LISA modules have been updated to use a more consistent logging which can be configured using a single configuraton file
Step1: Each modu... | Python Code:
!head -n12 $LISA_HOME/logging.conf
Explanation: Target Connectivity
Configurable logging system
All LISA modules have been updated to use a more consistent logging which can be configured using a single configuraton file:
End of explanation
!head -n30 $LISA_HOME/logging.conf | tail -n5
Explanation: Each mo... |
7,529 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Introduction
This tutorial shows how to use Google Cloud Platform technologies to work with structured healthcare data to build a predictive model.
Synthea
Synthea is a data generator that s... | Python Code:
from google.colab import auth
auth.authenticate_user()
credentials = auth._check_adc()
print(credentials)
Explanation: Introduction
This tutorial shows how to use Google Cloud Platform technologies to work with structured healthcare data to build a predictive model.
Synthea
Synthea is a data generator that... |
7,530 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Taylor approximations to color conversion
This notebook shows how to come up with all these magic constants that appear in the approximations to LinearRgb in my go-colorful library in order ... | Python Code:
%matplotlib inline
%config InlineBackend.figure_format = 'retina'
import matplotlib as mpl
import matplotlib.pyplot as plt
plt.style.use('ggplot')
import numpy as np
from sympy import *
init_printing()
Explanation: Taylor approximations to color conversion
This notebook shows how to come up with all these ... |
7,531 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<table style="width
Step1: Use debugging tools throughout!
Don't forget all the fun debugging tools we covered while you work on these exercises.
%debug
%pdb
import q;q.d()
And (if necessa... | Python Code:
%matplotlib inline
from __future__ import print_function
import os
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
PROJ_ROOT = os.path.join(os.pardir, os.pardir)
Explanation: <table style="width:100%; border: 0px solid black;">
<tr style="width: 100%; border: 0px solid black;"... |
7,532 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Using the C/C++ API
This notebook shows how to use the OpenMC C/C++ API through the openmc.lib module. This module is particularly useful for multiphysics coupling because it allows you to u... | Python Code:
%matplotlib inline
import openmc
import openmc.lib
Explanation: Using the C/C++ API
This notebook shows how to use the OpenMC C/C++ API through the openmc.lib module. This module is particularly useful for multiphysics coupling because it allows you to update the density of materials and the temperatures o... |
7,533 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Data exploration
To start with, let us load the dataframe, summarize the columns, and plot a sactter matrix of the data to check for e.g. missing values, non-linear scaling, etc..
Step1: Sc... | Python Code:
import pandas as pd
# Sample code number: id number
# Clump Thickness: 1 - 10
# 3. Uniformity of Cell Size: 1 - 10
# 4. Uniformity of Cell Shape: 1 - 10
# 5. Marginal Adhesion: 1 - 10
# 6. Single Epithelial Cell Size: 1 - 10
# 7. Bare Nuclei: 1 - 10
# 8. Bland Chromatin: 1 - 10
# 9. Normal Nucleoli: 1 ... |
7,534 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
What is the True Normal Human Body Temperature?
Background
The mean normal body temperature was held to be 37$^{\circ}$C or 98.6$^{\circ}$F for more than 120 years since it was first concept... | Python Code:
import pandas as pd
df = pd.read_csv('data/human_body_temperature.csv')
# Your work here.
# Load Matplotlib + Seaborn and SciPy libraries
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
from scipy import stats
%matplotlib inline
df.head(5)
Explanation: What is the True Normal Human... |
7,535 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<h1>2b. Machine Learning using tf.estimator </h1>
In this notebook, we will create a machine learning model using tf.estimator and evaluate its performance. The dataset is rather small (770... | Python Code:
!sudo chown -R jupyter:jupyter /home/jupyter/training-data-analyst
# Ensure the right version of Tensorflow is installed.
!pip freeze | grep tensorflow==2.6
import tensorflow as tf
import pandas as pd
import numpy as np
import shutil
print(tf.__version__)
Explanation: <h1>2b. Machine Learning using tf.esti... |
7,536 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Geotransforms
May-June, 2018, Mauro Alberti
Last version
Step1: Forward and backward transformation examples
Step2: calculating the X, Y geographic coordinate arrays | Python Code:
from pygsf.geometries.grids.geotransform import *
gt1 = GeoTransform(1500, 3000, 10, 10)
gt1
Explanation: Geotransforms
May-June, 2018, Mauro Alberti
Last version: 2021-04-24
Last running version: 2021-04-24
1. Examples
End of explanation
ijPixToxyGeogr(gt1, 0, 0)
xyGeogrToijPix(gt1, 1500, 3000)
ijPixToxyG... |
7,537 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
ES-DOC CMIP6 Model Properties - Landice
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', 'ncar', 'sandbox-3', 'landice')
Explanation: ES-DOC CMIP6 Model Properties - Landice
MIP Era: CMIP6
Institute: NCAR
Source ID: SANDBOX-3
Topic: Landice
Sub-Topics: Glaciers, Ice.
Prop... |
7,538 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<h1> Homework 2 </h1>
Matt Buchovecky
Astro 283
Step1: Set of measurements $\left{Y_{k}\right}$
at known locations $\left{X_{k}\right}$
Gaussian uncertainty $\sigma=1.0$
$p=30\%$ chance of ... | Python Code:
from scipy import random, optimize, std
from matplotlib import pyplot
%matplotlib inline
import numpy
import csv
Explanation: <h1> Homework 2 </h1>
Matt Buchovecky
Astro 283
End of explanation
sigma_meas = 1.0 # standard deviation of measurements
p_err = 0.30 # probability of experimental mistake occurri... |
7,539 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Brief look at Cartopy
Cartopy is a Python package that provides easy creation of maps with matplotlib.
Cartopy vs Basemap
Cartopy is better integrated with matplotlib and in a more active de... | Python Code:
import matplotlib.pyplot as plt
%matplotlib inline
Explanation: Brief look at Cartopy
Cartopy is a Python package that provides easy creation of maps with matplotlib.
Cartopy vs Basemap
Cartopy is better integrated with matplotlib and in a more active development state
Proper handling of datelines in carto... |
7,540 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step2: Optimization problems, objective functions and optimization benchmarks
TODO
Step3: Type of optimization problems
continuous vs discrete problems (possibly combinatorial if the set of... | Python Code:
%matplotlib inline
import numpy as np
import matplotlib
matplotlib.rcParams['figure.figsize'] = (8, 8)
import math
import matplotlib.pyplot as plt
import matplotlib.colors as colors
from mpl_toolkits.mplot3d import axes3d
from matplotlib import cm
import scipy.optimize
def plot_2d_contour_solution_space(fu... |
7,541 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Trying MountainCar
Step1: Let's try some arbitrary thetas
And see what the ratio depends on. I've seen above that it's probably not the order of the Fourier FA, but the number of dimensions... | Python Code:
mc_env = gym.make("MountainCar-v0")
mc_n_weights, mc_feature_vec = fourier_fa.make_feature_vec(
np.array([mc_env.low, mc_env.high]),
n_acts=3,
order=2)
mc_experience = linfa.init(lmbda=0.9,
... |
7,542 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Introduction to NumPy
numpy is a powerful set of tools to perform mathematical operations of on lists of numbers. It works faster than normal python lists operations and can manupilate high ... | Python Code:
import numpy as np
Explanation: Introduction to NumPy
numpy is a powerful set of tools to perform mathematical operations of on lists of numbers. It works faster than normal python lists operations and can manupilate high dimentional arrays too.
Additional material:
* Another tutorial
* Numpy Reference
Imp... |
7,543 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Introduction
NetworKit provides an easy interface to Gephi that uses the Gephi graph streaming plugin. To be able to use it, install the Graph Streaming plugin using the Gephi plugin manager... | Python Code:
G = generators.ErdosRenyiGenerator(300, 0.2).generate()
G.addEdge(0, 1) #We want to make sure this specific edge exists, for usage in an example later.
Explanation: Introduction
NetworKit provides an easy interface to Gephi that uses the Gephi graph streaming plugin. To be able to use it, install the Graph... |
7,544 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2020 The TensorFlow Authors.
Step1: Writing a training loop from scratch
<table class="tfo-notebook-buttons" align="left">
<td>
<a target="_blank" href="https
Step2: Introd... | Python Code:
#@title Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# dist... |
7,545 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
1A.data - Décorrélation de variables aléatoires
On construit des variables corrélées gaussiennes et on cherche à construire des variables décorrélées en utilisant le calcul matriciel.
Step1:... | Python Code:
from jyquickhelper import add_notebook_menu
add_notebook_menu()
Explanation: 1A.data - Décorrélation de variables aléatoires
On construit des variables corrélées gaussiennes et on cherche à construire des variables décorrélées en utilisant le calcul matriciel.
End of explanation
import random
import numpy ... |
7,546 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Intoduction to Pandas and Dataframes
<hr>
Venkat Malladi (Computational Biologist BICF)
Agenda
<hr>
Introduction to Pandas
DataSeries
Exercise 1
Exercise 2
Dataframe
Exercise 3
Exercise 4
E... | Python Code:
# Import Pandas and Numpy
import pandas as pd
import numpy as np
Explanation: Intoduction to Pandas and Dataframes
<hr>
Venkat Malladi (Computational Biologist BICF)
Agenda
<hr>
Introduction to Pandas
DataSeries
Exercise 1
Exercise 2
Dataframe
Exercise 3
Exercise 4
Exercise 5
Import and Store Data
Summari... |
7,547 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
← Back to Index
Jupyter Basics
You are looking at a Jupyter Notebook, an interactive Python shell inside of a web browser. With it, you can run individual Python commands and immediatel... | Python Code:
1+2
Explanation: ← Back to Index
Jupyter Basics
You are looking at a Jupyter Notebook, an interactive Python shell inside of a web browser. With it, you can run individual Python commands and immediately view their output. It's basically like the Matlab Desktop or Mathematica Notebook but for Python.... |
7,548 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Load station data based on NetCDF files
In this example we show how to load station data based on NetCDF files.
The data is loaded with the pymepps package. Thanks to Ingo Lange we
could use... | Python Code:
import pymepps
import matplotlib.pyplot as plt
Explanation: Load station data based on NetCDF files
In this example we show how to load station data based on NetCDF files.
The data is loaded with the pymepps package. Thanks to Ingo Lange we
could use original data from the Wettermast for this example. In t... |
7,549 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
AMPLPY
Step1: Google Colab & Kaggle interagration
Step2: Use %%ampl_eval to pass the model to AMPL
Step3: Set data
Step4: Use %%ampl_eval to display values
Step5: Use amplpy to retrive ... | Python Code:
!pip install -q amplpy ampltools
Explanation: AMPLPY: Jupyter Notebook Integration
Documentation: http://amplpy.readthedocs.io
GitHub Repository: https://github.com/ampl/amplpy
PyPI Repository: https://pypi.python.org/pypi/amplpy
Jupyter Notebooks: https://github.com/ampl/amplpy/tree/master/notebooks
Setup... |
7,550 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Create an auto transform to scale numeric columns automatically.
Step1: Create an XGBoost classifier and run 5-fold cross validation on the data. | Python Code:
df["target"] = df["target"] - 1
t_auto = auto.Auto_transform(exclude=["target"])
df2 = t_auto.fit_transform(df)
df2.head()
Explanation: Create an auto transform to scale numeric columns automatically.
End of explanation
from seldon import xgb
import seldon.pipeline.cross_validation as cf
xgb = xgb.XGBoostC... |
7,551 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Convergence on low-rank manifolds
Ivan Oseledets
Skolkovo Institute of Science and Technology
Based on joint work with C. Lubich, H. Walach, D. Kolesnikov
The topic of this talk
Recently, mu... | Python Code:
#2d case functions
def grad(A, x, x0):
#u, s, v = x
#u0, s0, v0 = x0
#u_new = np.linalg.qr(np.hstack((u, u0)))[0]
#v_new = np.linalg.qr(np.hstack((v, v0)))[0]
#s_new = u_new.T.dot(u).dot(s).dot(v.T.dot(v_new)) - u_new.T.dot(u0).dot(s0).dot(v0.T.dot(v_new))
return x0 - A.dot(full(x).... |
7,552 |
Given the following text problem statement, write Python code to implement the functionality described below in problem statement
Problem:
The function below generate_desc() implements this behavior and generates a textual description given a trained model, and a given prepared photo as input.
| Python Code::
# map an integer to a word
def word_for_id(integer, tokenizer):
for word, index in tokenizer.word_index.items():
if index == integer:
return word
return None
# generate a description for an image
def generate_desc(model, tokenizer, photo, max_length):
# seed the generation process
in_text = 'star... |
7,553 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Building a neural network with TensorFlow
In this module we are going to build a neural network for regression. Regression is the prediction of a real-valued number given some inputs.
Step1:... | Python Code:
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
Explanation: Building a neural network with TensorFlow
In this module we are going to build a neural network for regression. Regression is the prediction of a real-valued number given some inputs.
End of explanati... |
7,554 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Data management in the ocean, weather and climate sciences
If you use this lesson in a bootcamp or workshop, please let me know (irving.damien (at) gmail.com).
I'd love to keep track of whe... | Python Code:
from netCDF4 import Dataset
acorn_URL = 'http://thredds.aodn.org.au/thredds/dodsC/IMOS/eMII/demos/ACORN/monthly_gridded_1h-avg-current-map_non-QC/TURQ/2012/IMOS_ACORN_V_20121001T000000Z_TURQ_FV00_monthly-1-hour-avg_END-20121029T180000Z_C-20121030T160000Z.nc.gz'
acorn_DATA = Dataset(acorn_URL)
Explanation:... |
7,555 | Given the following text description, write Python code to implement the functionality described.
Description:
Print any pair of integers with sum of GCD and LCM equals to N
Function to print the required pair ; Print the pair ; Driver code
| Python Code:
def printPair(n ) :
print("1", end = "▁ ")
print(n - 1 )
n = 14
printPair(n )
|
7,556 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Storage of Network Data and Topology
Step1: Spreadsheet Analogy
The best analogy for explaining data storage in OpenPNM is the humble spreadsheet. According to this analogy, each pore (or ... | Python Code:
import openpnm as op
%config InlineBackend.figure_formats = ['svg']
import numpy as np
np.random.seed(0)
Explanation: Storage of Network Data and Topology
End of explanation
pn = op.network.Cubic(shape=[4, 1, 1])
geo = op.geometry.SpheresAndCylinders(network=pn, pores=pn.Ps, throats=pn.Ts)
Explanation: Spr... |
7,557 | Given the following text problem statement, write Python code to implement the functionality described below in problem statement
Problem:
I am trying to modify a DataFrame df to only contain rows for which the values in the column closing_price are not between 99 and 101 and trying to do this with the code below. | Problem:
import pandas as pd
import numpy as np
np.random.seed(2)
df = pd.DataFrame({'closing_price': np.random.randint(95, 105, 10)})
def g(df):
return df.query('closing_price < 99 or closing_price > 101')
result = g(df.copy()) |
7,558 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2020 The TensorFlow Authors.
Step1: こんにちは、多くの世界
<table class="tfo-notebook-buttons" align="left">
<td><a target="_blank" href="https
Step2: TensorFlow Quantum をインストールします。
Step3... | Python Code:
#@title Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# dist... |
7,559 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Using MySQLdb
mySQLdb - Library has to be pip'ed' before and now to be imported
Step1: Database Connection Properties and Connect to the database
Step12: Let's create a sample table and i... | Python Code:
import MySQLdb
Explanation: Using MySQLdb
mySQLdb - Library has to be pip'ed' before and now to be imported
End of explanation
#Enter the values for you database connection
dsn_database = "verein" # e.g. "MySQLdbtest"
dsn_hostname = "localhost" # e.g.: "mydbinstance.xyz.us-east-1.rds.amazonaws.com... |
7,560 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: Gc graph
imports "article_neg/pos/neu1.gml"
- saves "nodes_df_negative/positive/neutral.csv"
- node labels, degrees, and centralities for entire network
- saves "Gc_negative/posit... | Python Code:
# 1_network_df
import networkx as nx
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline
import os
from glob import glob
plt.style.use('ggplot')
pd.set_option('display.width', 5000)
pd.set_option('display.max_columns', 60)
#gml_files = glob('../output/network/article_... |
7,561 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
PyEarthScience
Step1: Add cyclic data. Set minimum and maximum contour values although the interval.
Step2: Open a workstation, here x11 window.
Step3: Set resources.
Step4: Draw the plo... | Python Code:
import Ngl,Nio
#-- define variables
fname = "/Users/k204045/NCL/general/data/new_data/rectilinear_grid_2D.nc" #-- data file name
#-- open file and read variables
f = Nio.open_file(fname,"r") #-- open data file
temp = f.variables["tsurf"][0,::-1,:] #-- first time step, reverse la... |
7,562 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Training a convolutional neural network on the MNIST data.
The original code in script form is here.
Step1: Neural Network Settings
Here are most of the settings that describe the neural ne... | Python Code:
# Import some stuff
from __future__ import print_function, absolute_import, division
import numpy as np
np.random.seed(1337) # for reproducibility
from keras.datasets import mnist
from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation, Flatten
from keras.layers import Conv... |
7,563 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
LAB04
Step1: Load taxifare dataset
The Taxi Fare dataset for this lab is 106,545 rows and has been pre-processed and split for use in this lab. Note that the dataset is the same as used in... | Python Code:
import datetime
import logging
import os
import matplotlib.pyplot as plt
import numpy as np
import tensorflow as tf
from tensorflow import feature_column as fc
from tensorflow.keras import layers
from tensorflow.keras import models
# set TF error log verbosity
logging.getLogger("tensorflow").setLevel(loggi... |
7,564 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
BigQuery Query To View
Create a BigQuery view.
License
Copyright 2020 Google LLC,
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in complian... | Python Code:
!pip install git+https://github.com/google/starthinker
Explanation: BigQuery Query To View
Create a BigQuery view.
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 may obtain a copy of the... |
7,565 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Exploring the Twitter trends API
In this notebook we'll take a quick look at the section of the Twitter Rest API that deals with trending terms
Step1: Basic calls
The first call trends/avai... | Python Code:
from collections import Counter
import os
from pprint import pprint
import tweepy
c_key = os.environ['CONSUMER_KEY']
c_secret = os.environ['CONSUMER_SECRET']
a_token = os.environ['ACCESS_TOKEN']
a_token_secret = os.environ['ACCESS_TOKEN_SECRET']
auth = tweepy.OAuthHandler(c_key, c_secret)
auth.set_access_t... |
7,566 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
NEST implementation of the aeif models
Hans Ekkehard Plesser and Tanguy Fardet, 2016-09-09
This notebook provides a reference solution for the Adaptive Exponential Integrate and Fire
(AEIF) ... | Python Code:
# Install assimulo package in the current Jupyter kernel
import sys
!{sys.executable} -m pip install assimulo
import numpy as np
from scipy.integrate import odeint
import matplotlib.pyplot as plt
%matplotlib inline
plt.rcParams['figure.figsize'] = (15, 6)
Explanation: NEST implementation of the aeif models... |
7,567 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: Correlation
In this section we will develop a measure of how tightly clustered a scatter diagram is about a straight line. Formally, this is called measuring linear association.
The c... | Python Code:
z = np.random.normal(0, 1, 500)
def r_scatter(xs, r):
Generate y-values for a scatter plot with correlation approximately r
return r*xs + (np.sqrt(1-r**2))*z
corr_opts = {
'aspect_ratio': 1,
'xlim': (-3.5, 3.5),
'ylim': (-3.5, 3.5),
}
nbi.scatter(np.random.normal(size=500), r_... |
7,568 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Introduction to Python and Natural Language Technologies
Lecture 01, Introduction to Python
September 6, 2017
About this part of the course
Goal
upper intermediate level Python
will cover so... | Python Code:
print("Hello world")
Explanation: Introduction to Python and Natural Language Technologies
Lecture 01, Introduction to Python
September 6, 2017
About this part of the course
Goal
upper intermediate level Python
will cover some advanced concepts
focus on string manipulation
Prerequisites
intermediate level ... |
7,569 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
1) With "Lil Wayne" and "Lil Kim" there are a lot of "Lil" musicians. Do a search and print a list of 50 that are playable in the USA (or the country of your choice), along with their popula... | Python Code:
import requests
response = requests.get('https://api.spotify.com/v1/search?query=artist:lil&type=artist&market=us&limit=50')
data = response.json()
artists = data['artists']['items']
for artist in artists:
print(artist['name'], artist['popularity'])
Explanation: 1) With "Lil Wayne" and "Lil Kim" there ... |
7,570 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
When I first ran this, my dataframes weren't "aligned".
So it's very important to check your datasets after every load.
The correspondence between dates and topics and numerical features is ... | Python Code:
print(len(dates))
print(len(topics))
print(len(nums))
sum(nums.index == dates.index) == len(dates)
sum(nums.index == topics.index) == len(dates)
disc = LinearDiscriminantAnalysis()
disc
category = (np.ceil(nums.favorite_count ** .13)).astype(np.int8)
disc = LinearDiscriminantAnalysis().fit(topics, category... |
7,571 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Getting Started with Batfish
This notebook uses pybatfish, a Python-based SDK for Batfish, to analyze a sample network. It shows how to submit your configurations and other network data for ... | Python Code:
# Import packages
%run startup.py
bf = Session(host="localhost")
Explanation: Getting Started with Batfish
This notebook uses pybatfish, a Python-based SDK for Batfish, to analyze a sample network. It shows how to submit your configurations and other network data for analysis and how to query its vendor-ne... |
7,572 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Transport a collection of particles
Step1: Optimization - Step 1
Step2: Optimization - Step 2
Step3: Optimization - Step 3
Step4: Optimization - Step 4 | Python Code:
def grid_of_particles(N, w):
# Create a grid of N evenly spaced particles
# covering a square patch of width and height w
# centered on the region 0 < x < 2, 0 < y < 1
x = np.linspace(1.0-w/2, 1.0+w/2, int(np.sqrt(N)))
y = np.linspace(0.5-w/2, 0.5+w/2, int(np.sqrt(N)))
x, y = np.m... |
7,573 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Names
Step2: 1. Python Return Statements
1.1 Functions Without Returns
Thus far we've not paid much attention to function return statements. As many of you have noticed, you don't HAVE to h... | Python Code:
from numpy import *
Explanation: Names: [Insert Your Names Here]
Lab 5 - Return Statements and Plotting Basics
Lab 5 Contents
Python Return Statements
Functions Without Returns
Return Statements as Code Breaks
Return Statements for Assigned Output
Basic Python Plotting
End of explanation
def dummy_func(x=0... |
7,574 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Getting started with The Joker
The Joker (pronounced Yo-kurr) is a highly specialized Monte Carlo (MC) sampler that is designed to generate converged posterior samplings for Keplerian orbita... | Python Code:
import astropy.table as at
from astropy.time import Time
import astropy.units as u
from astropy.visualization.units import quantity_support
import matplotlib.pyplot as plt
import numpy as np
%matplotlib inline
import thejoker as tj
# set up a random generator to ensure reproducibility
rnd = np.random.defau... |
7,575 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Multiple Hypothesis Testing!
aka "Plenty of P-Values"
by Zane Blanton
#### Data Scientist in Marketplace at trivago
Standard Hypothesis Testing
We set an $\alpha$ (False Error Rate) of 0.05.... | Python Code:
total_null = 500
total_alt = 500
rejected_null = total_null * 0.05
rejected_alt = total_alt * 0.95
hypothesis_df = pd.DataFrame({'null hypotheses': [total_null, total_null - rejected_null, 0],
'rejected nulls': [0, rejected_null, rejected_null],
'alt hypo... |
7,576 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Conditional Probability Activity & Exercise
Below is some code to create some fake data on how much stuff people purchase given their age range.
It generates 100,000 random "people" and rand... | Python Code:
from numpy import random
random.seed(0)
totals = {20:0, 30:0, 40:0, 50:0, 60:0, 70:0}
purchases = {20:0, 30:0, 40:0, 50:0, 60:0, 70:0}
totalPurchases = 0
for _ in range(100000):
ageDecade = random.choice([20, 30, 40, 50, 60, 70])
purchaseProbability = float(ageDecade) / 100.0
totals[ageDecade] ... |
7,577 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
ABU量化系统使用文档
<center>
<img src="./image/abu_logo.png" alt="" style="vertical-align
Step1: 之前的章节无论讲解策略优化,还是针对回测进行滑点或是手续费都是针对一支股票进行择时操作。
本节将示例讲解多支股票进行择时策略的实现,依然使用AbuFactorBuyBreak做为买入策... | Python Code:
from __future__ import print_function
from __future__ import division
import warnings
warnings.filterwarnings('ignore')
warnings.simplefilter('ignore')
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline
import os
import sys
# 使用insert 0即只使用github,避免交叉使用了pip安装的abupy,导致... |
7,578 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
1. Load train and test data
Step1: 2. Tokenize name into (surname, title, first name and maiden name)
Step2: 2.1 Extract features from Title variable
Step3: It seems we can extract some i... | Python Code:
train = pd.read_csv("data/train.csv")
train["dataset"] = "train"
train.head()
test = pd.read_csv("data/test.csv")
test["dataset"] = "test"
test.head()
#Combine both datasets to predict families
train = train.append(test)
train.set_index(train["PassengerId"],inplace=True)
Explanation: 1. Load train and test... |
7,579 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Explore LarterBreakspear model.
Run time
Step1: Perform the simulation
Step2: Plot pretty pictures of what we just did | Python Code:
# Third party python libraries
import numpy
# Try and import from "The Virtual Brain"
from tvb.simulator.lab import *
from tvb.datatypes.time_series import TimeSeriesRegion
import tvb.analyzers.fmri_balloon as bold
from tvb.simulator.plot import timeseries_interactive as timeseries_interactive
Explanation:... |
7,580 | Given the following text problem statement, write Python code to implement the functionality described below in problem statement
Problem:
I have the following dataframe: | Problem:
import pandas as pd
df = pd.DataFrame({'text': ['abc', 'def', 'ghi', 'jkl']})
def g(df):
return pd.DataFrame({'text': [', '.join(df['text'].str.strip('"').tolist())]})
result = g(df.copy()) |
7,581 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2020 The TensorFlow IO Authors.
Step1: 音频数据准备和增强
<table class="tfo-notebook-buttons" align="left">
<td><a target="_blank" href="https
Step2: 使用方法
读取音频文件
在 TensorFlow IO 中,利用类 t... | Python Code:
#@title Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# dist... |
7,582 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Kampff lab - Polytrode Impedance
Here a description of the dataset
Step1: create a DataIO (and remove if already exists)
Step2: CatalogueConstructor
Make catalogue on the first 280. After ... | Python Code:
# suposing the datset is downloaded here
# workdir = '/media/samuel/dataspikesorting/DataSpikeSortingHD2/kampff/polytrode Impedance/'
workdir = '/home/samuel/Documents/projet/DataSpikeSorting/kampff/polytrode Impedance/'
# Input file
filename = workdir + 'amplifier2017-02-02T17_18_46/amplifier2017-02-02T17... |
7,583 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Naive Bayes and Bayes Classifiers
author
Step1: Simple Gaussian Example
Step2: The data seems like it comes from two normal distributions, with the cyan class being more prevalent than the... | Python Code:
%matplotlib inline
import matplotlib.pyplot as plt
import seaborn; seaborn.set_style('whitegrid')
import numpy
from pomegranate import *
numpy.random.seed(0)
numpy.set_printoptions(suppress=True)
%load_ext watermark
%watermark -m -n -p numpy,scipy,pomegranate
Explanation: Naive Bayes and Bayes Classifiers
... |
7,584 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Solution to a problem posted at
https
Step1: Roll six 6-sided dice
Step2: Count how many times each outcome occurs and score accordingly
Step3: Run many times and accumulate scores
Step4:... | Python Code:
from __future__ import print_function, division
from numpy.random import choice
from collections import Counter
from collections import defaultdict
Explanation: Solution to a problem posted at
https://www.reddit.com/r/statistics/comments/4csjee/finding_pab_given_two_sets_of_data/
Copyright 2016 Allen Downe... |
7,585 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Energy Efficiency
What can you tell me about the data?
Step1: X2, X3, X4 might be candidates for normalization;
X5, X6, X8 likely to be discrete values;
Y1, Y2 within the same range
Step2:... | Python Code:
import matplotlib.pyplot as plt
%matplotlib inline
import pandas as pd
df = pd.read_csv('../data/energy/energy.csv')
df.shape
df.describe()
Explanation: Energy Efficiency
What can you tell me about the data?
End of explanation
import matplotlib.pyplot as plt
%matplotlib inline
from pandas.tools.plotting im... |
7,586 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
First, I made a mistake naming the data set! It's 2015 data, not 2014 data. But yes, still use 311-2014.csv. You can rename it.
Importing and preparing your data
Import your data, but only t... | Python Code:
df = pd.read_csv('311-2015.csv', dtype = str)
df.head()
import datetime
def created_date_to_datetime(date_str):
return datetime.datetime.strptime(date_str, '%m/%d/%Y %I:%M:%S %p')
df['created_datetime'] = df['Created Date'].apply(created_date_to_datetime)
df = df.set_index('created_datetime')
Explanati... |
7,587 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Simulating a Yo-Yo
Modeling and Simulation in Python
Copyright 2021 Allen Downey
License
Step1: Yo-yo
Suppose you are holding a yo-yo with a length of string wound around its axle, and you ... | Python Code:
# install Pint if necessary
try:
import pint
except ImportError:
!pip install pint
# download modsim.py if necessary
from os.path import exists
filename = 'modsim.py'
if not exists(filename):
from urllib.request import urlretrieve
url = 'https://raw.githubusercontent.com/AllenDowney/ModSim/... |
7,588 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Sentinel-2 Cloud Masking with s2cloudless
Author
Step1: Assemble cloud mask components
This section builds an S2 SR collection and defines functions to add cloud and cloud shadow component ... | Python Code:
import ee
# Trigger the authentication flow.
ee.Authenticate()
# Initialize the library.
ee.Initialize()
Explanation: Sentinel-2 Cloud Masking with s2cloudless
Author: jdbcode
This tutorial is an introduction to masking clouds and cloud shadows in Sentinel-2 (S2) surface reflectance (SR) data using Earth E... |
7,589 | 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 --quiet hvplot
Explanation: Planet Analytics API Tutorial
Summary Statistics: Buildings
Overview
Introduction
Post a stats job request
Get job report results
Visualize the time series
Customize area of interest and time range
1. Introduction
This notebook demonstrates how to request road summa... |
7,590 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
← Back to Index
Zero Crossing Rate
The zero crossing rate indicates the number of times that a signal crosses the horizontal axis.
Let's load a signal
Step1: Listen to the signal
Step2... | Python Code:
x, sr = librosa.load('audio/simple_loop.wav')
Explanation: ← Back to Index
Zero Crossing Rate
The zero crossing rate indicates the number of times that a signal crosses the horizontal axis.
Let's load a signal:
End of explanation
ipd.Audio(x, rate=sr)
Explanation: Listen to the signal:
End of explanat... |
7,591 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Outline
IPython and IPython Notebooks
Numpy
Pandas
Python and IPython
python is a programming language and also the name of the program that runs scripts written in that language.
If you're ... | Python Code:
# you don't have to rename numpy to np but it's customary to do so
import numpy as np
# you can create a 1-d array with a list of numbers
a = np.array([1, 4, 6])
print 'a:'
print a
print 'a.shape:', a.shape
print
# you can create a 2-d array with a list of lists of numbers
b = np.array([[6, 7], [3, 1], [4... |
7,592 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Bokeh
<a href="https
Step1: Plot lines
Source
Step2: Scatter plot
Source
Step3: Squares
Step4: Hex Tiles
Bokeh can plot hexagonal tiles, which are often used for showing binned aggregati... | Python Code:
import bokeh
from bokeh.plotting import figure, output_notebook, show
Explanation: Bokeh
<a href="https://colab.research.google.com/github/jdhp-docs/notebooks/blob/master/python_bokeh_en.ipynb"><img align="left" src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open in Colab" title="Open ... |
7,593 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
PolyFill
Step1: Methods
Geometry methods
Step2: Methods to add vertices and edges to table
Step3: Main Script
Set initial vertices
Step4: Force-directed graph | Python Code:
from IPython.core.display import HTML
from string import Template
import pandas as pd
import random, math
HTML('<script src="lib/d3/d3.min.js"></script>')
Explanation: PolyFill: Example of D3 in Jupyter
This example shows the combined use of Python and D3 for a randomized 2D space-filling algorithm and vis... |
7,594 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Matplotlib
Below are some code from the code source Data Science from Scratch
Step1: Bar Chart
Step2: Histogram
A bar chart can also be a good choice for plotting histograms of bucketed nu... | Python Code:
from matplotlib import pyplot as plt
import matplotlib.pyplot as plt
from collections import Counter
%matplotlib inline
years = [1950, 1960, 1970, 1980, 1990, 2000, 2010]
gdp = [300.2, 543.3, 1075.9, 2862.5, 5979.6, 10289.7, 14958.3]
# create a line chart, years on x-axis, gdp on y-axis
plt.plot(years, gd... |
7,595 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Background
In this notebook, we show how to feed the embeddings from the language model into the MLP classifier. Then, we take the github repo, kubernetes/kubernetes, as an example. We do tr... | Python Code:
import pandas as pd
combined_sig_df = pd.read_pickle('combined_sig_df.pkl')
feat_df = pd.read_csv('feat_df.csv')
# github issue contents
combined_sig_df.head(3)
# embeddings of github issues [mean, max]
feat_df.head(3)
# count the labels in the holdout set
from collections import Counter
c = Counter()
for ... |
7,596 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
We will try to learn from data using a very simple example of tossing a coin. We will first generate some data (30% heads and 70% tails) and will try to learn the CPD of the coin using Maxim... | Python Code:
# Generate data
import numpy as np
import pandas as pd
raw_data = np.array([0] * 30 + [1] * 70) # Representing heads by 0 and tails by 1
data = pd.DataFrame(raw_data, columns=['coin'])
print(data)
# Defining the Bayesian Model
from pgmpy.models import BayesianModel
from pgmpy.estimators import MaximumLikel... |
7,597 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
In this notebook a simple Q learner will be trained and evaluated. The Q learner recommends when to buy or sell shares of one particular stock, and in which quantity (in fact it determines t... | Python Code:
# Basic imports
import os
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import datetime as dt
import scipy.optimize as spo
import sys
from time import time
from sklearn.metrics import r2_score, median_absolute_error
from multiprocessing import Pool
%matplotlib inline
%pylab inline
... |
7,598 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
DAT-ATX-1 Capstone Project
Nikolaos Vergos, February 2016
nvergos@gmail.com
1. Data Preparation & Exploratory... | Python Code:
import warnings
warnings.filterwarnings('ignore')
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
%matplotlib inline
from scipy import stats # For correlation coefficient calculation
Explanation: DAT-ATX-1 Capstone Project
Nikolaos Vergos, February 2016
n&#... |
7,599 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Mock community quality control
This notebook maps observed mock community sequences, which are technically from unknown organisms, to "trueish" taxonomies, i.e., the most likely taxonomic ma... | Python Code:
from tax_credit import mock_quality
from os.path import expandvars, join
Explanation: Mock community quality control
This notebook maps observed mock community sequences, which are technically from unknown organisms, to "trueish" taxonomies, i.e., the most likely taxonomic match given a list of expected se... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.