Unnamed: 0
int64
0
16k
text_prompt
stringlengths
110
62.1k
code_prompt
stringlengths
37
152k
15,600
Given the following text description, write Python code to implement the functionality described below step by step Description: CM360 Bulkdozer Editor Bulkdozer is a tool that can reduce trafficking time in Campaign Manager by up to 80%% by providing automated bulk editing capabilities. License Copyright 2020 Google ...
Python Code: !pip install git+https://github.com/google/starthinker Explanation: CM360 Bulkdozer Editor Bulkdozer is a tool that can reduce trafficking time in Campaign Manager by up to 80%% by providing automated bulk editing capabilities. License Copyright 2020 Google LLC, Licensed under the Apache License, Version 2...
15,601
Given the following text description, write Python code to implement the functionality described below step by step Description: Code Generation for the Heat Equation The <a target="_blank" href="https Step1: We define the PDE using the pystencils building blocks for transient and spatial derivatives. The definition ...
Python Code: u, u_tmp = ps.fields("u, u_tmp: [2D]", layout='fzyx') kappa = sp.Symbol("kappa") dx = sp.Symbol("dx") dt = sp.Symbol("dt") Explanation: Code Generation for the Heat Equation The <a target="_blank" href="https://en.wikipedia.org/wiki/Heat_equation">heat equation</a> which is a simple partial differential eq...
15,602
Given the following text description, write Python code to implement the functionality described below step by step Description: Quantum SVM (quantum kernel method) Introduction Please refer to this file for introduction. This file shows an example how to use Aqua API to build SVM classifier and keep the instance for ...
Python Code: from datasets import * from qiskit_aqua.utils import split_dataset_to_data_and_labels, map_label_to_class_name from qiskit_aqua.input import get_input_instance from qiskit_aqua import run_algorithm, get_feature_map_instance, get_algorithm_instance, get_multiclass_extension_instance Explanation: Quantum SVM...
15,603
Given the following text problem statement, write Python code to implement the functionality described below in problem statement Problem: I want to make an 4 dimensional array of zeros in python. I know how to do this for a square array but I want the lists to have different lengths.
Problem: import numpy as np arr = np.zeros((20,10,10,2))
15,604
Given the following text description, write Python code to implement the functionality described below step by step Description: Explorando os contratos da cidade de São Paulo Na primeira parte deste tutorial, procurei mostrar como Step1: Um parêntesis! Como saber qual é o código do órgão que quero pesquisar? Na cons...
Python Code: import pandas as pd import requests import json import numpy as np TOKEN = '198f959a5f39a1c441c7c863423264' base_url = "https://gatewayapi.prodam.sp.gov.br:443/financas/orcamento/sof/v2.1.0" headers={'Authorization' : str('Bearer ' + TOKEN)} Explanation: Explorando os contratos da cidade de São Paulo Na pr...
15,605
Given the following text description, write Python code to implement the functionality described below step by step Description: ES-DOC CMIP6 Model Properties - Atmoschem MIP Era Step1: Document Authors Set document authors Step2: Document Contributors Specify document contributors Step3: Document Publication Speci...
Python Code: # DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'ec-earth-consortium', 'sandbox-1', 'atmoschem') Explanation: ES-DOC CMIP6 Model Properties - Atmoschem MIP Era: CMIP6 Institute: EC-EARTH-CONSORTIUM Source ID: SANDBOX-1 Topic: Atmosc...
15,606
Given the following text description, write Python code to implement the functionality described below step by step Description: Advanced Step1: As always, let's do imports and initialize a longger and a new Bundle. Step2: Accessing Settings Settings are found with their own context in the Bundle and can be accessed...
Python Code: #!pip install -I "phoebe>=2.3,<2.4" Explanation: Advanced: Settings The Bundle also contains a few Parameters that provide settings for that Bundle. Note that these are not system-wide and only apply to the current Bundle. They are however maintained when saving and loading a Bundle. Setup Let's first ma...
15,607
Given the following text description, write Python code to implement the functionality described below step by step Description: An Introduction to BioImage Data Analysis with Python developed by Jonas Hartmann (Gilmour group, EMBL Heidelberg)<br> as part of the EMBL Bio-IT Course on Intermediate Python Programming<br...
Python Code: # For python 2 users from __future__ import division, print_function # Scientific python import numpy as np import pandas as pd import matplotlib.pyplot as plt # Image analysis import scipy.ndimage as ndi from skimage import io, segmentation, graph, filters, measure # Machine learning from sklearn import ...
15,608
Given the following text description, write Python code to implement the functionality described below step by step Description: Interact Exercise 01 Import Step2: Interact basics Write a print_sum function that prints the sum of its arguments a and b. Step3: Use the interact function to interact with the print_sum ...
Python Code: %matplotlib inline from matplotlib import pyplot as plt import numpy as np from IPython.html.widgets import interact, interactive, fixed from IPython.display import display Explanation: Interact Exercise 01 Import End of explanation def print_sum(a, b): Print the sum of the arguments a and b. print...
15,609
Given the following text description, write Python code to implement the functionality described below step by step Description: Hidden Markov Models author Step1: CG rich region identification example Lets take the simplified example of CG island detection on a sequence of DNA. DNA is made up of the four canonical n...
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: Hidden Markov Models author: Jacob...
15,610
Given the following text description, write Python code to implement the functionality described below step by step Description: Featurizing Ligand-Protein trajectories Trajectories containing a protein and ligand can now be featurized in several ways. A reference frame with at least two chains, one of which is the pr...
Python Code: %matplotlib inline from matplotlib import pyplot as plt import numpy as np import pandas as pd import mdtraj as md top = md.Topology() c = top.add_chain() r0 = top.add_residue('HET', c) r1 = top.add_residue('HET', c) r2 = top.add_residue('HET', c) r3 = top.add_residue('HET', c) r4 = top.add_residue('HET', ...
15,611
Given the following text description, write Python code to implement the functionality described below step by step Description: The issues associated with validation and cross-validation are some of the most important aspects of the practice of machine learning. Selecting the optimal model for your data is vital, a...
Python Code: import numpy as np import matplotlib.pyplot as plt from sklearn.pipeline import Pipeline from sklearn.svm import SVR from sklearn import cross_validation rng = np.random.RandomState(42) n_samples = 200 kernels = ['linear', 'poly', 'rbf'] true_fun = lambda X: X ** 3 X = np.sort(5 * (rng.rand(n_samples) - .5...
15,612
Given the following text description, write Python code to implement the functionality described below step by step Description: Introduction In many simulations particles continuously enter the simulation domain while other particles leave the simulation domain. This example illustrates two key concepts in the coldat...
Python Code: import coldatoms import numpy as np %matplotlib notebook import matplotlib.pyplot as plt Explanation: Introduction In many simulations particles continuously enter the simulation domain while other particles leave the simulation domain. This example illustrates two key concepts in the coldatom library that...
15,613
Given the following text description, write Python code to implement the functionality described below step by step Description: Using ICsound csoundmagics includes an ICsound class which is adapted from Andrés Cabrera's icsound module. ICsound is bound to the %%csound and %csound magics command. This notebook is an a...
Python Code: import numpy as np import matplotlib.pyplot as plt %load_ext csoundmagics Explanation: Using ICsound csoundmagics includes an ICsound class which is adapted from Andrés Cabrera's icsound module. ICsound is bound to the %%csound and %csound magics command. This notebook is an adaptation of Andrés' icsound t...
15,614
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: Beautiful soup on test data Here, we create some simple HTML that include some frequently used tags. Note, however, that we have also left one paragraph tag unclosed. Step2: Once th...
Python Code: source = <!DOCTYPE html> <html> <head> <title>Scraping</title> </head> <body class="col-sm-12"> <h1>section1</h1> <p>paragraph1</p> <p>paragraph2</p> <div class="col-sm-2"> <h2>section2</h2> <p>paragraph3</p> <p>unclosed </div> </body> </html> soup =...
15,615
Given the following text description, write Python code to implement the functionality described below step by step Description: Conventions Our main data structure is a Box, which represents a bounding box somewhere in the image. Our coordinate system has its origin in the bottom-left of the image (with positive up a...
Python Code: class Box: def __init__(self, y, x, h, w): self.pos = (y, x) self.size = (h, w) @property def pos(self): return self._pos @pos.setter def pos(self, value): assert len(value) == 2 self._pos = np.array(value, dtype=int) @property ...
15,616
Given the following text description, write Python code to implement the functionality described below step by step Description: <center><img src="http Step1: Simple standard analysis Here we can see a simple example of basic spectral analysis for FITS PHA files from the Fermi Gamma-ray Burst Monitor. FITS PHA files ...
Python Code: from threeML import * import matplotlib.pyplot as plt %matplotlib inline %matplotlib notebook Explanation: <center><img src="http://identity.stanford.edu/overview/images/emblems/SU_BlockStree_2color.png" width="200" style="display: inline-block"><img src="http://upload.wikimedia.org/wikipedia/commons/thumb...
15,617
Given the following text description, write Python code to implement the functionality described below step by step Description: <figure> <IMG SRC="gfx/Logo_norsk_pos.png" WIDTH=100 ALIGN="right"> </figure> Linear algebra crash course Roberto Di Remigio, Luca Frediani This is a very brief and incomplete introduction...
Python Code: import numpy as np a = np.array([1, 2, 3]) # Create a rank 1 array print(type(a)) # Prints "<type 'numpy.ndarray'>" print(a.shape) # Prints "(3,)" Explanation: <figure> <IMG SRC="gfx/Logo_norsk_pos.png" WIDTH=100 ALIGN="right"> </figure> Linear algebra crash course Roberto Di Remig...
15,618
Given the following text description, write Python code to implement the functionality described below step by step Description: Exploratory Data Analysis with Pandas Exploratory data analysis (EDA) is an approach to analyzing data sets to summarize their main characteristics, often with visual methods. We will go thr...
Python Code: import urllib3 import pandas as pd url = "https://raw.githubusercontent.com/jpatokal/openflights/master/data/airports.dat" #load the csv airports = pd.read_csv(url,header=None) print("Check DataFrame types") display(airports.dtypes) Explanation: Exploratory Data Analysis with Pandas Exploratory data analys...
15,619
Given the following text description, write Python code to implement the functionality described below step by step Description: Last updated Step1: 1. Loading data More details, see http Step2: From a local text file Let's first load some temperature data which covers all lattitudes. Since read_table is supposed to...
Python Code: %matplotlib inline import pandas as pd import numpy as np import matplotlib.pyplot as plt pd.set_option("display.max_rows", 16) LARGE_FIGSIZE = (12, 8) # Change this cell to the demo location on YOUR machine %cd ~/Projects/pandas_tutorial/climate_timeseries/ %ls Explanation: Last updated: June 29th 2016 Cl...
15,620
Given the following text description, write Python code to implement the functionality described below step by step Description: Градиентный бустинг своими руками Внимание Step1: Задание 1 Как вы уже знаете из лекций, бустинг - это метод построения композиций базовых алгоритмов с помощью последовательного добавления ...
Python Code: from sklearn import cross_validation, datasets, metrics, tree, ensemble, learning_curve import numpy as np import pandas as pd %pylab inline boston = datasets.load_boston() X_train = boston.data[:379] X_test = boston.data[379:] y_train = boston.target[:379] y_test = boston.target[379:] Explanation: Градиен...
15,621
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', 'cas', 'fgoals-f3-h', 'atmos') Explanation: ES-DOC CMIP6 Model Properties - Atmos MIP Era: CMIP6 Institute: CAS Source ID: FGOALS-F3-H Topic: Atmos Sub-Topics: Dynamical Core, Radiatio...
15,622
Given the following text description, write Python code to implement the functionality described below step by step Description: Representational Similarity Analysis Representational Similarity Analysis is used to perform summary statistics on supervised classifications where the number of classes is relatively high. ...
Python Code: # Authors: Jean-Remi King <jeanremi.king@gmail.com> # Jaakko Leppakangas <jaeilepp@student.jyu.fi> # Alexandre Gramfort <alexandre.gramfort@telecom-paristech.fr> # # License: BSD (3-clause) import os.path as op import numpy as np from pandas import read_csv import matplotlib.pyplot as plt...
15,623
Given the following text description, write Python code to implement the functionality described below step by step Description: Schelling Segregation Model Background The Schelling (1971) segregation model is a classic of agent-based modeling, demonstrating how agents following simple rules lead to the emergence of q...
Python Code: import matplotlib.pyplot as plt %matplotlib inline from model import SchellingModel Explanation: Schelling Segregation Model Background The Schelling (1971) segregation model is a classic of agent-based modeling, demonstrating how agents following simple rules lead to the emergence of qualitatively differe...
15,624
Given the following text description, write Python code to implement the functionality described below step by step Description: Ian's Step3: [[ 0.56849023 0.56123475 -0.60152673] [ 0.81728005 -0.30155688 0.49103641] [ 0.09419218 -0.7707652 -0.63011811]] For a framing camera the interior orientation (intrinsic m...
Python Code: print(isd['omega']) print(isd['phi']) print(isd['kappa']) o = isd['omega'] p = isd['phi'] k = isd['kappa'] XL = 1728357.70312 YL = -2088409.0061 ZL = 2082873.92806 print(XL, YL, ZL) opk_to_rotation(o, p, k) Explanation: Ian's: o = 2.25613094079 p = 0.094332016311 k = -0.963037547862 XL = 1728357.70312 YL =...
15,625
Given the following text description, write Python code to implement the functionality described below step by step Description: Auftrieb umströmter Körper In diesem Kapitel werden wir sehen, dass auf einen Körper nur dann eine Auftriebskraft wirkt, wenn die Zirkulation $\Gamma$ - das Linienintegral des Geschwindigkei...
Python Code: import math import numpy as np import matplotlib.pyplot as plt %matplotlib inline nx = 400 # Anzahl der Punkte in x-Richtung ny = 200 # Anzahl der Punkte in y-Richtung x = np.linspace(-10, 10, nx) # 1D-Array mit x-Koordinaten y = np.linspac...
15,626
Given the following text description, write Python code to implement the functionality described below step by step Description: Algorithms Exercise 3 Imports Step2: Character counting and entropy Write a function char_probs that takes a string and computes the probabilities of each character in the string Step4: Th...
Python Code: %matplotlib inline from matplotlib import pyplot as plt import numpy as np from IPython.html.widgets import interact Explanation: Algorithms Exercise 3 Imports End of explanation def char_probs(s): Find the probabilities of the unique characters in the string s. Parameters ---------- s...
15,627
Given the following text description, write Python code to implement the functionality described below step by step Description: Copyright 2020 The TensorFlow Hub Authors. Licensed under the Apache License, Version 2.0 (the "License"); Step1: <table class="tfo-notebook-buttons" align="left"> <td><a target="_blank" ...
Python Code: #@title Copyright 2020 The TensorFlow Hub Authors. All Rights Reserved. # # 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 # # http://www.apache.org/licenses/LICENSE-2.0 # # Unl...
15,628
Given the following text description, write Python code to implement the functionality described below step by step Description: Scaling behavior Step1: Tools For generating scaling scenarios and running it through guv Step2: Workers versus queue length For different processing times (fixed deadline). Should general...
Python Code: %matplotlib inline import subprocess import json import os import pandas import numpy Explanation: Scaling behavior End of explanation def normalize_scenario(flat): # Pop out messages messages = flat['messages'] # Everything else assumed to be config roleconfig = flat.copy() del rolecon...
15,629
Given the following text description, write Python code to implement the functionality described below step by step Description: Welcome to Jupyter Notebook This is a Jupyter Notebook. It works just like python console, but you can freely go back and forth and reexecute pieces (cells) of code. To run code press Shift+...
Python Code: a = 2 a += 2 print(a) Explanation: Welcome to Jupyter Notebook This is a Jupyter Notebook. It works just like python console, but you can freely go back and forth and reexecute pieces (cells) of code. To run code press Shift+Enter End of explanation !ls -al Explanation: I can do to the second cell and run ...
15,630
Given the following text description, write Python code to implement the functionality described below step by step Description: Signal-space separation (SSS) and Maxwell filtering This tutorial covers reducing environmental noise and compensating for head movement with SSS and Maxwell filtering. As usual we'll start ...
Python Code: import os import matplotlib.pyplot as plt import seaborn as sns import pandas as pd import numpy as np import mne from mne.preprocessing import find_bad_channels_maxwell sample_data_folder = mne.datasets.sample.data_path() sample_data_raw_file = os.path.join(sample_data_folder, 'MEG', 'sample', ...
15,631
Given the following text description, write Python code to implement the functionality described below step by step Description: 1. Aggregate all blast results Step1: 2. Write annotated results out
Python Code: blast_file_regex = re.compile(r"(blast[np])_vs_([a-zA-Z0-9_]+).tsv") blast_cols = ["query_id","subject_id","pct_id","ali_len","mism", "gap_open","q_start","q_end","s_start","s_end", "e_value","bitscore","q_len","s_len","s_gi", "s_taxids","s_scinames","s_names","q_co...
15,632
Given the following text description, write Python code to implement the functionality described below step by step Description: Running Tune experiments with ZOOpt In this tutorial we introduce ZOOpt, while running a simple Ray Tune experiment. Tune’s Search Algorithms integrate with ZOOpt and, as a result, allow you...
Python Code: # !pip install ray[tune] !pip install zoopt==0.4.1 Explanation: Running Tune experiments with ZOOpt In this tutorial we introduce ZOOpt, while running a simple Ray Tune experiment. Tune’s Search Algorithms integrate with ZOOpt and, as a result, allow you to seamlessly scale up a ZOOpt optimization process ...
15,633
Given the following text description, write Python code to implement the functionality described below step by step Description: Jennifer 8. Lee et al have been using a Google spreadsheet to track the production of books in Project GITenberg Step1: Getting access to the spreadsheet (Method 1) Step3: Calculations on ...
Python Code: from __future__ import print_function import gspread import json # rtc50_settings.py holds URL related to the Google spreadsheet from rtc50_settings import (g_name, g_url, g_key) OFFICIAL_NAME_KEY = "Name in rtc/books.json, Official Name" Explanation: Jennifer 8. Lee et al have been using a Google spreads...
15,634
Given the following text description, write Python code to implement the functionality described below step by step Description: Week 14 - Astropy Today's Agenda Useful functions of Astropy Units Time Coordinates FITS files Analytic functions AstroPy Tables and different formats Astropy is a package that is meant to p...
Python Code: # Importing Modules %matplotlib inline import matplotlib.pyplot as plt import numpy as np import seaborn as sns sns.set_context("notebook") import astropy from astropy import units as u from astropy.coordinates import SkyCoord from astropy import constants as const Explanation: Week 14 - Astropy Today's Ag...
15,635
Given the following text description, write Python code to implement the functionality described below step by step Description: Copyright 2019 The TensorFlow Authors. Step1: Text classification with TensorFlow Lite Model Maker <table class="tfo-notebook-buttons" align="left"> <td> <a target="_blank" href="http...
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...
15,636
Given the following text problem statement, write Python code to implement the functionality described below in problem statement Problem: Following-up from this question years ago, is there a canonical "shift" function in numpy? Ideally it can be applied to 2-dimensional arrays.
Problem: import numpy as np a = np.array([[ 0., 1., 2., 3., 4., 5., 6., 7., 8., 9.], [1., 2., 3., 4., 5., 6., 7., 8., 9., 10.]]) shift = 3 def solution(xs, n): e = np.empty_like(xs) if n >= 0: e[:,:n] = np.nan e[:,n:] = xs[:,:-n] else: e[:,n:] = np.nan e[:,...
15,637
Given the following text description, write Python code to implement the functionality described below step by step Description: 8.1 RM-GF correlations tests Step1: Correlation between max chapter and answers method 1 Step2: method 2 use max chapter or <= max chapter? Step3: Clustering answers to find underlying co...
Python Code: %run "../Functions/8. RM-GF correlations.ipynb" allData = allDataPlaytestPhase1PretestPosttestUniqueProfilesVolunteers.copy() Explanation: 8.1 RM-GF correlations tests End of explanation #def getScoresOnQuestionsFromAllData(allData, Qs): Explanation: Correlation between max chapter and answers method 1: co...
15,638
Given the following text description, write Python code to implement the functionality described below step by step Description: Methods and Experiments Experimental Setup Basic Definitions Computation Steps Compute Experimental Data Load Trajectory Data Compute POI Info Construct Travelling Sequences Choose Travellin...
Python Code: %matplotlib inline import os import math import random import pickle import pandas as pd import numpy as np import numpy.matlib from datetime import datetime from joblib import Parallel, delayed import matplotlib.pyplot as plt nfeatures = 8 # number of features EPS = 1e-12 # smooth, deal with 0 probability...
15,639
Given the following text description, write Python code to implement the functionality described below step by step Description: An end-to-end Vertex Training Pipeline Demonstration Finally, check that you have correctly installed the packages. The KFP SDK version should be >=1.6 Step1: Then define the pipeline using...
Python Code: !python3 -c "import kfp; print('KFP SDK version: {}'.format(kfp.__version__))" import os import json from functools import partial import kfp import pprint import yaml from jinja2 import Template from kfp.v2 import dsl from kfp.v2.compiler import compiler from kfp.v2.dsl import Dataset from kfp.v2.google.c...
15,640
Given the following text description, write Python code to implement the functionality described below step by step Description: Python and other languages Interacting with other programs through API calls. The whole is greater than its parts Step1: However in the example above there is no real communication between ...
Python Code: import readline import rpy2.robjects as robjects robjects.r(''' source("http://www.bioconductor.org/biocLite.R") biocLite("ALL") library("ALL") data("ALL") #install.packages("gplots") eset <- ALL[, ALL$mol.biol %in% c("BCR/ABL", "ALL1/AF4")] library("limma") f <- factor(as.character(eset$mol.biol)) design ...
15,641
Given the following text description, write Python code to implement the functionality described below step by step Description: Dynamical X-ray Scattering In this example static and transient X-ray simulations are carried out employing the dynamical X-ray scattering formalism. Setup Do all necessary imports and setti...
Python Code: import udkm1Dsim as ud u = ud.u # import the pint unit registry from udkm1Dsim import scipy.constants as constants import numpy as np import matplotlib.pyplot as plt %matplotlib inline u.setup_matplotlib() # use matplotlib with pint units Explanation: Dynamical X-ray Scattering In this example static and...
15,642
Given the following text description, write Python code to implement the functionality described below step by step Description: Dataset split of AotM-2011/30Music playlists for playlist generation When a user in test set is unknown previously (cold user) Step1: Load playlists Load playlists. Step2: check duplicated...
Python Code: %matplotlib inline import os import sys import gzip import numpy as np import pickle as pkl from scipy.sparse import lil_matrix, issparse, hstack, vstack from collections import Counter import gensim import matplotlib.pyplot as plt import seaborn as sns from tqdm import tqdm np_settings0 = np.seterr(all='r...
15,643
Given the following text description, write Python code to implement the functionality described below step by step Description: HW3 visualisation Step1: Load the topojson with the Swiss cantons and the CSV containing the grants by canton Step2: The canton that don't receive any grant don't appear in the CSV. The we...
Python Code: import folium import pandas as pd import numpy as np from map_universities import * Explanation: HW3 visualisation End of explanation swiss_canton = 'ch-cantons.topojson.json' grant_data = pd.read_csv(r'all_canton_grants.csv') Explanation: Load the topojson with the Swiss cantons and the CSV containing the...
15,644
Given the following text description, write Python code to implement the functionality described below step by step Description: Tokenization Default tokenization Tokenization (the first of the five parts of the Gothenburg model) divides the texts to be collated into tokens, which are most commonly (but not obligatori...
Python Code: from collatex import * Explanation: Tokenization Default tokenization Tokenization (the first of the five parts of the Gothenburg model) divides the texts to be collated into tokens, which are most commonly (but not obligatorily) words. By default CollateX considers punctuation to be its own token, which m...
15,645
Given the following text description, write Python code to implement the functionality described below step by step Description: Executed Step1: Load software and filenames definitions Step2: Data folder Step3: List of data files Step4: Data load Initial loading of the data Step5: Load the leakage coefficient fro...
Python Code: ph_sel_name = "None" data_id = "12d" # data_id = "7d" Explanation: Executed: Mon Mar 27 11:38:45 2017 Duration: 7 seconds. usALEX-5samples - Template This notebook is executed through 8-spots paper analysis. For a direct execution, uncomment the cell below. End of explanation from fretbursts import * init_...
15,646
Given the following text description, write Python code to implement the functionality described below step by step Description: Copyright 2020 The TensorFlow Authors. Step1: Tokenizing with TF Text <table class="tfo-notebook-buttons" align="left"> <td> <a target="_blank" href="https Step2: Splitter API The ma...
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...
15,647
Given the following text description, write Python code to implement the functionality described below step by step Description: SimpleITK Images, They're Physical Objects <a href="https Step1: Load your first image and display it Step2: Image Construction There are a variety of ways to create an image. The followi...
Python Code: import SimpleITK as sitk # If the environment variable SIMPLE_ITK_MEMORY_CONSTRAINED_ENVIRONMENT is set, this will override the ReadImage # function so that it also resamples the image to a smaller size (testing environment is memory constrained). %run setup_for_testing %matplotlib inline import matplotlib...
15,648
Given the following text description, write Python code to implement the functionality described below step by step Description: Project Euler Step1: Find the square of the sum of the first 100 natural numbers Step2: Find and print the difference Step3: Success!
Python Code: sum_of_squares = sum([i ** 2 for i in range(1,101)]) Explanation: Project Euler: Problem 6 https://projecteuler.net/problem=6 The sum of the squares of the first ten natural numbers is, $$1^2 + 2^2 + ... + 10^2 = 385$$ The square of the sum of the first ten natural numbers is, $$(1 + 2 + ... + 10)^2 = 55^2...
15,649
Given the following text description, write Python code to implement the functionality described below step by step Description: ES-DOC CMIP6 Model Properties - Ocean MIP Era Step1: Document Authors Set document authors Step2: Document Contributors Specify document contributors Step3: Document Publication Specify d...
Python Code: # DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'ec-earth-consortium', 'ec-earth3-veg-lr', 'ocean') Explanation: ES-DOC CMIP6 Model Properties - Ocean MIP Era: CMIP6 Institute: EC-EARTH-CONSORTIUM Source ID: EC-EARTH3-VEG-LR Topic: ...
15,650
Given the following text description, write Python code to implement the functionality described below step by step Description: Karen Yu, Nick Vasios, Thibaut Perol AM207 Final Project Energy Disaggregation from Non-Intrusive Load Monitoring DISAGGREGATION USING COMBINATORIAL OPTIMIZATION Importing Necessary Packages...
Python Code: from __future__ import print_function, division import numpy as np import pandas as pd from os.path import join import pickle import copy from pylab import rcParams import matplotlib.pyplot as plt %matplotlib inline rcParams['figure.figsize'] = (13, 6) import nilmtk from nilmtk import DataSet, TimeFrame, M...
15,651
Given the following text description, write Python code to implement the functionality described below step by step Description: <h1 align="center">Scientific Programming in Python</h1> <h2 align="center">Topic 5 Step4: La distancia de Hausdorff nuevamente... En esta actividad volveremos a implementar la distancia/mé...
Python Code: import numba import numpy as np from math import sqrt %load_ext Cython Explanation: <h1 align="center">Scientific Programming in Python</h1> <h2 align="center">Topic 5: Accelerating Python with Cython: Writting C in Python </h2> Notebook created by Martín Villanueva - martin.villanueva@usm.cl - DI UTFSM - ...
15,652
Given the following text description, write Python code to implement the functionality described below step by step Description: <a href='http Step1: Declaring elements in a function If we write a function that accepts one or more parameters and constructs an element, we can build plots that do things like Step2: Th...
Python Code: import numpy as np import holoviews as hv hv.extension('bokeh') %opts Curve Area [width=600] Explanation: <a href='http://www.holoviews.org'><img src="assets/hv+bk.png" alt="HV+BK logos" width="40%;" align="left"/></a> <div style="float:right;"><h2>03. Exploration with Containers</h2></div> In the first tw...
15,653
Given the following text description, write Python code to implement the functionality described below step by step Description: I will be writing about the Extreme value theory (EVT) which was introduced to me by my brother Sudhanshu, while he was working on his internship project. I really liked the connection it ha...
Python Code: def draw_samples(dist, n, k=1): return dist.rvs(size=(n,k)) def plot_samples(dists, aggregations, n=1000, k_max=10000): rows, cols = len(aggregations), len(dists) fig, ax = plt.subplots(rows, cols, figsize=(5*cols, 3*rows)) fig_cum, ax_cum = plt.subplots(rows, cols, figsize=(5*cols, 3*rows)...
15,654
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', 'miroc', 'nicam16-9d-l78', 'land') Explanation: ES-DOC CMIP6 Model Properties - Land MIP Era: CMIP6 Institute: MIROC Source ID: NICAM16-9D-L78 Topic: Land Sub-Topics: Soil, Snow, Veget...
15,655
Given the following text description, write Python code to implement the functionality described below step by step Description: Goal Simulating fullCyc Day1 control gradients Not simulating incorporation (all 0% isotope incorp.) Don't know how much true incorporatation for emperical data Using parameters inferred fro...
Python Code: import os import glob import re import nestly %load_ext rpy2.ipython %load_ext pushnote %%R library(ggplot2) library(dplyr) library(tidyr) library(gridExtra) library(phyloseq) Explanation: Goal Simulating fullCyc Day1 control gradients Not simulating incorporation (all 0% isotope incorp.) Don't know how mu...
15,656
Given the following text description, write Python code to implement the functionality described below step by step Description: GPyOpt Step1: Next, we load the data. Step2: Now, we process the dataset. We selected only the data corresponding to the day April 22, 2014 and we remove the stations in Alaska and the US ...
Python Code: %matplotlib inline import matplotlib as mpl import matplotlib.pyplot as plt import numpy as np import GPyOpt Explanation: GPyOpt: armed bandits optimization Written by Javier Gonzalez, Amazon Reseach Cambridge, UK. Last updated Monday, 22 May 2016. In this notebook we will see how to do armed bandits opti...
15,657
Given the following text description, write Python code to implement the functionality described below step by step Description: Pandas Dataframes This notebook demonstrates how systematic analysis of tally scores is possible using Pandas dataframes. A dataframe can be automatically generated using the Tally.get_panda...
Python Code: import glob from IPython.display import Image import matplotlib.pyplot as plt import scipy.stats import numpy as np import pandas as pd import openmc %matplotlib inline Explanation: Pandas Dataframes This notebook demonstrates how systematic analysis of tally scores is possible using Pandas dataframes. A d...
15,658
Given the following text description, write Python code to implement the functionality described below step by step Description: MNIST from scratch This notebook walks through an example of training a TensorFlow model to do digit classification using the MNIST data set. MNIST is a labeled set of images of handwritten ...
Python Code: from __future__ import print_function from IPython.display import Image import base64 Image(data=base64.decodestring("iVBORw0KGgoAAAANSUhEUgAAAMYAAABFCAYAAAARv5krAAAYl0lEQVR4Ae3dV4wc1bYG4D3YYJucc8455yCSSIYrBAi4EjriAZHECyAk3rAID1gCIXGRgIvASIQr8UTmgDA5imByPpicTcYGY+yrbx+tOUWpu2e6u7qnZ7qXVFPVVbv2Xutfce+q7hlas...
15,659
Given the following text description, write Python code to implement the functionality described below step by step Description: Mie Scattering Efficiencies Scott Prahl Jan 2022 If miepython is not installed, uncomment the following cell (i.e., delete the #) and run (shift-enter) Step1: When a monochromatic plane wav...
Python Code: #!pip install --user miepython import importlib.resources import numpy as np import matplotlib.pyplot as plt try: import miepython except ModuleNotFoundError: print('miepython not installed. To install, uncomment and run the cell above.') print('Once installation is successful, rerun this cell ...
15,660
Given the following text description, write Python code to implement the functionality described below step by step Description: Introduction The Bureau of Economic Analysis (BEA) publishes economic statistics in a variety of formats. This document describes the BEA Data Retrieval Application Programming Interface (AP...
Python Code: import pybea Explanation: Introduction The Bureau of Economic Analysis (BEA) publishes economic statistics in a variety of formats. This document describes the BEA Data Retrieval Application Programming Interface (API) – including detailed instructions for retrieving data and meta-data published by BEA usi...
15,661
Given the following text description, write Python code to implement the functionality described below step by step Description: Although the notebook in Part 1 might have seemed simplistic, it is useful for determining the effectiveness and interpretability of multiple regression compared to more advanced methods. In...
Python Code: import pandas as pd import numpy as np import seaborn as sns from scipy import stats import matplotlib.pyplot as plt from sklearn import linear_model from sklearn.decomposition import PCA from sklearn.metrics import r2_score, mean_absolute_error from sklearn.model_selection import train_test_split %matplot...
15,662
Given the following text description, write Python code to implement the functionality described below step by step Description: TryAlgo Maps in Paris Here is a demo of the tryalgo package over Paris' graph. We are going to display a shortest path from Gare de Lyon to Place d'Italie. Let's first store the graph in an ...
Python Code: with open('paris.txt') as f: lines = f.read().splitlines() N, M, T, C, S = map(int, lines[0].split()) paris_coords = [] for i in range(1, N + 1): paris_coords.append(list(map(float, lines[i].split()))) # Read coords paris = {node: {} for node in range(N)} for i in range(N +...
15,663
Given the following text description, write Python code to implement the functionality described below step by step Description: Comparison between the magnetic field produced by a triaxial ellipsoid and a sphere Import the required modules and functions Step1: Set some parameters for modelling Step2: Triaxial ellip...
Python Code: %matplotlib inline import numpy as np from matplotlib import pyplot as plt from matplotlib.colors import BoundaryNorm from matplotlib.ticker import MaxNLocator from fatiando import gridder, utils from fatiando.gravmag import sphere from fatiando.mesher import Sphere import triaxial_ellipsoid from mesher im...
15,664
Given the following text description, write Python code to implement the functionality described below step by step Description: Równanie dyfuzji - dekompozycja siatki z zastosowaniem MPI Problem Step1: non-contigous slice Step2: N - slices
Python Code: %matplotlib inline import matplotlib.pyplot as plt import numpy as np import os print os.getenv("HOME") wd = os.path.join( os.getenv("HOME"),"mpi_tmpdir") if not os.path.isdir(wd): os.mkdir(wd) os.chdir(wd) print "WD is now:",os.getcwd() %%writefile mpi002.py from mpi4py import MPI import numpy as np ...
15,665
Given the following text description, write Python code to implement the functionality described below step by step Description: This is a notebook developed by Dustin Lang and Phil Marshall in Spring 2015, and distributed by them under the GPLv2 licence. We can pull bits out of this and make good use of them in some ...
Python Code: from straightline_utils import * %matplotlib inline from matplotlib import rcParams rcParams['savefig.dpi'] = 100 Explanation: This is a notebook developed by Dustin Lang and Phil Marshall in Spring 2015, and distributed by them under the GPLv2 licence. We can pull bits out of this and make good use of the...
15,666
Given the following text description, write Python code to implement the functionality described below step by step Description: Load airports of each country Step1: record schedules for 2 weeks, then augment count with weekly flight numbers. seasonal and seasonal charter will count as once per week for 3 months, so ...
Python Code: L=json.loads(file('../json/L.json','r').read()) M=json.loads(file('../json/M.json','r').read()) N=json.loads(file('../json/N.json','r').read()) import requests AP={} for c in M: if c not in AP:AP[c]={} for i in range(len(L[c])): AP[c][N[c][i]]=L[c][i] sch={} Explanation: Load airports of ea...
15,667
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: Forwards & backwards flows This recipe demonstrates how forwards and backwards flows work. For demonstration, the CSV data is written directly in the cell below -- in practice you wou...
Python Code: import pandas as pd from io import StringIO flows = pd.read_csv(StringIO( source,target,type,value a,b,main,2 a,c,main,1 c,d,main,3 b,c,back,2 )) flows Explanation: Forwards & backwards flows This recipe demonstrates how forwards and backwards flows work. For demonstration, the CSV data is written directly...
15,668
Given the following text description, write Python code to implement the functionality described below step by step Description: KBMOD Demo The purpose of this demo is to showcase how KBMOD can be used to search through images for moving objects. The images used here are from the Subaru telescope and were processed us...
Python Code: import numpy as np import matplotlib.pyplot as plt from searchImage import searchImage from analyzeImage import analyzeImage %matplotlib inline %load_ext autoreload %autoreload 2 Explanation: KBMOD Demo The purpose of this demo is to showcase how KBMOD can be used to search through images for moving object...
15,669
Given the following text description, write Python code to implement the functionality described. Description: Given a string representing a space separated lowercase letters, return a dictionary of the letter with the most repetition and containing the corresponding count. If several letters have the same occu...
Python Code: def histogram(test): dict1={} list1=test.split(" ") t=0 for i in list1: if(list1.count(i)>t) and i!='': t=list1.count(i) if t>0: for i in list1: if(list1.count(i)==t): dict1[i]=t return dict1
15,670
Given the following text description, write Python code to implement the functionality described below step by step Description: A Convolutional Neural Network for MNIST Classification. This solution got me a score of 0.98 on the leaderboard. Note Step1: Simulation Constants Download notebook and use commented out va...
Python Code: %matplotlib inline import numpy as np import pandas as pd import tensorflow as tf import matplotlib.pyplot as plt from sklearn.model_selection import ShuffleSplit from sklearn.preprocessing import StandardScaler, LabelEncoder, OneHotEncoder Explanation: A Convolutional Neural Network for MNIST Classificati...
15,671
Given the following text description, write Python code to implement the functionality described below step by step Description: Text Classification of Movie Reviews Unpack data - this only works on linux and (maybe?) OS X. Unpack using 7zip on Windows. Step1: N-Grams
Python Code: #! tar -xf data/aclImdb.tar.bz2 --directory data from sklearn.datasets import load_files reviews_train = load_files("data/aclImdb/train/") text_train, y_train = reviews_train.data, reviews_train.target print("Number of documents in training data: %d" % len(text_train)) print(np.bincount(y_train)) reviews_t...
15,672
Given the following text description, write Python code to implement the functionality described below step by step Description: Reading and writing data -- Tour of Beam So far we've learned some of the basic transforms like Map, FlatMap, Filter, Combine, and GroupByKey. These allow us to transform data in any way, bu...
Python Code: # Install apache-beam with pip. !pip install --quiet apache-beam # Create a directory for our data files. !mkdir -p data %%writefile data/my-text-file-1.txt This is just a plain text file, UTF-8 strings are allowed 🎉. Each line in the file is one element in the PCollection. %%writefile data/my-text-file-2...
15,673
Given the following text description, write Python code to implement the functionality described below step by step Description: <div align="right">Python 3.6 Jupyter Notebook</div> Graph signal processing <br> <div class="alert alert-warning"> <b>Note</b> Step1: First, simple filtering on a noisy graph signal will b...
Python Code: %%html %matplotlib inline import matplotlib #import pygsp #Uncomment if you have pygsp installed. import numpy as np import matplotlib.pylab as plt import networkx as nx import pandas as pd plt.rcParams['figure.figsize'] = (6, 6) Explanation: <div align="right">Python 3.6 Jupyter Notebook</div> Graph signa...
15,674
Given the following text description, write Python code to implement the functionality described below step by step Description: WavefunctionPlot The WavefunctionPlot class will help you very easily generate and display wavefunctions from a Hamiltonian or any other source. If you already have your wavefunction in a gr...
Python Code: import sisl import sisl.viz Explanation: WavefunctionPlot The WavefunctionPlot class will help you very easily generate and display wavefunctions from a Hamiltonian or any other source. If you already have your wavefunction in a grid, you can use GridPlot. <div class="alert alert-info"> Note `Wavefunctio...
15,675
Given the following text description, write Python code to implement the functionality described below step by step Description: Xarray with Dask Arrays <img src="images/dataset-diagram-logo.png" align="right" width="66%" alt="Xarray Dataset"> Xarray is an open source project and Python package that ex...
Python Code: %matplotlib inline from dask.distributed import Client import xarray as xr Explanation: Xarray with Dask Arrays <img src="images/dataset-diagram-logo.png" align="right" width="66%" alt="Xarray Dataset"> Xarray is an open source project and Python package that extends the labeled data functi...
15,676
Given the following text description, write Python code to implement the functionality described below step by step Description: Sample for KFServing SDK v1beta1 This is a sample for KFServing SDK v1beta1. The notebook shows how to use KFServing SDK to create, get and delete InferenceService. Step1: Define namespace...
Python Code: from kubernetes import client from kfserving import KFServingClient from kfserving import constants from kfserving import utils from kfserving import V1beta1InferenceService from kfserving import V1beta1InferenceServiceSpec from kfserving import V1beta1PredictorSpec from kfserving import V1beta1TFServingS...
15,677
Given the following text description, write Python code to implement the functionality described below step by step Description: Нейронные сети Step1: Выполним загрузку данных Step2: В качестве альтернативного варианта, можно выполнить загрузку данных напрямую из репозитория UCI, воспользовавшись библиотекой urllib....
Python Code: # Выполним инициализацию основных используемых модулей %matplotlib inline import random import matplotlib.pyplot as plt from sklearn.preprocessing import normalize import numpy as np Explanation: Нейронные сети: зависимость ошибки и обучающей способности от числа нейронов В этом задании вы будете настраива...
15,678
Given the following text description, write Python code to implement the functionality described below step by step Description: Lab 6 Step1: Rapidgram The date Step4: Question 1 Step7: Question 2 Step10: Question 3 Step13: Question 4 Step15: Question 5 Step18: Do you think this query will work as intended? Why...
Python Code: !pip install ipython-sql %load_ext sql %sql sqlite:///./lab06.sqlite import sqlalchemy engine = sqlalchemy.create_engine("sqlite:///lab05.sqlite") connection = engine.connect() !pip install -U okpy from client.api.notebook import Notebook ok = Notebook('lab06.ok') Explanation: Lab 6: SQL End of explan...
15,679
Given the following text description, write Python code to implement the functionality described below step by step Description: Index - Back - Next Step1: Building a Custom Widget - Email widget The widget framework is built on top of the Comm framework (short for communication). The Comm framework is a framework t...
Python Code: from __future__ import print_function Explanation: Index - Back - Next End of explanation from traitlets import Unicode, Bool, validate, TraitError from ipywidgets import DOMWidget, register @register class Email(DOMWidget): _view_name = Unicode('EmailView').tag(sync=True) _view_module = Unicode('e...
15,680
Given the following text description, write Python code to implement the functionality described below step by step Description: Copyright 2017 Google LLC. Step1: # Concepts de programmation de TensorFlow Objectifs de formation  Step2: N'oubliez pas d'exécuter le bloc de code qui précède (les déclarations import). A...
Python Code: # 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 # distribute...
15,681
Given the following text description, write Python code to implement the functionality described below step by step Description: US Treasury Yield Curve Animation The notebook uses daily US Treasury yield data from FRED (https Step1: Download Data and Merge into DataFrame Step2: Construct Figure Step3: Create Anima...
Python Code: import matplotlib matplotlib.use("Agg") import fredpy as fp import pandas as pd import matplotlib.pyplot as plt plt.style.use('classic') import matplotlib.animation as animation import os import time # Approximately when the program started start_time = time.time() # start and end dates start_date = '1965-...
15,682
Given the following text description, write Python code to implement the functionality described below step by step Description: Week 05 - Numpy II and Scipy Today's Agenda Numpy II Scipy Numpy II Last time in Week 05, we covered Numpy and Matplotlib. This time we will be focusing on more advanced concepts of Numpy. S...
Python Code: # Loading modules %matplotlib inline import numpy as np import matplotlib.pyplot as plt Explanation: Week 05 - Numpy II and Scipy Today's Agenda Numpy II Scipy Numpy II Last time in Week 05, we covered Numpy and Matplotlib. This time we will be focusing on more advanced concepts of Numpy. End of explanatio...
15,683
Given the following text description, write Python code to implement the functionality described below step by step Description: Learning About the Singular Value Decomposition This notebook explores the Singular Value Decomposition (SVD) Step1: Start With A Simple Matrix Step2: Now Take the SVD Step3: Check U, S a...
Python Code: # import numpy for SVD function import numpy # import matplotlib.pyplot for visualising arrays import matplotlib.pyplot as plt Explanation: Learning About the Singular Value Decomposition This notebook explores the Singular Value Decomposition (SVD) End of explanation # create a really simple matrix A = nu...
15,684
Given the following text description, write Python code to implement the functionality described below step by step Description: Análisis de redes en Python (Networkx) Bienvenidos Step3: Ahora le vamos a agregar nodos Step7: Borremos los nodos Step10: Vamos a darle nombre! Se pueden asignar atributos a la gráfica...
Python Code: %matplotlib inline import networkx as nx import matplotlib.pyplot as gr import scipy as sc G=nx.Graph() G.graph Explanation: Análisis de redes en Python (Networkx) Bienvenidos :D En esta sesión aprenderemos a utilizar la librería "Networkx" (http://networkx.readthedocs.io/en/networkx-1.11/index.html) que ...
15,685
Given the following text description, write Python code to implement the functionality described below step by step Description: In this notebook I do first some data cleaning, then I perform some basic analysis of the dataset (no. cases per year, correlation population/no. of cases etc...). <p> I analyze finally the ...
Python Code: import pandas as pd import numpy as np from sklearn import linear_model import seaborn as sns import matplotlib.pyplot as plt sns.set(style="white", color_codes=True) %matplotlib inline Explanation: In this notebook I do first some data cleaning, then I perform some basic analysis of the dataset (no. cases...
15,686
Given the following text description, write Python code to implement the functionality described below step by step Description: Modeling and Simulation in Python Copyright 2017 Allen Downey License Step1: Low pass filter Step2: Now I'll create a Params object to contain the quantities we need. Using a Params objec...
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 functions from the modsim.py module from modsim import * Explanation: Modeling and Si...
15,687
Given the following text description, write Python code to implement the functionality described below step by step Description: <span style="color Step1: Short Tutorial Step2: The tree table In the treeslider tool you have the option to collapse individuals from the same species or population into a single taxon us...
Python Code: # conda install ipyrad -c bioconda # conda install toyplot -c eaton-lab import ipyrad.analysis as ipa import toyplot from ipyrad.analysis.clade_weights import * Explanation: <span style="color:gray">ipyrad-analysis toolkit:</span> clade_weights <h5><span style="color:red">(Reference only method)</span></h5...
15,688
Given the following text description, write Python code to implement the functionality described below step by step Description: Imagine that you are at a casino, and you find an unbalanced roulette wheel that looks like the following Step1: After spending a significant amount of time spinning the wheel, you feel a l...
Python Code: import random from numba import jit # Monte Carlo simulation function. This is defined as # a function so the numba library can be used to speed # up execution. Otherwise, this would run much slower. # p1 is the probability of the first area, and s1 is the # score of the first area, and so on. The probabil...
15,689
Given the following text description, write Python code to implement the functionality described below step by step Description: Copyright 2018 The TensorFlow Authors. Step2: Training checkpoints <table class="tfo-notebook-buttons" align="left"> <td> <a target="_blank" href="https Step3: Saving from tf.keras t...
Python Code: #@title Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # dist...
15,690
Given the following text description, write Python code to implement the functionality described below step by step Description: Planning Observations Planning of observations is currently a weakness in python. We have the following packages to perform this task Step1: In order to know the altitude and azimuth of a f...
Python Code: %matplotlib inline import numpy as np import math import matplotlib.pyplot as plt import seaborn from astropy.io import fits from astropy import units as u from astropy.coordinates import SkyCoord plt.rcParams['figure.figsize'] = (12, 8) plt.rcParams['font.size'] = 14 plt.rcParams['lines.linewidth'] = 2 pl...
15,691
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', 'mohc', 'ukesm1-0-ll', 'toplevel') Explanation: ES-DOC CMIP6 Model Properties - Toplevel MIP Era: CMIP6 Institute: MOHC Source ID: UKESM1-0-LL Sub-Topics: Radiative Forcings. Properti...
15,692
Given the following text description, write Python code to implement the functionality described below step by step Description: Find MEG reference channel artifacts Use ICA decompositions of MEG reference channels to remove intermittent noise. Many MEG systems have an array of reference channels which are used to det...
Python Code: # Authors: Jeff Hanna <jeff.hanna@gmail.com> # # License: BSD (3-clause) import mne from mne import io from mne.datasets import refmeg_noise from mne.preprocessing import ICA import numpy as np print(__doc__) data_path = refmeg_noise.data_path() Explanation: Find MEG reference channel artifacts Use ICA dec...
15,693
Given the following text description, write Python code to implement the functionality described below step by step Description: verify pyEMU results with the henry problem Step1: instaniate pyemu object and drop prior info. Then reorder the jacobian and save as binary. This is needed because the pest utilities req...
Python Code: %matplotlib inline import os import numpy as np import matplotlib.pyplot as plt import pandas as pd import pyemu Explanation: verify pyEMU results with the henry problem End of explanation la = pyemu.Schur("freyberg.jcb",verbose=False,forecasts=[]) la.drop_prior_information() jco_ord = la.jco.get(la.pst.ob...
15,694
Given the following text description, write Python code to implement the functionality described below step by step Description: Recreate multilabel example from scikit-learn.org This example simulates a multi-label document classification problem. The dataset is generated randomly based on the following process Step1...
Python Code: %matplotlib inline import numpy as np import matplotlib.pyplot as plt from sklearn.datasets import make_multilabel_classification from sklearn.multiclass import OneVsRestClassifier from sklearn.svm import SVC from sklearn.preprocessing import LabelBinarizer from sklearn.decomposition import PCA from sklear...
15,695
Given the following text description, write Python code to implement the functionality described below step by step Description: Introduction In this notebook, we will walk through a hacker's approach to statistical thinking, as applied to network analysis. Statistics in a Nutshell All of statistics can be broken down...
Python Code: # Read in the data. # Note from above that we have to skip the first two rows, and that there's no header column,and that the edges are # delimited by spaces in between the nodes. Hence the syntax below: G = cf.load_propro_network() Explanation: Introduction In this notebook, we will walk through a hacker'...
15,696
Given the following text description, write Python code to implement the functionality described below step by step Description: CDR EDA First, import relevant libraries Step1: Then, load the data (takes a few moments) Step2: The code below creates a calls-per-person frequency distribution, which is the first thing ...
Python Code: import warnings warnings.filterwarnings('ignore') import numpy as np import pandas as pd %matplotlib inline import matplotlib.pyplot as plt Explanation: CDR EDA First, import relevant libraries: End of explanation # Load data df = pd.read_csv("./aws-data/firence_foreigners_3days_past_future.csv", header=No...
15,697
Given the following text description, write Python code to implement the functionality described below step by step Description: Simplifica tu vida con sistemas complejos y algoritmos genéticos Parte 3 - El dilema Exploración - Explotación Step1: Supongamos que esta curva representa a una función cuyo máximo buscamos...
Python Code: %matplotlib inline import numpy as np # Usaremos arrays import matplotlib.pyplot as plt # Para pintar resultados Explanation: Simplifica tu vida con sistemas complejos y algoritmos genéticos Parte 3 - El dilema Exploración - Explotación: feedback positivo y negativo Cuando usamos algoritmos genéticos y s...
15,698
Given the following text description, write Python code to implement the functionality described below step by step Description: Adapters example Demonstration using the networkx adapter. This example requires installing the networkx library before continuing Step1: Construct data and a simple Mapper Step2: Convert...
Python Code: import kmapper from sklearn import datasets import networkx as nx Explanation: Adapters example Demonstration using the networkx adapter. This example requires installing the networkx library before continuing: pip install networkx End of explanation data = datasets.make_circles(n_samples=1000)[0] km = km...
15,699
Given the following text description, write Python code to implement the functionality described below step by step Description: Testing string match functions Note Step1: Cosine Similarity Step2: String comparison using cosine similarity https Step3: Cosine works fine with whole words and word transposition but wi...
Python Code: # Note - these lines added to make it work with shared Jupyter Hub instance, # modifying the system path so that locally installed modules installed with the shell commands below will be found - # they would need to be modified for your instance, or to install the modules normally remove the --user param...