Unnamed: 0 int64 0 16k | text_prompt stringlengths 110 62.1k | code_prompt stringlengths 37 152k |
|---|---|---|
6,100 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Fine Tune Language Model
The results of the above query can be downloaded as a csv file from this link
Step2: Filter Labels By YAML File
Step3: Explore The Data
Count Labels
Filter Issues ... | Python Code:
import os
import torch
from torch.cuda import empty_cache
os.environ["CUDA_DEVICE_ORDER"]="PCI_BUS_ID"
os.environ["CUDA_VISIBLE_DEVICES"]="3"
import pandas as pd
import numpy as np
import re
pd.set_option('max_colwidth', 1000)
df = pd.read_csv('https://storage.googleapis.com/issue_label_bot/k8s_issues/0000... |
6,101 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
PARTIAL ORDER PLANNER
A partial-order planning algorithm is significantly different from a total-order planner.
The way a partial-order plan works enables it to take advantage of problem de... | Python Code:
from planning import *
from notebook import psource
psource(PartialOrderPlanner)
Explanation: PARTIAL ORDER PLANNER
A partial-order planning algorithm is significantly different from a total-order planner.
The way a partial-order plan works enables it to take advantage of problem decomposition and work on... |
6,102 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Widget
Step1: Then, create an instance of CAD
Step2: Display the widget | Python Code:
from ipcad.widgets import CAD
Explanation: Widget: CAD
<i class="fa fa-info-circle fa-2x text-primary"></i> Execute each of these cells in order, such as with <label class="label label-default">Shift+Enter</label>
First, load CAD from your module:
End of explanation
cadExample = CAD(assembly_url="examples/... |
6,103 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Solving problems by Searching
This notebook serves as supporting material for topics covered in Chapter 3 - Solving Problems by Searching and Chapter 4 - Beyond Classical Search from the boo... | Python Code:
from search import *
from notebook import psource, heatmap, gaussian_kernel, show_map, final_path_colors, display_visual, plot_NQueens
# Needed to hide warnings in the matplotlib sections
import warnings
warnings.filterwarnings("ignore")
Explanation: Solving problems by Searching
This notebook serves as su... |
6,104 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Keras tutorial - the Happy House
Welcome to the first assignment of week 2. In this assignment, you will
Step1: Note
Step3: Details of the "Happy" dataset
Step4: You have now built a func... | Python Code:
import numpy as np
from keras import layers
from keras.layers import Input, Dense, Activation, ZeroPadding2D, BatchNormalization, Flatten, Conv2D
from keras.layers import AveragePooling2D, MaxPooling2D, Dropout, GlobalMaxPooling2D, GlobalAveragePooling2D
from keras.models import Model
from keras.preprocess... |
6,105 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Overfitting demo
Create a dataset based on a true sinusoidal relationship
Let's look at a synthetic dataset consisting of 30 points drawn from the sinusoid $y = \sin(4x)$
Step1: Create rand... | Python Code:
import graphlab
import math
import random
import numpy
from matplotlib import pyplot as plt
%matplotlib inline
Explanation: Overfitting demo
Create a dataset based on a true sinusoidal relationship
Let's look at a synthetic dataset consisting of 30 points drawn from the sinusoid $y = \sin(4x)$:
End of expl... |
6,106 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Day80
Step1: Using the Basemap module, we are able to draw the earth.
Step2: Orthographic projection
Example from
Step3: Mercator projection
Let say we want to map Vancouver, BC (as drawn... | Python Code:
from mpl_toolkits.basemap import Basemap as Basemap
Explanation: Day80: Drawing maps
Often in urban data, there is information about location. Today I use to draw maps. Because this is unfamiliar to me, I will use python for drawing maps (because “python” is easier to google than “R”).
Basemap module
End o... |
6,107 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Think Bayes
This notebook presents code and exercises from Think Bayes, second edition.
Copyright 2016 Allen B. Downey
MIT License
Step1: The flea beetle problem
Different species of flea b... | Python Code:
# Configure Jupyter so figures appear in the notebook
%matplotlib inline
# Configure Jupyter to display the assigned value after an assignment
%config InteractiveShell.ast_node_interactivity='last_expr_or_assign'
import math
import numpy as np
from thinkbayes2 import Pmf, Cdf, Suite
import thinkplot
Explan... |
6,108 | 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... |
6,109 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Initial setup
Jump_to lesson 9 video
Step1: Annealing
We define two new callbacks
Step2: Let's start with a simple linear schedule going from start to end. It returns a function that takes... | Python Code:
x_train,y_train,x_valid,y_valid = get_data()
train_ds,valid_ds = Dataset(x_train, y_train),Dataset(x_valid, y_valid)
nh,bs = 50,512
c = y_train.max().item()+1
loss_func = F.cross_entropy
data = DataBunch(*get_dls(train_ds, valid_ds, bs), c)
#export
def create_learner(model_func, loss_func, data):
retur... |
6,110 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Brax
Step1: Brax Config
Here's a brax config that defines a bouncy ball
Step2: We visualize this system config like so
Step3: Brax State
$\text{QP}$, brax's dynamic state, is a structure ... | Python Code:
#@title Colab setup and imports
from matplotlib.lines import Line2D
from matplotlib.patches import Circle
import matplotlib.pyplot as plt
import numpy as np
try:
import brax
except ImportError:
from IPython.display import clear_output
!pip install git+https://github.com/google/brax.git@main
clear_... |
6,111 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Simplified ZZ analysis
This is based on the ZZ analysis in the ATLAS outreach paper, but including all possible pairs of muons rather than selecting the combination closest to the Z mass.
Th... | Python Code:
from ROOT import TChain, TH1F, TLorentzVector, TCanvas
Explanation: Simplified ZZ analysis
This is based on the ZZ analysis in the ATLAS outreach paper, but including all possible pairs of muons rather than selecting the combination closest to the Z mass.
This time we will use ROOT histograms instead of Ma... |
6,112 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
CycleGAN, Image-to-Image Translation
In this notebook, we're going to define and train a CycleGAN to read in an image from a set $X$ and transform it so that it looks as if it belongs in set... | Python Code:
# loading in and transforming data
import os
import torch
from torch.utils.data import DataLoader
import torchvision
import torchvision.datasets as datasets
import torchvision.transforms as transforms
# visualizing data
import matplotlib.pyplot as plt
import numpy as np
import warnings
%matplotlib inline
E... |
6,113 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Fetch GitHub Issues and Compute Embeddings
This notebook downloads GitHub Issues and then computes the embeddings using a trained model
issues_loader.ipynb is a very similar notebook
That no... | Python Code:
import logging
import os
from pathlib import Path
import sys
logging.basicConfig(format='%(message)s')
logging.getLogger().setLevel(logging.INFO)
home = str(Path.home())
# Installing the python packages locally doesn't appear to have them automatically
# added the path so we need to manually add the direct... |
6,114 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
DAP Zonal Queries (or Spaxel Queries)
Marvin allows you to perform queries on individual spaxels within and across the MaNGA dataset.
Step1: Let's grab all spaxels with an Ha-flux > 25 from... | Python Code:
from marvin import config
from marvin.tools.query import Query
config.mode='remote'
Explanation: DAP Zonal Queries (or Spaxel Queries)
Marvin allows you to perform queries on individual spaxels within and across the MaNGA dataset.
End of explanation
config.setRelease('MPL-5')
f = 'emline_gflux_ha_6564 > 25... |
6,115 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Lesson 1 Dogbreeds CodeAlong
Step1: 2. Initial Exploration
Step2: 3. Initial Model
starting w/ small images, large batch sizes to train model v.fast in beginning; increase image size and d... | Python Code:
%reload_ext autoreload
%autoreload 2
%matplotlib inline
from fastai.imports import *
from fastai.torch_imports import *
from fastai.transforms import *
from fastai.model import *
from fastai.dataset import *
from fastai.sgdr import *
from fastai.plots import *
from fastai.conv_learner import *
PATH = "data... |
6,116 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
The Alien Blaster problem
This notebook presents solutions to exercises in Think Bayes.
Copyright 2016 Allen B. Downey
MIT License
Step1: Part One
In preparation for an alien invasion, the ... | Python Code:
from __future__ import print_function, division
% matplotlib inline
import warnings
warnings.filterwarnings('ignore')
import numpy as np
from thinkbayes2 import Hist, Pmf, Cdf, Suite, Beta
import thinkplot
Explanation: The Alien Blaster problem
This notebook presents solutions to exercises in Think Bayes.
... |
6,117 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Visualize Evoked data
In this tutorial we focus on plotting functions of
Step1: First we read the evoked object from a file. Check out
tut_epoching_and_averaging to get to this stage from ... | Python Code:
import os.path as op
import numpy as np
import matplotlib.pyplot as plt
import mne
# sphinx_gallery_thumbnail_number = 9
Explanation: Visualize Evoked data
In this tutorial we focus on plotting functions of :class:mne.Evoked.
End of explanation
data_path = mne.datasets.sample.data_path()
fname = op.join(da... |
6,118 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Minimal Contact Binary System
Setup
Let's first make sure we have the latest version of PHOEBE 2.2 installed. (You can comment out this line if you don't use pip for your installation or don... | Python Code:
!pip install -I "phoebe>=2.2,<2.3"
Explanation: Minimal Contact Binary System
Setup
Let's first make sure we have the latest version of PHOEBE 2.2 installed. (You can comment out this line if you don't use pip for your installation or don't want to update to the latest release).
End of explanation
%matplot... |
6,119 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2018 The TensorFlow Authors.
Licensed under the Apache License, Version 2.0 (the "License").
Image Captioning with Attention
<table class="tfo-notebook-buttons" align="left"><td>
<... | Python Code:
# Import TensorFlow and enable eager execution
# This code requires TensorFlow version >=1.9
import tensorflow as tf
tf.enable_eager_execution()
# We'll generate plots of attention in order to see which parts of an image
# our model focuses on during captioning
import matplotlib.pyplot as plt
# Scikit-lear... |
6,120 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<h1 align="center">Images</h1>
<table width="100%">
<tr style="background-color
Step1: Load your first image and display it
Step2: Image Construction
There are a variety of ways to create ... | Python Code:
import SimpleITK as sitk
from __future__ import print_function
import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np
from ipywidgets import interact, fixed
import os
OUTPUT_DIR = 'Output'
# Utility method that either downloads data from the MIDAS repository or
# if already downloaded return... |
6,121 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Think Bayes
Copyright 2018 Allen B. Downey
MIT License
Step1: The Space Shuttle problem
Here's a problem from Bayesian Methods for Hackers
On January 28, 1986, the twenty-fifth flight of th... | Python Code:
# Configure Jupyter so figures appear in the notebook
%matplotlib inline
# Configure Jupyter to display the assigned value after an assignment
%config InteractiveShell.ast_node_interactivity='last_expr_or_assign'
import numpy as np
import pandas as pd
# import classes from thinkbayes2
from thinkbayes2 impo... |
6,122 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Reading a file using CF module
The main difference with the previous example is the way we will read the data from the file.
Instead of the netCDF4 module, we will use the cf-python package,... | Python Code:
%matplotlib inline
import cf
import netCDF4
import matplotlib.pyplot as plt
Explanation: Reading a file using CF module
The main difference with the previous example is the way we will read the data from the file.
Instead of the netCDF4 module, we will use the cf-python package, which implements the CF dat... |
6,123 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Natural language inference
Step1: Contents
Overview
Our version of the task
Primary resources
Set-up
SNLI
SNLI properties
Working with SNLI
MultiNLI
MultiNLI properties
Working with MultiNL... | Python Code:
__author__ = "Christopher Potts"
__version__ = "CS224u, Stanford, Spring 2022"
Explanation: Natural language inference: task and datasets
End of explanation
import nli
import os
import pandas as pd
import random
from datasets import load_dataset
DATA_HOME = os.path.join("data", "nlidata")
ANNOTATIONS_HOME ... |
6,124 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Building a CNN
In this notebook we'll rebuild the network presented in <a href="http
Step1: The MNIST data that TensorFlow pre-loads comes as 28x28x1 images.
However, the LeNet architecture... | Python Code:
import numpy as np
import tensorflow as tf
from sklearn.utils import shuffle
from tensorflow.examples.tutorials.mnist import input_data
from tensorflow.contrib.layers import flatten
mnist = input_data.read_data_sets("MNIST_data/", reshape=False)
X_train, y_train = mnist.train.images, mnist.train.... |
6,125 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Detecting Changes in Sentinel-1 Imagery (Part 2)
Author
Step1: Datasets and Python modules
One dataset will be used in the tutorial
Step2: And to make use of interactive graphics, we impor... | Python Code:
import ee
# Trigger the authentication flow.
ee.Authenticate()
# Initialize the library.
ee.Initialize()
Explanation: Detecting Changes in Sentinel-1 Imagery (Part 2)
Author: mortcanty
Run me first
Run the following cell to initialize the API. The output will contain instructions on how to grant this noteb... |
6,126 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Defining mock connections
Start with some setup.
Step1: Create a simple resource
Step2: Define a mock for the resource
Here we define an object with a method named document and assign it t... | Python Code:
import sys
sys.path.append('/opt/rhc')
import rhc.micro as micro
import rhc.async as async
import logging
logging.basicConfig(level=logging.DEBUG)
Explanation: Defining mock connections
Start with some setup.
End of explanation
p=micro.load_connection([
'CONNECTION placeholder http://jsonplaceholder.ty... |
6,127 | Given the following text description, write Python code to implement the functionality described.
Description:
Return True is list elements are monotonically increasing or decreasing.
This is how the function will work:
monotonic([1, 2, 4, 20])
True
This is how the function will work:
monotonic([1, 20, ... | Python Code:
def monotonic(l: list):
if l == sorted(l) or l == sorted(l, reverse=True):
return True
return False |
6,128 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Partial Dependence Plots
While feature importance shows what variables most affect predictions, partial dependence plots show how a feature affects predictions.
This is useful to answer ques... | Python Code:
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
from sklearn.tree import DecisionTreeClassifier
data = pd.read_csv('../input/fifa-2018-match-statistics/FIFA 2018 Statistics.csv')
y = (data['Man of the Match'] ==... |
6,129 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2018 Verily Life Sciences LLC.
Licensed under the Apache License, Version 2.0 (the "License");
Step1: This notebook demonstrates how one can dive deeper into QC results to explain... | Python Code:
#@title Default title text
# 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 wri... |
6,130 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<center>
<br><br>
<font size=6>
First Steps with<br><br>
Numerical Computing in Python
</font>
</b>
<br><br>
<font size=3>
Paul M. Magwene
<br>
Spring 2016
</font>
</center>
How to use IPyth... | Python Code:
help(min)
?min # this will pop-up a documentation window in the ipython notebook
Explanation: <center>
<br><br>
<font size=6>
First Steps with<br><br>
Numerical Computing in Python
</font>
</b>
<br><br>
<font size=3>
Paul M. Magwene
<br>
Spring 2016
</font>
</center>
How to use IPython notebooks
This docum... |
6,131 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
2.1.1. Question
Step1: 2.1.2. Question
Step2: 2.2. Exercise
Step3: 2.3. Exercise
Step4: 2.4. Exercise | Python Code:
from neurodynex.leaky_integrate_and_fire import LIF
print("resting potential: {}".format(LIF.V_REST))
Explanation: 2.1.1. Question: minimal current (calculation)
For the default neuron parameters (see above) compute the minimal amplitude i_min of a step current to elicitate a spike. You can access these de... |
6,132 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Representation with a Feature Cross
In this exercise, you'll experiment with different ways to represent features.
Learning Objectives
Step1: Call the import statements
The following code i... | Python Code:
%tensorflow_version 2.x
Explanation: Representation with a Feature Cross
In this exercise, you'll experiment with different ways to represent features.
Learning Objectives:
After doing this Colab, you'll know how to:
Use tf.feature_column methods to represent features in different ways.
Represent features ... |
6,133 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Generating a training set of typical geological structures
(Based on 4-Create-model)
Step1: Single normal fault
We first start with a very simple 3-layer model of a fault
Step2: Idea
Step3... | Python Code:
from matplotlib import rc_params
from IPython.core.display import HTML
css_file = 'pynoddy.css'
HTML(open(css_file, "r").read())
import sys, os
import matplotlib.pyplot as plt
# adjust some settings for matplotlib
from matplotlib import rcParams
# print rcParams
rcParams['font.size'] = 15
# determine path ... |
6,134 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Generative Adversarial Networks in Keras
Step1: The original GAN!
See this paper for details of the approach we'll try first for our first GAN. We'll see if we can generate hand-drawn numbe... | Python Code:
%matplotlib inline
import importlib
import utils2; importlib.reload(utils2)
from utils2 import *
from tqdm import tqdm
Explanation: Generative Adversarial Networks in Keras
End of explanation
from keras.datasets import mnist
(X_train, y_train), (X_test, y_test) = mnist.load_data()
X_train.shape
n = len(X_t... |
6,135 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Tutorial
Step1: Estimating the optimal number of topics ($k$)
Non-negative matrix factorization approximates $A$, the document-term matrix, in the following way
Step2: Weighted Jaccard ave... | Python Code:
from tom_lib.structure.corpus import Corpus
from tom_lib.visualization.visualization import Visualization
corpus = Corpus(source_file_path='input/egc_lemmatized.csv',
language='french',
vectorization='tfidf',
max_relative_frequency=0.8,
min_ab... |
6,136 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<a href="https
Step1: https
Step2: $$I_{xivia} \approx (twitter + instagram + \Delta facebook ) \bmod 2$$
$$I_{xivia} \approx (note + mathtodon) \bmod 2$$ | Python Code:
# 読書計画用スニペット
from datetime import date
import math
def reading_plan(title, total_number_of_pages, period):
current_page = int(input("Current page?: "))
deadline = (date(*period) - date.today()).days
remaining_pages = total_number_of_pages - current_page
print(title, period, "まで", ... |
6,137 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
An Introduction to Visualizing Astronomical Images
Version 0.1
This session has focused on image processing, with particular attention paid to how we make standard measurements (such as flux... | Python Code:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from astropy.io import fits
%matplotlib notebook
Explanation: An Introduction to Visualizing Astronomical Images
Version 0.1
This session has focused on image processing, with particular attention paid to how we make standard measuremen... |
6,138 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Content under Creative Commons Attribution license CC-BY 4.0, code under BSD 3-Clause License © 2017 L.A. Barba, N.C. Clementi, modified by D. Koehn © 2019
Step1: Short Jupyter and Python t... | Python Code:
# Execute this cell to load the notebook's style sheet, then ignore it
from IPython.core.display import HTML
css_file = '../style/custom.css'
HTML(open(css_file, "r").read())
Explanation: Content under Creative Commons Attribution license CC-BY 4.0, code under BSD 3-Clause License © 2017 L.A. Barba, N.C. C... |
6,139 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Sentiment Classification & How To "Frame Problems" for a Neural Network
by Andrew Trask
Twitter
Step1: Lesson
Step2: Project 1 | Python Code:
def pretty_print_review_and_label(i):
print(labels[i] + "\t:\t" + reviews[i][:80] + "...")
g = open('reviews.txt','r') # What we know!
reviews = list(map(lambda x:x[:-1],g.readlines()))
g.close()
g = open('labels.txt','r') # What we WANT to know!
labels = list(map(lambda x:x[:-1].upper(),g.readlines())... |
6,140 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2020 Google
Step1: Quantum Chess REST Client
<table class="tfo-notebook-buttons" align="left">
<td>
<a target="_blank" href="https
Step2: The server for the Quantum Chess R... | 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... |
6,141 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Repeated measures ANOVA on source data with spatio-temporal clustering
This example illustrates how to make use of the clustering functions
for arbitrary, self-defined contrasts beyond stand... | Python Code:
# Authors: Alexandre Gramfort <alexandre.gramfort@inria.fr>
# Eric Larson <larson.eric.d@gmail.com>
# Denis Engemannn <denis.engemann@gmail.com>
#
# License: BSD (3-clause)
import os.path as op
import numpy as np
from numpy.random import randn
import matplotlib.pyplot as plt
import mne
fr... |
6,142 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<a href="https
Step1: WithTimestamps
<script type="text/javascript">
localStorage.setItem('language', 'language-py')
</script>
Assigns timestamps to all the elements of a collection.
Setup
... | Python Code:
#@title Licensed under the Apache License, Version 2.0 (the "License")
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this fi... |
6,143 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Loading the necessary libraries
Step1: Loading the dataset 0750-0805
Description of the dataset is at
Step2: What is the number of different vehicles for the 15 min
How many timestamps? Ar... | Python Code:
%matplotlib inline
from pandas import Series, DataFrame
import pandas as pd
from itertools import *
import itertools
import numpy as np
import csv
import math
import matplotlib.pyplot as plt
from matplotlib import pylab
from scipy.signal import hilbert, chirp
import scipy
import networkx as nx
Explanation:... |
6,144 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Class 7
Step1: The variable y1 in the preceding example stores the computed value for $y_1$. We can continue to iterate on Equation (4) to compute $y_2$, $y_3$, and so on. For example
Step2... | Python Code:
# Initialize parameter values
y0 = 0
rho = 0.5
w1 = 1
# Compute the period 1 value of y
y1 = rho*y0 + w1
# Print the result
print('y1 =',y1)
Explanation: Class 7: Deterministic Time Series Models
Time series models are at the foundatation of dynamic macroeconomic theory. A time series model is an equation ... |
6,145 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Piscataway Machine Learning Meetup
Introduction to Python 01
Python is a scripting language which is very easy to learn. The syntax is very easy to grasp, which makes it very popular for pro... | Python Code:
# COMMENTS begin with a pound sign (#) and extend to the end of the line.
# Comments are ignored by the computer. They are used to explain what the code is supposed to do.
# It is best practice to use LOTS of comments.
# That way, when you look back at your code, you can more quickly understand what you m... |
6,146 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
ES-DOC CMIP6 Model Properties - Seaice
MIP Era
Step1: Document Authors
Set document authors
Step2: Document Contributors
Specify document contributors
Step3: Document Publication
Specify ... | Python Code:
# DO NOT EDIT !
from pyesdoc.ipython.model_topic import NotebookOutput
# DO NOT EDIT !
DOC = NotebookOutput('cmip6', 'csiro-bom', 'sandbox-1', 'seaice')
Explanation: ES-DOC CMIP6 Model Properties - Seaice
MIP Era: CMIP6
Institute: CSIRO-BOM
Source ID: SANDBOX-1
Topic: Seaice
Sub-Topics: Dynamics, The... |
6,147 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Source localization with single dipole fit
This shows how to fit a dipole using mne-python.
For a comparison of fits between MNE-C and mne-python, see
Step1: Let's localize the N100m (using... | Python Code:
from os import path as op
import numpy as np
import matplotlib.pyplot as plt
import mne
from mne.forward import make_forward_dipole
from mne.evoked import combine_evoked
from mne.simulation import simulate_evoked
data_path = mne.datasets.sample.data_path()
subjects_dir = op.join(data_path, 'subjects')
fnam... |
6,148 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
TRAPpy custom events
Detailed information on Trappy can be found at examples/trappy/trappy_example.ipynb.
Step1: Test environment setup
For more details on this please check out examples/ut... | Python Code:
import logging
from conf import LisaLogging
LisaLogging.setup()
# Generate plots inline
%matplotlib inline
import copy
import json
import os
import time
import math
import logging
# Support to access the remote target
import devlib
from env import TestEnv
# Support to configure and run RTApp based workload... |
6,149 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Random Sampling
Copyright 2016 Allen Downey
License
Step1: Part One
Suppose we want to estimate the average weight of men and women in the U.S.
And we want to quantify the uncertainty of th... | Python Code:
from __future__ import print_function, division
import numpy
import scipy.stats
import matplotlib.pyplot as pyplot
from ipywidgets import interact, interactive, fixed
import ipywidgets as widgets
# seed the random number generator so we all get the same results
numpy.random.seed(18)
# some nicer colors fro... |
6,150 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<h1> Text Classification using Native Tensorflow Pre-processing</h1>
This notebook continues from <a href="text_classification.ipynb">text_classification.ipynb</a> -- in particular, we assum... | Python Code:
# change these to try this notebook out
BUCKET = 'cloud-training-demos-ml'
PROJECT = 'cloud-training-demos'
REGION = 'us-central1'
import os
os.environ['BUCKET'] = BUCKET
os.environ['PROJECT'] = PROJECT
os.environ['REGION'] = REGION
os.environ['TFVERSION'] = '1.8'
if 'COLAB_GPU' in os.environ: # this is a... |
6,151 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<small><i>This notebook was prepared by Donne Martin. Source and license info is on GitHub.</i></small>
Challenge Notebook
Problem
Step1: Unit Test
The following unit test is expected to fa... | Python Code:
%run ../linked_list/linked_list.py
%load ../linked_list/linked_list.py
class MyLinkedList(LinkedList):
def find_loop_start(self):
# TODO: Implement me
pass
Explanation: <small><i>This notebook was prepared by Donne Martin. Source and license info is on GitHub.</i></small>
Challenge Note... |
6,152 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Python Numpy
<img src="images/numpylogo.svg" alt="matplotlib" style="width
Step1: A numpy array
A numpy array is a grid of values, all of the same type. The number of dimensions give the ra... | Python Code:
import numpy as np
Explanation: Python Numpy
<img src="images/numpylogo.svg" alt="matplotlib" style="width: 400px;"/>
Numpy is a numerical package used extensively in python coding. You can call the install the numpy package by
pip install numpy
When you import a module, you can choose to bound an alias t... |
6,153 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Advanced Functions Test
For this test, you should use the built-in functions to be able to write the requested functions in one line.
Problem 1
Use map to create a function which finds the l... | Python Code:
def word_lengths(phrase):
# return map(lambda word: len(word), [word for word in phrase.split()])
return map(lambda word: len(word), phrase.split())
word_lengths('How long are the words in this phrase')
Explanation: Advanced Functions Test
For this test, you should use the built-in functions t... |
6,154 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
ES-DOC CMIP6 Model Properties - Land
MIP Era
Step1: Document Authors
Set document authors
Step2: Document Contributors
Specify document contributors
Step3: Document Publication
Specify do... | Python Code:
# DO NOT EDIT !
from pyesdoc.ipython.model_topic import NotebookOutput
# DO NOT EDIT !
DOC = NotebookOutput('cmip6', 'inm', 'inm-cm5-0', 'land')
Explanation: ES-DOC CMIP6 Model Properties - Land
MIP Era: CMIP6
Institute: INM
Source ID: INM-CM5-0
Topic: Land
Sub-Topics: Soil, Snow, Vegetation, Energy ... |
6,155 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
DeepDreaming with TensorFlow
Loading and displaying the model graph
Naive feature visualization
Multiscale image generation
Laplacian Pyramid Gradient Normalization
Playing with feature visu... | Python Code:
# boilerplate code
import os
from cStringIO import StringIO
import numpy as np
from functools import partial
import PIL.Image
from IPython.display import clear_output, Image, display, HTML
import tensorflow as tf
Explanation: DeepDreaming with TensorFlow
Loading and displaying the model graph
Naive feature... |
6,156 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Introduction
When writing production standard code, your program must be tested at many different levels.
For now, let us just talk about the lowest level of tests called Unit Tests. Lowest ... | Python Code:
import unittest
def cube(x):
return x ** 3
def square(x):
return x**2
def add(x, y):
return x + y
class CalcTest(unittest.TestCase):
def test_square(self):
self.assertTrue(square(3) == 9)
self.assertFalse(square(1) == 2)
with self.assertRaises(TypeError):
... |
6,157 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
LSTM Time Series Example
This tutorial is based on Time Series Forecasting with the Long Short-Term Memory Network in Python by Jason Brownlee.
Part 1 - Data Prep
Before we get into the exam... | Python Code:
# load and plot dataset
from pandas import read_csv
from pandas import datetime
from matplotlib import pyplot
# load dataset
def parser(x):
return datetime.strptime(x, '%Y-%m-%d')
series = read_csv('../data/yellowstone-visitors.csv', header=0, parse_dates=[0], index_col=0, squeeze=True, date_parser=par... |
6,158 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Posting files to the web server
Using the requests library
Step1: The success/error messages from the server are stored in the response
Step2: To send multiple files to the web service, ju... | Python Code:
import requests
# define urls for token generation and file upload
upload_token_url = 'http://ciwsdbs.uwrl.usu.edu/auth'
upload_url = 'http://ciwsdbs.uwrl.usu.edu/data-api'
client_passcode = 'XhTVtPjQWyw64awm7td+3ygiIpLDkE3uBaHSc7Yz/AA='
# store file and filename for server request
data_file = open('series... |
6,159 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2020 The TensorFlow Authors.
Step1: Build, train and evaluate models with TensorFlow Decision Forests
<table class="tfo-notebook-buttons" align="left">
<td>
<a target="_blan... | 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... |
6,160 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Finding Lane Lines on the Road
In this project, you will use the tools you learned about in the lesson to identify lane lines on the road. You can develop your pipeline on a series of indiv... | Python Code:
#importing some useful packages
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import numpy as np
import cv2
%matplotlib inline
#reading in an image
image = mpimg.imread('test_images/solidWhiteRight.jpg')
#printing out some stats and plotting
print('This image is:', type(image), 'with dim... |
6,161 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
JSON file beolvasás
Step1: Excel file beolvasás
Step2: numpy egy matematikai bővítőcsomag
Step3: A nan értékek numpy-ban vannak definiálva.
Step4: ffill azt jelenti forward fill, és a na... | Python Code:
pd.read_json('data.json')
Explanation: JSON file beolvasás
End of explanation
df=pd.read_excel('2.17deaths causes.xls',sheet_name='2.17',skiprows=5)
Explanation: Excel file beolvasás: sorok kihagyhatók a file tetejéről, munkalap neve választható.
End of explanation
import numpy as np
Explanation: numpy egy... |
6,162 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
\title{Upsampling and Downsampling in myHDL}
\author{Steven K Armour}
\maketitle
Python Libraries Utilized
Step1: Acknowledgments
The orgianl Interpolation Decimation componetswritten in my... | Python Code:
import numpy as np
import scipy.signal as sig
import pandas as pd
from sympy import *
init_printing()
from IPython.display import display, Math, Latex
from myhdl import *
from myhdlpeek import Peeker
import matplotlib.pyplot as plt
%matplotlib inline
Explanation: \title{Upsampling and Downsampling in myH... |
6,163 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
tsam - Segmentation
Example usage of the time series aggregation module (tsam)
Date
Step1: Input data
Read in time series from testdata.csv with pandas
Step2: Create a plot function for th... | Python Code:
%load_ext autoreload
%autoreload 2
import copy
import os
import pandas as pd
import matplotlib.pyplot as plt
import tsam.timeseriesaggregation as tsam
%matplotlib inline
Explanation: tsam - Segmentation
Example usage of the time series aggregation module (tsam)
Date: 31.10.2019
Author: Maximilian Hoffmann
... |
6,164 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
The Class Structure in Python
Lesson Page
Step1: The attributes in Client are name, balance and level.
Note
Step2: We can see the attributes of John_Doe, or Jane_Defoe by calling them
Ste... | Python Code:
# create the Client class below
class Client(object):
def __init__(self, name, balance):
self.name = name
self.balance = balance + 100
#define account level
if self.balance < 5000:
self.level = "Basic"
elif self.balance < 15000:
s... |
6,165 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Artificial Intelligence for Humans
Introduction to the Math of Neural Networks
Understanding the Summation Operator
You will frequently summations, as shown below
Step1: Understanding the P... | Python Code:
import numpy as np
i = np.arange(1,11) # 11, because arange is not inclusive
s = np.sum(2*i)
print(s)
More traditional looping (non-Numpy) would perform the summation as follows:
s = 0
for i in range(1,11):
s += 2*i
print(s)
Explanation: Artificial Intelligence for Humans
Introduction to the Math... |
6,166 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Dependencies
Step1: nbformat doc
Step2: whoosh doc
Step3: widget discussion | Python Code:
import nbformat
Explanation: Dependencies:
- whoosh
- yattag
- hurry.filesize
End of explanation
from whoosh.index import create_in
from whoosh.fields import *
from whoosh.qparser import QueryParser
Explanation: nbformat doc: http://nbformat.readthedocs.org/en/latest/api.html
End of explanation
import o... |
6,167 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Model Versioning Design Pattern
In the Model Versioning design pattern, backward compatibility is achieved by deploying a changed model as a microservice with a different REST endpoint. This... | Python Code:
import json
import numpy as np
import pandas as pd
import xgboost as xgb
import tensorflow as tf
from sklearn.utils import shuffle
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
from google.cloud import bigquery
Explanation: Model Versioning Design Pattern
I... |
6,168 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Obsah dnesnej prednasky
1. Rozsah platnosti premennej
2. Vnorena funkcia
3. Closure
4. Decorator
Closure - Uzaver
Funkcia, ktora pouziva neglobalnu premennu definovanu mimo svojho tela (vysv... | Python Code:
def f1(a):
print(a)
print(b)
f1(3)
b = 6
f1(3)
Explanation: Obsah dnesnej prednasky
1. Rozsah platnosti premennej
2. Vnorena funkcia
3. Closure
4. Decorator
Closure - Uzaver
Funkcia, ktora pouziva neglobalnu premennu definovanu mimo svojho tela (vysvetlim)
Da sa to pouzit napriklad na asynchronne p... |
6,169 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Defining labels
Everything is actually done in terms of ensembles. We can map the ensembles to any labels. In our case, we use the initial replica ID associated with the ensemble. We use thi... | Python Code:
sset0 = storage.samplesets[0]
numeric_labels = { s.ensemble : s.replica for s in sset0}
string_labels = { s.ensemble : str(s.replica) for s in sset0 }
numeric_to_string = { numeric_labels[e] : string_labels[e] for e in numeric_labels.keys()}
Explanation: Defining labels
Everything is actually done in terms... |
6,170 | 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 をインストールします。... | 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... |
6,171 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Minimal Working Example for LongHCPulse
This notebook is a minimal working example for LongHCPulse which computes the heat capacity of $\rm{Yb_2Ti_2O_7}$.
This can serve as a template for pr... | Python Code:
# Minimal Working Example for LongHCPulse
# Allen Scheie
# import libraries
%matplotlib notebook
import numpy as np
import matplotlib.pyplot as plt
from LongHCPulse import LongHCPulse # class to compute heat capacity
# Find Yb2Ti2O7 molar mass
mmYb = 173.201 # g/mol (from WolframAlpha.com)
mmTi = 47.867... |
6,172 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
ES-DOC CMIP6 Model Properties - Land
MIP Era
Step1: Document Authors
Set document authors
Step2: Document Contributors
Specify document contributors
Step3: Document Publication
Specify do... | Python Code:
# DO NOT EDIT !
from pyesdoc.ipython.model_topic import NotebookOutput
# DO NOT EDIT !
DOC = NotebookOutput('cmip6', 'inpe', 'besm-2-7', 'land')
Explanation: ES-DOC CMIP6 Model Properties - Land
MIP Era: CMIP6
Institute: INPE
Source ID: BESM-2-7
Topic: Land
Sub-Topics: Soil, Snow, Vegetation, Energy ... |
6,173 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Working with large data sets
Lazy evaluation, pure functions and higher order functions
Lazy and eager evaluation
A list comprehension is eager.
Step1: A generator expression is lazy.
Step2... | Python Code:
[x*x for x in range(3)]
Explanation: Working with large data sets
Lazy evaluation, pure functions and higher order functions
Lazy and eager evaluation
A list comprehension is eager.
End of explanation
(x*x for x in range(3))
Explanation: A generator expression is lazy.
End of explanation
g = (x*x for x in ... |
6,174 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Recurrent Neural network example
This is multilayer feed forward network with a Recurrent layer. Help observing the inner workingsof backpropagation through time.
Step1: We wil demonstrate ... | Python Code:
%matplotlib inline
import matplotlib
import numpy as np
import matplotlib.pyplot as plt
# Module with the neural net classes
import DNN
import Solvers
Explanation: Recurrent Neural network example
This is multilayer feed forward network with a Recurrent layer. Help observing the inner workingsof backpropa... |
6,175 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Regression Week 4
Step1: Polynomial regression, revisited
We build on the material from Week 3, where we wrote the function to produce an SFrame with columns containing the powers of a give... | Python Code:
import graphlab
Explanation: Regression Week 4: Ridge Regression (interpretation)
In this notebook, we will run ridge regression multiple times with different L2 penalties to see which one produces the best fit. We will revisit the example of polynomial regression as a means to see the effect of L2 regular... |
6,176 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Lista de Exercícios - WEDER CASEMIRO DE SOUZA
Os exercícios valem 30% da nota final.
Data Entrega
Step1: Teste para as seguintes situações
Step2: Exercício 2
(0.5 ponto) Crie uma função ch... | Python Code:
def soma_tres_num (valor1, valor2, valor3=150):
total = valor1 + valor2 + valor3
return(total)
Explanation: Lista de Exercícios - WEDER CASEMIRO DE SOUZA
Os exercícios valem 30% da nota final.
Data Entrega: 18/09/2016
Formato da Entrega: .ipynb - Clique em File -> Download as -> IPython Notebook (.... |
6,177 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Lesson 36
Step2: Factorial Program
Create a program that can return the n! of a number (5! = 1 * 2 * 3 * 4 * 5 = 120).
Step4: The factorial program is returning a 0 output, which is invali... | Python Code:
import logging
logging.basicConfig(level=logging.DEBUG, format = '%(asctime)s - %(levelname)s - %(message)s') # Format for basic logging
Explanation: Lesson 36:
Logging
Logging involves printing code output to a file that can be reviewed later.
The logging module contains tools for logging in Python.
logg... |
6,178 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Problem
Step1: Two candidate discretizations
Step2: Discretization_fast
Step3: Discretization_slow
Step4: Extract discrete trajectories
Step5: Cross-validation | Python Code:
# construct and simulate toy example: diffusive dynamics in a double-well potential
import numpy as np
import numpy.random as npr
import matplotlib.pyplot as plt
%matplotlib inline
offset = np.array([3,0])
def q(x):
''' unnormalized probability '''
return np.exp(-np.sum((x-offset)**2)) + np.exp(-np... |
6,179 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Intro to Snorkel
Step1: We repeat our definition of the Spouse Candidate subclass from Parts II and III.
Step2: Using a labeled development set
In our setting here, we will use the phrase ... | Python Code:
%load_ext autoreload
%autoreload 2
%matplotlib inline
import os
# TO USE A DATABASE OTHER THAN SQLITE, USE THIS LINE
# Note that this is necessary for parallel execution amongst other things...
# os.environ['SNORKELDB'] = 'postgres:///snorkel-intro'
import numpy as np
from snorkel import SnorkelSession
ses... |
6,180 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
How to make a 3D web visualisation without a single line of code
In this notebook we use QGIS to create a shareable terrain model with a data overlay, which can be shared on a web server, wi... | Python Code:
###ignore this block of code - it is required only to show the map in iPython - you won't need it!
from IPython.core.display import display, HTML
display(HTML('<iframe width="800" height="600" frameborder="1" scrolling ="no" src="./qgis2threejs/ACT_elevs_test_1.html"></iframe>'))
Explanation: How to make a... |
6,181 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Environment and RL Agent Controller for a Thermostat
Author
Step1: Goal and Reward
The goal here is to make an agent that will take actions that will keep the temperature between 0.4 and 0.... | Python Code:
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import math
## Compute the response for a given action and current temperature
def respond(action, current_temp, tau):
return action + (current_temp - action) * math.exp(-1.0/tau)
## Actions of a series of on, then off
sAction = pd.... |
6,182 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Demo - Poisson equation 2D
Solve Poisson's equation in 2D with homogeneous Dirichlet bcs in one direction and periodicity in the other.
$$
\begin{align}
\nabla^2 u(x, y) &= f(x, y), \quad ... | Python Code:
from shenfun import *
import matplotlib.pyplot as plt
N = (16, 12)
BX = FunctionSpace(N[0], 'L', bc=(0, 0))
BY = FunctionSpace(N[1], 'F')
V = TensorProductSpace(comm, (BX, BY))
v = TestFunction(V)
u = TrialFunction(V)
A = inner(grad(u), grad(v))
print(A)
Explanation: Demo - Poisson equation 2D
Solve Poisso... |
6,183 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Analyzing patient data
Words are useful, but what’s more useful are the sentences and stories we build with them.
A lot of powerful tools are built into languages like Python, even more live... | Python Code:
import numpy
Explanation: Analyzing patient data
Words are useful, but what’s more useful are the sentences and stories we build with them.
A lot of powerful tools are built into languages like Python, even more live in the libraries they are used to build
We need to import a library called NumPy
Use this ... |
6,184 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Service Creation
Metadata
| Metadata | Value |
|
Step1: Download & Process Security Dataset
Step2: Analytic I
Look for new services being created in your environment and stack t... | Python Code:
from openhunt.mordorutils import *
spark = get_spark()
Explanation: Service Creation
Metadata
| Metadata | Value |
|:------------------|:---|
| collaborators | ['@Cyb3rWard0g', '@Cyb3rPandaH'] |
| creation date | 2019/08/13 |
| modification date | 2020/09/20 |
| playbook related | [] |
... |
6,185 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Fitting censored data
Experimental measurements are sometimes censored such that we only know partial information about a particular data point. For example, in measuring the lifespan of mic... | Python Code:
import numpy as np
n = 30 # number of variables
M = 50 # number of censored observations
K = 200 # total number of observations
np.random.seed(n*M*K)
X = np.random.randn(K*n).reshape(K, n)
c_true = np.random.rand(n)
# generating the y variable
y = X.dot(c_true) + .3*np.sqrt(n)*np.random.randn(K)
# ordering... |
6,186 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: Image Classification
In this project, you'll classify images from the CIFAR-10 dataset. The dataset consists of airplanes, dogs, cats, and other objects. You'll preprocess the images... | Python Code:
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
from urllib.request import urlretrieve
from os.path import isfile, isdir
from tqdm import tqdm
import problem_unittests as tests
import tarfile
cifar10_dataset_folder_path = 'cifar-10-batches-py'
# Use Floyd's cifar-10 dataset if present
floyd_cifa... |
6,187 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
练习 1:写程序,可由键盘读入用户姓名例如Mr. right,让用户输入出生的月份与日期,判断用户星座,假设用户是金牛座,则输出,Mr. right,你是非常有性格的金牛座!。
Step1: 练习 2:写程序,可由键盘读入两个整数m与n(n不等于0),询问用户意图,如果要求和则计算从m到n的和输出,如果要乘积则计算从m到n的积并输出,如果要求余数则计算m除以n的余数的值并输出... | Python Code:
name=input('请输入你的名字,回车结束:')
birthday = float(input('请输入你的出生日期(如5月20日,则输入5.20),按下回车键结束:'))
if 3.21<= birthday <=3.31 or 4.1<= birthday <=4.19:
print(name,'你是热情自信的白羊座喔!',sep='!')
elif 4.20<= birthday <= 4.30 or 5.1<= birthday <=5.20:
print(name,'你是固执又有韧性的金牛座喔!',sep='!')
elif 5.21<= birthday... |
6,188 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Modeling Protein-Ligand Interactions with Atomic Convolutions
By Nathan C. Frey | Twitter and Bharath Ramsundar | Twitter
This DeepChem tutorial introduces the Atomic Convolutional Neural Ne... | Python Code:
!curl -Lo conda_installer.py https://raw.githubusercontent.com/deepchem/deepchem/master/scripts/colab_install.py
import conda_installer
conda_installer.install()
!/root/miniconda/bin/conda info -e
!/root/miniconda/bin/conda install -c conda-forge mdtraj -y -q # needed for AtomicConvs
!pip install --pre de... |
6,189 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Test script to find all locations with large swirl
Aim is to take a velocity field, find all locations with large swirl, and then identify distinct blobs of swirl.
This script makes use of ... | Python Code:
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
import h5py
from importlib import reload
import sep
f = h5py.File('/Users/Owen/Dropbox/Data/ABL/SBL PIV data/RNV45-RI2.mat')
#list(f.keys())
Swirl = np.asarray(f['Swirl'])
X = np.asarray(f['X'])
Y = np.asarray(f['Y'])
X = np.transpose(... |
6,190 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Tables illustration of working with computational models of probability
David Culler
This notebook seeks to illustrate simple datascience.Table operations as part of a basic lesson on probab... | Python Code:
# HIDDEN - generic nonsense for setting up environment
from datascience import *
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plots
plots.style.use('fivethirtyeight')
from ipywidgets import interact
# datascience version number of last run of this notebook
version.__version__
Explanati... |
6,191 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
SymPyとチャート式で復習する高校数学I - PyLadies Tokyo Meetup #6 LT
お前だれよ?
@iktakahiro
blog
Step1: 式の計算
次の計算をせよ。(13頁, 基礎例題5)
(1) $(5x^3+3x-2x^2-4)+(3x^3-3x^2+5)$
Step2: 答え
Step3: 答え
Step4: 答え
Step5: 答え... | Python Code:
import sympy
# 記号の定義
x, y = sympy.symbols('x y')
# 式の定義
expr = 2 * x + y
print('定義された式:\n', expr)
# x, y に数値を代入
a1 = expr.subs([(x, 4), (y, 3)])
print('\nx=4, Y=3の場合:\n', a1)
a2 = expr - y
print('\nexpr から y をマイナス:\n', a2)
Explanation: SymPyとチャート式で復習する高校数学I - PyLadies Tokyo Meetup #6 LT
お前だれよ?
@iktakahiro
... |
6,192 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Seminar 14
Newton method
Reminder
Descent methods
Descent directions
Gradient descent
Step size selection rules
Convergence theorem
Experiments
Drawbacks of gradient descent
Linear convergen... | Python Code:
import numpy as np
USE_COLAB = False
if USE_COLAB:
!pip install git+https://github.com/amkatrutsa/liboptpy
import liboptpy.unconstr_solvers as methods
import liboptpy.step_size as ss
n = 1000
m = 200
x0 = np.zeros((n,))
A = np.random.rand(n, m) * 10
Explanation: Seminar 14
Newton method
Remind... |
6,193 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2021 The TensorFlow Similarity Authors.
Step1: Tensorflow Similarity Sampler I/O Cookbook
<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
# dis... |
6,194 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Advanced Pandas
Step1: <a id=wants></a>
Example
Step2: Reminders
What kind of object does each of the following produce?
Step3: Wants
We might imagine doing several different things with ... | Python Code:
%matplotlib inline
import pandas as pd # data package
import matplotlib.pyplot as plt # graphics module
import datetime as dt # date and time module
import numpy as np # foundation for Pandas
Explanation: Advanced Pandas... |
6,195 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Tutorial Goal
This tutorial aims to show how RTApp performance metrics are computed
and reported by the perf analysis module provided by LISA.
Step1: Collected results
Step2: Trace inspect... | Python Code:
import logging
reload(logging)
logging.basicConfig(
format='%(asctime)-9s %(levelname)-8s: %(message)s',
datefmt='%I:%M:%S')
# Enable logging at INFO level
logging.getLogger().setLevel(logging.INFO)
# Execute this cell to report devlib debugging information
logging.getLogger('ssh').setLevel(logging... |
6,196 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Linear Regression
written by Gene Kogan
Now we will introduce the task of linear regression, the simplest type of machine learning problem. The goal of linear regression is to fit a line to ... | Python Code:
import numpy as np
import matplotlib.pyplot as plt
# x, y
data = np.array([
[2.4, 1.7],
[2.8, 1.85],
[3.2, 1.79],
[3.6, 1.95],
[4.0, 2.1],
[4.2, 2.0],
[5.0, 2.7]
])
Explanation: Linear Regression
written by Gene Kogan
Now we will introduce the task of linear regression, th... |
6,197 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Solution of 5.9.1, Bee Checklist
First of all, we import the two modules we'll need to read the csv file, and to use regular expressions
Step1: Then, we read the file, and store the columns... | Python Code:
import csv
import re
Explanation: Solution of 5.9.1, Bee Checklist
First of all, we import the two modules we'll need to read the csv file, and to use regular expressions:
End of explanation
with open('../data/bee_list.txt') as f:
csvr = csv.DictReader(f, delimiter = '\t')
species = []
authors ... |
6,198 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Introduction to Python 3
Python is a modern programming language that
* is open source
* is interpreted
* interpreters exist for most platforms
* is multi-paradigm (incl. object-oriented)
... | Python Code:
print("hello world!")
Explanation: Introduction to Python 3
Python is a modern programming language that
* is open source
* is interpreted
* interpreters exist for most platforms
* is multi-paradigm (incl. object-oriented)
* comes with batteries included whenever possible
Versions
Version 2 of the Python... |
6,199 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Python Crash Course Exercises - Solutions
This is an optional exercise to test your understanding of Python Basics. If you find this extremely challenging, then you probably are not ready fo... | Python Code:
7 **4
Explanation: Python Crash Course Exercises - Solutions
This is an optional exercise to test your understanding of Python Basics. If you find this extremely challenging, then you probably are not ready for the rest of this course yet and don't have enough programming experience to continue. I would su... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.