Unnamed: 0
int64
0
16k
text_prompt
stringlengths
110
62.1k
code_prompt
stringlengths
37
152k
4,100
Given the following text description, write Python code to implement the functionality described below step by step Description: Traverse a Square - Part 2 - Variables In this notebook, we will introduce one of the most powerful ideas in programming Step1: Try changing the message in the previous code cell and re-run...
Python Code: # Create the message variable and assign the value "Hello World" to it message="Hello World" # Use the variable in a print statement # The print statement retrieves the value assigned to the variable and displays the value print(message) Explanation: Traverse a Square - Part 2 - Variables In this notebook,...
4,101
Given the following text description, write Python code to implement the functionality described below step by step Description: CS229 Homework 1 Problem 1 In this exercise we use logistic regression to construct a decision boundary for a binary classification problem. In order to do so, we must first load the data. S...
Python Code: import numpy as np import pandas as pd import logistic_regression as lr Explanation: CS229 Homework 1 Problem 1 In this exercise we use logistic regression to construct a decision boundary for a binary classification problem. In order to do so, we must first load the data. End of explanation X = np.loadtxt...
4,102
Given the following text description, write Python code to implement the functionality described below step by step Description: JLab ML Lunch 2 - Data Exploration Second ML challenge hosted On October 30th, a test dataset will be released, and predictions must be submitted within 24 hours Let's take a look at the tra...
Python Code: %matplotlib widget import pandas as pd import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import axes3d import imageio Explanation: JLab ML Lunch 2 - Data Exploration Second ML challenge hosted On October 30th, a test dataset will be released, and predictions must be submitted wit...
4,103
Given the following text description, write Python code to implement the functionality described below step by step Description: Análisis de los datos obtenidos Uso de ipython para el análsis y muestra de los datos obtenidos durante la producción.Se implementa un regulador experto. Los datos analizados son del día 13 ...
Python Code: #Importamos las librerías utilizadas import numpy as np import pandas as pd import seaborn as sns #Mostramos las versiones usadas de cada librerías print ("Numpy v{}".format(np.__version__)) print ("Pandas v{}".format(pd.__version__)) print ("Seaborn v{}".format(sns.__version__)) #Abrimos el fichero csv co...
4,104
Given the following text description, write Python code to implement the functionality described below step by step Description: N2 - Eurocode 8, CEN (2005) This simplified nonlinear procedure for the estimation of the seismic response of structures uses capacity curves and inelastic spectra. This method has been deve...
Python Code: import N2Method from rmtk.vulnerability.common import utils %matplotlib inline Explanation: N2 - Eurocode 8, CEN (2005) This simplified nonlinear procedure for the estimation of the seismic response of structures uses capacity curves and inelastic spectra. This method has been developed to be used in comb...
4,105
Given the following text description, write Python code to implement the functionality described below step by step Description: Quality Controlling Saildrone T/S Objective Step1: First, learn about the data Load the data Step2: Let's learn about this dataset, starting from the attributes. Step3: Great, it follows ...
Python Code: import xarray as xr from cotede.qc import ProfileQC Explanation: Quality Controlling Saildrone T/S Objective: This notebook shows how to use CoTeDe to evaluate temperature and salinity measured along-track from a Saildrone. The nature of this dataset is similar to a Thermosalinograph (TSG) on vessels of op...
4,106
Given the following text description, write Python code to implement the functionality described below step by step Description: Hyperparameter optimization using pyGPGO by José Jiménez (Oct 18, 2017) In this tutorial, we will learn the basics of the Bayesian optimization (BO) framework through a step-by-step example ...
Python Code: import numpy as np from sklearn.datasets import make_moons np.random.seed(20) X, y = make_moons(n_samples = 200, noise = 0.3) # Data and target Explanation: Hyperparameter optimization using pyGPGO by José Jiménez (Oct 18, 2017) In this tutorial, we will learn the basics of the Bayesian optimization (BO) f...
4,107
Given the following text description, write Python code to implement the functionality described below step by step Description: The Step1: Load and inspect example data This data set contains source estimation data from an audio visual task. It has been mapped onto the inflated cortical surface representation obtai...
Python Code: import os from mne import read_source_estimate from mne.datasets import sample print(__doc__) # Paths to example data sample_dir_raw = sample.data_path() sample_dir = os.path.join(sample_dir_raw, 'MEG', 'sample') subjects_dir = os.path.join(sample_dir_raw, 'subjects') fname_stc = os.path.join(sample_dir, '...
4,108
Given the following text description, write Python code to implement the functionality described below step by step Description: <p> <img src="http Step1: defs Step2: testing Step3: $\mathfrak{p}={1^{j+1}0^{j}}$ Step4: $\mathfrak{p}={0^{j+1}1^{j}}$ Step5: $\mathfrak{p}={1^{j}0^{j}}$ Step6: $\mathfrak{p}={(10)}^{...
Python Code: from sympy import * from IPython.display import Markdown, Latex from oeis import oeis_search init_printing() %run ~/Developer/working-copies/programming-contests/competitive-programming/python-libs/oeis.py Explanation: <p> <img src="http://www.cerm.unifi.it/chianti/images/logo%20unifi_positivo.jpg" ...
4,109
Given the following text description, write Python code to implement the functionality described below step by step Description: Cliff Walking Problem solved with TD(0) Algorithms Step1: The OpenAI Gym toolkit includes the below environment for the "Cliff-Walking" problem Step2: Load the Cliff-Walking environment St...
Python Code: import gym import random import numpy as np import pandas as pd import seaborn as sns from matplotlib import pyplot as plt from collections import OrderedDict Explanation: Cliff Walking Problem solved with TD(0) Algorithms: Implementation & Comparisons 1. Load Libraries & Define Environment End of explanat...
4,110
Given the following text description, write Python code to implement the functionality described below step by step Description: FDMS TME3 Kaggle How Much Did It Rain? II Florian Toque & Paul Willot Dear professor Denoyer... Warning This is an early version of our entry for the Kaggle challenge It's still very mes...
Python Code: # from __future__ import exam_success from __future__ import absolute_import from __future__ import print_function %matplotlib inline import sklearn import matplotlib.pyplot as plt import seaborn as sns import numpy as np import random import pandas as pd # Sk cheats from sklearn.cross_validation import cr...
4,111
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', 'ncc', 'sandbox-2', 'toplevel') Explanation: ES-DOC CMIP6 Model Properties - Toplevel MIP Era: CMIP6 Institute: NCC Source ID: SANDBOX-2 Sub-Topics: Radiative Forcings. Properties: 85...
4,112
Given the following text description, write Python code to implement the functionality described below step by step Description: Yahoo API Example This notebook is an example of using yahoo api to get fantasy sports data. Step1: Prerequisite First we need to create a Yahoo APP at https Step2: Step 1 Step3: Step 2 S...
Python Code: from rauth import OAuth2Service import webbrowser import json Explanation: Yahoo API Example This notebook is an example of using yahoo api to get fantasy sports data. End of explanation clientId= "dj0yJmk9M3gzSWJZYzFmTWZtJmQ9WVdrOU9YcGxTMHB4TXpnbWNHbzlNQS0tJnM9Y29uc3VtZXJzZWNyZXQmeD1kZg--" clinetSecrect="...
4,113
Given the following text description, write Python code to implement the functionality described. Description: Find if given matrix is Toeplitz or not Python3 program to check whether given matrix is a Toeplitz matrix or not ; Function to check if all elements present in descending diagonal starting from position ( i ,...
Python Code: N = 5 M = 4 def checkDiagonal(mat , i , j ) : res = mat[i ][j ] i += 1 j += 1 while(i < N and j < M ) : if(mat[i ][j ] != res ) : return False  i += 1 j += 1  return True  def isToeplitz(mat ) : for j in range(M ) : if not(checkDiagonal(mat , 0 , j ) ) : return False ...
4,114
Given the following text description, write Python code to implement the functionality described below step by step Description: 01 Step1: Set all graphics from matplotlib to display inline Step2: Read the csv in (it should be UTF-8 already so you don't have to worry about encoding), save it with the proper boring n...
Python Code: import pandas as pd Explanation: 01: Building a pandas Cheat Sheet, Part 1 Use the csv I've attached to answer the following questions: Import pandas with the right name End of explanation %matplotlib inline Explanation: Set all graphics from matplotlib to display inline End of explanation df = pd.read_csv...
4,115
Given the following text description, write Python code to implement the functionality described below step by step Description: <h1>Demand forecasting with BigQuery and TensorFlow</h1> In this notebook, we will develop a machine learning model to predict the demand for taxi cabs in New York. To develop the model, we ...
Python Code: !sudo pip install --user pandas-gbq !pip install --user pandas_gbq !pip install tensorflow==1.15.3 Explanation: <h1>Demand forecasting with BigQuery and TensorFlow</h1> In this notebook, we will develop a machine learning model to predict the demand for taxi cabs in New York. To develop the model, we will ...
4,116
Given the following text description, write Python code to implement the functionality described below step by step Description: Copyright 2020 The TensorFlow Authors. Step1: Introduction to gradients and automatic differentiation <table class="tfo-notebook-buttons" align="left"> <td> <a target="_blank" href="h...
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...
4,117
Given the following text description, write Python code to implement the functionality described below step by step Description: Twitter + Watson Tone Analyzer Sample Notebook In this sample notebook, we show how to load and analyze data from the Twitter + Watson Tone Analyzer Spark sample application (code can be fou...
Python Code: # Import SQLContext and data types from pyspark.sql import SQLContext from pyspark.sql.types import * Explanation: Twitter + Watson Tone Analyzer Sample Notebook In this sample notebook, we show how to load and analyze data from the Twitter + Watson Tone Analyzer Spark sample application (code can be found...
4,118
Given the following text description, write Python code to implement the functionality described below step by step Description: ES-DOC CMIP6 Model Properties - Land MIP Era Step1: Document Authors Set document authors Step2: Document Contributors Specify document contributors Step3: Document Publication Specify do...
Python Code: # DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'miroc', 'miroc-es2h', 'land') Explanation: ES-DOC CMIP6 Model Properties - Land MIP Era: CMIP6 Institute: MIROC Source ID: MIROC-ES2H Topic: Land Sub-Topics: Soil, Snow, Vegetation, E...
4,119
Given the following text description, write Python code to implement the functionality described below step by step Description: Multi-layer Perceptron (MLP) Neural Network Implementation in Padasip - Basic Examples This tutorial explains how to use MLP through several examples. Lets start with importing Padasip. In t...
Python Code: import numpy as np import matplotlib.pylab as plt import padasip as pa %matplotlib inline plt.style.use('ggplot') # nicer plots np.random.seed(52102) # always use the same random seed to make results comparable Explanation: Multi-layer Perceptron (MLP) Neural Network Implementation in Padasip - Basic Examp...
4,120
Given the following text problem statement, write Python code to implement the functionality described below in problem statement Problem: I am struggling with the basic task of constructing a DataFrame of counts by value from a tuple produced by np.unique(arr, return_counts=True), such as:
Problem: import numpy as np import pandas as pd np.random.seed(123) birds = np.random.choice(['African Swallow', 'Dead Parrot', 'Exploding Penguin'], size=int(5e4)) someTuple = np.unique(birds, return_counts=True) def g(someTuple): return pd.DataFrame(np.column_stack(someTuple),columns=['birdType','birdCount']) res...
4,121
Given the following text description, write Python code to implement the functionality described below step by step Description: Copyright 2019 The TensorFlow Hub Authors. Licensed under the Apache License, Version 2.0 (the "License"); Step3: Fast Style Transfer for Arbitrary Styles <table class="tfo-notebook-buttons...
Python Code: # Copyright 2019 The TensorFlow Hub Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless re...
4,122
Given the following text problem statement, write Python code to implement the functionality described below in problem statement Problem: Find permutation of numbers upto N with a specific sum in a specific range Function to check if sum is possible with remaining numbers ; Stores the minimum sum possible with x nu...
Python Code:: def possible(x,S,N): minSum = (x * (x + 1))//2 maxSum = (x * ((2 * N) - x + 1))//2 if(S < minSum or S > maxSum): return False return True def findPermutation(N ,L ,R ,S ): x = R - L + 1 if (not possible( x , S , N)) : print(" - 1") return else : v = [] for i in range(N , 0 , ...
4,123
Given the following text description, write Python code to implement the functionality described below step by step Description: Building a text classification model with TF Hub In this notebook, we'll walk you through building a model to predict the genres of a movie given its description. The emphasis here is not on...
Python Code: import os import numpy as np import pandas as pd import tensorflow as tf import tensorflow_hub as hub import json import pickle import urllib from sklearn.preprocessing import MultiLabelBinarizer print(tf.__version__) Explanation: Building a text classification model with TF Hub In this notebook, we'll wal...
4,124
Given the following text description, write Python code to implement the functionality described below step by step Description: Analyzing the Air Pollution Decrease Caused by the Global COVID-19 Pandemic Last December 2019, we heard about the first COVID-19 cases in China. Now, three months later, the WHO has officia...
Python Code: %matplotlib notebook %matplotlib inline import numpy as np import dh_py_access.lib.datahub as datahub import xarray as xr import matplotlib.pyplot as plt import ipywidgets as widgets from mpl_toolkits.basemap import Basemap,shiftgrid import dh_py_access.package_api as package_api import matplotlib.colors a...
4,125
Given the following text description, write Python code to implement the functionality described below step by step Description: TOC trends 2015 Step1: Woohoo - that was much easier than expected! Right, on with the data cleaning, staring with the easiest stuff first... 2. Remove some of US sites from the analysis Th...
Python Code: # Create connection # Use custom RESA2 function to connect to db r2_func_path = r'C:\Data\James_Work\Staff\Heleen_d_W\ICP_Waters\Upload_Template\useful_resa2_code.py' resa2 = imp.load_source('useful_resa2_code', r2_func_path) engine, conn = resa2.connect_to_resa2() # Test SQL statement sql = ('SELECT proje...
4,126
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: Scrape swear word list We scrape swear words from the web from the site Step4: Testing TextBlob I don't really like TextBlob as it tries to be "nice", but lacks a lot of basic functi...
Python Code: import string import os import requests from fake_useragent import UserAgent from lxml import html def requests_get(url): ua = UserAgent().random return requests.get(url, headers={'User-Agent': ua}) def get_swear_words(save_file='swear-words.txt'): Scrapes a comprehensive list o...
4,127
Given the following text description, write Python code to implement the functionality described below step by step Description: VARMAX models This is a brief introduction notebook to VARMAX models in Statsmodels. The VARMAX model is generically specified as Step1: Model specification The VARMAX class in Statsmodels ...
Python Code: %matplotlib inline import numpy as np import pandas as pd import statsmodels.api as sm import matplotlib.pyplot as plt dta = sm.datasets.webuse('lutkepohl2', 'https://www.stata-press.com/data/r12/') dta.index = dta.qtr endog = dta.loc['1960-04-01':'1978-10-01', ['dln_inv', 'dln_inc', 'dln_consump']] Explan...
4,128
Given the following text description, write Python code to implement the functionality described below step by step Description: PMOD ALS Sensor demonstration This demonstration shows how to use the PmodALS. You will also see how to plot a graph using matplotlib. The PmodALS and a light source is required. E.g. cell p...
Python Code: from pynq import Overlay Overlay("base.bit").download() from pynq.iop import Pmod_ALS from pynq.iop import PMODB # ALS sensor is on PMODB my_als = Pmod_ALS(PMODB) my_als.read() Explanation: PMOD ALS Sensor demonstration This demonstration shows how to use the PmodALS. You will also see how to plot a graph ...
4,129
Given the following text description, write Python code to implement the functionality described below step by step Description: Training, Tuning and Deploying a PyTorch Text Classification Model on Vertex AI Fine-tuning pre-trained BERT model for sentiment classification task Overview This example is inspired from To...
Python Code: import os # The Google Cloud Notebook product has specific requirements IS_GOOGLE_CLOUD_NOTEBOOK = os.path.exists("/opt/deeplearning/metadata/env_version") # Google Cloud Notebook requires dependencies to be installed with '--user' USER_FLAG = "" if IS_GOOGLE_CLOUD_NOTEBOOK: USER_FLAG = "--user" !pip -...
4,130
Given the following text description, write Python code to implement the functionality described below step by step Description: Copyright 2020 The TensorFlow Authors. Step1: Fairness Indicators on TF-Hub Text Embeddings <table class="tfo-notebook-buttons" align="left"> <td> <a target="_blank" href="https Step2...
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...
4,131
Given the following text description, write Python code to implement the functionality described below step by step Description: How we solve a model defined by the IndShockConsumerType class The IndShockConsumerType reprents the work-horse consumption savings model with temporary and permanent shocks to income, finit...
Python Code: from HARK.ConsumptionSaving.ConsIndShockModel import IndShockConsumerType, init_lifecycle import numpy as np import matplotlib.pyplot as plt LifecycleExample = IndShockConsumerType(**init_lifecycle) LifecycleExample.cycles = 1 # Make this consumer live a sequence of periods exactly once LifecycleExample.so...
4,132
Given the following text description, write Python code to implement the functionality described below step by step Description: <a href='http Step1: 1. Create a Doc object from the file peterrabbit.txt<br> HINT Step2: 2. For every token in the third sentence, print the token text, the POS tag, the fine-grained TAG ...
Python Code: # RUN THIS CELL to perform standard imports: import spacy nlp = spacy.load('en_core_web_sm') from spacy import displacy Explanation: <a href='http://www.pieriandata.com'> <img src='../Pierian_Data_Logo.png' /></a> Parts of Speech Assessment For this assessment we'll be using the short story The Tale of Pet...
4,133
Given the following text description, write Python code to implement the functionality described below step by step Description: ConvNet Let's get the data and training interface from where we left in the last notebook. Jump_to lesson 10 video Step1: Batchnorm Custom Let's start by building our own BatchNorm layer fr...
Python Code: x_train,y_train,x_valid,y_valid = get_data() x_train,x_valid = normalize_to(x_train,x_valid) train_ds,valid_ds = Dataset(x_train, y_train),Dataset(x_valid, y_valid) nh,bs = 50,512 c = y_train.max().item()+1 loss_func = F.cross_entropy data = DataBunch(*get_dls(train_ds, valid_ds, bs), c) mnist_view = view_...
4,134
Given the following text description, write Python code to implement the functionality described below step by step Description: Employee scheduling pyschedule can be used for employee scheduling. The following example is motivated by instances from Step1: Solving without shift requests First build the scenario witho...
Python Code: employee_names = ['A','B','C','D','E','F','G','H'] n_days = 14 # number of days days = list(range(n_days)) max_seq = 5 # max number of consecutive shifts min_seq = 2 # min sequence without gaps max_work = 10 # max total number of shifts min_work = 7 # min total number of shifts max_weekend = 3 # max number...
4,135
Given the following text description, write Python code to implement the functionality described below step by step Description: 1.1 Reading data from a csv file You can read data from a CSV file using the read_csv function. By default, it assumes that the fields are comma-separated. We're going to be looking some cyc...
Python Code: broken_df = pd.read_csv('../data/bikes.csv') # Look at the first 3 rows broken_df[:3] Explanation: 1.1 Reading data from a csv file You can read data from a CSV file using the read_csv function. By default, it assumes that the fields are comma-separated. We're going to be looking some cyclist data from Mon...
4,136
Given the following text description, write Python code to implement the functionality described below step by step Description: Abstract This paper introduces PyEDA, a Python library for electronic design automation (EDA). PyEDA provides both a high level interface to the representation of Boolean functions, and blaz...
Python Code: a, b, c, d = map(exprvar, 'abcd') Explanation: Abstract This paper introduces PyEDA, a Python library for electronic design automation (EDA). PyEDA provides both a high level interface to the representation of Boolean functions, and blazingly-fast C extensions for fundamental algorithms where performance i...
4,137
Given the following text description, write Python code to implement the functionality described below step by step Description: Visualizing Evoked data This tutorial shows the different visualization methods for Step1: Instead of creating the ~mne.Evoked object from an ~mne.Epochs object, we'll load an existing ~mne...
Python Code: import os import numpy as np import mne Explanation: Visualizing Evoked data This tutorial shows the different visualization methods for :class:~mne.Evoked objects. :depth: 2 As usual we'll start by importing the modules we need: End of explanation sample_data_folder = mne.datasets.sample.data_path() sa...
4,138
Given the following text description, write Python code to implement the functionality described below step by step Description: Interactions and ANOVA Note Step1: Take a look at the data Step2: Fit a linear model Step3: Have a look at the created design matrix Step4: Or since we initially passed in a DataFrame, w...
Python Code: %matplotlib inline from __future__ import print_function from statsmodels.compat import urlopen import numpy as np np.set_printoptions(precision=4, suppress=True) import statsmodels.api as sm import pandas as pd pd.set_option("display.width", 100) import matplotlib.pyplot as plt from statsmodels.formula.ap...
4,139
Given the following text description, write Python code to implement the functionality described below step by step Description: Copyright 2018 The TensorFlow Hub Authors. Licensed under the Apache License, Version 2.0 (the "License"); Step1: 如何使用 TF-Hub 构建简单的文本分类器 注:本教程使用已弃用的 TensorFlow 1 功能。有关完成此任务的新方式,请参阅 TensorFl...
Python Code: # Copyright 2018 The TensorFlow Hub Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless re...
4,140
Given the following text description, write Python code to implement the functionality described below step by step Description: Chapter 1 Exploratory data analysis Anecdotal evidence usually fails, because Step1: DataFrames DataFrame is the fundamental data structure provided by pandas. A DataFrame contains a row f...
Python Code: import matplotlib import pandas as pd %matplotlib inline Explanation: Chapter 1 Exploratory data analysis Anecdotal evidence usually fails, because: - Small number of observations - Selection bias - Confirmation bias - Inaccuracy To address the limitations of anecdotes, we will use the tools of statisti...
4,141
Given the following text description, write Python code to implement the functionality described below step by step Description: AXON is eXtended Object Notation. It's a simple notation of objects, documents and data. It's also a text based serialization format in first place. It tries to combine the best of JSON, XM...
Python Code: from __future__ import print_function from axon import loads, dumps from pprint import pprint Explanation: AXON is eXtended Object Notation. It's a simple notation of objects, documents and data. It's also a text based serialization format in first place. It tries to combine the best of JSON, XML and YAML...
4,142
Given the following text description, write Python code to implement the functionality described below step by step Description: UTSC Machine Learning Workshop Introduction to Linear Regression Adapted from Chapter 3 of An Introduction to Statistical Learning Motivation Regression problems are supervised learning prob...
Python Code: # imports import pandas as pd import seaborn as sns #import statsmodels.formula.api as smf from sklearn.linear_model import LinearRegression from sklearn import metrics import numpy as np # allow plots to appear directly in the notebook %matplotlib inline Explanation: UTSC Machine Learning Workshop Introdu...
4,143
Given the following text description, write Python code to implement the functionality described below step by step Description: A brief tour of Redis A one-hour or less tour of Redis. tl Step1: Note Step2: Remember we need to connect to the server, using Python as the client, just like we would connect to a databas...
Python Code: import redis Explanation: A brief tour of Redis A one-hour or less tour of Redis. tl:dr version: If you don't have time to read/run this, go to Try Redis and try it yourself. Redis is a data structure server. Not quite a database, not quite a key-value store. It is very fast and is a great tool for rapid a...
4,144
Given the following text description, write Python code to implement the functionality described below step by step Description: Copyright 2021 The TensorFlow Authors. Step1: Migration Examples Step2: prepare some simple data for demonstration from the standard Titanic dataset, Step3: and create a method to instant...
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...
4,145
Given the following text description, write Python code to implement the functionality described below step by step Description: 1A.algo - Tri plus rapide que prévu Dans le cas général, le coût d'un algorithme de tri est en $O(n \ln n)$. Mais il existe des cas particuliers pour lesquels on peut faire plus court. Par e...
Python Code: from jyquickhelper import add_notebook_menu add_notebook_menu() %matplotlib inline Explanation: 1A.algo - Tri plus rapide que prévu Dans le cas général, le coût d'un algorithme de tri est en $O(n \ln n)$. Mais il existe des cas particuliers pour lesquels on peut faire plus court. Par exemple, on suppose qu...
4,146
Given the following text description, write Python code to implement the functionality described below step by step Description: Planet Analytics API Tutorial Getting Analytic Feed Results This notebook shows how to paginate through Planet Analytic Feed Results for an existing analytics Subscription to construct a com...
Python Code: import os import requests # if your Planet API Key is not set as an environment variable, you can paste it below API_KEY = os.environ.get('PL_API_KEY', 'PASTE_YOUR_KEY_HERE') # alternatively, you can just set your API key directly as a string variable: # API_KEY = "YOUR_PLANET_API_KEY_HERE" # construct aut...
4,147
Given the following text description, write Python code to implement the functionality described below step by step Description: Step2: Unsupervised Anomaly Detection based on Forecasts Anomaly detection detects data points in data that does not fit well with the rest of data. In this notebook we demonstrate how to do...
Python Code: def get_result_df(y_true_unscale, y_pred_unscale, ano_index, look_back,target_col='cpu_usage'): Add prediction and anomaly value to dataframe. result_df = pd.DataFrame({"y_true": y_true_unscale.squeeze(), "y_pred": y_pred_unscale.squeeze()}) result_df['anomalies'] = 0 result_df.lo...
4,148
Given the following text description, write Python code to implement the functionality described below step by step Description: ## <p style="text-align Step1: how to draw samples from a gaussian distribution Step2: other distributions ... Step3: $\log_{10}(d) = 1 + \mu /5 $ Step4: 2. plotting Step5: 3. IO (text ...
Python Code: import numpy as np print(dir(np.random)) Explanation: ## <p style="text-align: center; font-size: 4em;"> Python tutorial 2 </p> 1. random number generators: numpy.random https://docs.scipy.org/doc/numpy/reference/routines.random.html End of explanation %pylab inline import matplotlib.pyplot as plt from mat...
4,149
Given the following text description, write Python code to implement the functionality described below step by step Description: Multiple Stripe Analysis (MSA) for Single Degree of Freedom (SDOF) Oscillators In this method, a single degree of freedom (SDOF) model of each structure is subjected to non-linear time histo...
Python Code: import MSA_on_SDOF from rmtk.vulnerability.common import utils import numpy as np %matplotlib inline Explanation: Multiple Stripe Analysis (MSA) for Single Degree of Freedom (SDOF) Oscillators In this method, a single degree of freedom (SDOF) model of each structure is subjected to non-linear time history...
4,150
Given the following text description, write Python code to implement the functionality described below step by step Description: Save out dataset for Evaluation Step1: Merge user data with feature data Step2: Eliminate Rows with viewed items that don't have features this may break up some trajectories (view1,view2,v...
Python Code: import pandas as pd import numpy as np import matplotlib.pyplot as plt %matplotlib inline # get data user_profile = pd.read_csv('../data_user_view_buy/user_profile.csv',sep='\t',header=None) user_profile.columns = ['user_id','buy_spu','buy_sn','buy_ct3','view_spu','view_sn','view_ct3','time_interval','view...
4,151
Given the following text description, write Python code to implement the functionality described below step by step Description: GTEx v8 eQTL tissue-specific all SNP gene associations Files in gs Step1: After generating the text files as above, ran the below to get the files bgzipped so we can read them in and create...
Python Code: # Generate list of all eQTL all association files in gs://gtex-resources list_eqtl_files_gz = subprocess.run(["gsutil", "-u", "broad-ctsa", "ls", "gs://gtex-re...
4,152
Given the following text description, write Python code to implement the functionality described below step by step Description: %matplotlib inline Linear Regression Example This example uses the only the first feature of the diabetes dataset, in order to illustrate a two-dimensional plot of this regression technique....
Python Code: print(__doc__) # Code source: Jaques Grobler # License: BSD 3 clause import matplotlib.pyplot as plt import numpy as np from sklearn import datasets, linear_model # Load the diabetes dataset diabetes = datasets.load_diabetes() # Use only one feature diabetes_X = diabetes.data[:, np.newaxis, 2] # Split the ...
4,153
Given the following text description, write Python code to implement the functionality described below step by step Description: Point source plotting basics In 3ML, we distinguish between data and model plotting. Data plots contian real data points and the over-plotted model is (sometimes) folded through an instrumen...
Python Code: %matplotlib inline jtplot.style(context="talk", fscale=1, ticks=True, grid=False) import matplotlib.pyplot as plt plt.style.use("mike") import numpy as np from threeML import * from threeML.io.package_data import get_path_of_data_file #mle1 = load_analysis_results(get_path_of_data_file("datasets/toy_xy_mle...
4,154
Given the following text description, write Python code to implement the functionality described below step by step Description: Running Spatial Correlations + options The goal of this log is to show the API of the spatial correlations and the options available. With this code, it is possible to run the spatial correl...
Python Code: %matplotlib inline import numpy as np #from pyCXD.tools.CrossCorrelator import CrossCorrelator from skbeam.core.correlation import CrossCorrelator import matplotlib.pyplot as plt from skbeam.core.roi import ring_edges, segmented_rings # for some convolutions, used to smooth images (make spatially correlate...
4,155
Given the following text description, write Python code to implement the functionality described below step by step Description: Non-parametric between conditions cluster statistic on single trial power This script shows how to compare clusters in time-frequency power estimates between conditions. It uses a non-parame...
Python Code: # Authors: Alexandre Gramfort <alexandre.gramfort@inria.fr> # # License: BSD-3-Clause import numpy as np import matplotlib.pyplot as plt import mne from mne.time_frequency import tfr_morlet from mne.stats import permutation_cluster_test from mne.datasets import sample print(__doc__) Explanation: Non-parame...
4,156
Given the following text description, write Python code to implement the functionality described below step by step Description: Selecting model hyperparameters by cross-validation The overview is that we will split the dataset into args.num_folds distinct partitions ("folds"). (This example description will use args....
Python Code: %load_ext autoreload %autoreload 2 %matplotlib inline # initialize a logger for ipython import pyllars.logging_utils as logging_utils logger = logging_utils.get_ipython_logger() # create an argparse namespace to hold parameters from argparse import Namespace args = Namespace() # create (or connect to) a da...
4,157
Given the following text problem statement, write Python code to implement the functionality described below in problem statement Problem: Survived SibSp Parch
Problem: import pandas as pd df = pd.DataFrame({'Survived': [0,1,1,1,0], 'SibSp': [1,1,0,1,0], 'Parch': [0,0,0,0,1]}) import numpy as np def g(df): family = np.where((df['SibSp'] + df['Parch']) >= 1 , 'Has Family', 'No Family') return df.groupby(family)['Survived'].mean() r...
4,158
Given the following text description, write Python code to implement the functionality described below step by step Description: Advanced settings for WHFast Step1: By default WHFast synchronizes and recalculates the Jacobi coordinates from the inertial ones every timestep. This guarantees that the user always gets ...
Python Code: import rebound import numpy as np def test_case(): sim = rebound.Simulation() sim.integrator = 'whfast' sim.add(m=1.) # add the Sun sim.add(m=3.e-6, a=1.) # add Earth sim.move_to_com() sim.dt = 0.2 return sim Explanation: Advanced settings for WHFast: Extra speed, accuracy, and...
4,159
Given the following text description, write Python code to implement the functionality described below step by step Description: Performing an unbinned analysis In this tutorial you will learn to fit a parametric model to the event data (unbinned fit) and how to inspect the fit residuals Now you are ready to fit the m...
Python Code: import gammalib import ctools import cscripts Explanation: Performing an unbinned analysis In this tutorial you will learn to fit a parametric model to the event data (unbinned fit) and how to inspect the fit residuals Now you are ready to fit the models for the source and the background to the data. We st...
4,160
Given the following text description, write Python code to implement the functionality described below step by step Description: Kmeans from scratch 1.data production Step1: 我们以(1, 1), (1, 2), (2, 2), (2, 1)四个点为中心产生了随机分布的点,如果我们的聚类算法正确的话,我们找到的中心点应该和这四个点很接近。先用简单的语言描述 kmeans 算法步骤: 第一步 - 随机选择 K 个点作为点的聚类中心,这表示我们要将数据分为 K 类...
Python Code: #produce data set near the center import numpy as np import matplotlib.pyplot as plt real_center = [(1,1),(1,2),(2,2),(2,1)] point_number = 50 points_x = [] points_y = [] for center in real_center: offset_x, offset_y = np.random.randn(point_number) * 0.3, np.random.randn(point_number) * 0.25 x_val,...
4,161
Given the following text description, write Python code to implement the functionality described below step by step Description: Initialization Welcome to the first assignment of "Improving Deep Neural Networks". Training your neural network requires specifying an initial value of the weights. A well chosen initializ...
Python Code: import numpy as np import matplotlib.pyplot as plt import sklearn import sklearn.datasets from init_utils import sigmoid, relu, compute_loss, forward_propagation, backward_propagation from init_utils import update_parameters, predict, load_dataset, plot_decision_boundary, predict_dec %matplotlib inline plt...
4,162
Given the following text description, write Python code to implement the functionality described below step by step Description: ES-DOC CMIP6 Model Properties - Ocean MIP Era Step1: Document Authors Set document authors Step2: Document Contributors Specify document contributors Step3: Document Publication Specify d...
Python Code: # DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'messy-consortium', 'sandbox-2', 'ocean') Explanation: ES-DOC CMIP6 Model Properties - Ocean MIP Era: CMIP6 Institute: MESSY-CONSORTIUM Source ID: SANDBOX-2 Topic: Ocean Sub-Topics: Ti...
4,163
Given the following text description, write Python code to implement the functionality described below step by step Description: ES-DOC CMIP6 Model Properties - Aerosol MIP Era Step1: Document Authors Set document authors Step2: Document Contributors Specify document contributors Step3: Document Publication Specify...
Python Code: # DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'csiro-bom', 'sandbox-2', 'aerosol') Explanation: ES-DOC CMIP6 Model Properties - Aerosol MIP Era: CMIP6 Institute: CSIRO-BOM Source ID: SANDBOX-2 Topic: Aerosol Sub-Topics: Transport,...
4,164
Given the following text description, write Python code to implement the functionality described below step by step Description: <figure> <IMG SRC="gfx/Logo_norsk_pos.png" WIDTH=100 ALIGN="right"> </figure> Operators and commutators Roberto Di Remigio, Luca Frediani We will be exercising our knowledge of operators a...
Python Code: from sympy import * # Define symbols x, y, z = symbols('x y z') # We want results to be printed to screen init_printing(use_unicode=True) # Calculate the derivative with respect to x diff(exp(x**2), x) Explanation: <figure> <IMG SRC="gfx/Logo_norsk_pos.png" WIDTH=100 ALIGN="right"> </figure> Operators an...
4,165
Given the following text description, write Python code to implement the functionality described below step by step Description: Predict with pre-trained models This is a demo for predicting with a pre-trained model on the full imagenet dataset, which contains over 10 million images and 10 thousands classes. For a mor...
Python Code: import os, urllib import mxnet as mx def download(url,prefix=''): filename = prefix+url.split("/")[-1] if not os.path.exists(filename): urllib.urlretrieve(url, filename) path='http://data.mxnet.io/models/imagenet-11k/' download(path+'resnet-152/resnet-152-symbol.json', 'full-') download(pat...
4,166
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: Gaussian Mixture Models and Expectation Maximisation in Shogun By Heiko Strathmann - heiko.strathmann@gmail.com - http Step2: Set up the model in Shogun Step3: Sampling from mixture...
Python Code: import os import numpy as np import matplotlib.pyplot as plt %matplotlib inline SHOGUN_DATA_DIR=os.getenv('SHOGUN_DATA_DIR', '../../../data') import shogun as sg from matplotlib.patches import Ellipse # a tool for visualisation def get_gaussian_ellipse_artist(mean, cov, nstd=1.96, color="red", linewidth=3)...
4,167
Given the following text description, write Python code to implement the functionality described below step by step Description: Using Adaptive Median Filter Step1: Original Image (converted to grayscale) Step2: Output with Python's native Median Filter function Step3: As shown from the above print, AMF results in ...
Python Code: Image.fromarray(output) Explanation: Using Adaptive Median Filter End of explanation Image.fromarray(grayscale_image) Explanation: Original Image (converted to grayscale) End of explanation native_output = image_org.filter(ImageFilter.MedianFilter(size = 3)) native_output deviation_native = np.sqrt(np.sum(...
4,168
Given the following text description, write Python code to implement the functionality described below step by step Description: Divergences as a Function of $\mu_q$ Let us start by simply varying $\mu_q$ and seeing the result. We will hold $\sigma_q$ fixed to $\sigma_p$ and $\alpha = -0.5$. Step1: Derivative of Dive...
Python Code: a = -0.7 j_vals = [] kl_vals = [] mus = np.linspace(0,1,100) for mu in mus: j_vals.append(J(mu,p_sig,a)[0]) kl_vals.append(KL(mu,p_sig)[0]) fig = plt.figure(figsize=(15,5)) p_vals = p(mus) plt.plot(mus, p_vals/p_vals.max(), label="$p(x)$") #plt.plot(mus, j_vals/np.max(np.abs(j_vals)), label='$J$') ...
4,169
Given the following text description, write Python code to implement the functionality described below step by step Description: Algorithms Exercise 3 Imports Step2: Character counting and entropy Write a function char_probs that takes a string and computes the probabilities of each character in the string Step4: Th...
Python Code: %matplotlib inline from matplotlib import pyplot as plt import numpy as np from IPython.html.widgets import interact Explanation: Algorithms Exercise 3 Imports End of explanation def char_probs(s): Find the probabilities of the unique characters in the string s. Parameters ---------- s...
4,170
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: The Landscape of the Major Food Staples in Ghana The dataset used in this project is a CSV file of the Global Food Prices Database by WFP - World Food Programme. Step2: The regions w...
Python Code: # Open the file and read its content. raw_data = open('WFPVAM_FoodPrices_24-01-2017.csv', 'r').read() # Split the raw_data on every newline. raw_data = raw_data.split('\n') # Take of the headers raw_data_no_header = raw_data[1:] # Make a list of lists of the raw_data_no_header staples_data = [] for food_in...
4,171
Given the following text description, write Python code to implement the functionality described below step by step Description: Morphological operations Morphology is the study of shapes. In image processing, some simple operations can get you a long way. The first things to learn are erosion and dilation. In erosion...
Python Code: import numpy as np from matplotlib import pyplot as plt, cm import skdemo plt.rcParams['image.cmap'] = 'cubehelix' plt.rcParams['image.interpolation'] = 'none' image = np.array([[0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 1, 1, 0, 0], [0, 0,...
4,172
Given the following text description, write Python code to implement the functionality described below step by step Description: Breakable Commitments... Code to generate figures Karna Basu and Jonathan Conning Department of Economics, Hunter College and The Graduate Center, City University of New York Step1: Abstrac...
Python Code: %reload_ext watermark %watermark -u -n -t Explanation: Breakable Commitments... Code to generate figures Karna Basu and Jonathan Conning Department of Economics, Hunter College and The Graduate Center, City University of New York End of explanation %matplotlib inline import numpy as np import matplotlib.p...
4,173
Given the following text description, write Python code to implement the functionality described below step by step Description: Demo of resizing Run the cells one at a time. Initially you'll see a squashed up chart. The next cell will let you programatically set it's height. NOTE Step1: Set height of 'figure' Step2:...
Python Code: line = Line(index=[1990, 1991, 1993, 1994], values=[1, 2, 3, 4], height=100) show(line) print(line.ref['id']) plot_height = 300 HTML("<script>Bokeh.index['%s'].model.set('plot_height', %d);</script>" % (line.ref['id'], plot_height)) Explanation: Demo of resizing Run the cells one at a time. Initially you'l...
4,174
Given the following text description, write Python code to implement the functionality described below step by step Description: Martín Noblía Tp3 <img src="files/copy_left.png" style="float Step2: Recordemos que el espacio de trabajo alcanzable es la región espacial a la que el efector final puede llegar, con al men...
Python Code: from IPython.core.display import Image Image(filename='Imagenes/copy_left.png') Image(filename='Imagenes/dibujo_robot2_tp2.png') #imports from sympy import * import numpy as np #Con esto las salidas van a ser en LaTeX init_printing(use_latex=True) Explanation: Martín Noblía Tp3 <img src="files/copy_left.pn...
4,175
Given the following text description, write Python code to implement the functionality described below step by step Description: To do for 07282017 Step1: Try TSNE and time it It turns out that TSNE is too time consuming even for small set of data. It is also because of how I transformed the data. Thus, in the PCA, I...
Python Code: import pandas as pd import numpy as np import os from sklearn.manifold import TSNE from sklearn.decomposition import PCA os.chdir('/Users/Walkon302/Desktop/deep-learning-models-master/view2buy') # Read the preprocessed file, containing the user profile and item features from view2buy folder df = pd.read_pi...
4,176
Given the following text description, write Python code to implement the functionality described below step by step Description: Hidden Markov Models author Step1: Note Step2: This seems far more reasonable. There is a single CG island surrounded by background sequence, and something at the end. If we knew that CG i...
Python Code: from pomegranate import * import numpy as np %pylab inline seq = list('CGACTACTGACTACTCGCCGACGCGACTGCCGTCTATACTGCGCATACGGC') d1 = DiscreteDistribution({'A': 0.25, 'C': 0.25, 'G': 0.25, 'T': 0.25}) d2 = DiscreteDistribution({'A': 0.10, 'C': 0.40, 'G': 0.40, 'T': 0.10}) s1 = State( d1, name='background' ) s2...
4,177
Given the following text description, write Python code to implement the functionality described below step by step Description: Notes on Columns From data reference PDF tree_dbh Diameter of the tree, measured at approximately 54" / 137cm above the ground. Data was collected for both living and dead trees; for stumps,...
Python Code: # Make tree diameter an integer df.tree_dbh = df.tree_dbh.astype("int64") df.describe() len(df[df["tree_dbh"] < 50]) df[df["tree_dbh"] > 100] df[df["tree_dbh"] < 40].tree_dbh.value_counts(sort=False).plot(kind="bar") Explanation: Notes on Columns From data reference PDF tree_dbh Diameter of the tree, measu...
4,178
Given the following text description, write Python code to implement the functionality described below step by step Description: PMOD TIMER In this notebook, PMOD Timer functionalities are illustrated. The Timer has two sub-modules Step1: Instantiate Pmod_Timer class. The method stop() will stop both timer sub-module...
Python Code: from pynq.overlays.base import BaseOverlay base = BaseOverlay("base.bit") Explanation: PMOD TIMER In this notebook, PMOD Timer functionalities are illustrated. The Timer has two sub-modules: Timer0 and Timer1. The Generate output and Capture Input of Timer 0 are assumed to be connected to PMODA pin 0. ...
4,179
Given the following text description, write Python code to implement the functionality described below step by step Description: Instruction This tutorial explain how to use calc_barriers wrapper calc_barriers is high level wrapeer used for calculation of migration barriers. The calculations are performed by executin...
Python Code: import sys sys.path.extend(['/home/aksenov/Simulation_wrapper/siman']) import header from calc_manage import add, res from database import write_database, read_database from set_functions import read_vasp_sets from calc_manage import smart_structure_read from SSHTools import SSHTools from project_funcs imp...
4,180
Given the following text description, write Python code to implement the functionality described below step by step Description: 机器学习工程师纳米学位 机器学习基础 项目 0 Step1: 从泰坦尼克号的数据样本中,我们可以看到船上每位旅客的特征 Survived:是否存活(0代表否,1代表是) Pclass:社会阶级(1代表上层阶级,2代表中层阶级,3代表底层阶级) Name:船上乘客的名字 Sex:船上乘客的性别 Age Step3: 这个例子展示了如何将泰坦尼克号的 Survived 数据从 ...
Python Code: # 检查你的Python版本 from sys import version_info if version_info.major != 2 and version_info.minor != 7: raise Exception('请使用Python 2.7来完成此项目') import numpy as np import pandas as pd # 数据可视化代码 from titanic_visualizations import survival_stats from IPython.display import display %matplotlib inline # 加载数据集 in...
4,181
Given the following text description, write Python code to implement the functionality described below step by step Description: You can download water chemistry of an entire HUC. It downloads wells and springs and major ions by default, unless specified otherwise. Step1: Standardize the headers and units in the res...
Python Code: chem = wa.WQP(16020301,'huc') Explanation: You can download water chemistry of an entire HUC. It downloads wells and springs and major ions by default, unless specified otherwise. End of explanation Results = chem.massage_results() Stations = chem.massage_stations() Piv = chem.piv_chem() Piv.reset_index(i...
4,182
Given the following text description, write Python code to implement the functionality described below step by step Description: How to run TARDIS with a custom ejecta model This notebook will go through multiple detailed examples of how to properly run TARDIS with a custom ejecta profile specified by a custom density...
Python Code: import tardis import matplotlib.pyplot as plt import numpy as np Explanation: How to run TARDIS with a custom ejecta model This notebook will go through multiple detailed examples of how to properly run TARDIS with a custom ejecta profile specified by a custom density file and a custom abundance file. End ...
4,183
Given the following text description, write Python code to implement the functionality described below step by step Description: Data Analysis with Pandas Dataframe Pandas is a popular library for manipulating vectors, tables, and time series. We will frequently use Pandas data structures instead of the built-in pytho...
Python Code: import pandas as pd Explanation: Data Analysis with Pandas Dataframe Pandas is a popular library for manipulating vectors, tables, and time series. We will frequently use Pandas data structures instead of the built-in python data structures, as they provide much richer functionality. Also, Pandas is fast, ...
4,184
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: Introduction In an upcoming analysis, we want to calculate the structural similarity between test cases. For this, we need the information which test methods call which code in the ap...
Python Code: import py2neo import pandas as pd graph = py2neo.Graph() query = MATCH (testMethod:Method) -[:ANNOTATED_BY]->()-[:OF_TYPE]-> (:Type {fqn:"org.junit.Test"}), (testType:Type)-[:DECLARES]->(testMethod), (type)-[:DECLARES]->(method:Method), (testMethod)-[i:INVOKES]->(method) WHERE NOT typ...
4,185
Given the following text description, write Python code to implement the functionality described below step by step Description: Timescales in QuTiP Andrew M.C. Dawes — 2016 An overview to one frequently asked question about QuTiP. Introduction QuTiP is a python package, if you are new to QuTiP, you should first read ...
Python Code: from qutip import * import numpy as np import matplotlib.pyplot as plt %matplotlib inline Explanation: Timescales in QuTiP Andrew M.C. Dawes — 2016 An overview to one frequently asked question about QuTiP. Introduction QuTiP is a python package, if you are new to QuTiP, you should first read the tutorial m...
4,186
Given the following text description, write Python code to implement the functionality described below step by step Description: <h1>Create an experiment</h1> Step1: <h1>Get a list of mzML files that you uploaded and assign them to a group</h1> Step2: <h1>Specify the descriptive names for each group</h1> Step3: <h1...
Python Code: myExperiment = metatlas_objects.Experiment(name = 'QExactive_Hilic_Pos_Actinobacteria_Phylogeny') Explanation: <h1>Create an experiment</h1> End of explanation myPath = '/global/homes/b/bpb/ExoMetabolomic_Example_Data/' myPath = '/project/projectdirs/metatlas/data_for_metatlas_2/20150324_LPSilva_BHedlund_c...
4,187
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: 很多刚接触交易的人总喜欢把交易看成一种有固定收入的工作,比如他们有自己的规矩,周五一定要把所有股票都卖了,安安心心过周末,周一看情况一切良好再把股票买回来。 还有一些人有着很奇怪的癖好...
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安装的...
4,188
Given the following text description, write Python code to implement the functionality described below step by step Description: Emojify! Welcome to the second assignment of Week 2. You are going to use word vector representations to build an Emojifier. Have you ever wanted to make your text messages more expressive?...
Python Code: import numpy as np from emo_utils import * import emoji import matplotlib.pyplot as plt %matplotlib inline Explanation: Emojify! Welcome to the second assignment of Week 2. You are going to use word vector representations to build an Emojifier. Have you ever wanted to make your text messages more expressi...
4,189
Given the following text description, write Python code to implement the functionality described below step by step Description: Filter hits Step1: Keep best hit per database for each cluster Filtered by e-value < 1e-3 and best domain e-value < 1
Python Code: filt_hits = all_hmmer_hits[ (all_hmmer_hits.e_value < 1e-3) & (all_hmmer_hits.best_dmn_e_value < 1e-3) ] filt_hits.to_csv("1_out/filtered_hmmer_all_hits.csv",index=False) print(filt_hits.shape) filt_hits.head() Explanation: Filter hits End of explanation gb = filt_hits.groupby(["cluster","db"]) reliable_fa...
4,190
Given the following text description, write Python code to implement the functionality described below step by step Description: Primitive generators This notebook contains tests for tohu's primitive generators. Step1: Constant Constant simply returns the same, constant value every time. Step2: Boolean Boolean retur...
Python Code: import tohu from tohu.v4.primitive_generators import * from tohu.v4.dispatch_generators import * from tohu.v4.utils import print_generated_sequence print(f'Tohu version: {tohu.__version__}') Explanation: Primitive generators This notebook contains tests for tohu's primitive generators. End of explanation g...
4,191
Given the following text description, write Python code to implement the functionality described below step by step Description: Reusing a pool of workers Some algorithms require to make several consecutive calls to a parallel function interleaved with processing of the intermediate results. Calling Parallel several t...
Python Code: with Parallel(n_jobs=2) as parallel: accumulator = 0. n_iter = 0 while accumulator < 1000: results = parallel(delayed(sqrt)(accumulator + i ** 2)for i in range(5)) accumulator += sum(results) # synchronization barrier n_iter += 1 (accumulator, n_iter) Explanation: Reusi...
4,192
Given the following text description, write Python code to implement the functionality described below step by step Description: Introduction With all that you've learned, your SQL queries are getting pretty long, which can make them hard understand (and debug). You are about to learn how to use AS and WITH to tidy up...
Python Code: #$HIDE_INPUT$ from google.cloud import bigquery # Create a "Client" object client = bigquery.Client() # Construct a reference to the "crypto_bitcoin" dataset dataset_ref = client.dataset("crypto_bitcoin", project="bigquery-public-data") # API request - fetch the dataset dataset = client.get_dataset(dataset...
4,193
Given the following text description, write Python code to implement the functionality described below step by step Description: DiscreteDP Implementation Details Daisuke Oyama Faculty of Economics, University of Tokyo This notebook describes the implementation details of the DiscreteDP class. For the theoretical back...
Python Code: import numpy as np import pandas as pd from quantecon.markov import DiscreteDP n = 2 # Number of states m = 2 # Number of actions # Reward array R = [[5, 10], [-1, -float('inf')]] # Transition probability array Q = [[(0.5, 0.5), (0, 1)], [(0, 1), (0.5, 0.5)]] # Probabilities in Q[1, 1] are arbi...
4,194
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"><a href="#Example-of-GibbsLDA-and-vbLDA"><span class="toc-item-num">1 - </span>Example of GibbsLDA and vbLDA</a></div><div class="lev2"><a href="#Loadi...
Python Code: import logging import numpy as np from ptm import GibbsLDA from ptm import vbLDA from ptm.nltk_corpus import get_reuters_ids_cnt from ptm.utils import convert_cnt_to_list, get_top_words Explanation: Table of Contents <p><div class="lev1"><a href="#Example-of-GibbsLDA-and-vbLDA"><span class="toc-item-num">1...
4,195
Given the following text description, write Python code to implement the functionality described below step by step Description: Changepoint analysis This notebook reflects an intermediate stage of work on the project that became "You say you found a revolution." Underwood was attempting to directly compare non-overla...
Python Code: %matplotlib inline import matplotlib.pyplot as plt import csv, os, random import numpy as np from collections import Counter from scipy import spatial songsbyquarter = dict() numfields = 14 fieldnames = [] for i in range(14): fieldnames.append('PC' + str(i+1)) maxquarter = 0 with open('EvolutionPopUSA_...
4,196
Given the following text description, write Python code to implement the functionality described below step by step Description: Identifying Spam from SMS Text Messages This analysis attempts to identify spam messages from a corpus of 5,574 SMS text messages. The corpus is labeled as either spam or ham (legitimate me...
Python Code: %matplotlib inline import os import json import time import pickle import requests from io import BytesIO from zipfile import ZipFile import numpy as np import pandas as pd import matplotlib.pyplot as plt from sklearn.feature_extraction.text import CountVectorizer from sklearn.feature_extraction import tex...
4,197
Given the following text description, write Python code to implement the functionality described below step by step Description: Economics with Jupyter Notebooks Jupyter Notebook is "a web application that allows you to create and share documents that contain live code, equations, visualizations and explanatory text. ...
Python Code: import matplotlib.pyplot as plt %matplotlib inline import pandas as pd import seaborn as sns from ipywidgets import interact df = pd.read_stata(".\data\country.dta") Explanation: Economics with Jupyter Notebooks Jupyter Notebook is "a web application that allows you to create and share documents that conta...
4,198
Given the following text description, write Python code to implement the functionality described below step by step Description: In the last chapter, our tests failed. This time we'll go about fixing them. Our First Django App, and Our First Unit Test Django encourages you to structure your code into apps Step1: Unit...
Python Code: %cd ../examples/superlists/ # Make a new app called lists !python3 manage.py startapp lists !tree . Explanation: In the last chapter, our tests failed. This time we'll go about fixing them. Our First Django App, and Our First Unit Test Django encourages you to structure your code into apps: the theory is t...
4,199
Given the following text description, write Python code to implement the functionality described below step by step Description: Spatial Model fitting in GLS In this exercise we will fit a linear model using a Spatial structure as covariance matrix. We will use GLS to get better estimators. As always we will need to ...
Python Code: # Load Biospytial modules and etc. %matplotlib inline import sys sys.path.append('/apps') sys.path.append('..') sys.path.append('../spystats') import django django.setup() import pandas as pd import matplotlib.pyplot as plt import numpy as np ## Use the ggplot style plt.style.use('ggplot') import tools Exp...