Unnamed: 0
int64
0
16k
text_prompt
stringlengths
110
62.1k
code_prompt
stringlengths
37
152k
9,900
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', 'hammoz-consortium', 'sandbox-2', 'landice') Explanation: ES-DOC CMIP6 Model Properties - Landice MIP Era: CMIP6 Institute: HAMMOZ-CONSORTIUM Source ID: SANDBOX-2 Topic: Landice Sub-To...
9,901
Given the following text description, write Python code to implement the functionality described below step by step Description: Non-parametric between conditions cluster statistic on single trial power This script shows how to compare clusters in time-frequency power estimates between conditions. It uses a non-parame...
Python Code: # Authors: Alexandre Gramfort <alexandre.gramfort@telecom-paristech.fr> # # License: BSD (3-clause) import numpy as np import matplotlib.pyplot as plt import mne from mne.time_frequency import tfr_morlet from mne.stats import permutation_cluster_test from mne.datasets import sample print(__doc__) Explanati...
9,902
Given the following text description, write Python code to implement the functionality described below step by step Description: GCE Lab 3 - Constrain Galaxy Model This notebook presents how to plot the basic galaxy evolution properties of your simple Milky Way model. Those plots will allow you to calibrate your model...
Python Code: # Import the standard Python packages import matplotlib import matplotlib.pyplot as plt import numpy as np # Two-zone galactic chemical evolution code import JINAPyCEE.omega_plus as omega_plus # Matplotlib option %matplotlib inline Explanation: GCE Lab 3 - Constrain Galaxy Model This notebook presents how ...
9,903
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 ../../stacks_queues/stack/stack.py %load ../../stacks_queues/stack/stack.py def hanoi(num_disks, src, dest, buff): # TODO: Implement me pass Explanation: <small><i>This notebook was prepared by Donne Martin. Source and license info is on GitHub.</i></small> Challenge Notebook Problem: Implemen...
9,904
Given the following text description, write Python code to implement the functionality described below step by step Description: Import Modules Step1: Import Scrapped Reviews Step2: Import Hu & Liu (2004) Word Dictionary and Wrangled Large Users Step3: Connect to the AWS Instance and get the restaurant reviews from...
Python Code: import json import pandas as pd import re import random import matplotlib.pyplot as plt %matplotlib inline from ast import literal_eval as make_tuple from scipy import sparse import numpy as np from pymongo import MongoClient from nltk.corpus import stopwords from sklearn import svm from sklearn.decompos...
9,905
Given the following text description, write Python code to implement the functionality described below step by step Description: Step3: Task Include the curvature as an extra parameter to your likelihood Step4: Now let's analize the chains First just an histogram Step5: How to obtain the confidence regions of a vari...
Python Code: import numpy as np import scipy.integrate as integrate def E(z,OmDE,OmM): This function computes the integrand for the computation of the luminosity distance for a flat universe z -> float OmDE -> float OmM -> float gives E -> float Omk=1-OmDE-OmM return 1/np.sqrt(...
9,906
Given the following text description, write Python code to implement the functionality described below step by step Description: GMaps on Android The goal of this experiment is to test out GMaps on a Pixel device running Android and collect results. Step1: Test environment setup For more details on this please check ...
Python Code: from conf import LisaLogging LisaLogging.setup() %pylab inline import json import os # Support to access the remote target import devlib from env import TestEnv # Import support for Android devices from android import Screen, Workload # Support for trace events analysis from trace import Trace # Suport for...
9,907
Given the following text description, write Python code to implement the functionality described below step by step Description: Detección de caras mediante Machine Learning Previamente a utilizar esta técnica para reconocer los fitolitos en nuestras imagenes, utilizaremos esta técnica para reconocer caras en diversas...
Python Code: #Imports %matplotlib inline import matplotlib.pyplot as plt import numpy as np Explanation: Detección de caras mediante Machine Learning Previamente a utilizar esta técnica para reconocer los fitolitos en nuestras imagenes, utilizaremos esta técnica para reconocer caras en diversas imagenes. Si el reconoci...
9,908
Given the following text description, write Python code to implement the functionality described below step by step Description: DiscreteDP Example Step1: We follow the state-action pairs formulation approach. We let the state space consist of the possible values of the asset price and the state indicating that "the ...
Python Code: %matplotlib inline import numpy as np from scipy import sparse import matplotlib.pyplot as plt import quantecon as qe from quantecon.markov import DiscreteDP, backward_induction, sa_indices T = 0.5 # Time expiration (years) vol = 0.2 # Annual volatility r = 0.05 # Annual interest rate strike...
9,909
Given the following text description, write Python code to implement the functionality described below step by step Description: Base Question Visualization Step1: Reading data back from npz file Step2: I use interact on my plotter function to plot the positions of the stars and galaxies in my system at every time v...
Python Code: %matplotlib inline import matplotlib.pyplot as plt import numpy as np from scipy.integrate import odeint from IPython.html.widgets import interact, interactive, fixed from IPython.display import YouTubeVideo from plotting_function import plotter,static_plot,com_plot,static_plot_com Explanation: Base Questi...
9,910
Given the following text description, write Python code to implement the functionality described below step by step Description: Committees Step1: Party Step2: [ { "id"
Python Code: #List all committees query = 'classification:Committee' r = requests.get('http://api.openhluttaw.org/en/search/organizations?q='+query) pages = r.json()['num_pages'] committees = [] for page in range(1,pages+1): r = requests.get('http://api.openhluttaw.org/en/search/organizations?q='+query+'&page='+str...
9,911
Given the following text description, write Python code to implement the functionality described below step by step Description: 1. Feature Reduction For Training Data Select the top 10%, 20%, 30%, 40% and 50% of features with the most variance. Starting with 1006 ASM features the process will select about 100,...
Python Code: train_data = pd.read_csv('data/train-malware-features-asm.csv') labels = pd.read_csv('data/trainLabels.csv') sorted_train_data = train_data.sort(columns='filename', axis=0, ascending=True, inplace=False) sorted_train_labels = labels.sort(columns='Id', axis=0, ascending=True, inplace=False) X = sorted_train...
9,912
Given the following text description, write Python code to implement the functionality described below step by step Description: Running a Hyperparameter Tuning Job with Vertex Training Learning objectives In this notebook, you learn how to Step1: Restart the kernel After you install the additional packages, you need...
Python Code: import os # The Google Cloud Notebook product has specific requirements IS_GOOGLE_CLOUD_NOTEBOOK = os.path.exists("/opt/deeplearning/metadata/env_version") # Google Cloud Notebook requires dependencies to be installed with '--user' USER_FLAG = "" if IS_GOOGLE_CLOUD_NOTEBOOK: USER_FLAG = "--user" # Inst...
9,913
Given the following text description, write Python code to implement the functionality described below step by step Description: Plotting There are several plotting modules in python. Matplolib is the most complete/versatile package for all 2D plotting. The easiest way to construct a new plot is to have a look at http...
Python Code: %matplotlib import numpy as np import matplotlib.pyplot as plt # To get interactive plotting (otherwise you need to # type plt.show() at the end of the plotting commands) plt.ion() x = np.linspace(0, 10) y = np.sin(x) # basic X/Y line plotting with '--' dashed line and linewidth of 2 plt.plot(x, y, '--',...
9,914
Given the following text description, write Python code to implement the functionality described below step by step Description: Example of discrete and inverse discrete Fourier transform Step1: In this notebook, we provide examples of the discrete Fourier transform (DFT) and its inverse, and how xrft automatically h...
Python Code: import numpy as np import numpy.testing as npt import xarray as xr import xrft import numpy.fft as npft import scipy.signal as signal import dask.array as dsar import matplotlib.pyplot as plt %matplotlib inline Explanation: Example of discrete and inverse discrete Fourier transform End of explanation k0 = ...
9,915
Given the following text description, write Python code to implement the functionality described below step by step Description: Machine Learning Engineer Nanodegree Deep Learning Project Step5: Using MNIST dataset Loading pickled MNIST dataset Step6: Question 1 What approach did you take in coming up with a solutio...
Python Code: # These are all the modules we'll be using later. Make sure you can import them # before proceeding further. from __future__ import print_function import matplotlib.pyplot as plt import numpy as np import random import os import sys import tarfile import cPickle import gzip import theano import theano.tens...
9,916
Given the following text description, write Python code to implement the functionality described below step by step Description: In this tutorial, you will learn how to use cross-validation for better measures of model performance. Introduction Machine learning is an iterative process. You will face choices about wha...
Python Code: #$HIDE$ import pandas as pd # Read the data data = pd.read_csv('../input/melbourne-housing-snapshot/melb_data.csv') # Select subset of predictors cols_to_use = ['Rooms', 'Distance', 'Landsize', 'BuildingArea', 'YearBuilt'] X = data[cols_to_use] # Select target y = data.Price Explanation: In this tutorial, ...
9,917
Given the following text description, write Python code to implement the functionality described below step by step Description: Burst statistics of 5 smFRET samples Step1: 8-spot paper plot style Step2: Compute Burst Data Burst Search Parameters Step3: Multispot Correction Factors Load the leakage coefficient from...
Python Code: from fretbursts import * sns = init_notebook() import os from glob import glob import pandas as pd from IPython.display import display %config InlineBackend.figure_format='retina' # for hi-dpi displays import lmfit print('lmfit version:', lmfit.__version__) figure_size = (5, 4) default_figure = lambda: pl...
9,918
Given the following text description, write Python code to implement the functionality described below step by step Description: Atomic Charge Prediction Introduction In this notebook we will machine-learn the relationship between an atomic descriptor and its electron density using neural networks. The atomic descript...
Python Code: # --- INITIAL DEFINITIONS --- from sklearn.neural_network import MLPRegressor import numpy, math, random from scipy.sparse import load_npz import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D from ase import Atoms from visualise import view Explanation: Atomic Charge Prediction Introduct...
9,919
Given the following text description, write Python code to implement the functionality described below step by step Description: Homework 5 CHE 116 Step1: $$2^{10} \approx 10^3$$ $$2^{20} \approx 10^6$$ $$2^{10n} \approx 10^{3n}$$ 1.2 Answer Step2: 1.3 Answer Step3: 1.4 Answer Step4: 2. Watching Youtube with the G...
Python Code: import numpy as np ints = np.arange(1,21) pows = 2**ints print(pows) print(pows[9], pows[19]) Explanation: Homework 5 CHE 116: Numerical Methods and Statistics Prof. Andrew White Version 1.1 (2/9/2016) 1. Python Practice (20 Points) Answer the following problems in Python [4 points] Using Numpy, create the...
9,920
Given the following text description, write Python code to implement the functionality described below step by step Description: Mean field inference for $\mathbb{Z}_2$ Syncronization We illustrate the $\mathbb{Z}_2$ syncronization inference problem using pyro. Step1: The model Our model is $$ Y_{ij} = \frac{\lambda}...
Python Code: # import some dependencies import torch from torch.autograd import Variable import numpy as np import pyro import pyro.distributions as dist import pyro from pyro.infer import SVI Explanation: Mean field inference for $\mathbb{Z}_2$ Syncronization We illustrate the $\mathbb{Z}_2$ syncronization inference p...
9,921
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: <h1 align="center">Visualizing TensorFlow Step2: The TensorFlow Execution Graph If we now launch tensorboard and navigate to http Step3: After re-running with the loss function summ...
Python Code: %pylab inline pylab.style.use('ggplot') import numpy as np import tensorflow as tf import os import shutil from contextlib import contextmanager @contextmanager def event_logger(logdir, session): Hands out a managed tensorflow summary writer. Cleans up the event log directory before every run...
9,922
Given the following text description, write Python code to implement the functionality described below step by step Description: PANDAS Module 1 Step1: Overview Two primary data structures of pandas * Series (1-dimensional) array * DataFrame (tabular, spreadsheet) Indexing and slicing of pandas objects Arithmetic op...
Python Code: import pandas as pd import numpy as np import matplotlib.pyplot as plt %matplotlib inline Explanation: PANDAS Module 1: Data Structure and Applications pandas is an open source, BSD-licensed Python library providing fast, flexible, easy-to-use, data structures and data analysis tools for working with “rela...
9,923
Given the following text description, write Python code to implement the functionality described below step by step Description: =========================================================== Plot single trial activity, grouped by ROI and sorted by RT =========================================================== This will ...
Python Code: # Authors: Jona Sassenhagen <jona.sassenhagen@gmail.com> # # License: BSD (3-clause) import mne from mne.datasets import testing from mne import Epochs, io, pick_types from mne.event import define_target_events print(__doc__) Explanation: =========================================================== Plot sin...
9,924
Given the following text description, write Python code to implement the functionality described below step by step Description: <!-- dom Step1: Here follows a simple example where we set up an array of ten elements, all determined by random numbers drawn according to the normal distribution, Step2: We defined a vec...
Python Code: import numpy as np Explanation: <!-- dom:TITLE: Data Analysis and Machine Learning: Getting started, our first data and Machine Learning encounters --> Data Analysis and Machine Learning: Getting started, our first data and Machine Learning encounters <!-- dom:AUTHOR: Morten Hjorth-Jensen at Department of ...
9,925
Given the following text description, write Python code to implement the functionality described below step by step Description: Gaussian Process Regression Gaussian Process regression is a non-parametric approach to regression or data fitting that assumes that observed data points $y$ are generated by some unknown la...
Python Code: %matplotlib inline import matplotlib.pyplot as plt import matplotlib.cm as cmap cm = cmap.inferno import numpy as np import scipy as sp import theano import theano.tensor as tt import theano.tensor.nlinalg import sys sys.path.insert(0, "../../..") import pymc3 as pm Explanation: Gaussian Process Regressio...
9,926
Given the following text description, write Python code to implement the functionality described below step by step Description: Class 26 Step1: Define a log likelihood function for the vertex degree distribution Step2: Define a vectorized log-factorial function, since it doesn't seem to be a builtin in python Step3...
Python Code: import pandas g_discret_data = pandas.read_csv("shared/sachs_data_discretized.txt", sep="\t") g_discret_data.head(n=6) Explanation: Class 26: Bayesian Networks Infer a Bayesian network from a matrix of discretized phospho-flow cytometry data. Based on supplementary data fr...
9,927
Given the following text description, write Python code to implement the functionality described below step by step Description: Denoising Autoencoder Sticking with the MNIST dataset, let's add noise to our data and see if we can define and train an autoencoder to de-noise the images. <img src='notebook_ims/autoencode...
Python Code: import torch import numpy as np from torchvision import datasets import torchvision.transforms as transforms # convert data to torch.FloatTensor transform = transforms.ToTensor() # load the training and test datasets train_data = datasets.MNIST(root='data', train=True, do...
9,928
Given the following text description, write Python code to implement the functionality described below step by step Description: <a href="https Step1: Template matching Let's first download an image and a template to search for. The template is a smaller part of the original image. Step2: Both the image used for pro...
Python Code: import glob # to extend file name pattern to list import cv2 # OpenCV for image processing from cv2 import aruco # to find ArUco markers import numpy as np # for matrices import matplotlib.pyplot as plt # to show images Exp...
9,929
Given the following text description, write Python code to implement the functionality described below step by step Description: Likelihood of a coin being fair $$ P(\theta|X) = \frac{P(X|\theta)P(\theta)}{P(X)} $$ Here, $P(X|\theta)$ is the likelihood, $P(\theta)$ is the prior on theta, $P(X)$ is the evidence, while ...
Python Code: def get_likelihood(theta, n, k, normed=False): ll = (theta**k)*((1-theta)**(n-k)) if normed: num_combs = comb(n, k) ll = num_combs*ll return ll get_likelihood(0.5, 2, 2, normed=True) get_likelihood(0.5, 10, np.arange(10), normed=True) N = 100 plt.plot( np.arange(N), get_...
9,930
Given the following text description, write Python code to implement the functionality described below step by step Description: <h1>Table of Contents<span class="tocSkip"></span></h1> <div class="toc"><ul class="toc-item"><li><span><a href="#Searching,-Hashing,-Sorting" data-toc-modified-id="Searching,-Hashing,-Sorti...
Python Code: from jupyterthemes import get_themes from jupyterthemes.stylefx import set_nb_theme themes = get_themes() set_nb_theme(themes[1]) %load_ext watermark %watermark -a 'Ethen' -d -t -v -p jupyterthemes Explanation: <h1>Table of Contents<span class="tocSkip"></span></h1> <div class="toc"><ul class="toc-item"><l...
9,931
Given the following text description, write Python code to implement the functionality described below step by step Description: Homework assignment #3 These problem sets focus on using the Beautiful Soup library to scrape web pages. Problem Set #1 Step1: Now, in the cell below, use Beautiful Soup to write an express...
Python Code: from bs4 import BeautifulSoup from urllib.request import urlopen html_str = urlopen("http://static.decontextualize.com/widgets2016.html").read() document = BeautifulSoup(html_str, "html.parser")#python读取html里所有代码,用beautifulsoup Explanation: Homework assignment #3 These problem sets focus on using the Beaut...
9,932
Given the following text description, write Python code to implement the functionality described below step by step Description: Bombora Topic Interest Datasets Explaining Bombora topic interest score datasets. 0. Surge vs Interest? As a matter of clarification, topic surge as a product is generated from topic interes...
Python Code: !ls -lh ../../data/topic-interest-score/ Explanation: Bombora Topic Interest Datasets Explaining Bombora topic interest score datasets. 0. Surge vs Interest? As a matter of clarification, topic surge as a product is generated from topic interest models. In technical discussions, we'll refer to both the pro...
9,933
Given the following text description, write Python code to implement the functionality described below step by step Description: Errors, or bugs, in your software Today we'll cover dealing with errors in your Python code, an important aspect of writing software. What is a software bug? According to Wikipedia (accessed...
Python Code: import numpy as np Explanation: Errors, or bugs, in your software Today we'll cover dealing with errors in your Python code, an important aspect of writing software. What is a software bug? According to Wikipedia (accessed 16 Oct 2018), a software bug is an error, flaw, failure, or fault in a computer prog...
9,934
Given the following text description, write Python code to implement the functionality described below step by step Description: Copyright 2020 The TensorFlow Authors. Step1: <table class="tfo-notebook-buttons" align="left"> <td> <a target="_blank" href="https Step2: Vectorize an example sentence Consider the ...
Python Code: #@title Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # dist...
9,935
Given the following text description, write Python code to implement the functionality described below step by step Description: plot_sky_brightness_model Visualizing the machine-learned (PTF) sky brightness model Step1: Let's look at the range of the data Step2: So there are clearly outliers. Let's look at histogr...
Python Code: # hack to get the path right import sys sys.path.append('..') from ztf_sim.SkyBrightness import SkyBrightness from ztf_sim.magnitudes import limiting_mag import astropy.units as u import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns %matplotlib inline sns.set_style('...
9,936
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: 変数の作成 変数を作成するには、初期値を指定します。tf.Variable は、初期...
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...
9,937
Given the following text description, write Python code to implement the functionality described below step by step Description: Labeled Data Labeled Data - contains the features and target attribute with correct answer Training Set Part of labeled data that is used for training the model. 60-70% of the labeled data i...
Python Code: # read the bike train csv file df = pd.read_csv(regression_example) df.head() df.corr() df['count'].describe() df.season.value_counts() df.holiday.value_counts() df.workingday.value_counts() df.weather.value_counts() df.temp.describe() Explanation: Labeled Data Labeled Data - contains the features and targ...
9,938
Given the following text description, write Python code to implement the functionality described below step by step Description: <hr> Patrick BROCKMANN - LSCE (Climate and Environment Sciences Laboratory)<br> <img align="left" width="40%" src="http Step1: "Classic" use with cell magic Step2: Explore interactive widg...
Python Code: %load_ext ferretmagic Explanation: <hr> Patrick BROCKMANN - LSCE (Climate and Environment Sciences Laboratory)<br> <img align="left" width="40%" src="http://www.lsce.ipsl.fr/Css/img/banniere_LSCE_75.png" ><br><br> <hr> Updated: 2019/11/13 Load the ferret extension End of explanation %%ferret -s 600,400 set...
9,939
Given the following text description, write Python code to implement the functionality described below step by step Description: Recommender Engine Perhaps the most famous example of a recommender engine in the Data Science world was the Netflix competition started in 2006, in which teams from all around the world c...
Python Code: # Importing the data import pandas as pd import numpy as np header = ['user_id', 'item_id', 'rating', 'timestamp'] data_movie_raw = pd.read_csv('../data/ml-100k/u.data', sep='\t', names=header) data_movie_raw.head() Explanation: Recommender Engine Perhaps the most famous example of a recommender engine i...
9,940
Given the following text description, write Python code to implement the functionality described below step by step Description: Geo Query Dataset Analysis Step1: Do some cleanup Step2: Query Frequency Analysis Let's take a look Step3: The frequency of queries drops off pretty quickly, suggesting a long tail of low...
Python Code: import os import sys import pandas as pd import seaborn as sns import matplotlib import matplotlib.pyplot as plt import utils %matplotlib inline %load_ext autoreload %autoreload 2 CSV_PATH = '../../data/unique_counts_semi.csv' # load data initial_df = utils.load_queries(CSV_PATH) Explanation: Geo Query Dat...
9,941
Given the following text description, write Python code to implement the functionality described below step by step Description: ES-DOC CMIP6 Model Properties - Atmos MIP Era Step1: Document Authors Set document authors Step2: Document Contributors Specify document contributors Step3: Document Publication Specify d...
Python Code: # DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'pcmdi', 'pcmdi-test-1-0', 'atmos') Explanation: ES-DOC CMIP6 Model Properties - Atmos MIP Era: CMIP6 Institute: PCMDI Source ID: PCMDI-TEST-1-0 Topic: Atmos Sub-Topics: Dynamical Core...
9,942
Given the following text description, write Python code to implement the functionality described below step by step Description: Introduction When life was easy At some point in my calculus education I developed a simple rule, when in doubt set the derivative equal to zero and solve for x. You might recall doing this,...
Python Code: #load all the things! from pulp import * Explanation: Introduction When life was easy At some point in my calculus education I developed a simple rule, when in doubt set the derivative equal to zero and solve for x. You might recall doing this, and the reason for doing it is because for a smooth function ...
9,943
Given the following text description, write Python code to implement the functionality described below step by step Description: Build local cache file from Argo data sources - first in a series of Notebooks Execute commands to pull data from the Internet into a local HDF cache file so that we can better interact with...
Python Code: from biofloat import ArgoData ad = ArgoData(verbosity=2) Explanation: Build local cache file from Argo data sources - first in a series of Notebooks Execute commands to pull data from the Internet into a local HDF cache file so that we can better interact with the data Import the ArgoData class and instati...
9,944
Given the following text description, write Python code to implement the functionality described below step by step Description: Bayesian Data Analysis, 3rd ed Chapter 4, demo 1 Normal approximaton for Bioassay model. Step1: The following demonstrates an alternative "bad" way of calcuting the posterior density p in a...
Python Code: import numpy as np from scipy import optimize, stats %matplotlib inline import matplotlib.pyplot as plt import os, sys # add utilities directory to path util_path = os.path.abspath(os.path.join(os.path.pardir, 'utilities_and_data')) if util_path not in sys.path and os.path.exists(util_path): sys.path.i...
9,945
Given the following text description, write Python code to implement the functionality described below step by step Description: Flopy MODFLOW Boundary Conditions Flopy has a new way to enter boundary conditions for some MODFLOW packages. These changes are substantial. Boundary condtions can now be entered as a list...
Python Code: #begin by importing flopy import os import sys import numpy as np #flopypath = '../..' #if flopypath not in sys.path: # sys.path.append(flopypath) import flopy workspace = os.path.join('data') #make sure workspace directory exists if not os.path.exists(workspace): os.makedirs(workspace) Explanation:...
9,946
Given the following text description, write Python code to implement the functionality described below step by step Description: Programming with Escher This notebook is a collection of preliminary notes about a "code camp" (or a series of lectures) aimed at young students inspired by the fascinating Functional Geomet...
Python Code: f Explanation: Programming with Escher This notebook is a collection of preliminary notes about a "code camp" (or a series of lectures) aimed at young students inspired by the fascinating Functional Geometry paper of Peter Henderson. In such work the Square Limit woodcut by Maurits Cornelis Escher is recon...
9,947
Given the following text description, write Python code to implement the functionality described below step by step Description: Supervised Learning learn the link between two datasets Step1: 2 Linear regression linear models Step2: shrinkage Step3: An example of bias/variance tradeoff, the larger the ridge $\alpha...
Python Code: import numpy as np from sklearn import datasets iris = datasets.load_iris() iris_X = iris.data iris_y = iris.target np.random.seed(0) indices = np.random.permutation(len(iris_X)) iris_X_train = iris_X[indices[:-10]] iris_y_train = iris_y[indices[:-10]] iris_X_test = iris_X[indices[-10:]] iris_y_test = iris...
9,948
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', 'miroc', 'sandbox-1', 'seaice') Explanation: ES-DOC CMIP6 Model Properties - Seaice MIP Era: CMIP6 Institute: MIROC Source ID: SANDBOX-1 Topic: Seaice Sub-Topics: Dynamics, Thermodynam...
9,949
Given the following text description, write Python code to implement the functionality described below step by step Description: TensorFlow Basics Step1: Constants Step2: Operations Step3: Placeholders Instead of using a constant, we can define a placeholder that allows us to provide the value at the time of execut...
Python Code: import tensorflow as tf import numpy as np import matplotlib.pyplot as plt %matplotlib inline tf.__version__ Explanation: TensorFlow Basics End of explanation h = tf.constant('Hello World') h h.graph is tf.get_default_graph() x = tf.constant(100) x # Create Session object in which we can run operations. # ...
9,950
Given the following text description, write Python code to implement the functionality described below step by step Description: Deep Learning Assignment 1 The objective of this assignment is to learn about simple data curation practices, and familiarize you with some of the data we'll be reusing later. This notebook ...
Python Code: # These are all the modules we'll be using later. Make sure you can import them # before proceeding further. import matplotlib.pyplot as plt import numpy as np import os import tarfile import urllib from IPython.display import display, Image from scipy import ndimage from sklearn.linear_model import Logist...
9,951
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: Planet OS API demo for GEFS <font color=red>This notebook is not working right now as GEFS Ensambled forecast is updating only by request! Let us know if you would like to use it</fon...
Python Code: %matplotlib inline import numpy as np import matplotlib.pyplot as plt import dateutil.parser import datetime from urllib.request import urlopen, Request import simplejson as json import pandas as pd def extract_reference_time(API_data_loc): Find reference time that corresponds to most complete forecast...
9,952
Given the following text description, write Python code to implement the functionality described below step by step Description: Magics to Access the JVM Kernels from Python BeakerX has magics for Python so you can run cells in the other languages. The first few cells below show how complete the implementation is with...
Python Code: %%groovy println("stdout works") f = {it + " work"} f("results") %%groovy new Plot(title:"plots work", initHeight: 200) %%groovy [a:"tables", b:"work"] %%groovy "errors work"/1 %%groovy HTML("<h1>HTML works</h1>") %%groovy def p = new Plot(title : 'Plots Work', xLabel: 'Horizontal', yLabel: 'Vertical'); p ...
9,953
Given the following text description, write Python code to implement the functionality described below step by step Description: K-means clustering Authors Ndèye Gagnessiry Ndiaye and Christin Seifert License This work is licensed under the Creative Commons Attribution 3.0 Unported License https Step1: We load the ...
Python Code: import pandas as pd import numpy as np import pylab as plt import matplotlib.pyplot as plt from sklearn.cluster import KMeans import sklearn.metrics as sm Explanation: K-means clustering Authors Ndèye Gagnessiry Ndiaye and Christin Seifert License This work is licensed under the Creative Commons Attribut...
9,954
Given the following text description, write Python code to implement the functionality described below step by step Description: Plots Entropy vs langton blue = all, red = our random Step1: Chi-square vs langton blue = all, red = our random Step2: Mean vs langton blue = all, red = our random Step3: Monte-Carlo-Pi v...
Python Code: # Plot Entropy of all rules against the langton parameter ax1 = plt.gca() d_five.plot("langton", "Entropy", ax=ax1, kind="scatter", marker='o', alpha=.5, s=40) d_five_p10_90.plot("langton", "Entropy", ax=ax1, kind="scatter", color="r", marker='o', alpha=.5, s=40) plt.show() ax1 = plt.gca() d_five.plot("lan...
9,955
Given the following text description, write Python code to implement the functionality described below step by step Description: Least squares fitting of models to data This is a quick introduction to statsmodels for physical scientists (e.g. physicists, astronomers) or engineers. Why is this needed? Because most of s...
Python Code: import numpy as np import pandas as pd import statsmodels.api as sm Explanation: Least squares fitting of models to data This is a quick introduction to statsmodels for physical scientists (e.g. physicists, astronomers) or engineers. Why is this needed? Because most of statsmodels was written by statistici...
9,956
Given the following text description, write Python code to implement the functionality described below step by step Description: Understanding Electronic Health Records with BigQuery ML This tutorial introduces BigQuery ML (BQML) in the context of working with the MIMIC3 dataset. BigQuery ML adds only a few statements...
Python Code: from __future__ import print_function from google.colab import auth from google.cloud import bigquery import numpy as np import pandas as pd import seaborn as sns import matplotlib.pyplot as plt auth.authenticate_user() Explanation: Understanding Electronic Health Records with BigQuery ML This tutorial int...
9,957
Given the following text description, write Python code to implement the functionality described below step by step Description: W7 Lab Assignment Step1: Cumulative histogram and CDF How can we plot a cumulative histogram? Step2: Does it reach 1.0? Why should it become 1.0 at the right end? Also you can do the plot ...
Python Code: import matplotlib.pyplot as plt import pandas as pd import seaborn as sns import numpy as np import random sns.set_style('white') %matplotlib inline Explanation: W7 Lab Assignment End of explanation # TODO: Load IMDB data into movie_df using pandas movie_df = pd.read_csv('imdb.csv', delimiter='\t') movie_d...
9,958
Given the following text description, write Python code to implement the functionality described below step by step Description: On-Axis Field of a Finite Solenoid This formula uses the formula for the field due to a thin shell solenoid, integrated over a range of radii to obtain the magnetic field at any point on th...
Python Code: %matplotlib inline from scipy.special import ellipk, ellipe, ellipkm1 from numpy import pi, sqrt, linspace, log from pylab import plot, xlabel, ylabel, suptitle, legend, show uo = 4E-7*pi # Permeability constant - units of H/m # Compute G Factor from unitless parameters def GFactorUnitless(a, b, g=0.0)...
9,959
Given the following text description, write Python code to implement the functionality described. Description: Number of n digit numbers that do not contain 9 function to find number of n digit numbers possible ; driver function
Python Code: def totalNumber(n ) : return 8 * pow(9 , n - 1 ) ;  n = 3 print(totalNumber(n ) )
9,960
Given the following text description, write Python code to implement the functionality described below step by step Description: CSV 파일 다루기와 데이터 시각화 수정 사항 좀 더 복잡한 csv 데이터 활용 예제 추가 필요 주요 내용 데이터 분석을 위해 가장 기본적으로 할 수 있고, 해야 하는 일이 데이터 시각화이다. 데이터를 시각화하는 것은 어렵지 않지만, 적합한 시각화를 만드는 일은 매우 어려우며, 많은 훈련과 직관이 요구된다. 여기서는 데이터를 탐색하여 얻...
Python Code: import matplotlib.pyplot as plt %matplotlib inline Explanation: CSV 파일 다루기와 데이터 시각화 수정 사항 좀 더 복잡한 csv 데이터 활용 예제 추가 필요 주요 내용 데이터 분석을 위해 가장 기본적으로 할 수 있고, 해야 하는 일이 데이터 시각화이다. 데이터를 시각화하는 것은 어렵지 않지만, 적합한 시각화를 만드는 일은 매우 어려우며, 많은 훈련과 직관이 요구된다. 여기서는 데이터를 탐색하여 얻어진 데이터를 시각화하는 기본적인 방법 네 가지를 배운다. 선그래프 막대그래프 히스토그램 산점도...
9,961
Given the following text description, write Python code to implement the functionality described below step by step Description: Obtaining the first trajectories for a Toy Model Tasks covered in this notebook Step1: Basic system setup First we set up our system Step2: Set up the toy system For the toy model, we need...
Python Code: # Basic imports from __future__ import print_function import openpathsampling as paths import numpy as np %matplotlib inline # used for visualization of the 2D toy system # we use the %run magic because this isn't in a package %run ../resources/toy_plot_helpers.py Explanation: Obtaining the first trajector...
9,962
Given the following text description, write Python code to implement the functionality described below step by step Description: Maxwell filter data with movement compensation Demonstrate movement compensation on simulated data. The simulated data contains bilateral activation of auditory cortices, repeated over 14 di...
Python Code: # Authors: Eric Larson <larson.eric.d@gmail.com> # # License: BSD-3-Clause from os import path as op import mne from mne.preprocessing import maxwell_filter print(__doc__) data_path = op.join(mne.datasets.misc.data_path(verbose=True), 'movement') head_pos = mne.chpi.read_head_pos(op.join(data_path, 'simula...
9,963
Given the following text description, write Python code to implement the functionality described below step by step Description: PUMP IT Using data from Taarifa and the Tanzanian Ministry of Water, can you predict which pumps are functional, which need some repairs, and which don't work at all? This is an intermediate...
Python Code: import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns sns.set(color_codes=True) np.random.seed(69572) %matplotlib inline %load_ext writeandexecute # plt.figure(figsize=(120,10)) small = (4,3) mid = (10, 8) large = (12, 8) Explanation: PUMP IT Using data from Taarifa a...
9,964
Given the following text description, write Python code to implement the functionality described below step by step Description: Simple RL Welcome! Here we'll showcase some basic examples of typical RL programming tasks. Example 1 Step1: Next, we make an MDP and a few agents Step2: The real meat of <i>simple_rl</i> ...
Python Code: # Add simple_rl to system path. import os import sys parent_dir = os.path.abspath(os.path.join(os.getcwd(), os.pardir)) sys.path.insert(0, parent_dir) from simple_rl.agents import QLearningAgent, RandomAgent from simple_rl.tasks import GridWorldMDP from simple_rl.run_experiments import run_agents_on_mdp Ex...
9,965
Given the following text description, write Python code to implement the functionality described below step by step Description: Python and Friends This is a very quick run-through of some python syntax Step1: The Python Language Lets talk about using Python as a calculator... Step2: Notice integer division and floa...
Python Code: # The %... is an iPython thing, and is not part of the Python language. # In this case we're just telling the plotting library to draw things on # the notebook, instead of on a separate window. %matplotlib inline #this line above prepares IPython notebook for working with matplotlib # See all the "as ..."...
9,966
Given the following text description, write Python code to implement the functionality described below step by step Description: XID+ Example Run Script (This is based on a Jupyter notebook, available in the XID+ package and can be interactively run and edited) XID+ is a probababilistic deblender for confusion dominat...
Python Code: import numpy as np from astropy.io import fits from astropy import wcs import pickle import dill import sys import os import xidplus import copy from xidplus import moc_routines, catalogue from xidplus import posterior_maps as postmaps from builtins import input Explanation: XID+ Example Run Script (This i...
9,967
Given the following text description, write Python code to implement the functionality described below step by step Description: This notebook demonstrates how to use the Python MagicDataFrame object. A MagicDataFrame contains the data from one MagIC-format table and provides functionality for accessing and editing t...
Python Code: from pmagpy import new_builder as nb from pmagpy import ipmag import os import json import numpy as np import sys import pandas as pd from pandas import DataFrame from pmagpy import pmag working_dir = os.path.join("..", "3_0", "Osler") Explanation: This notebook demonstrates how to use the Python MagicData...
9,968
Given the following text description, write Python code to implement the functionality described below step by step Description: Data Frame Plots documentation Step1: The plot method on Series and DataFrame is just a simple wrapper around plt.plot() If the index consists of dates, it calls gcf().autofmt_xdate() to tr...
Python Code: import pandas as pd import numpy as np import matplotlib.pyplot as plt plt.style.use('ggplot') Explanation: Data Frame Plots documentation: http://pandas.pydata.org/pandas-docs/stable/visualization.html End of explanation ts = pd.Series(np.random.randn(1000), index=pd.date_range('1/1/2000', periods=1000)) ...
9,969
Given the following text description, write Python code to implement the functionality described below step by step Description: Soring, searching, and counting Step1: Sorting Q1. Sort x along the second axis. Step2: Q2. Sort pairs of surnames and first names and return their indices. (first by surname, then by name...
Python Code: import numpy as np np.__version__ author = 'kyubyong. longinglove@nate.com' Explanation: Soring, searching, and counting End of explanation x = np.array([[1,4],[3,1]]) out = np.sort(x, axis=1) x.sort(axis=1) assert np.array_equal(out, x) print out Explanation: Sorting Q1. Sort x along the second axis. End ...
9,970
Given the following text description, write Python code to implement the functionality described below step by step Description: 1A.soft - Calcul numérique et Cython Python est très lent. Il est possible d'écrire certains parties en C mais le dialogue entre les deux langages est fastidieux. Cython propose un mélange d...
Python Code: from jyquickhelper import add_notebook_menu add_notebook_menu() Explanation: 1A.soft - Calcul numérique et Cython Python est très lent. Il est possible d'écrire certains parties en C mais le dialogue entre les deux langages est fastidieux. Cython propose un mélange de C et Python qui accélère la conception...
9,971
Given the following text description, write Python code to implement the functionality described below step by step Description: ES-DOC CMIP6 Model Properties - Ocnbgchem MIP Era Step1: Document Authors Set document authors Step2: Document Contributors Specify document contributors Step3: Document Publication Speci...
Python Code: # DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'nasa-giss', 'sandbox-3', 'ocnbgchem') Explanation: ES-DOC CMIP6 Model Properties - Ocnbgchem MIP Era: CMIP6 Institute: NASA-GISS Source ID: SANDBOX-3 Topic: Ocnbgchem Sub-Topics: Trac...
9,972
Given the following text description, write Python code to implement the functionality described below step by step Description: Adding river levels Developed by R.A. Collenteur & D. Brakenhoff In this example it is shown how to create a Pastas model that not only includes precipitation and evaporation, but also obser...
Python Code: import pandas as pd import pastas as ps import matplotlib.pyplot as plt ps.show_versions() ps.set_log_level("INFO") Explanation: Adding river levels Developed by R.A. Collenteur & D. Brakenhoff In this example it is shown how to create a Pastas model that not only includes precipitation and evaporation, bu...
9,973
Given the following text description, write Python code to implement the functionality described below step by step Description: Grand Canonical Monte Carlo of atomic species using tabulated pair potentials Step1: Download and build faunus Step2: Generate an artificial, tabulated potential This is just a damped sinu...
Python Code: from __future__ import division, unicode_literals, print_function import matplotlib as mpl import matplotlib.pyplot as plt %matplotlib inline import numpy as np, pandas as pd import os.path, os, sys, json, filecmp, copy plt.rcParams.update({'font.size': 16, 'figure.figsize': [8.0, 6.0]}) try: workdir e...
9,974
Given the following text description, write Python code to implement the functionality described below step by step Description: OP-WORKFLOW-CAGEscan-short-reads-v2.0 This document is an example of how to process a C1 CAGE library with a Jupyter notebook from raw reads to single molecule count. All the steps are descr...
Python Code: import subprocess, os, csv, signal, pysam Explanation: OP-WORKFLOW-CAGEscan-short-reads-v2.0 This document is an example of how to process a C1 CAGE library with a Jupyter notebook from raw reads to single molecule count. All the steps are described in the tutorial section of this repository. In the follow...
9,975
Given the following text description, write Python code to implement the functionality described below step by step Description: Plotly and Cufflinks for plotting with Pandas Get cufflinks Cufflinks integrates plotly with pandas to allow plotting right from pandas dataframes. Install using pip pip install cufflinks St...
Python Code: import numpy as np import pandas as pd import cufflinks as cf from plotly.offline import download_plotlyjs, init_notebook_mode from plotly.offline import plot, iplot #set notebook mode init_notebook_mode(connected=True) cf.go_offline() df = pd.DataFrame(np.random.randn(100,4), columns='A...
9,976
Given the following text description, write Python code to implement the functionality described below step by step Description: 门面模式(Facade Pattern) 1 代码 假设有一组火警报警系统,由三个子元件构成:一个警报器,一个喷水器,一个自动拨打电话的装置。其抽象如下: Step1: 在业务中如果需要将三个部件启动,例如,如果有一个烟雾传感器,检测到了烟雾。在业务环境中需要做如下操作: Step2: 但如果在多个业务场景中需要启动三个部件,怎么办?Ctrl+C加上Ctrl+V么?当然...
Python Code: class AlarmSensor: def run(self): print ("Alarm Ring...") class WaterSprinker: def run(self): print ("Spray Water...") class EmergencyDialer: def run(self): print ("Dial 119...") Explanation: 门面模式(Facade Pattern) 1 代码 假设有一组火警报警系统,由三个子元件构成:一个警报器,一个喷水器,一个自动拨打电话的装置。其抽象如下:...
9,977
Given the following text description, write Python code to implement the functionality described below step by step Description: A decomposition of spatial forecast errors for wildfires using a modification of the contiguous rain area (CRA) method. Copyright Bureau Of Meteorology. This software is provided under licen...
Python Code: import matplotlib.pyplot as plt import numpy as np import pandas as pd from shapely import geometry, ops from scipy import optimize from skimage import transform from IPython import display %matplotlib inline Explanation: A decomposition of spatial forecast errors for wildfires using a modification of the ...
9,978
Given the following text description, write Python code to implement the functionality described below step by step Description: 2A.data - Classification, régression, anomalies - énoncé Le jeu de données Wine Quality Data Set contient 5000 vins décrits par leurs caractéristiques chimiques et évalués par un expert. Peu...
Python Code: %matplotlib inline import matplotlib.pyplot as plt from jyquickhelper import add_notebook_menu add_notebook_menu() Explanation: 2A.data - Classification, régression, anomalies - énoncé Le jeu de données Wine Quality Data Set contient 5000 vins décrits par leurs caractéristiques chimiques et évalués par un ...
9,979
Given the following text description, write Python code to implement the functionality described below step by step Description: <img src='https Step1: Customizing matplotlib http Step2: Quick, easy, simple plots. Object-oriented pyplot interface No global variables Separates style from graph Can easily have multipl...
Python Code: #inline to use with notebook (from pylab import *) %pylab inline Explanation: <img src='https://www.rc.colorado.edu/sites/all/themes/research/logo.png'> Introduction to Data Visualization with matplotlib Thomas Hauser <img src='https://s3.amazonaws.com/research_computing_tutorials/mpl-overview.png'> Obje...
9,980
Given the following text description, write Python code to implement the functionality described below step by step Description: Path function The goal of the MADlib path function is to perform regular pattern matching over a sequence of rows, and to extract useful information about the pattern matches. The useful inf...
Python Code: %load_ext sql # %sql postgresql://gpdbchina@10.194.10.68:55000/madlib %sql postgresql://fmcquillan@localhost:5432/madlib %sql select madlib.version(); Explanation: Path function The goal of the MADlib path function is to perform regular pattern matching over a sequence of rows, and to extract useful inform...
9,981
Given the following text description, write Python code to implement the functionality described below step by step Description: Bayesian Networks author Step1: The Monty Hall Gameshow The Monty Hall problem arose from the gameshow <i>Let's Make a Deal</i>, where a guest had to choose which one of three doors had a p...
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: Bayesian Networks author: Jacob Sc...
9,982
Given the following text description, write Python code to implement the functionality described below step by step Description: Dynamic factors and coincident indices Factor models generally try to find a small number of unobserved "factors" that influence a subtantial portion of the variation in a larger number of o...
Python Code: %matplotlib inline import numpy as np import pandas as pd import statsmodels.api as sm import matplotlib.pyplot as plt np.set_printoptions(precision=4, suppress=True, linewidth=120) from pandas_datareader.data import DataReader # Get the datasets from FRED start = '1979-01-01' end = '2014-12-01' indprod = ...
9,983
Given the following text description, write Python code to implement the functionality described below step by step Description: 计算传播与机器学习 王成军 wangchengjun@nju.edu.cn 计算传播网 http Step1: 使用sklearn做logistic回归 王成军 wangchengjun@nju.edu.cn 计算传播网 http Step2: 使用sklearn实现贝叶斯预测 王成军 wangchengjun@nju.edu.cn 计算传播网 http Step3: n...
Python Code: %matplotlib inline from sklearn import datasets from sklearn import linear_model import matplotlib.pyplot as plt import sklearn print sklearn.__version__ # boston data boston = datasets.load_boston() y = boston.target ' '.join(dir(boston)) boston['feature_names'] regr = linear_model.LinearRegression() lm =...
9,984
Given the following text description, write Python code to implement the functionality described below step by step Description: <a href="https Step1: Load and prepare the dataset You will use the MNIST dataset to train the generator and the discriminator. The generator will generate handwritten digits resembling the...
Python Code: from __future__ import absolute_import, division, print_function, unicode_literals try: # %tensorflow_version only exists in Colab. %tensorflow_version 2.x except Exception: pass import tensorflow as tf tf.__version__ import glob import imageio import matplotlib.pyplot as plt import numpy as np...
9,985
Given the following text description, write Python code to implement the functionality described below step by step Description: ES-DOC CMIP6 Model Properties - Toplevel MIP Era Step1: Document Authors Set document authors Step2: Document Contributors Specify document contributors Step3: Document Publication Specif...
Python Code: # DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'dwd', 'sandbox-1', 'toplevel') Explanation: ES-DOC CMIP6 Model Properties - Toplevel MIP Era: CMIP6 Institute: DWD Source ID: SANDBOX-1 Sub-Topics: Radiative Forcings. Properties: 85...
9,986
Given the following text description, write Python code to implement the functionality described below step by step Description: Downloaded a few comma-delimited data from the <b>United States Department of Transportation, Bureau of Transportation Statistics website.</b> <br> This data ranges from the months of <b>Jan...
Python Code: # Assign a list of available files in my data directory (../data/2016/) to a variable files = os.listdir("data/2016"); # Display files # Read through all files and concat all df into a single dataframe, df. framelist = [] for file in files: tempdf = pd.read_csv("data/2016/" + file) framelist.append...
9,987
Given the following text description, write Python code to implement the functionality described below step by step Description: Step2: ServerSim Overview and Tutorial Introduction This is an overview and tutorial about ServerSim, a framework for the creation of discrete event simulation models to analyze the performa...
Python Code: # %load simulate_deployment_scenario.py from __future__ import print_function from typing import List, Tuple, Sequence from collections import namedtuple import random import simpy from serversim import * def simulate_deployment_scenario(num_users, weight1, weight2, server_range1, ...
9,988
Given the following text description, write Python code to implement the functionality described below step by step Description: Introdução à Programação em Python Nesse Notebook aprenderemos Step1: A ordem que as operações são executadas seguem uma ordem de precedência Step2: A ordem pode ser alterada com o uso de ...
Python Code: # todo texto escrito após "#" é um comentário e não é interpretado pelo Python 1+2 # realiza a operação 1+2 e imprime na tela 2-1 3*5 7/2 7//2 2**3 5%2 Explanation: Introdução à Programação em Python Nesse Notebook aprenderemos: operações básicas do Python, tipos básicos de variáveis, entrada e saída de ...
9,989
Given the following text description, write Python code to implement the functionality described below step by step Description: Kaggle Dogs Vs. Cats Using LeNet on Google Colab TPU Required setup Update api_token with kaggle api key for downloading dataset - Login to kaggle - My Profile &gt; Edit Profile &gt; Cr...
Python Code: !pip install kaggle api_token = {"username":"xxxxx","key":"xxxxxxxxxxxxxxxxxxxxxxxx"} import json import zipfile import os os.mkdir('/root/.kaggle') with open('/root/.kaggle/kaggle.json', 'w') as file: json.dump(api_token, file) !chmod 600 /root/.kaggle/kaggle.json # !kaggle config path -p /root !kaggl...
9,990
Given the following text description, write Python code to implement the functionality described below step by step Description: Four Axes This notebook demonstrates the use of Cube Browser to produce multiple plots using only the code (i.e. no selection widgets). Step1: Load and prepare your cubes Step2: Set up you...
Python Code: import iris import iris.plot as iplt import matplotlib.pyplot as plt from cube_browser import Contour, Browser, Contourf, Pcolormesh Explanation: Four Axes This notebook demonstrates the use of Cube Browser to produce multiple plots using only the code (i.e. no selection widgets). End of explanation air_po...
9,991
Given the following text description, write Python code to implement the functionality described below step by step Description: Whiskey Data This data set contains data on a small number of whiskies Step1: Summaries Shown below are the following charts Step2: Some Analysis Here we use the sci-kit decision tree regr...
Python Code: import pandas as pd from numpy import log, abs, sign, sqrt import brunel whiskey = pd.read_csv("data/whiskey.csv") print('Data on whiskies:', ', '.join(whiskey.columns)) Explanation: Whiskey Data This data set contains data on a small number of whiskies End of explanation %%brunel data('whiskey') x(country...
9,992
Given the following text description, write Python code to implement the functionality described below step by step Description: Interpolation Exercise 2 Step1: Sparse 2d interpolation In this example the values of a scalar field $f(x,y)$ are known at a very limited set of points in a square domain Step2: The follow...
Python Code: %matplotlib inline import matplotlib.pyplot as plt import seaborn as sns import numpy as np sns.set_style('white') from scipy.interpolate import griddata Explanation: Interpolation Exercise 2 End of explanation x = np.empty((1,),dtype=int) x[0] = 0 for i in range(-4,5): x = np.hstack((x,np.array((i,i))...
9,993
Given the following text description, write Python code to implement the functionality described below step by step Description: Hands-on Tutorial Step1: Install library and data dependencies Load and pre-process data sets Step2: Let's examine some rows in these datasets. Step3: Understanding the data There are man...
Python Code: import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns from sklearn import metrics from keras.preprocessing.text import Tokenizer from tensorflow.keras.utils import to_categorical from keras.preprocessing.sequence import pad_sequences from keras.layers import Embedding...
9,994
Given the following text description, write Python code to implement the functionality described below step by step Description: Pandas 数据类型 Step1: 数据丢弃 Step2: 排序 Step3: 获取数据信息 Step4: 数据摘要 Step5: 选择 Step6: 数据聚合 Step7: 帮助 help(pd.Series.loc) 使用函数 Step8: 数据对齐 Step9: 输入输出 读取和写入csv pd.read_csv('file.csv', header=...
Python Code: s = pd.Series([3, -5, 7, 4], index=['a', 'b', 'c', 'd']) data = {'Country': ['Belgium', 'India', 'Brazil'], 'Capital': ['Brussels', 'New Delhi', 'Brasília'], 'Population': [11190846, 1303171035, 207847528]} df = pd.DataFrame(data, columns=['Country', 'Capital', 'Population']) #Pivvot, data = {'Date': ['201...
9,995
Given the following text description, write Python code to implement the functionality described below step by step Description: Finding Sprints, Formally We present an example use of Montre on a data set obtained by tracking positions of players in a real soccer match. In this example, we find all sprints performed b...
Python Code: # Speed (m/s) and acceleration (m/s^2) categories accel_desc = ['nhigh','nmedium', 'nlow','around_zero', 'low', 'medium', 'high'] accel_syms = ['a', 'b', 'c', 'd', 'e', 'f', 'g'] accel_bins = [-100, -1.60, -1.17,-0.57, 0.57, 1.17, 1.60, 100] speed_desc = ['low', 'medium', 'high', 'very_high'] speed_syms =...
9,996
Given the following text description, write Python code to implement the functionality described below step by step Description: QuTiP Example Step1: Overview Here we aim to reproduce the experimental results from Step2: Run Simulation Step3: Plot Results Step4: Versions
Python Code: %matplotlib inline import matplotlib.pyplot as plt import numpy as np from qutip import * Explanation: QuTiP Example: Birth and Death of Photons in a Cavity J.R. Johansson and P.D. Nation For more information about QuTiP see http://qutip.org End of explanation N=5 a=destroy(N) H=a.dag()*a # Simple osc...
9,997
Given the following text description, write Python code to implement the functionality described below step by step Description: PyScopus Step1: <hr> General Search Step2: Full text link Step3: For those with full text links, you are able to get all the text by calling scopus.retrieve_full_text() Step4: <hr> Searc...
Python Code: import pyscopus pyscopus.__version__ from pyscopus import Scopus key = 'YOUR_OWN_API' scopus = Scopus(key) Explanation: PyScopus: Quick Start PyScopus is a Python wrapper of Elsevier Scopus API. More details of this Python package can be found here. <hr> Import Scopus class and initialize with your own API...
9,998
Given the following text description, write Python code to implement the functionality described below step by step Description: Preprocessing and Pipelines Step1: Cross-validated pipelines including scaling, we need to estimate mean and standard deviation separately for each fold. To do that, we build a pipeline. St...
Python Code: from sklearn.datasets import load_digits from sklearn.cross_validation import train_test_split digits = load_digits() X_train, X_test, y_train, y_test = train_test_split(digits.data, digits.target) Explanation: Preprocessing and Pipelines End of explanati...
9,999
Given the following text description, write Python code to implement the functionality described below step by step Description: Aprendizado Supervisionado Vamos começar o estudo da aprendizagem de máquina com o tipo de aprendizado denominado de Supervisionado. Aprendizado Supervisionado (Supervised Learning) Step1: ...
Python Code: # Imports necessários para a parte de Regressão Linear import pandas as pd import matplotlib.pyplot as plt from sklearn.linear_model import LinearRegression from sklearn.model_selection import cross_val_score %matplotlib inline Explanation: Aprendizado Supervisionado Vamos começar o estudo da aprendizagem ...