Unnamed: 0
int64
0
16k
text_prompt
stringlengths
110
62.1k
code_prompt
stringlengths
37
152k
8,100
Given the following text description, write Python code to implement the functionality described below step by step Description: Built-in plotting methods for Raw objects This tutorial shows how to plot continuous data as a time series, how to plot the spectral density of continuous data, and how to plot the sensor lo...
Python Code: import os import mne sample_data_folder = mne.datasets.sample.data_path() sample_data_raw_file = os.path.join(sample_data_folder, 'MEG', 'sample', 'sample_audvis_raw.fif') raw = mne.io.read_raw_fif(sample_data_raw_file) raw.crop(tmax=60).load_data() Explanation: Built-in...
8,101
Given the following text description, write Python code to implement the functionality described below step by step Description: Lab 3 - Basic Artificial Neural Network In this lab we will build a very rudimentary Artificial Neural Network (ANN) and use it to solve some basic classification problems. This example is i...
Python Code: %matplotlib inline import random import numpy as np import matplotlib.pyplot as plt import seaborn as sns; sns.set(style="ticks", color_codes=True) from sklearn.preprocessing import OneHotEncoder from sklearn.utils import shuffle Explanation: Lab 3 - Basic Artificial Neural Network In this lab we will buil...
8,102
Given the following text description, write Python code to implement the functionality described below step by step Description: Section 1 - About Functional Programming What is Functional Programming Functional programming is a programming paradigm that revolves around pure functions. A pure function is a function w...
Python Code: # not so functional function a = 0 def global_sum(x): global a x += a return x print(global_sum(1)) print(a) a = 11 print(global_sum(1)) print(a) # not so functional function a = 0 def global_sum(x): global a return x + a print(global_sum(x=1)) print(a) a = 11 print(global_sum(x=1)) pri...
8,103
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: Check that the folder exists Step4: List of data files in data_dir Step5: Data load Initial loading of ...
Python Code: ph_sel_name = "all-ph" data_id = "27d" # ph_sel_name = "all-ph" # data_id = "7d" Explanation: Executed: Mon Mar 27 11:37:43 2017 Duration: 8 seconds. usALEX-5samples - Template This notebook is executed through 8-spots paper analysis. For a direct execution, uncomment the cell below. End of explanation fro...
8,104
Given the following text description, write Python code to implement the functionality described below step by step Description: Parameters Step2: Imports Step3: tf.data.Dataset Step4: Let's have a look at the data Step5: Keras model If you are not sure what cross-entropy, dropout, softmax or batch-normalization m...
Python Code: BATCH_SIZE = 64 EPOCHS = 10 training_images_file = 'gs://mnist-public/train-images-idx3-ubyte' training_labels_file = 'gs://mnist-public/train-labels-idx1-ubyte' validation_images_file = 'gs://mnist-public/t10k-images-idx3-ubyte' validation_labels_file = 'gs://mnist-public/t10k-labels-idx1-ubyte' Expla...
8,105
Given the following text description, write Python code to implement the functionality described below step by step Description: Test Script Used by tests. License Copyright 2020 Google LLC, Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License....
Python Code: !pip install git+https://github.com/google/starthinker Explanation: Test Script Used by tests. License Copyright 2020 Google LLC, Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at https://...
8,106
Given the following text description, write Python code to implement the functionality described below step by step Description: Clustering Methods Covered Here K Means, Hclus, DBSCAN, Gaussian Mixture Models, Birch, miniBatch Kmeans Mean Shift Silhouette Coefficient If the ground truth labels are not known, evalua...
Python Code: import warnings warnings.filterwarnings("ignore") from collections import Counter import numpy as np from scipy import stats import pandas as pd import matplotlib.pyplot as plt from sklearn.cluster import KMeans from sklearn import metrics from sklearn.metrics import pairwise_distances from sklearn.cluster...
8,107
Given the following text description, write Python code to implement the functionality described below step by step Description: Copyright 2018 The TensorFlow Probability Authors. Licensed under the Apache License, Version 2.0 (the "License"); Step1: TensorFlow Probability Case Study Step2: Step 1 Step3: Generate s...
Python Code: #@title Licensed under the Apache License, Version 2.0 (the "License"); { display-mode: "form" } # 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...
8,108
Given the following text description, write Python code to implement the functionality described below step by step Description: Ke Contrast The constrast is based on the calculation of the aggregated RGB histogram of the image. Step1: Then the width of 98% mass is calculated Step2: Ke brightness The mean brightness...
Python Code: channels = cv2.split(image) colors = ('r', 'g', 'b') histogram = [0.0] for (channel, color) in zip(channels, colors): histogram += cv2.calcHist([channel], [0], None, [256], [0, 256]) normalized_histogram = normalize(histogram, norm='l1', axis=0, copy=True, return_norm=False) Explanation: Ke Contrast Th...
8,109
Given the following text description, write Python code to implement the functionality described below step by step Description: 'lp' (Line Profile) Datasets and Options Setup Let's first make sure we have the latest version of PHOEBE 2.3 installed (uncomment this line if running in an online notebook session such as ...
Python Code: #!pip install -I "phoebe>=2.3,<2.4" Explanation: 'lp' (Line Profile) Datasets and Options Setup Let's first make sure we have the latest version of PHOEBE 2.3 installed (uncomment this line if running in an online notebook session such as colab). End of explanation import phoebe logger = phoebe.logger() b ...
8,110
Given the following text description, write Python code to implement the functionality described below step by step Description: SYDE 556/750 Step1: So everything works fine if we drive each population with the same $x$, let's switch to $\hat{x}$ in the middle Step2: Looks pretty much the same! (just delayed, maybe)...
Python Code: %pylab inline import numpy as np import nengo from nengo.dists import Uniform from nengo.processes import WhiteSignal from nengo.solvers import LstsqL2 T = 1.0 max_freq = 10 model = nengo.Network('Communication Channel', seed=3) with model: stim = nengo.Node(output=WhiteSignal(T, high=max_freq, rms=0.5...
8,111
Given the following text description, write Python code to implement the functionality described below step by step Description: Facies classification using machine learning techniques Copy of <a href="https Step1: Load data Let us load training data and store features, labels and other data into numpy arrays. Step2:...
Python Code: # Import from __future__ import division %matplotlib inline import matplotlib as mpl import matplotlib.pyplot as plt mpl.rcParams['figure.figsize'] = (20.0, 10.0) inline_rc = dict(mpl.rcParams) from classification_utilities import make_facies_log_plot import pandas as pd import numpy as np #import seaborn ...
8,112
Given the following text description, write Python code to implement the functionality described below step by step Description: Train a Simple TensorFlow Lite for Microcontrollers model This notebook demonstrates the process of training a 2.5 kB model using TensorFlow and converting it for use with TensorFlow Lite fo...
Python Code: # Define paths to model files import os MODELS_DIR = 'models/' if not os.path.exists(MODELS_DIR): os.mkdir(MODELS_DIR) MODEL_TF = MODELS_DIR + 'model' MODEL_NO_QUANT_TFLITE = MODELS_DIR + 'model_no_quant.tflite' MODEL_TFLITE = MODELS_DIR + 'model.tflite' MODEL_TFLITE_MICRO = MODELS_DIR + 'model.cc' Exp...
8,113
Given the following text description, write Python code to implement the functionality described below step by step Description: Lecture 9 Step1: Anytime you see a statement that starts with import, you'll recognize that the programmer is pulling in some sort of external functionality not previously available to Pyth...
Python Code: import numpy Explanation: Lecture 9: Vectorized Programming CSCI 1360E: Foundations for Informatics and Analytics Overview and Objectives We've covered loops and lists, and how to use them to perform some basic arithmetic calculations. In this lecture, we'll see how we can use an external library to make t...
8,114
Given the following text description, write Python code to implement the functionality described below step by step Description: Integrating arbitrary ODEs Although REBOUND is primarily an N-body integrator, it can also integrate arbitrary ordinary differential equations (ODEs). Even better Step1: We first set up our...
Python Code: import rebound import numpy as np import matplotlib.pyplot as plt Explanation: Integrating arbitrary ODEs Although REBOUND is primarily an N-body integrator, it can also integrate arbitrary ordinary differential equations (ODEs). Even better: it can integrate arbitrary ODEs in parallel with an N-body simul...
8,115
Given the following text description, write Python code to implement the functionality described below step by step Description: Object Detection Demo Welcome to the object detection inference walkthrough! This notebook will walk you step by step through the process of using a pre-trained model to detect objects in a...
Python Code: import numpy as np import os import six.moves.urllib as urllib import sys import tarfile import tensorflow as tf import zipfile from collections import defaultdict from io import StringIO from matplotlib import pyplot as plt from PIL import Image # This is needed since the notebook is stored in the object_...
8,116
Given the following text description, write Python code to implement the functionality described below step by step Description: <h1 align="center">Letter Recognition - UCI</h1> Step1: Getting the Data This is a dataset of 20 image features for uppercase English characters. https Step3: Next we attach the column nam...
Python Code: import pandas as pd import numpy as np %pylab inline pylab.style.use('ggplot') Explanation: <h1 align="center">Letter Recognition - UCI</h1> End of explanation url = 'https://archive.ics.uci.edu/ml/machine-learning-databases/letter-recognition/letter-recognition.data' letter_df = pd.read_csv(url, header=No...
8,117
Given the following text description, write Python code to implement the functionality described below step by step Description: Module As your code grows more and more complex, it is useful to collect all code in a an external file. Here we store all the functions form our notebook in a single file grm.py. Nothing ne...
Python Code: from IPython.core.display import HTML, display display(HTML('material/images/grm.html')) Explanation: Module As your code grows more and more complex, it is useful to collect all code in a an external file. Here we store all the functions form our notebook in a single file grm.py. Nothing new happens, we ...
8,118
Given the following text description, write Python code to implement the functionality described below step by step Description: Make the ONCdb Here are step-by-step instructions on how to generate the ONCdb from VizieR catalogs. Step 1 Step1: Step 2 Step2: Step 3
Python Code: # Initialize a database onc = astrocat.Catalog() # Ingest a VizieR catalog by supplying a path, catalog name, and column name of a unique identifier onc.ingest_data(DIR_PATH+'/raw_data/viz_acs.tsv', 'ACS', 'ONCacs', count=10) # The raw dataset is stored as an attribute print(onc.ACS) # Add another one! (T...
8,119
Given the following text description, write Python code to implement the functionality described below step by step Description: Traverse a Square - Part 3 - Loops Compared to the original programme, the programme that contains the variables is easier to modify. But it still contains a lot of repetition. Let's remind ...
Python Code: for count in range(0,3): print(count) print("And the final value of `count` is", count) Explanation: Traverse a Square - Part 3 - Loops Compared to the original programme, the programme that contains the variables is easier to modify. But it still contains a lot of repetition. Let's remind ourselv...
8,120
Given the following text description, write Python code to implement the functionality described below step by step Description: REINFORCE in TensorFlow Just like we did before for q-learning, this time we'll design a neural network to learn CartPole-v0 via policy gradient (REINFORCE). Step1: Building the policy netw...
Python Code: # This code creates a virtual display to draw game images on. # If you are running locally, just ignore it import os if type(os.environ.get("DISPLAY")) is not str or len(os.environ.get("DISPLAY")) == 0: !bash ../xvfb start os.environ['DISPLAY'] = ':1' import gym import numpy as np, pandas as pd im...
8,121
Given the following text description, write Python code to implement the functionality described below step by step Description: Implementing binary decision trees The goal of this notebook is to implement your own binary decision tree classifier. You will Step1: Load LendingClub Loans dataset We will be using a data...
Python Code: import json import numpy as np import pandas as pd import matplotlib as mpl import matplotlib.pyplot as plt import seaborn as sns sns.set_style('darkgrid') %matplotlib inline Explanation: Implementing binary decision trees The goal of this notebook is to implement your own binary decision tree classifier. ...
8,122
Given the following text description, write Python code to implement the functionality described below step by step Description: Behavior of the median filter with noised sine waves DW 2015.11.12 Step1: 1. Create all needed arrays and data. Step2: Figure 1. Behavior of the median filter with given window length and ...
Python Code: import numpy as np import matplotlib.pyplot as plt from scipy.signal import medfilt import sys # Add a new path with needed .py files. sys.path.insert(0, 'C:\Users\Dominik\Documents\GitRep\kt-2015-DSPHandsOn\MedianFilter\Python') import functions import gitInformation %matplotlib inline gitInformation.pri...
8,123
Given the following text description, write Python code to implement the functionality described below step by step Description: Memprediksi jenis kelamin dari nama bahasa Indonesia menggunakan Machine Learning Loading dataset Step1: Cleansing dataset Step2: Split Dataset Dataset yang adalah akan dipecah menjadi dua...
Python Code: import pandas as pd # pandas is a dataframe library df = pd.read_csv("./data/data-pemilih-kpu.csv", encoding = 'utf-8-sig') #dimensi dataset terdiri dari 13137 baris dan 2 kolom df.shape #melihat 5 baris pertama dataset df.head(5) #melihat 5 baris terakhir dataset df.tail(5) Explanation: Me...
8,124
Given the following text description, write Python code to implement the functionality described below step by step Description: <h1> 2d. Distributed training and monitoring </h1> In this notebook, we refactor to call train_and_evaluate instead of hand-coding our ML pipeline. This allows us to carry out evaluation as ...
Python Code: !sudo chown -R jupyter:jupyter /home/jupyter/training-data-analyst # Ensure the right version of Tensorflow is installed. !pip freeze | grep tensorflow==2.5 from google.cloud import bigquery import tensorflow as tf import numpy as np import shutil print(tf.__version__) Explanation: <h1> 2d. Distributed tra...
8,125
Given the following text description, write Python code to implement the functionality described below step by step Description: Table of Contents <p><div class="lev1 toc-item"><a href="#Formatando-arrays-para-impressão" data-toc-modified-id="Formatando-arrays-para-impressão-1"><span class="toc-item-num">1&nbsp;&nbsp;...
Python Code: import numpy as np A = np.exp(np.linspace(0.1,10,32)).reshape(4,8)/3000. print('A: \n', A) Explanation: Table of Contents <p><div class="lev1 toc-item"><a href="#Formatando-arrays-para-impressão" data-toc-modified-id="Formatando-arrays-para-impressão-1"><span class="toc-item-num">1&nbsp;&nbsp;</span>Format...
8,126
Given the following text description, write Python code to implement the functionality described below step by step Description: Copyright 2021 The TensorFlow Authors. Step1: Migrate SessionRunHook to Keras callbacks <table class="tfo-notebook-buttons" align="left"> <td> <a target="_blank" href="https Step3: 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...
8,127
Given the following text problem statement, write Python code to implement the functionality described below in problem statement Problem: Given a list of variant length features, for example:
Problem: import pandas as pd import numpy as np import sklearn features = load_data() from sklearn.preprocessing import MultiLabelBinarizer new_features = MultiLabelBinarizer().fit_transform(features) rows, cols = new_features.shape for i in range(rows): for j in range(cols): if new_features[i, j] == 1: ...
8,128
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: Table of Contents <p><div class="lev1 toc-item"><a href="#Looping-the-Property-Extraction" data-toc-modified-id="Looping-the-Property-Extraction-1"><span class="toc-item-num">1&nbsp;&...
Python Code: # Import required packages # File handling import os import glob # Array handling import numpy as np # Image handling from skimage.io import imread # Image thresholding and measurement from skimage.filters import threshold_otsu from skimage.morphology import remove_small_objects from skimage.measure impor...
8,129
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', 'cas', 'fgoals-f3-l', 'toplevel') Explanation: ES-DOC CMIP6 Model Properties - Toplevel MIP Era: CMIP6 Institute: CAS Source ID: FGOALS-F3-L Sub-Topics: Radiative Forcings. Properties...
8,130
Given the following text description, write Python code to implement the functionality described below step by step Description: \title{Phase Lock Loop Components in myHDL} \author{Steven K Armour} \maketitle This notebook is an exploration into the building and testing the Phase Lock Detector and the frequency divide...
Python Code: from myhdl import * from myhdlpeek import Peeker #helper functions to read in the .v and .vhd generated files into python def VerilogTextReader(loc, printresult=True): with open(f'{loc}.v', 'r') as vText: VerilogText=vText.read() if printresult: print(f'***Verilog modual from {loc}...
8,131
Given the following text description, write Python code to implement the functionality described below step by step Description: <a name="top"></a> DaViTpy - models This notebook introduces useful space science models included in davitpy. Currently we have ported/wrapped the following models to python Step1: <a nam...
Python Code: %pylab inline from datetime import datetime as dt from davitpy.models import * from davitpy import utils Explanation: <a name="top"></a> DaViTpy - models This notebook introduces useful space science models included in davitpy. Currently we have ported/wrapped the following models to python: <a href="#...
8,132
Given the following text description, write Python code to implement the functionality described below step by step Description: Method to try to match lines, mainly in absorption, with known lines at different velocities. The lineid must be identified first to discard wrong detections. Step1: We define the source to...
Python Code: import sys sys.path.append("/home/stephane/git/alma-calibrator/src") import lineTools as lt import pickle import matplotlib.pyplot as pl al = lt.analysisLines("/home/stephane/Science/RadioGalaxy/ALMA/absorptions/analysis/a/lineAll.db") %matplotlib inline Explanation: Method to try to match lines, mainly in...
8,133
Given the following text description, write Python code to implement the functionality described below step by step Description: <a href="https Step1: Chapter 20 - Tables and Networks In the previous chapter we looked into various types of charts and correlations that are useful for scientific analysis in Python. Her...
Python Code: %%capture !wget https://github.com/cltl/python-for-text-analysis/raw/master/zips/Data.zip !wget https://github.com/cltl/python-for-text-analysis/raw/master/zips/images.zip !wget https://github.com/cltl/python-for-text-analysis/raw/master/zips/Extra_Material.zip !unzip Data.zip -d ../ !unzip images.zip -d ....
8,134
Given the following text description, write Python code to implement the functionality described below step by step Description: MNIST Convolutional Neural Network - Ensemble Learning In this notebook we will verify if our single-column architecture can get any advantage from using ensemble learning, so a multi-column...
Python Code: import os.path from IPython.display import Image from util import Util u = Util() import numpy as np # Explicit random seed for reproducibility np.random.seed(1337) from keras.callbacks import ModelCheckpoint from keras.models import Sequential from keras.layers import Dense, Dropout, Activation, Flatten...
8,135
Given the following text description, write Python code to implement the functionality described below step by step Description: Basic Feature Engineering in Keras Learning Objectives Create an input pipeline using tf.data Engineer features to create categorical, crossed, and numerical feature columns Introduction In ...
Python Code: # Run the chown command to change the ownership !sudo chown -R jupyter:jupyter /home/jupyter/training-data-analyst # Install Sklearn # scikit-learn simple and efficient tools for predictive data analysis # Built on NumPy, SciPy, and matplotlib !python3 -m pip install --user sklearn # You can use any Python...
8,136
Given the following text description, write Python code to implement the functionality described below step by step Description: Copyright 2018 The TensorFlow Authors. Step1: Time windows <table class="tfo-notebook-buttons" align="left"> <td> <a target="_blank" href="https Step2: Time Windows First, we will tr...
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...
8,137
Given the following text description, write Python code to implement the functionality described below step by step Description: Literate Computing for Reproducible Infrastructure <img src="./images/literate_computing-logo.png" alt='LC_LOGO' align='left'/> NII Cloud Operation is a team supporting researchers and teach...
Python Code: ! echo "This is 1st step" > foo; cat foo ! echo ".. 2nd step..." >> foo && cat foo !echooooo ".. 3rd step... will fail" >> foo && cat foo Explanation: Literate Computing for Reproducible Infrastructure <img src="./images/literate_computing-logo.png" alt='LC_LOGO' align='left'/> NII Cloud Operation is a tea...
8,138
Given the following text description, write Python code to implement the functionality described below step by step Description: Lesson 6 v1.1, 2020.4 5, edit by David Yi 本次内容要点 随机数 思考:猜数游戏等 随机数 随机数这一概念在不同领域有着不同的含义,在密码学、通信领域有着非常重要的用途。 Python 的随机数模块是 random,random 模块主要有以下函数,结合例子来看看。 random.choice() 从序列中获取一个随机元素 random....
Python Code: import random # random.choice(sequence)。参数sequence表示一个有序类型。 # random.choice 从序列中获取一个随机元素。 print(random.choice(range(1,100))) # 从一个列表中产生随机元素 list1 = ['a', 'b', 'c'] print(random.choice(list1)) # random.sample() # 创建指定范围内指定个数的整数随机数 print(random.sample(range(1,100), 10)) print(random.sample(range(1,10), 5)) #...
8,139
Given the following text description, write Python code to implement the functionality described below step by step Description: Interact Exercise 6 Imports Put the standard imports for Matplotlib, Numpy and the IPython widgets in the following cell. Step1: Exploring the Fermi distribution In quantum statistics, the ...
Python Code: %matplotlib inline import matplotlib.pyplot as plt import numpy as np from IPython.display import Image from IPython.html.widgets import interact, interactive, fixed Explanation: Interact Exercise 6 Imports Put the standard imports for Matplotlib, Numpy and the IPython widgets in the following cell. End of...
8,140
Given the following text description, write Python code to implement the functionality described below step by step Description: CS446/519 - Class Session 7 - Transitivity (Clustering Coefficients) In this class session we are going to compute the local clustering coefficient of all vertices in the undirected human pr...
Python Code: from igraph import Graph from igraph import summary import pandas import numpy import timeit from pympler import asizeof import bintrees Explanation: CS446/519 - Class Session 7 - Transitivity (Clustering Coefficients) In this class session we are going to compute the local clustering coefficient of all ve...
8,141
Given the following text description, write Python code to implement the functionality described below step by step Description: Histogrammar advanced tutorial Histogrammar is a Python package that allows you to make histograms from numpy arrays, and pandas and spark dataframes. (There is also a scala backend for Hist...
Python Code: %%capture # install histogrammar (if not installed yet) import sys !"{sys.executable}" -m pip install histogrammar import histogrammar as hg import pandas as pd import numpy as np import matplotlib Explanation: Histogrammar advanced tutorial Histogrammar is a Python package that allows you to make histogra...
8,142
Given the following text description, write Python code to implement the functionality described below step by step Description: Chapter 16 - The BART model of risk taking 16.1 The BART model Balloon Analogue Risk Task (BART Step1: 16.2 A hierarchical extension of the BART model $$ \mu_{\gamma^{+}} \sim \text{Uniform...
Python Code: p = .15 # (Belief of) bursting probability ntrials = 90 # Number of trials for the BART Data = pd.read_csv('data/GeorgeSober.txt', sep='\t') # Data.head() cash = np.asarray(Data['cash']!=0, dtype=int) npumps = np.asarray(Data['pumps'], dtype=int) options = cash + npumps d = np.full([ntrials,30], np.nan)...
8,143
Given the following text description, write Python code to implement the functionality described below step by step Description: $$ f\left( v \right) = k_1 \cdot v^2 + k_2 \cdot v + k_3 $$ Step1: $$ \dot{v} = f\left( v \right) - u + I $$ Step2: $$ \dot{u} = a \cdot \left( b \cdot v - u \right) $$ Step3: $$ v \appro...
Python Code: def f(v): return k[0] * (v**2) + k[1] * v + k[2] Explanation: $$ f\left( v \right) = k_1 \cdot v^2 + k_2 \cdot v + k_3 $$ End of explanation def Vt(v, u, I): return f(v) - u + I Explanation: $$ \dot{v} = f\left( v \right) - u + I $$ End of explanation def Ut(v, u): return a * (b * v - u) Explan...
8,144
Given the following text description, write Python code to implement the functionality described below step by step Description: Модель №2 Вход Данные Step1: Загрузка модели word2vec Step2: Подготовка данных Step3: Обучение модели Step4: Результаты Результаты на тестовой выборке (20% от исходных данных) целевые пе...
Python Code: reviews_test = pd.read_csv('data/reviews_test.csv', header=0, encoding='utf-8') reviews_train = pd.read_csv('data/reviews_train.csv', header=0, encoding='utf-8') X_train_raw = reviews_train.comment y_train_raw = reviews_train.reting X_test_raw = reviews_test.comment y_test_raw = reviews_test.reting Explana...
8,145
Given the following text description, write Python code to implement the functionality described below step by step Description: Constraint Satisfaction Problems (CSPs) This IPy notebook acts as supporting material for topics covered in Chapter 6 Constraint Satisfaction Problems of the book Artificial Intelligence Ste...
Python Code: from csp import * Explanation: Constraint Satisfaction Problems (CSPs) This IPy notebook acts as supporting material for topics covered in Chapter 6 Constraint Satisfaction Problems of the book Artificial Intelligence: A Modern Approach. We make use of the implementations in csp.py module. Even though this...
8,146
Given the following text description, write Python code to implement the functionality described below step by step Description: <a href="https Step2: Then we need to create a function Step3: In order to register a magic it has to have few properties Step4: This does produce quite a lot of values, let's filter it o...
Python Code: #@title Only execute if you are connecting to a hosted kernel !pip install picatrix from picatrix.lib import framework from picatrix.lib import utils # This should not be included in the magic definition file, only used # in this notebook since we are comparing all magic registration. from picatrix import ...
8,147
Given the following text description, write Python code to implement the functionality described below step by step Description: Reusable workflows Nipype doesn't just allow you to create your own workflows. It also already comes with predefined workflows, developed by the community, for the community. For a full list...
Python Code: from nipype.workflows.fmri.fsl.preprocess import create_susan_smooth smoothwf = create_susan_smooth() Explanation: Reusable workflows Nipype doesn't just allow you to create your own workflows. It also already comes with predefined workflows, developed by the community, for the community. For a full list o...
8,148
Given the following text description, write Python code to implement the functionality described below step by step Description: 신경망 기초 이론 신경망(neural network) 모형은 퍼셉트론, 서포트 벡터 머신, 로지스틱 회귀 등의 분류 모형과 달리 기저 함수(basis function)도 사용자 파라미터에 의해 변화할 수 있는 적응형 기저 함수 모형(adaptive basis function model)이며 구조적으로는 여러개의 퍼셉트론을 쌓아놓은 형태이므...
Python Code: %%tikz \tikzstyle{neuron}=[circle, draw, minimum size=23pt,inner sep=0pt] \tikzstyle{bias}=[text centered] \node[neuron] (node) at (2,0) {$z$}; \node[neuron] (x1) at (0, 1) {$x_1$}; \node[neuron] (x2) at (0, 0) {$x_2$}; \node[neuron] (x3) at (0,-1) {$x_3$}; \node[neuron] (b) at (0,-2) {$1$}; \node[neuron]...
8,149
Given the following text description, write Python code to implement the functionality described below step by step Description: 面向对象程序设计 Step1: 当访问mycircle.radius,实际上是通过字典 mycircle.dict 查看相应的值。但是,如果回到类这一层,属性也是存储在类的字典里面 Step2: 也就是说,在查找属性或者方法的时候,会递归的查找mro中的内容,直到找到一个匹配项。 在传统的Python编码中,我们可以用下面的方式破坏面向对象的封装性: Step3: 可以看...
Python Code: class Circle(object): PI = 3.14 #类变量 def __init__(self,radius): self.radius = radius #实例变量 def get_areas(self): return PI * self.radius * self.radius mycircle = Circle(2) #实例化 print(mycircle.radius) # 实例变量 print(mycircle.PI) #类变量 print(Circle.PI) #也可以使用类名直接调用类变量 Explanation: 面向对...
8,150
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: TV Script Generation In this project, you'll generate your own Simpsons TV scripts using RNNs. You'll be using part of the Simpsons dataset of scripts from 27 seasons. The Neural Ne...
Python Code: DON'T MODIFY ANYTHING IN THIS CELL import helper data_dir = './data/simpsons/moes_tavern_lines.txt' text = helper.load_data(data_dir) # Ignore notice, since we don't use it for analysing the data text = text[81:] Explanation: TV Script Generation In this project, you'll generate your own Simpsons TV script...
8,151
Given the following text description, write Python code to implement the functionality described below step by step Description: Time series in Pastas R.A. Collenteur, University of Graz, 2020 Time series are at the heart of time series analysis, and therefore need to be considered carefully when dealing with time ser...
Python Code: import numpy as np import pandas as pd import matplotlib.pyplot as plt import pastas as ps ps.show_versions() Explanation: Time series in Pastas R.A. Collenteur, University of Graz, 2020 Time series are at the heart of time series analysis, and therefore need to be considered carefully when dealing with ti...
8,152
Given the following text description, write Python code to implement the functionality described below step by step Description: <img src="http Step1: OIS Data & Discounting We start by importing OIS term structure data (source Step2: Next we replace the year fraction index by a DatetimeIndex. Step3: Let us have a ...
Python Code: import dx import datetime as dt import time import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns; sns.set() %matplotlib inline Explanation: <img src="http://hilpisch.com/tpq_logo.png" alt="The Python Quants" width="45%" align="right" border="4"> Interest Rate Swaps V...
8,153
Given the following text description, write Python code to implement the functionality described below step by step Description: DKRZ PyNGL example - Filled circles instead of grid cells; the size depends on a quality value. Description Step1: Global variables Step2: Create dummy data and coordinates Step3: Open gr...
Python Code: from __future__ import print_function import numpy as np import Ngl,Nio Explanation: DKRZ PyNGL example - Filled circles instead of grid cells; the size depends on a quality value. Description: Draw two plots, first plot is a raster contour plot and the second shows the data using filled circles which are ...
8,154
Given the following text description, write Python code to implement the functionality described below step by step Description: Generative Adversarial Network In this notebook, we'll be building a generative adversarial network (GAN) trained on the MNIST dataset. From this, we'll be able to generate new handwritten d...
Python Code: %matplotlib inline import pickle as pkl import numpy as np import tensorflow as tf import matplotlib.pyplot as plt from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets('MNIST_data') Explanation: Generative Adversarial Network In this notebook, we'll be building a gen...
8,155
Given the following text description, write Python code to implement the functionality described below step by step Description: Simple Harmonic Oscillator model This example shows how the Simple Harmonic Oscillator model can be used. A model for a particle undergoing Newtonian dynamics that experiences a force in pro...
Python Code: import pints import pints.toy import matplotlib.pyplot as plt import numpy as np model = pints.toy.SimpleHarmonicOscillatorModel() Explanation: Simple Harmonic Oscillator model This example shows how the Simple Harmonic Oscillator model can be used. A model for a particle undergoing Newtonian dynamics that...
8,156
Given the following text description, write Python code to implement the functionality described below step by step Description: Descriptive statistics Acknowledging that variables and models are uncertain assumes that we directly or indirectly can describe them through probability distributions. However for most appl...
Python Code: import chaospy uniform = chaospy.Uniform(0, 4) chaospy.E(uniform) Explanation: Descriptive statistics Acknowledging that variables and models are uncertain assumes that we directly or indirectly can describe them through probability distributions. However for most applications the distribution is a messy e...
8,157
Given the following text description, write Python code to implement the functionality described below step by step Description: Understand TopicSimilarity.json Step1: Now we see that the values of "source" and "target" in links indicate the indexes of nodes. I haven't figured out what does "value" in nodes represent...
Python Code: # read a test version (w/o JS codes) of TopicSimilarity.json file = 'testSim.json' with open(file) as train_file: dict_train = json.load(train_file) dict_train len(dict_train['links']), len(dict_train['nodes']) links = pd.DataFrame(dict_train['links']) nodes = pd.DataFrame(dict_train['nodes']) links.he...
8,158
Given the following text description, write Python code to implement the functionality described below step by step Description: Solution Step2: 2. Create yet another function that takes the name of the region as an input and returns SST values for the corresponding region This function can look something like the on...
Python Code: def calc_heat_flux(u_atm, t_sea, rho=1.2, c_p=1004.5, c_h=1.2e-3, u_sea=1, t_atm=17): q = rho * c_p * c_h * (u_atm - u_sea) * (t_sea - t_atm) return q Explanation: Solution: create a module and reuse code from it (1 h) Extend the exercise from today by applying what you've just learned about packag...
8,159
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', 'nerc', 'ukesm1-0-ll', 'toplevel') Explanation: ES-DOC CMIP6 Model Properties - Toplevel MIP Era: CMIP6 Institute: NERC Source ID: UKESM1-0-LL Sub-Topics: Radiative Forcings. Properti...
8,160
Given the following text description, write Python code to implement the functionality described below step by step Description: Class 02 Machine Learning Models Step1: It is pretty clear that there is a linear trend here. If I wanted to predict what would happen if we tried the input of x=0.6, it would be a good gue...
Python Code: import pandas as pd fakedata1 = pd.DataFrame( [[ 0.862, 2.264], [ 0.694, 1.847], [ 0.184, 0.705], [ 0.41 , 1.246]], columns=['input','output']) fakedata1.plot(x='input',y='output',kind='scatter') Explanation: Class 02 Machine Learning Models: Linear regression & Validation ...
8,161
Given the following text description, write Python code to implement the functionality described below step by step Description: $\LaTeX$ definition block $\newcommand{\sign}{\operatorname{sign}}$ Distant Supervision This notebook has a few cute experiments to explore distant supervision. Setup In the distant supervis...
Python Code: # Constants D = 2 N = 100 K = 2 w = np.random.randn(D) w = normalize(w) theta = np.arctan2(w[0], w[1]) X = np.random.randn(N,D,K) y = np.zeros(N) for i in range(N): m = w.dot(X[i]) X[i] = X[i][:,np.argsort(-m)] y[i] = np.sign(max(m)) # Visualize data plt.plot(np.arange(-3,3), -w[0]/w[1] * np.ar...
8,162
Given the following text description, write Python code to implement the functionality described below step by step Description: <center> Kafka Producer for Twitter </center> Acquire and decompress Kafka $ wget http Step1: To delete a topic Step2: Setup Confluent_Kafka First, install your own Anaconda to a local dir...
Python Code: !cd ~/software/kafka_2.11-1.0.0; \ ./bin/kafka-topics.sh --zookeeper localhost:2181 --delete --topic test !cd ~/software/kafka_2.11-1.0.0; \ ./bin/kafka-topics.sh --create --zookeeper localhost:2181 --replication-factor 1 --partitions 1 --topic test !cd ~/software/kafka_2.11-1.0.0; \ ./bin/kafk...
8,163
Given the following text description, write Python code to implement the functionality described below step by step Description: First we need to 'binarize' the picture we want to embed in the markow field. This function does it Step1: We load and prepare the picture Step2: We now define the spin-spin correlation fu...
Python Code: def prep_datas(pic, size): X=resize(pic,(size,size)) # reduce the size of the image from 100X100 to 32X32. Also flattens the color levels X=np.reshape(X,size**2) # reshape from 32x32 to a flat 1024 vector X=np.array(X) # transforms it into an array for j in range(len(X)): # let's ...
8,164
Given the following text description, write Python code to implement the functionality described below step by step Description: Copyright 2020 The TensorFlow Authors. Step1: MLMD Model Card Toolkit Demo <table class="tfo-notebook-buttons" align="left"> <td> <a target="_blank" href="https Step2: Did you restar...
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...
8,165
Given the following text description, write Python code to implement the functionality described below step by step Description: Coronagraph Basics This set of exercises guides the user through a step-by-step process of simulating NIRCam coronagraphic observations of the HR 8799 exoplanetary system. The goal is to fam...
Python Code: # Import the usual libraries import numpy as np import matplotlib import matplotlib.pyplot as plt # Enable inline plotting at lower left %matplotlib inline Explanation: Coronagraph Basics This set of exercises guides the user through a step-by-step process of simulating NIRCam coronagraphic observations of...
8,166
Given the following text description, write Python code to implement the functionality described below step by step Description: Data Structures This chapter describes some things you’ve learned about already in more detail, and adds some new things as well. More on Lists list.append(x) Add an item to the end of the l...
Python Code: from __future__ import print_function a = [66.25, 333, 333, 1, 1234.5] print(a.count(333), a.count(66.25), a.count('x')) a.insert(2, -1) a.append(333) a a.index(333) a.remove(333) a a.reverse() a a.sort() a a.pop() a Explanation: Data Structures This chapter describes some things you’ve learned about alrea...
8,167
Given the following text description, write Python code to implement the functionality described below step by step Description: Parsing a Protein Databank File In this notebook we will do some simple parsings and analysis on a Protein Databank (PDB) file. You don't need to care about proteins to follow this example. ...
Python Code: filein = open('../data/protein.pdb', 'r') fileout = open('../data/protein_hie.pdb', 'w') #Finish... filein.close() fileout.close() Explanation: Parsing a Protein Databank File In this notebook we will do some simple parsings and analysis on a Protein Databank (PDB) file. You don't need to care abo...
8,168
Given the following text description, write Python code to implement the functionality described below step by step Description: Problem 01 - solution The following are my approach to solving these problems. Note that there may be more than one approach to each, and we could even debate the exact solutions. Problem 1...
Python Code: !wget https://raw.githubusercontent.com/gwsb-istm-6212-fall-2016/syllabus-and-schedule/master/projects/project-01/women.txt !cat women.txt | grep -oE '\w{{2,}}' \ | grep -e "Jo\|Beth\|Meg\|Amy" \ | tr '[:upper:]' '[:lower:]' \ | sort | uniq -c | sort -rn Explanation: Problem 01 - solution The foll...
8,169
Given the following text description, write Python code to implement the functionality described below step by step Description: Facies classification using Convolutional Neural Networks Team StoDIG - Statoil Deep-learning Interest Group David Wade, John Thurmond & Eskil Kulseth Dahl In this python notebook we propos...
Python Code: %%sh pip install pandas pip install scikit-learn pip install keras pip install sklearn from __future__ import print_function import time import numpy as np %matplotlib inline import pandas as pd import matplotlib.pyplot as plt import matplotlib.colors as colors from mpl_toolkits.axes_grid1 import make_axes...
8,170
Given the following text description, write Python code to implement the functionality described below step by step Description: 주 단위 데이터를 일 단위 데이터로 늘리기 네이버 검색 트렌드는 주 단위로 특정 검색어에 대한 검색량을 제공하고 있음 주별 검색량을 검색 기간 사이의 최소검색량, 최대검색량을 기준으로 0~100 사이의 수로 scaling하여 보여줌 이 주 단위의 데이터를 차후 데이터 분석 프로젝트(종속변수 예측)에서 입력변수로 사용할 때 단순히 한 주의...
Python Code: ##1년은 52주로 구성됨 week = list(range(1, 53)) #range 함수의 첫 번째 파라매터에는 시작할 숫자, 두 번째 파라매터에는 끝나는 숫자보다 1 큰 수를 넣어줌 week len(week) Explanation: 주 단위 데이터를 일 단위 데이터로 늘리기 네이버 검색 트렌드는 주 단위로 특정 검색어에 대한 검색량을 제공하고 있음 주별 검색량을 검색 기간 사이의 최소검색량, 최대검색량을 기준으로 0~100 사이의 수로 scaling하여 보여줌 이 주 단위의 데이터를 차후 데이터 분석 프로젝트(종속변수 예측)에서 입력변수로 ...
8,171
Given the following text description, write Python code to implement the functionality described. Description: Minimum cost to modify a string Function to return the minimum cost ; Initialize result ; To store the frequency of characters of the string ; Update the frequencies of the characters of the string ; Loop to c...
Python Code: def minCost(str1 , K ) : n = len(str1 ) res = 999999999 count = 0 cnt =[0 for i in range(27 ) ] for i in range(n ) : cnt[ord(str1[i ] ) - ord(' a ' ) + 1 ] += 1  for i in range(1 , 26 - K + 1 , 1 ) : a = i b = i + K count = 0 for j in range(1 , 27 , 1 ) : if(cnt[j ] > 0 ) : ...
8,172
Given the following text description, write Python code to implement the functionality described below step by step Description: Endpoint layer pattern Author Step1: Usage of endpoint layers in the Functional API An "endpoint layer" has access to the model's targets, and creates arbitrary losses and metrics using add...
Python Code: import tensorflow as tf from tensorflow import keras import numpy as np Explanation: Endpoint layer pattern Author: fchollet<br> Date created: 2019/05/10<br> Last modified: 2019/05/10<br> Description: Demonstration of the "endpoint layer" pattern (layer that handles loss management). Setup End of explanati...
8,173
Given the following text description, write Python code to implement the functionality described below step by step Description: All sky research Solo ∼ 3 × 10 3 stelle di neutroni osservate su ∼ 10 9 stimate nella Via Lattea ⇒ ricerca “alla cieca” su tutto il cielo. Problemi * ampiezze molto piccole; * modulazione Do...
Python Code: binh_df0ORIG=zeros(nbin_d,nbin_f0); % HM matrix container for it = 1:nTimeSteps kf=(peaks(2,ii0:ii(it))-inifr)/ddf; % normalized frequencies w=peaks(5,ii0:ii(it)); % wiener weights t=peaks(1,ii0)*Day_inSeconds; % time conversion days to s tddf=t/ddf; f0_a=kf-deltaf2; ...
8,174
Given the following text description, write Python code to implement the functionality described below step by step Description: Estimize Step1: Let's go over the columns Step2: How many records do we have now? Step3: Let's break it down by user Step4: Let's convert it over to a Pandas DataFrame so we can chart it...
Python Code: # import the free sample of the dataset from quantopian.interactive.data.estimize import estimates_free # or if you want to import the full dataset, use: # from quantopian.interactive.data.estimize import estimates # import data operations from odo import odo # import other libraries we will use import pan...
8,175
Given the following text description, write Python code to implement the functionality described below step by step Description: Serving models using NVIDIA Triton Inference Server and Vertex AI Prediction This notebook demonstrates how to serve NVIDIA Merlin HugeCTR deep learning models using NVIDIA Triton Inference ...
Python Code: import json import os import shutil import time from pathlib import Path from src.serving import export from google.cloud import aiplatform as vertex_ai Explanation: Serving models using NVIDIA Triton Inference Server and Vertex AI Prediction This notebook demonstrates how to serve NVIDIA Merlin HugeCTR de...
8,176
Given the following text description, write Python code to implement the functionality described below step by step Description: Trips in time and space order Sorts output trips in time and space order, which is useful for disaggregate (individual) dynamic traffic assignment and person time/space visualization. Trips...
Python Code: pipeline_filename = '../test_example_mtc/output/pipeline.h5' output_trip_filename = "../test_example_mtc/output/final_trips_time_space_order.csv" Explanation: Trips in time and space order Sorts output trips in time and space order, which is useful for disaggregate (individual) dynamic traffic assignment a...
8,177
Given the following text description, write Python code to implement the functionality described below step by step Description: Machine Learning Engineer Nanodegree Unsupervised Learning Project 3 Step1: Data Exploration In this section, you will begin exploring the data through visualizations and code to understand...
Python Code: # Import libraries necessary for this project import numpy as np import pandas as pd import renders as rs from IPython.display import display # Allows the use of display() for DataFrames # Show matplotlib plots inline (nicely formatted in the notebook) %matplotlib inline # Load the wholesale customers data...
8,178
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: Apparent horizons We're now going to use finite differences to find a black hole apparent horizon. The spacetime we're going to look at is simplified Step3: We now need to solve the ...
Python Code: import numpy from matplotlib import pyplot %matplotlib notebook def horizon_RHS(H, theta, z_singularities): The RHS function for the apparent horizon problem. Parameters ---------- H : array vector [h, dh/dtheta] theta : double angle z_singularities : ...
8,179
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: Session 4 Step2: <a name="part-1---pretrained-networks"></a> Part 1 - Pretrained Networks In the libs module, you'll see that I've included a few modules for loading some state of th...
Python Code: # First check the Python version import sys if sys.version_info < (3,4): print('You are running an older version of Python!\n\n', 'You should consider updating to Python 3.4.0 or', 'higher as the libraries built for this course', 'have only been tested in Python 3.4 and hi...
8,180
Given the following text description, write Python code to implement the functionality described below step by step Description: Artificial Intelligence Nanodegree Convolutional Neural Networks In your upcoming project, you will download pre-computed bottleneck features. In this notebook, we'll show you how to calcul...
Python Code: from keras.applications.vgg16 import preprocess_input from keras.preprocessing import image import numpy as np import glob img_paths = glob.glob("images/*.jpg") def path_to_tensor(img_path): # loads RGB image as PIL.Image.Image type img = image.load_img(img_path, target_size=(224, 224)) # conve...
8,181
Given the following text description, write Python code to implement the functionality described below step by step Description: With an equal number of origins and destinations (n=16) Step1: # With non-equal number of origins (n=9) and destinations (m=25)
Python Code: origins = ps.weights.lat2W(4,4) dests = ps.weights.lat2W(4,4) origins.n dests.n ODw = ODW(origins, dests) print ODw.n, 16*16 ODw.full()[0].shape Explanation: With an equal number of origins and destinations (n=16) End of explanation origins = ps.weights.lat2W(3,3) dests = ps.weights.lat2W(5,5) origins.n de...
8,182
Given the following text description, write Python code to implement the functionality described below step by step Description: In this notebook we will add diffusion in addition to reactions. We will first study the simplest possible chemical reaction set Step1: The diffusion follows Fick's law of diffusion Step2: ...
Python Code: reactions = [ ('k', {'A': 1}, {'B': 1, 'A': -1}), ] names, params = 'A B'.split(), ['k'] Explanation: In this notebook we will add diffusion in addition to reactions. We will first study the simplest possible chemical reaction set: $$ A \overset{k}{\rightarrow} B $$ we will consider a flat geometry whe...
8,183
Given the following text description, write Python code to implement the functionality described below step by step Description: What is a dataset? A dataset is a collection of information (or data) that can be used by a computer. A dataset typically has some number of examples, where each example has features associa...
Python Code: # Print figures in the notebook %matplotlib inline import numpy as np import matplotlib.pyplot as plt from matplotlib.colors import ListedColormap from sklearn import datasets # Import datasets from scikit-learn # Import patch for drawing rectangles in the legend from matplotlib.patches import Rectangle #...
8,184
Given the following text description, write Python code to implement the functionality described below step by step Description: R-CNN is a state-of-the-art detector that classifies region proposals by a finetuned Caffe model. For the full details of the R-CNN system and model, refer to its project site and the paper ...
Python Code: !mkdir -p _temp !echo `pwd`/images/fish-bike.jpg > _temp/det_input.txt !../python/detect.py --crop_mode=selective_search --pretrained_model=../models/bvlc_reference_rcnn_ilsvrc13/bvlc_reference_rcnn_ilsvrc13.caffemodel --model_def=../models/bvlc_reference_rcnn_ilsvrc13/deploy.prototxt --gpu --raw_scale=255...
8,185
Given the following text description, write Python code to implement the functionality described below step by step Description: Indutores Jupyter Notebook desenvolvido por Gustavo S.S. Um indutor consiste em uma bobina de fio condutor. Qualquer condutor de corrente elétrica possui propriedades indutivas e pode ser co...
Python Code: print("Exemplo 6.8") import numpy as np from sympy import * L = 0.1 t = symbols('t') i = 10*t*exp(-5*t) v = L*diff(i,t) w = (L*i**2)/2 print("Tensão no indutor:",v,"V") print("Energia:",w,"J") Explanation: Indutores Jupyter Notebook desenvolvido por Gustavo S.S. Um indutor consiste em uma bobina de fio con...
8,186
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="#Basic-Data-Structure" data-toc-modified-id="Basic-Data-Structure-1"><span cl...
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...
8,187
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="#Intro" data-toc-modified-id="Intro-1"><span class="toc-item-num">1&nbsp;&nbs...
Python Code: import numpy as np import matplotlib.pyplot as plt import matplotlib.animation as animation from PIL import Image, ImageDraw import tqdm from pathlib import Path %matplotlib notebook Explanation: <h1>Table of Contents<span class="tocSkip"></span></h1> <div class="toc"><ul class="toc-item"><li><span><a href...
8,188
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. %matplotlib inline from __future__ import print_function import matplotlib.pyplot as plt import numpy as np import os import sys import tarfile from IPython.display import display, Image from scipy ...
8,189
Given the following text description, write Python code to implement the functionality described below step by step Description: Getting Started with Symbulate Section 3. Multiple Random Variables and Joint Distributions <Random variables | Contents | Conditioning> Every time you start Symbulate, you must first run (S...
Python Code: from symbulate import * %matplotlib inline Explanation: Getting Started with Symbulate Section 3. Multiple Random Variables and Joint Distributions <Random variables | Contents | Conditioning> Every time you start Symbulate, you must first run (SHIFT-ENTER) the following commands. End of explanation def nu...
8,190
Given the following text description, write Python code to implement the functionality described below step by step Description: <span style="color Step1: Set up and connect to the ipyparallel cluster Depending on the number of tests, abba-baba analysis can be computationally intensive, so we will first set up a clus...
Python Code: import ipyrad.analysis as ipa import ipyparallel as ipp import toytree import toyplot print(ipa.__version__) print(toyplot.__version__) print(toytree.__version__) Explanation: <span style="color:gray">ipyrad-analysis toolkit:</span> abba-baba The baba tool can be used to measure abba-baba statistics across...
8,191
Given the following text description, write Python code to implement the functionality described below step by step Description: Spectral Energy Density Fitting and Dark Matter Limit Extraction Motivation Now we are going to discuss how we can use build a summary data product that can be used to quickly fit a wide var...
Python Code: %load_ext autoreload %autoreload 2 %matplotlib inline import numpy as np import matplotlib.pyplot as plt import LikeFitUtils as lfu import SedUtils as SED # lets open the file and have a look import yaml f_sed = yaml.load(open("results/draco_sed.yaml")) len(f_sed) Explanation: Spectral Energy Density Fitti...
8,192
Given the following text description, write Python code to implement the functionality described below step by step Description: Thesis 2019 symposium clinical workshop by Cyrille BONAMY, Antoine MATHIEU and Julien CHAUCHAT (LEGI, University of Grenoble Alpes, GINP/CNRS, Grenoble, France) Introduction The aim of this ...
Python Code: # # Import section # import subprocess import sys import numpy as np import fluidfoam from pylab import figure, subplot, axis, xlabel, ylabel, show, savefig, plot from pylab import title, matplotlib import matplotlib.gridspec as gridspec import matplotlib as mpl Explanation: Thesis 2019 symposium clinical ...
8,193
Given the following text description, write Python code to implement the functionality described below step by step Description: Sympy is a Python package used for solving equations using symbolic math. Let's solve the following problem with SymPy. Given Step1: We need to define six different symbols Step2: Next w...
Python Code: from sympy import symbols, nonlinsolve Explanation: Sympy is a Python package used for solving equations using symbolic math. Let's solve the following problem with SymPy. Given: The density of two different polymer samples $\rho_1$ and $\rho_2$ are measured. $$ \rho_1 = 1.408 \ g/cm^3 $$ $$ \rho_2 = 1....
8,194
Given the following text description, write Python code to implement the functionality described below step by step Description: Simple keyword spotting with CMSIS-DSP Python wrapper and Arduino The goal of this notebook is to demonstrate how to use the CMSIS-DSP Python wrapper on an example which is complex enough. I...
Python Code: import cmsisdsp as dsp import cmsisdsp.fixedpoint as fix import numpy as np import os.path import glob import pathlib import random import soundfile as sf import matplotlib.pyplot as plt from IPython.display import display,Audio,HTML import scipy.signal from numpy.lib.stride_tricks import sliding_window_vi...
8,195
Given the following text description, write Python code to implement the functionality described below step by step Description: Project Euler Step1: Then I created a new variable, sum_squares, which would hold the sum of the squares, and set it to zero. I looped through all the values in my list, squared them, then...
Python Code: lst = range(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 = 552 = 3025$$ Hence the difference betwee...
8,196
Given the following text description, write Python code to implement the functionality described below step by step Description: Source of the materials Step1: Note that the default settings on the NCBI BLAST website are not quite the same as the defaults on QBLAST. If you get different results, you’ll need to check ...
Python Code: from Bio.Blast import NCBIWWW help(NCBIWWW.qblast) Explanation: Source of the materials: Biopython cookbook (Adapted) <font color='red'> New status: Draft</font> BLAST Running BLAST over the Internet Saving blast output Running BLAST locally Parsing BLAST output The BLAST record class Parsing plain-text BL...
8,197
Given the following text description, write Python code to implement the functionality described below step by step Description: <div style='background-image Step1: 1. Initialization of setup Step2: 2. Elemental Mass and Stiffness matrices The mass and the stiffness matrix are calculated prior time extrapolation, so...
Python Code: # Import all necessary libraries, this is a configuration step for the exercise. # Please run it before the simulation code! import numpy as np import matplotlib.pyplot as plt from gll import gll from lagrange1st import lagrange1st from flux_homo import flux # Show the plots in the Notebook. plt.switch_bac...
8,198
Given the following text description, write Python code to implement the functionality described below step by step Description: Constants Step1: Toy Dataset ("Gaussian blobs") Step2: Typical Model Specification for Logistic Regression Step3: Alternative Specification An alternative specification isolates the posit...
Python Code: n_samples = 100 n_features = 2 n_classes = 2 seed = 42 rng = np.random.RandomState(seed) Explanation: Constants End of explanation x_test, y_test = make_blobs(n_samples=n_samples, centers=n_classes, random_state=rng) # class labels are balanced np.sum(y_test) fig, ax = plt.subplots(figsize=(7, 5)) cb = ax....
8,199
Given the following text description, write Python code to implement the functionality described below step by step Description: First Trading Algorithm Pairs Trading Pairs trading is a strategy that uses two stocks that are highly correlated. We can then use the difference in price between the two stocks as signal if...
Python Code: import numpy as np import pandas as pd import matplotlib.pyplot as plt %matplotlib inline import quandl Explanation: First Trading Algorithm Pairs Trading Pairs trading is a strategy that uses two stocks that are highly correlated. We can then use the difference in price between the two stocks as signal if...