Unnamed: 0
int64
0
16k
text_prompt
stringlengths
110
62.1k
code_prompt
stringlengths
37
152k
4,500
Given the following text description, write Python code to implement the functionality described below step by step Description: Decomposition Example First step, set the paths to where to find the motif dictionary and associated code. Note that these are available at http Step1: Load some motifs from the motif datab...
Python Code: motifdbcodepath = '/Users/simon/git/motifdb/code/utilities/' motifdbpath = '/Users/simon/git/motifdb/motifs/' Explanation: Decomposition Example First step, set the paths to where to find the motif dictionary and associated code. Note that these are available at http://github.com/sdrogers/motifdb End of ex...
4,501
Given the following text description, write Python code to implement the functionality described below step by step Description: <h1> Homework Set 6</h1> Matt Buchovecky Astro 283 / Fitz Step1: <h2> Problem 1 Step7: To estimate the values of $(\alpha,\beta)$, we maximize the posterior function $p(\alpha,\beta\mid{D}...
Python Code: import numpy as np from scipy import optimize, special from matplotlib import pyplot as plt from astropy.io import fits %matplotlib inline Explanation: <h1> Homework Set 6</h1> Matt Buchovecky Astro 283 / Fitz End of explanation # open the data file and load data into a list of points infile = open("./sa...
4,502
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', 'ncc', 'sandbox-1', 'atmoschem') Explanation: ES-DOC CMIP6 Model Properties - Atmoschem MIP Era: CMIP6 Institute: NCC Source ID: SANDBOX-1 Topic: Atmoschem Sub-Topics: Transport, Emiss...
4,503
Given the following text description, write Python code to implement the functionality described below step by step Description: Counting Stars with NumPy This example introduces some of the image processing capabilities available with NumPy and the SciPy ndimage package. More extensive documentation and tutorials ca...
Python Code: import scipy.ndimage as ndi import requests from StringIO import StringIO #Pick an image from the list above and fetch it with requests.get #The default picture here is of M45 - the Pleiades Star Cluster. response = requests.get("http://imgsrc.hubblesite.org/hu/db/images/hs-2004-20-a-large_web.jpg") pic =...
4,504
Given the following text description, write Python code to implement the functionality described below step by step Description: It is assumed that this notebook is in the same folder as the python-files randomGraphsNumerical.py, transitionMatrix.py, transitionMatrixDirected.py, AmplifierQ.py and Plot.py. Also there h...
Python Code: popSize = 4 # This is the number of nodes in the network update = 'BD' # Either 'BD' or 'DB' for Birth-death or death-Birth updating respectively direction = 'undirected' # Either 'directed' or 'undirected' graphs are used stepSize = 0.05 # Step size for the probability for each link in the network to be p...
4,505
Given the following text description, write Python code to implement the functionality described below step by step Description: Image Space Projection using Autoencoders In this example we are going to autoencode the faces of the olivetti dataset and try to reconstruct them back. Step1: http Step3: We now need some...
Python Code: %matplotlib inline import matplotlib import numpy as np import pandas as pd import scipy.io import matplotlib.pyplot as plt from IPython.display import Image, display import h2o from h2o.estimators.deeplearning import H2OAutoEncoderEstimator h2o.init() Explanation: Image Space Projection using Autoencoders...
4,506
Given the following text description, write Python code to implement the functionality described below step by step Description: Content under Creative Commons Attribution license CC-BY 4.0, code under BSD 3-Clause License © 2018 parts of this notebook are from Derivative Approximation by Finite Differences by David E...
Python Code: # Execute this cell to load the notebook's style sheet, then ignore it from IPython.core.display import HTML css_file = '../style/custom.css' HTML(open(css_file, "r").read()) Explanation: Content under Creative Commons Attribution license CC-BY 4.0, code under BSD 3-Clause License © 2018 parts of this note...
4,507
Given the following text description, write Python code to implement the functionality described below step by step Description: Template for test Step1: Controlling for Random Negatve vs Sans Random in Imbalanced Techniques using S, T, and Y Phosphorylation. Included is N Phosphorylation however no benchmarks are av...
Python Code: from pred import Predictor from pred import sequence_vector from pred import chemical_vector Explanation: Template for test End of explanation par = ["pass", "ADASYN", "SMOTEENN", "random_under_sample", "ncl", "near_miss"] for i in par: print("y", i) y = Predictor() y.load_data(file="Data/Train...
4,508
Given the following text description, write Python code to implement the functionality described below step by step Description: df_infl_ctry.rename(columns = dic) tt = df_infl_ctry.copy() tt['month'] = tt.index.month tt['year'] = tt.index.year melted_df = pd.melt(tt,id_vars=['month','year']) melted_df.head() Step1: ...
Python Code: df_infl_ctry['min'] = df_infl_ctry.apply(min,axis=1) df_infl_ctry['max'] = df_infl_ctry.apply(max,axis=1) df_infl_ctry['mean'] = df_infl_ctry.apply(np.mean,axis=1) df_infl_ctry['mode'] = df_infl_ctry.quantile(q=0.5, axis=1) df_infl_ctry['10th'] = df_infl_ctry.quantile(q=0.10, axis=1) df_infl_ctry['90th'] =...
4,509
Given the following text description, write Python code to implement the functionality described below step by step Description: Regular Expressions Regular expressions are text matching patterns described with a formal syntax. You'll often hear regular expressions referred to as 'regex' or 'regexp' in conversation. R...
Python Code: import re # List of patterns to search for patterns = [ 'term1', 'term2' ] # Text to parse text = 'This is a string with term1, but it does not have the other term.' for pattern in patterns: print 'Searching for "%s" in: \n"%s"' % (pattern, text), #Check for match if re.search(pattern, te...
4,510
Given the following text description, write Python code to implement the functionality described below step by step Description: <span style="color Step1: Here the line (<span style="color Step2: Replacing the first line with <span style="color Step3: <img src="Tutorial7/MatplotlibQt.png" width="500" > This GUI all...
Python Code: %matplotlib inline import matplotlib.pyplot as plt Explanation: <span style="color: #B40486">BASIC PYTHON FOR RESEARCHERS</span> by Megat Harun Al Rashid bin Megat Ahmad last updated: April 14, 2016 <span style="color: #29088A">7. Data Visualization and Plotting</span> The <span style="color: #0000FF">$Mat...
4,511
Given the following text description, write Python code to implement the functionality described below step by step Description: WEB_API Scrapper Step1: I would like to get the Best Seller list for the Month of October 2015. First I signed up to the New York Times API, and afterwards received a key in seconds. Step2:...
Python Code: import urllib2 import json import pandas as pd Explanation: WEB_API Scrapper End of explanation url = urllib2.urlopen('http://api.nytimes.com/svc/books/v3/lists/2015-10-01/hardcover-fiction.json?callback=books&sort-by=rank&sort-order=DESC&api-key=efb1f6ff386ce33c0b913d44bce40fd8%3A10%3A73015082') Explanati...
4,512
Given the following text description, write Python code to implement the functionality described below step by step Description: <h2 align="center">点击下列图标在线运行HanLP</h2> <div align="center"> <a href="https Step1: 加载模型 HanLP的工作流程是先加载模型,模型的标示符存储在hanlp.pretrained这个包中,按照NLP任务归类。 Step2: 调用hanlp.load进行加载,模型会自动下载到本地缓存: ...
Python Code: !pip install hanlp -U Explanation: <h2 align="center">点击下列图标在线运行HanLP</h2> <div align="center"> <a href="https://colab.research.google.com/github/hankcs/HanLP/blob/doc-zh/plugins/hanlp_demo/hanlp_demo/zh/srl_mtl.ipynb" target="_blank"><img src="https://colab.research.google.com/assets/colab-badge.svg" ...
4,513
Given the following text description, write Python code to implement the functionality described below step by step Description: <b>This notebook analyses senders, repliers and interactions.</b> What it does Step1: Let's compute and plot the top senders Step2: Let's compute and plot the top repliers Step3: Let's co...
Python Code: %matplotlib inline import bigbang.mailman as mailman from bigbang.archive import load as load_archive import bigbang.graph as graph import bigbang.process as process from bigbang.parse import get_date from bigbang.archive import Archive import bigbang.twopeople as twoppl reload(process) import pandas as pd...
4,514
Given the following text description, write Python code to implement the functionality described below step by step Description: Title Step1: Create Matrix Step2: Invert Matrix
Python Code: # Load library import numpy as np Explanation: Title: Invert A Matrix Slug: invert_a_matrix Summary: How to invert a matrix in Python. Date: 2017-09-03 12:00 Category: Machine Learning Tags: Vectors Matrices Arrays Authors: Chris Albon Preliminaries End of explanation # Create matrix matrix = np.arr...
4,515
Given the following text description, write Python code to implement the functionality described below step by step Description: Group Galaxy Catalog for the DR5 Gallery The purpose of this notebook is to build a group catalog (using a simple friends-of-friends algorithm) from a diameter-limited (D25>5 arcsec) parent ...
Python Code: import os import numpy as np import matplotlib.pyplot as plt import astropy.units as u from astropy.table import Table, Column from astropy.coordinates import SkyCoord import fitsio from pydl.pydlutils.spheregroup import spheregroup %matplotlib inline LSLGAdir = os.getenv('LSLGA_DIR') mindiameter = 0.25 # ...
4,516
Given the following text description, write Python code to implement the functionality described below step by step Description: Receiver Operating Characteristics (ROC) Step1: 1. Binary classification Step2: Accuracy, precision, recall Step3: Note Step4: The problem here is that we're not passing the correct seco...
Python Code: %matplotlib inline from IPython.display import Image import numpy as np import matplotlib.pyplot as plt # some classification metrics # more here: # http://scikit-learn.org/stable/modules/classes.html#module-sklearn.metrics from sklearn.metrics import (auc, roc_curve, roc_auc_score, ...
4,517
Given the following text description, write Python code to implement the functionality described below step by step Description: TD 1 Step1: Partie 1 Un langage de programmation permet de décrire avec précision des opérations très simples sur des données. Comme tout langage, il a une grammaire et des mot-clés. La co...
Python Code: from jyquickhelper import add_notebook_menu add_notebook_menu() Explanation: TD 1 : Premiers pas en Python End of explanation x = 5 y = 10 z = x + y print (z) # affiche z Explanation: Partie 1 Un langage de programmation permet de décrire avec précision des opérations très simples sur des données. Comme...
4,518
Given the following text description, write Python code to implement the functionality described below step by step Description: Как помочь нам разобрать протокол? Вот пример как это делается в простом случае. Есть устройство на чипе HS1527 и к нему даже нашелся datasheet Step1: Посмотрим на гистограммы длин импульсо...
Python Code: # takes filename # open file, read binary data # returns numpy.array of impulses (positive integer) # and pauses (negative integer) def file_to_data(filename): pic = open(filename, "rb") data = [] while True: buf = pic.read(4) if not buf or len(buf) != 4: break ...
4,519
Given the following text description, write Python code to implement the functionality described below step by step Description: Overview Step1: Extract NN Features Step2: Predicting Own Labels from Selected Images within a folder (find class 1, class 0). (split into test train) get matrix of img X features X class...
Python Code: import sys import os sys.path.append(os.getcwd()+'/../') # our lib from lib.resnet50 import ResNet50 from lib.imagenet_utils import preprocess_input, decode_predictions #keras from keras.preprocessing import image from keras.models import Model # sklearn import sklearn from sklearn.linear_model import Lo...
4,520
Given the following text description, write Python code to implement the functionality described below step by step Description: Theory and Practice of Visualization Exercise 1 Imports Step1: Graphical excellence and integrity Find a data-focused visualization on one of the following websites that is a positive examp...
Python Code: from IPython.display import Image Explanation: Theory and Practice of Visualization Exercise 1 Imports End of explanation # Add your filename and uncomment the following line: Image(filename='good data viz.png') Explanation: Graphical excellence and integrity Find a data-focused visualization on one of the...
4,521
Given the following text description, write Python code to implement the functionality described below step by step Description: Coroutines A coroutine is a type of subroutine which can have multiple entry and exit points. They're useful for a number of concurrency patterns. Python introduced coroutines as "Enhanced G...
Python Code: def print_if_error(error_is="error"): while True: line = yield if line.startswith(error_is): print(line) Explanation: Coroutines A coroutine is a type of subroutine which can have multiple entry and exit points. They're useful for a number of concurrency patterns. Python int...
4,522
Given the following text description, write Python code to implement the functionality described below step by step Description: 1. Kalman Filter applied to 1D Movement with constant velocity Step1: Parameters The system under consideration is an object traveling under constant velocity. Its motion (in both time and ...
Python Code: # allow use of python3 syntax from __future__ import division, print_function, absolute_import import numpy as np # local script with often used import kalman as k # contents of local file kalman.py # %load kalman.py import numpy as np import matplotlib.pyplot as plt def kalman_predict( A, # transition m...
4,523
Given the following text description, write Python code to implement the functionality described below step by step Description: python libs for all vis things Step1: bokeh Step2: bokeh + ipywidgets
Python Code: %pylab inline t = arange(0.0, 1.0, 0.01) y1 = sin(2*pi*t) y2 = sin(2*2*pi*t) import pandas as pd df = pd.DataFrame({'t': t, 'y1': y1, 'y2': y2}) df.head(10) Explanation: python libs for all vis things End of explanation from bokeh.plotting import figure, output_notebook, show # output inline with notebook ...
4,524
Given the following text description, write Python code to implement the functionality described below step by step Description: Performance Overview Here, we will example the performance of FNGS as a function of time on several datasets. These investigations were performed on a 4 core machine (4 threads) with a 4.0 G...
Python Code: %%script false ## disklog.sh #!/bin/bash -e # run this in the background with nohup ./disklog.sh > disk.txt & # while true; do echo "$(du -s $1 | awk '{print $1}')" sleep 30 done ##cpulog.sh import psutil import time import argparse def cpulog(outfile): with open(outfile, 'w') as outf: ...
4,525
Given the following text description, write Python code to implement the functionality described below step by step Description: Fast brain decoding with random sampling and random projections Andres HOYOS-IDROBO, Gael VAROQUAUX and Bertrand THIRION PARIETAL TEAM, INRIA, CEA, University Paris-Saclay Presented on Step1...
Python Code: %matplotlib inline import numpy as np import time import matplotlib.pyplot as plt from nilearn.plotting import plot_stat_map from nilearn.input_data import NiftiMasker Explanation: Fast brain decoding with random sampling and random projections Andres HOYOS-IDROBO, Gael VAROQUAUX and Bertrand THIRION PARIE...
4,526
Given the following text description, write Python code to implement the functionality described below step by step Description: Tutorial on the Analytical Advection kernel in Parcels While Lagrangian Ocean Analysis has been around since at least the 1980s, the Blanke and Raynaud (1997) paper has really spurred the us...
Python Code: %pylab inline from parcels import FieldSet, ParticleSet, ScipyParticle, JITParticle, Variable from parcels import AdvectionAnalytical, AdvectionRK4, plotTrajectoriesFile import numpy as np from datetime import timedelta as delta import matplotlib.pyplot as plt Explanation: Tutorial on the Analytical Advect...
4,527
Given the following text description, write Python code to implement the functionality described below step by step Description: L'objectif est de décrire l'évolution des montants des accises de la TICPE depuis 1993 Import de modules généraux Step1: Import de fonctions spécifiques à Openfisca Indirect Taxation Step2:...
Python Code: import seaborn seaborn.set_palette(seaborn.color_palette("Set2", 12)) %matplotlib inline Explanation: L'objectif est de décrire l'évolution des montants des accises de la TICPE depuis 1993 Import de modules généraux End of explanation from openfisca_france_indirect_taxation.examples.utils_example import gr...
4,528
Given the following text description, write Python code to implement the functionality described below step by step Description: 1. Import the necessary packages to read in the data, plot, and create a linear regression model Step1: 2. Read in the hanford.csv file Step2: <img src="images/hanford_variables.png"> 3. C...
Python Code: import pandas as pd %matplotlib inline import matplotlib.pyplot as plt import statsmodels.formula.api as smf import numpy as np import scipy as sp Explanation: 1. Import the necessary packages to read in the data, plot, and create a linear regression model End of explanation df = pd.read_csv("hanford.csv...
4,529
Given the following text description, write Python code to implement the functionality described below step by step Description: Read in parquet files from pre-processing Step1: To make templates Step2: Add cluster labels to sentences and mentions (entities) Step3: Get the size of each cluster Step4: Get the distr...
Python Code: # do the reading templates = pd.read_parquet('data/processed_dfs/templates.parquet' ) sentences = pd.read_parquet('data/processed_dfs/sentences.parquet') mentions = pd.read_parquet('data/processed_dfs/mentions.parquet') umls = pd.read_parquet('data/processed_dfs/umls.parquet') sentences.head() mentions.hea...
4,530
Given the following text description, write Python code to implement the functionality described below step by step Description: MNIST classification with Vowpal Wabbit Step1: Train I found some help with parameters here Step2: Predict -t is for test file -i specifies the model file created earlier -p whe...
Python Code: from __future__ import division import re import numpy as np from sklearn.metrics import confusion_matrix import matplotlib.pyplot as plt %matplotlib inline #%qtconsole Explanation: MNIST classification with Vowpal Wabbit End of explanation !rm train.vw.cache !rm mnist_train.model !vw -d data/mnist_train.v...
4,531
Given the following text description, write Python code to implement the functionality described below step by step Description: Using spaCy for Text Preprocessing Date Step1: 1. What is spaCy spaCy is a free, open-source library for NLP in Python Providing optimized pipelines for taking models to production, i.e., f...
Python Code: # Common imports import numpy as np import pandas as pd import zipfile as zp from termcolor import colored import seaborn as sns import matplotlib.pyplot as plt %matplotlib inline %config InlineBackend.figure_format = 'retina' #To wrap long text lines from IPython.display import HTML, display def set_css...
4,532
Given the following text description, write Python code to implement the functionality described below step by step Description: Basic Pie Chart Step1: Update Data Step2: Display Values Step3: Enable sort Step4: Set different styles for selected slices Step5: For more on piechart interactions, see the Mark Intera...
Python Code: data = np.random.rand(3) pie = Pie(sizes=data, display_labels="outside", labels=list(string.ascii_uppercase)) fig = Figure(marks=[pie], animation_duration=1000) fig Explanation: Basic Pie Chart End of explanation n = np.random.randint(1, 10) pie.sizes = np.random.rand(n) Explanation: Update Data End of exp...
4,533
Given the following text description, write Python code to implement the functionality described below step by step Description: <a href="https Step1: Transforming an input to a known output Step2: relation between input and output is linear Step3: Defining the model to train untrained single unit (neuron) also out...
Python Code: # import and check version import tensorflow as tf # tf can be really verbose tf.logging.set_verbosity(tf.logging.ERROR) print(tf.__version__) # a small sanity check, does tf seem to work ok? sess = tf.Session() hello = tf.constant('Hello TF!') print(sess.run(hello)) sess.close() Explanation: <a href="htt...
4,534
Given the following text description, write Python code to implement the functionality described below step by step Description: Práctica 2 - Cinemática directa y dinámica de manipuladores Una vez obtenida la dinámica del manipulador, tenemos la necesidad de construir una función f para poder simular el comportamiento...
Python Code: def f(t, x): # Se importan funciones matematicas necesarias from numpy import matrix, sin, cos # Se desenvuelven las variables que componen al estado q1, q2, q̇1, q̇2 = x # Se definen constantes del sistema g = 9.81 m1, m2, J1, J2 = 0.3, 0.2, 0.0005, 0.0002 l1, l2 = 0.4, 0.3...
4,535
Given the following text description, write Python code to implement the functionality described below step by step Description: SAP Router The following subsections show a graphical representation of the main protocol packets and how to generate them. First we need to perform some setup to import the packet classes S...
Python Code: from pysap.SAPRouter import * from IPython.display import display Explanation: SAP Router The following subsections show a graphical representation of the main protocol packets and how to generate them. First we need to perform some setup to import the packet classes: End of explanation for command in rout...
4,536
Given the following text description, write Python code to implement the functionality described below step by step Description: CRA prediction with Regression Reference link. Importing packages This packages will be used to analysis data and train the models. Step1: Reading data This command shows a sample from data...
Python Code: #enconding=utf8 import copy import pandas as pd import numpy as np import seaborn as sns import matplotlib import matplotlib.pyplot as plt from scipy import stats from scipy.stats import skew from scipy.stats.stats import pearsonr %config InlineBackend.figure_format = 'retina' #set 'png' here when working...
4,537
Given the following text description, write Python code to implement the functionality described below step by step Description: Step2: 10. Syntax — Lab exercises Preparations Introduction In this lab, we are going to use the Python Natural Language Toolkit (nltk). It has an API that allows you to create, read, and pa...
Python Code: import graphviz import nltk from nltk import Nonterminal from nltk.parse.generate import generate from nltk.tree import Tree def does_tcl_work(): Checks if Tcl is installed and works (e.g. it won't on a headless server). tree = nltk.tree.Tree('test', []) try: tree._repr_png_() r...
4,538
Given the following text description, write Python code to implement the functionality described below step by step Description: Illustration of A-projection How to deal with direction- and baseline-dependent delays when imaging using $A$-kernels. Step1: Generate baseline coordinates for a short observation with the ...
Python Code: %matplotlib inline import sys sys.path.append('../..') from matplotlib import pylab pylab.rcParams['figure.figsize'] = 10, 10 import functools import numpy import scipy import scipy.special import astropy import astropy.units as u from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt from...
4,539
Given the following text description, write Python code to implement the functionality described below step by step Description: ★ Monte Carlo Simulation To Calculate PI ★ Step1: Necesaary Function For Monte Carlo Simulation Step2: Monte Carlo Simulation (with Minimal standard random number generator) Step3: Monte ...
Python Code: # Import modules import time import math import numpy as np import scipy import matplotlib.pyplot as plt Explanation: ★ Monte Carlo Simulation To Calculate PI ★ End of explanation def linear_congruential_generator(x, a, b, m): x = (a * x + b) % m u = x / m return u, x, a, b, m def stdrand(x): ...
4,540
Given the following text description, write Python code to implement the functionality described below step by step Description: <a id='top'></a> Complex vibration modes Complex vibration modes arise in experimental research and numerical simulations with non proportional damping. In such cases the eigenproblem is non...
Python Code: import sys import numpy as np import scipy as sp import matplotlib as mpl print('System: {}'.format(sys.version)) print('numpy version: {}'.format(np.__version__)) print('scipy version: {}'.format(sp.__version__)) print('matplotlib version: {}'.format(mpl.__version__)) Explanation: <a id='top'></a> Complex...
4,541
Given the following text description, write Python code to implement the functionality described below step by step Description: Predicting Babyweight Using BigQuery ML Learning Objectives - Explore the machine learning capabilities of BigQuery - Learn how to train a linear regression model in BigQuery - Examine the T...
Python Code: PROJECT = 'cloud-training-demos' # Replace with your PROJECT BUCKET = 'cloud-training-bucket' # Replace with your BUCKET REGION = 'us-central1' # Choose an available region for Cloud MLE import os os.environ['BUCKET'] = BUCKET os.environ['PROJECT'] = PROJECT os.environ['REGION'] = REGION %%bas...
4,542
Given the following text description, write Python code to implement the functionality described below step by step Description: Implementation of time blocking for compression/serialization and de-serialization/de-compression of wavefields with Devito operators Introduction The goal of this tutorial is to prototype t...
Python Code: # NBVAL_IGNORE_OUTPUT # Install pyzfp package in the current Jupyter kernel import sys !{sys.executable} -m pip install blosc import blosc Explanation: Implementation of time blocking for compression/serialization and de-serialization/de-compression of wavefields with Devito operators Introduction The goal...
4,543
Given the following text description, write Python code to implement the functionality described below step by step Description: This page briefly goes over the regression metrics found in scikit-learn. The metrics are first calculated with NumPy and then calculated using the higher level functions available in sklear...
Python Code: from sklearn.linear_model import LinearRegression from sklearn.datasets import make_regression import matplotlib.pyplot as plt %matplotlib inline #Generate data regression_data, regression_values = make_regression(n_samples=100,n_features=1,n_informative=1,noise=10) #Set X, y_true (and shift to quadrant 1)...
4,544
Given the following text description, write Python code to implement the functionality described below step by step Description: Convergence between teaching and doing quant finance with QuantSA Quantitative finance is a broad term, here I am referring to solving pricing problems in the capital markets space (with all...
Python Code: import clr # to be able to use the C# library clr.AddReference("System.Collections") clr.AddReference(r'C:\Dev\QuantSA\QuantSA\Valuation\bin\Debug\QuantSA.General.dll') clr.AddReference(r'C:\Dev\QuantSA\QuantSA\Valuation\bin\Debug\QuantSA.Valuation.dll') from System.Collections.Generic import List from Qua...
4,545
Given the following text description, write Python code to implement the functionality described below step by step Description: Character-based LSTM Grab all Chesterton texts from Gutenberg Step1: Create the Training set Build a training and test dataset. Take 40 characters and then save the 41st character. We will ...
Python Code: from nltk.corpus import gutenberg gutenberg.fileids() text = '' for txt in gutenberg.fileids(): if 'chesterton' in txt: text += gutenberg.raw(txt).lower() chars = sorted(list(set(text))) char_indices = dict((c, i) for i, c in enumerate(chars)) indices_char = dict((i, c) for i, c in enu...
4,546
Given the following text description, write Python code to implement the functionality described below step by step Description: Загрузка данных и краткий обзор Step1: Сравним численность людей, вернувших кредит, и не вернувших его. Step2: Вспомогательные методы Step3: Задание 1. Размер кредитного лимита (LIMIT_BAL...
Python Code: data = pd.read_csv('credit_card_default_analysis.csv', index_col=0) data.head() data.shape data.describe() Explanation: Загрузка данных и краткий обзор End of explanation data.default.value_counts() Explanation: Сравним численность людей, вернувших кредит, и не вернувших его. End of explanation def make_hi...
4,547
Given the following text description, write Python code to implement the functionality described below step by step Description: Intro analysis to the dataset <a class="tocSkip"> Providing a simple visualization and classic statistical data analysis. Imports Import dependencies Step1: Import data Step2: Cleaning Dat...
Python Code: import numpy as np import pandas as pd import matplotlib.style as style style.use('ggplot') #print(style.available) import matplotlib.pyplot as plt %matplotlib inline import csv import datetime from IPython.core.display import display, HTML Explanation: Intro analysis to the dataset <a class="tocSkip"> Pro...
4,548
Given the following text description, write Python code to implement the functionality described below step by step Description: Modifying data in-place Many of MNE-Python's data objects (~mne.io.Raw, ~mne.Epochs, ~mne.Evoked, etc) have methods that modify the data in-place (either optionally or obligatorily). This ca...
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') # the preload flag loads the data into memory now raw = mne.io.read_raw_fif(sample_data_raw_file, p...
4,549
Given the following text description, write Python code to implement the functionality described below step by step Description: Data Wrangling NI House Price Index Data This is a 'messy' 'blog post' that's just a braindump of a notebook to step through NI House Price Index datasets I was playing around with. It's mo...
Python Code: from bs4 import BeautifulSoup import pandas as pd import requests # Pull the latest pages of https://www.finance-ni.gov.uk/publications/ni-house-price-index-statistical-reports and extract links base_url= 'https://www.finance-ni.gov.uk/publications/ni-house-price-index-statistical-reports' base_content = r...
4,550
Given the following text description, write Python code to implement the functionality described. Description: Minimum characters to be replaced to make frequency of all characters same Function to find the minimum operations to convert given string to another with equal frequencies of characters ; Frequency of charact...
Python Code: def minOperations(s ) : freq =[0 ] * 26 n = len(s ) for i in range(n ) : freq[ord(s[i ] ) - ord(' A ' ) ] += 1  freq . sort(reverse = True ) answer = n for i in range(1 , 27 ) : if(n % i == 0 ) : x = n // i y = 0 for j in range(i ) : y += min(freq[j ] , x )  answer = min(an...
4,551
Given the following text description, write Python code to implement the functionality described below step by step Description: Handling spectral energy distributions This notebook illustrates how to use the sed module of nmmn. This module is very convenient for dealing with spectral energy distributions (SEDs)—the d...
Python Code: %pylab inline import nmmn.sed as sed Explanation: Handling spectral energy distributions This notebook illustrates how to use the sed module of nmmn. This module is very convenient for dealing with spectral energy distributions (SEDs)—the distributions of luminosity $\nu L_\nu$ as a function of $\nu$. Oft...
4,552
Given the following text description, write Python code to implement the functionality described below step by step Description: IA369Z - Reprodutibilidade em Pesquisa Computacional. testes teste teste teste teste teste Descrição de códigos para devices e coletas Code Client Device ESP8266 Runing program language LUA....
Python Code: -- Campainha IoT - LHC - v1.1 -- ESP Inicializa pinos, Configura e Conecta no Wifi, Cria conexão TCP -- e na resposta de um "Tocou" coloca o ESP em modo DeepSleep para economizar bateria. -- Se nenhuma resposta for recebida em 15 segundos coloca o ESP em DeepSleep. led_pin = 3 status_led = gpio.LOW ip_serv...
4,553
Given the following text description, write Python code to implement the functionality described below step by step Description: <a href="https Step1: Preparing the Dataset The MNIST dataset is normalized to [0,1] range as per the explanation here Step2: Make the train and test datasets Step3: Visualization Data l...
Python Code: #pip install --force-reinstall torch==1.2.0 torchvision==0.4.0 -f https://download.pytorch.org/whl/torch_stable.html %pylab inline import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from torch.utils.data import Dataset import torch.utils.data.dataloader as dataloader impo...
4,554
Given the following text description, write Python code to implement the functionality described below step by step Description: EX 4 Step1: (二)準備測試資料 利用make_classification產生分類資料,n_features=2表示共有兩個特徵, n_informative=2 代表有兩個類別 所產生之 X Step2: (三)測試分類器並作圖 接下來這段程式碼有兩個for 迴圈,外迴圈走過三個的dataset,內迴圈則走過所有的分類器。 為求簡要說明,我們將程式碼簡略如下:...
Python Code: import numpy as np import matplotlib.pyplot as plt from matplotlib.colors import ListedColormap from sklearn.cross_validation import train_test_split from sklearn.preprocessing import StandardScaler from sklearn.datasets import make_moons, make_circles, make_classification from sklearn.neighbors import KNe...
4,555
Given the following text description, write Python code to implement the functionality described below step by step Description: Generate a Cubic Lattice with an Interpenetrating Dual Cubic Lattice OpenPNM offers several options for generating dual networks. This tutorial will outline the use of the basic CubicDual c...
Python Code: import scipy as sp import numpy as np import openpnm as op import matplotlib.pyplot as plt %matplotlib inline np.random.seed(10) wrk = op.Workspace() # Initialize a workspace object wrk.settings['loglevel'] = 50 Explanation: Generate a Cubic Lattice with an Interpenetrating Dual Cubic Lattice OpenPNM offe...
4,556
Given the following text description, write Python code to implement the functionality described below step by step Description: Single-layer Perceptron For MNIST Dataset Load the dataset Step1: Visualize a sample subset of data Step2: Side Note Step3: Tensorflow Session Step4: Evaluating the model
Python Code: import tensorflow as tf import numpy as np from tensorflow.examples.tutorials.mnist import input_data mnist_data = input_data.read_data_sets('/tmp/data', one_hot=True) Explanation: Single-layer Perceptron For MNIST Dataset Load the dataset End of explanation ## Visualize a sample subset of data import matp...
4,557
Given the following text description, write Python code to implement the functionality described below step by step Description: Optimization Exercise 1 Imports Step1: Hat potential The following potential is often used in Physics and other fields to describe symmetry breaking and is often known as the "hat potential...
Python Code: %matplotlib inline import matplotlib.pyplot as plt import numpy as np import scipy.optimize as opt Explanation: Optimization Exercise 1 Imports End of explanation def hat(x,a,b): V=-a*x**2+b*x**4 return V assert hat(0.0, 1.0, 1.0)==0.0 assert hat(0.0, 1.0, 1.0)==0.0 assert hat(1.0, 10.0, 1.0)==-9.0...
4,558
Given the following text description, write Python code to implement the functionality described below step by step Description: Cauchy noise inference example The Cauchy distribution (a Student-t with 1 degree of freedom) has fatter tails than the normal, meaning that it can be a better approximation to the noise pro...
Python Code: import pints import pints.toy as toy import pints.plot import numpy as np import matplotlib.pyplot as plt import scipy.stats x = np.linspace(-15, 15, 1000) y_c = scipy.stats.t.pdf(x, 1, loc=0, scale=1) y_t = scipy.stats.t.pdf(x, 3, loc=0, scale=1) y_norm = scipy.stats.norm.pdf(x, 0, 3) plt.plot(x, y_c, lab...
4,559
Given the following text description, write Python code to implement the functionality described below step by step Description: DataFrame object Create SparkContext and SparkSession Step1: Create a DataFrame object Creat DataFrame by reading a file Step2: Create DataFrame with createDataFrame function From an RDD E...
Python Code: # create entry points to spark try: sc.stop() except: pass from pyspark import SparkContext, SparkConf from pyspark.sql import SparkSession sc=SparkContext() spark = SparkSession(sparkContext=sc) Explanation: DataFrame object Create SparkContext and SparkSession End of explanation mtcars = spark.re...
4,560
Given the following text description, write Python code to implement the functionality described below step by step Description: Cahn-Hilliard with Primtive and Legendre Bases This example uses a Cahn-Hilliard model to compare two different bases representations to discretize the microstructure. One basis representaio...
Python Code: %matplotlib inline %load_ext autoreload %autoreload 2 import numpy as np import matplotlib.pyplot as plt Explanation: Cahn-Hilliard with Primtive and Legendre Bases This example uses a Cahn-Hilliard model to compare two different bases representations to discretize the microstructure. One basis representai...
4,561
Given the following text description, write Python code to implement the functionality described below step by step Description: Data Generators One-hot encoding classes Step1: Stratified split into train/val Step2: Generator class Step3: Generator instances Step4: PR-AUC-based Callback The callback would be used ...
Python Code: train_df = pd.read_csv('/home/dex/Desktop/ml/cloud data/train.csv') train_df.head() train_df = train_df[~train_df['EncodedPixels'].isnull()] train_df['Image'] = train_df['Image_Label'].map(lambda x: x.split('_')[0]) train_df['Class'] = train_df['Image_Label'].map(lambda x: x.split('_')[1]) classes = train_...
4,562
Given the following text description, write Python code to implement the functionality described below step by step Description: barf Step1: Gives a simple framework for defined what the different fields in the data should look like The parsing is done with third-party libraries
Python Code: import re import string class SequenceModel(object): def __init__(self, alphabet, flags=re.IGNORECASE): self.alphabet = alphabet self.pattern = re.compile(r'[{alphabet}]*$'.format(alphabet=alphabet), flags=flags) def __str__(self): return 'S...
4,563
Given the following text description, write Python code to implement the functionality described below step by step Description: Frost Number Model Link to this notebook Step1: Part 1 Adapt the base case configuration to a mean temperature of the coldest month of -13C, and of the warmest month +19.5C (the actual valu...
Python Code: # Import standard Python modules import numpy as np import pandas import matplotlib.pyplot as plt # Import the FrostNumber PyMT model import pymt.models frost_number = pymt.models.FrostNumber() Explanation: Frost Number Model Link to this notebook: https://github.com/csdms/pymt/blob/master/docs/demos/frost...
4,564
Given the following text description, write Python code to implement the functionality described below step by step Description: Chapter 3 - Generative Models This chapter introduces learning from a bayesian perspective, giving some simple examples and showing how Naive Bayes relies on this kind of theory. Bayesian co...
Python Code: coin = bernoulli(0.7) samples = coin.rvs(20) num_heads = sum(samples) num_tails = len(samples) - num_heads Explanation: Chapter 3 - Generative Models This chapter introduces learning from a bayesian perspective, giving some simple examples and showing how Naive Bayes relies on this kind of theory. Bayesian...
4,565
Given the following text problem statement, write Python code to implement the functionality described below in problem statement Problem: logistic Regression using sklearn
Python Code:: from sklearn.model_selection import train_test_split from sklearn.linear_model import LogisticRegression model = LogisticRegression() X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.25) model.fit(X_train, y_train)
4,566
Given the following text description, write Python code to implement the functionality described below step by step Description: Calculate Asym vs. Emin from bhm_e Rewriting calc_Asym_vs_emin_energies for bhm_e. Generate Asym_df for a specific dataset. P. Schuster July 18, 2018 Step1: Load data Step2: Functionalize
Python Code: import matplotlib import matplotlib.pyplot as plt import seaborn as sns sns.set(style='ticks') import sys import os import os.path import scipy.io as sio import time import numpy as np np.set_printoptions(threshold=np.nan) # print entire matrices import pandas as pd from tqdm import * sys.path.append('../s...
4,567
Given the following text problem statement, write Python code to implement the functionality described below in problem statement Problem: downloading small dataset of less than 100MB from tensorflow_datasets
Python Code:: import tensorflow_datasets as tfds ds, meta = tfds.load('citrus_leaves', with_info=True, split='train', shuffle_files=True)
4,568
Given the following text description, write Python code to implement the functionality described below step by step Description: NiftyNet provides a "CRF-RNN" layer for image segmentation, following the idea proposed in Zheng et al., Conditional Random Fields as Recurrent Neural Networks, ICCV 2015. Different from man...
Python Code: import sys niftynet_path = '/Users/demo/Documents/NiftyNet/' sys.path.insert(0, niftynet_path) from niftynet.layer.crf import CRFAsRNNLayer import nibabel as nib import numpy as np import matplotlib.pyplot as plt import tensorflow as tf ct_image = nib.load('100_CT.nii').get_data() logits = nib.load('100__n...
4,569
Given the following text description, write Python code to implement the functionality described below step by step Description: Predicting sentiment from product reviews Fire up GraphLab Create Step1: Read some product review data Loading reviews for a set of baby products. Step2: Let's explore this data together D...
Python Code: import graphlab; Explanation: Predicting sentiment from product reviews Fire up GraphLab Create End of explanation products = graphlab.SFrame('amazon_baby.gl/') Explanation: Read some product review data Loading reviews for a set of baby products. End of explanation products.head() Explanation: Let's explo...
4,570
Given the following text description, write Python code to implement the functionality described below step by step Description: Advanced Notebook Step1: BQPlot Examples here are shamelessly stolen from the amazing Step2: ipyvolume
Python Code: %matplotlib inline import numpy as np import pandas as pd from pandas.tools.plotting import scatter_matrix from sklearn.datasets import load_boston import matplotlib as mpl import matplotlib.pyplot as plt import seaborn as sns sns.set_context('poster') sns.set_style('whitegrid') plt.rcParams['figure.figsiz...
4,571
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> Geotagging WiFi access points <div class="alert alert-warning"> **This notebook contains advanced exercises that are only applicable to s...
Python Code: # Load relevant libraries. from os import path import pandas as pd import numpy as np import folium import glob from tqdm import tqdm import random %matplotlib inline # Load custom modules. import sys sys.path.append('..') from utils import getmedian, haversine from utils import llaToECEF as coords_to_geom...
4,572
Given the following text description, write Python code to implement the functionality described below step by step Description: SciPy - Library of scientific algorithms for Python J.R. Johansson (jrjohansson at gmail.com) The latest version of this IPython notebook lecture is available at http Step1: Introduction Th...
Python Code: # what is this line all about? Answer in lecture 4 %matplotlib inline import matplotlib.pyplot as plt from IPython.display import Image Explanation: SciPy - Library of scientific algorithms for Python J.R. Johansson (jrjohansson at gmail.com) The latest version of this IPython notebook lecture is available...
4,573
Given the following text description, write Python code to implement the functionality described below step by step Description: 计算传播与机器学习 王成军 wangchengjun@nju.edu.cn 计算传播网 http Step1: 训练集和测试集 Step2: 交叉验证 cross-validation k-fold CV, the training set is split into k smaller sets (other approaches are described below,...
Python Code: %matplotlib inline import sklearn from sklearn import datasets from sklearn import linear_model import matplotlib.pyplot as plt from sklearn.metrics import classification_report from sklearn.preprocessing import scale # boston data boston = datasets.load_boston() y = boston.target X = boston.data ' '.join(...
4,574
Given the following text description, write Python code to implement the functionality described below step by step Description: ABU量化系统使用文档 <center> <img src="./image/abu_logo.png" alt="" style="vertical-align Step1: 上一节使用AbuFactorBuyBreak和AbuFactorSellBreak且混入基本止盈止损策略AbuFactorAtrNStop, 风险控制止损策略AbuFactorPreA...
Python Code: from __future__ import print_function from __future__ import division import warnings warnings.filterwarnings('ignore') warnings.simplefilter('ignore') import numpy as np import pandas as pd import matplotlib.pyplot as plt %matplotlib inline import os import sys # 使用insert 0即只使用github,避免交叉使用了pip安装的abupy,导致...
4,575
Given the following text description, write Python code to implement the functionality described below step by step Description: How to plot topomaps the way EEGLAB does If you have previous EEGLAB experience you may have noticed that topomaps (topoplots) generated using MNE-Python look a little different from those c...
Python Code: # Authors: Mikołaj Magnuski <mmagnuski@swps.edu.pl> # # License: BSD (3-clause) import numpy as np from matplotlib import pyplot as plt import mne print(__doc__) Explanation: How to plot topomaps the way EEGLAB does If you have previous EEGLAB experience you may have noticed that topomaps (topoplots) gener...
4,576
Given the following text description, write Python code to implement the functionality described below step by step Description: Loading large datasets Learning Objectives - Understand difference between loading data entirely in-memory and loading in batches from disk - Practice loading a .csv file from disk in ba...
Python Code: import tensorflow as tf import shutil print(tf.__version__) tf.enable_eager_execution() Explanation: Loading large datasets Learning Objectives - Understand difference between loading data entirely in-memory and loading in batches from disk - Practice loading a .csv file from disk in batches using the ...
4,577
Given the following text problem statement, write Python code to implement the functionality described below in problem statement Problem: Linear Regression using sklearn
Python Code:: from sklearn.model_selection import train_test_split from sklearn.linear_model import LinearRegression X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.25) model = LinearRegression() model.fit(X_train, y_train)
4,578
Given the following text description, write Python code to implement the functionality described below step by step Description: Gaussian Mixture Model with ADVI Here, we describe how to use ADVI for inference of Gaussian mixture model. First, we will show that inference with ADVI does not need to modify the stochasti...
Python Code: %matplotlib inline import theano theano.config.floatX = 'float64' import pymc3 as pm from pymc3 import Normal, Metropolis, sample, MvNormal, Dirichlet, \ DensityDist, find_MAP, NUTS, Slice import theano.tensor as tt from theano.tensor.nlinalg import det import numpy as np import matplotlib.pyplot as pl...
4,579
Given the following text description, write Python code to implement the functionality described below step by step Description: <img src='rc_logo.png' style="height Step1: Locally and Remote Run locally Connect to the cloud (e.g AWS) Connect to supercomputer (e.g. XSEDE Resource) Add compute power Step2: Plot a His...
Python Code: 2+4 print("hello") print("Hello world!") Explanation: <img src='rc_logo.png' style="height:75px"> Efficient Data Analysis with the IPython Notebook <img src='data_overview.png' style="height:500px"> Objectives Become familiar with the IPython Notebook. Introduce the IPython landscape. Getting started with ...
4,580
Given the following text description, write Python code to implement the functionality described below step by step Description: Classifiers A classifier is a function from an asset and a moment in time to a categorical output such as a string or integer label Step1: Previously, we saw that the latest attribute produ...
Python Code: from quantopian.pipeline.data import Fundamentals # Since the underlying data of Fundamentals.exchange_id # is of type string, .latest returns a Classifier exchange = Fundamentals.exchange_id.latest Explanation: Classifiers A classifier is a function from an asset and a moment in time to a categorical outp...
4,581
Given the following text description, write Python code to implement the functionality described below step by step Description: To build an automaton, simply call translate() with a formula, and a list of options to characterize the automaton you want (those options have the same name as the long options name of the ...
Python Code: a = spot.translate('(a U b) & GFc & GFd', 'BA', 'complete'); a Explanation: To build an automaton, simply call translate() with a formula, and a list of options to characterize the automaton you want (those options have the same name as the long options name of the ltl2tgba tool, and they can be abbreviate...
4,582
Given the following text description, write Python code to implement the functionality described below step by step Description: Test with toy model Step1: We'll define the modifier at two different temperatures, and we'll run each for 10000 snapshots. Note also that our two atoms have different masses. Step2: Withi...
Python Code: topology = paths.engines.toy.Topology(n_spatial=3, n_atoms=2, masses=np.array([2.0, 8.0]), pes=None) initial_snapshot = paths.engines.toy.Snapshot( coordinates=np.array([[0.0, 0.0, 0.0],...
4,583
Given the following text description, write Python code to implement the functionality described below step by step Description: Compute the power spectral density of raw data This script shows how to compute the power spectral density (PSD) of measurements on a raw dataset. It also show the effect of applying SSP to ...
Python Code: # Authors: Alexandre Gramfort <alexandre.gramfort@inria.fr> # Martin Luessi <mluessi@nmr.mgh.harvard.edu> # Eric Larson <larson.eric.d@gmail.com> # License: BSD (3-clause) import numpy as np import matplotlib.pyplot as plt import mne from mne import io, read_proj, read_selection from mne....
4,584
Given the following text description, write Python code to implement the functionality described below step by step Description: Running Tune experiments with Dragonfly In this tutorial we introduce Dragonfly, while running a simple Ray Tune experiment. Tune’s Search Algorithms integrate with Dragonfly and, as a resul...
Python Code: # !pip install ray[tune] !pip install dragonfly-opt==0.1.6 Explanation: Running Tune experiments with Dragonfly In this tutorial we introduce Dragonfly, while running a simple Ray Tune experiment. Tune’s Search Algorithms integrate with Dragonfly and, as a result, allow you to seamlessly scale up a Dragonf...
4,585
Given the following text description, write Python code to implement the functionality described below step by step Description: Neural Networks with TensorFlow and Keras Step1: First Step Step2: Second Step Step3: What is the intuition here Step4: No overfitting, probably as good as it gets Does this look like yo...
Python Code: import warnings warnings.filterwarnings('ignore') %matplotlib inline %pylab inline import pandas as pd print(pd.__version__) import tensorflow as tf tf.logging.set_verbosity(tf.logging.ERROR) print(tf.__version__) import keras print(keras.__version__) Explanation: Neural Networks with TensorFlow and Keras ...
4,586
Given the following text description, write Python code to implement the functionality described below step by step Description: Brewing Logistic Regression then Going Deeper While Caffe is made for deep networks it can likewise represent "shallow" models like logistic regression for classification. We'll do simple lo...
Python Code: import numpy as np import matplotlib.pyplot as plt %matplotlib inline import os os.chdir('..') import sys sys.path.insert(0, './python') import caffe import os import h5py import shutil import tempfile import sklearn import sklearn.datasets import sklearn.linear_model import pandas as pd Explanation: Brewi...
4,587
Given the following text description, write Python code to implement the functionality described below step by step Description: Data Science Tutorial Now that we've covered some Python basics, we will begin a tutorial going through many tasks a data scientist may perform. We will obtain real world data and go throug...
Python Code: def download_file(url, local_filename): import requests # stream = True allows downloading of large files; prevents loading entire file into memory r = requests.get(url, stream = True) with open(local_filename, 'wb') as f: for chunk in r.iter_content(chunk_size=1024): ...
4,588
Given the following text description, write Python code to implement the functionality described below step by step Description: First, I'm going to define a function that will print the power (watts per square meter) that the earth would receive from the sun if there were no atmosphere. Step1: Now I'm going to take ...
Python Code: def Solar_Power_Calculator(Day_Of_Year,Lattitude,Hour_of_Day): '''This function will tell you how much power the sun is radiating on one square meter of the earth when it is sunny in any location in the world at any time. Inputs: Day_Of_Year, Lattitude, Hour_of_Day Output: Power (watts)''' ...
4,589
Given the following text description, write Python code to implement the functionality described below step by step Description: Dénes Csala MCC, 2022 Based on Elements of Data Science (Allen B. Downey, 2021) and Python Data Science Handbook (Jake VanderPlas, 2018) License Step1: Motivating Random Forests Step2: T...
Python Code: %matplotlib inline import numpy as np import matplotlib.pyplot as plt from scipy import stats plt.style.use('seaborn') Explanation: Dénes Csala MCC, 2022 Based on Elements of Data Science (Allen B. Downey, 2021) and Python Data Science Handbook (Jake VanderPlas, 2018) License: MIT Supervised Learning In-...
4,590
Given the following text description, write Python code to implement the functionality described below step by step Description: Les déterminants du choix de contraception en Indonésie Présentation littéraire Selon de récentes estimations, l'Indonésie a une population d'environ 255 millions d'habitants. Petit à petit ...
Python Code: %%javascript $.getScript('https://kmahelona.github.io/ipython_notebook_goodies/ipython_notebook_toc.js') Explanation: Les déterminants du choix de contraception en Indonésie Présentation littéraire Selon de récentes estimations, l'Indonésie a une population d'environ 255 millions d'habitants. Petit à petit...
4,591
Given the following text description, write Python code to implement the functionality described below step by step Description: ES-DOC CMIP6 Model Properties - Seaice MIP Era Step1: Document Authors Set document authors Step2: Document Contributors Specify document contributors Step3: Document Publication Specify ...
Python Code: # DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'mohc', 'hadgem3-gc31-ll', 'seaice') Explanation: ES-DOC CMIP6 Model Properties - Seaice MIP Era: CMIP6 Institute: MOHC Source ID: HADGEM3-GC31-LL Topic: Seaice Sub-Topics: Dynamics, T...
4,592
Given the following text description, write Python code to implement the functionality described below step by step Description: Example for bulk function management Shows Step1: Demonstration model Step2: NOTE Step3: The result of the function call is very important. It tells us what was created and the names. The...
Python Code: import veneer v = veneer.Veneer() %matplotlib inline Explanation: Example for bulk function management Shows: Creating multiple modelled variables Creating multiple functions of the same form, each using one of the newly created modelled variables Applying multiple functions End of explanation v.network()....
4,593
Given the following text description, write Python code to implement the functionality described below step by step Description: Cross Country Production Data This program extracts particular series from the Penn World Tables (PWT). Data and documentation for the PWT are available at https Step1: Construct data sets ...
Python Code: # Set the current value of the PWT data file current_pwt_file = 'pwt100.xlsx' # Import data from local source or download if not present if os.path.exists('../xslx/pwt100.xlsx'): info = pd.read_excel('../xslx/'+current_pwt_file,sheet_name='Info',header=None) legend = pd.read_excel('../xslx/'+curren...
4,594
Given the following text description, write Python code to implement the functionality described below step by step Description: Short demo of psydata functions Step1: I'll demo some functions here using a dataset I simulated earlier. Step2: Bin bernoulli trials, compute binomial statistics Compute binomial trials f...
Python Code: import seaborn as sns import psyutils as pu %load_ext autoreload %autoreload 2 %matplotlib inline sns.set_style("white") sns.set_style("ticks") Explanation: Short demo of psydata functions End of explanation # load data: dat = pu.psydata.load_psy_data() dat.info() Explanation: I'll demo some functions here...
4,595
Given the following text description, write Python code to implement the functionality described below step by step Description: Ejemplo práctico de uso de diccionarios y for loops ( y gráficas). Comportamiento de neuronas. Utilizando un modelo matemático (modelo de electrodifusión). El modelo describe la actividad el...
Python Code: %matplotlib inline Explanation: Ejemplo práctico de uso de diccionarios y for loops ( y gráficas). Comportamiento de neuronas. Utilizando un modelo matemático (modelo de electrodifusión). El modelo describe la actividad eléctrica de una neurona, al variar los distintos parámetros. <br /> Yo tengo un sistem...
4,596
Given the following text description, write Python code to implement the functionality described below step by step Description: GA360 Segmentology GA360 funnel analysis using Census data. License Copyright 2020 Google LLC, Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file excep...
Python Code: !pip install git+https://github.com/google/starthinker Explanation: GA360 Segmentology GA360 funnel analysis using Census data. 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 ...
4,597
Given the following text description, write Python code to implement the functionality described below step by step Description: DKRZ CMIP6 submission form for ESGF data publication General Information (to be completed based on official CMIP6 references) Data to be submitted for ESGF data publication must follow the r...
Python Code: from dkrz_forms import form_widgets form_widgets.show_status('form-submission') Explanation: DKRZ CMIP6 submission form for ESGF data publication General Information (to be completed based on official CMIP6 references) Data to be submitted for ESGF data publication must follow the rules outlined in the CM...
4,598
Given the following text description, write Python code to implement the functionality described below step by step Description: 1. Linear Regression Step1: First let's add the new features. Step2: Step3: 1.1 Training the Model 1.1.1 Correlation Matrix Step4: Should I have multiplied those features by num_answers...
Python Code: import pandas as pd import json json_data = open('/home/yohna/Documents/quora_challenges/views/sample/input00.in') # Edit this to where you have put the input00.in file data = [] for line in json_data: data.append(json.loads(line)) data.remove(9000) data.remove(1000) df = pd.DataFrame(data) df['anonymo...
4,599
Given the following text description, write Python code to implement the functionality described below step by step Description: Classifiers A classifier is a function from an asset and a moment in time to a categorical output such as a string or integer label Step1: Previously, we saw that the latest attribute produ...
Python Code: from quantopian.pipeline.data import morningstar # Since the underlying data of morningstar.share_class_reference.exchange_id # is of type string, .latest returns a Classifier exchange = morningstar.share_class_reference.exchange_id.latest Explanation: Classifiers A classifier is a function from an asset a...