Unnamed: 0
int64
0
16k
text_prompt
stringlengths
110
62.1k
code_prompt
stringlengths
37
152k
13,600
Given the following text description, write Python code to implement the functionality described below step by step Description: Modeling dynamics of FS Peptide This example shows a typical, basic usage of the MSMBuilder command line to model dynamics of a protein system. Step1: Get example data Step2: Featurization...
Python Code: # Work in a temporary directory import tempfile import os os.chdir(tempfile.mkdtemp()) # Since this is running from an IPython notebook, # we prefix all our commands with "!" # When running on the command line, omit the leading "!" ! msmb -h Explanation: Modeling dynamics of FS Peptide This example shows a...
13,601
Given the following text description, write Python code to implement the functionality described below step by step Description: Classification with Neural Decision Forests Author Step1: Prepare the data Step2: Remove the first record (because it is not a valid data example) and a trailing 'dot' in the class labels....
Python Code: import tensorflow as tf import numpy as np import pandas as pd from tensorflow import keras from tensorflow.keras import layers import math Explanation: Classification with Neural Decision Forests Author: Khalid Salama<br> Date created: 2021/01/15<br> Last modified: 2021/01/15<br> Description: How to train...
13,602
Given the following text description, write Python code to implement the functionality described below step by step Description: Линейная регрессия и стохастический градиентный спуск Задание основано на материалах лекций по линейной регрессии и градиентному спуску. Вы будете прогнозировать выручку компании в зависимос...
Python Code: def write_answer_to_file(answer, filename): with open(filename, 'w') as f_out: f_out.write(str(round(answer, 3))) Explanation: Линейная регрессия и стохастический градиентный спуск Задание основано на материалах лекций по линейной регрессии и градиентному спуску. Вы будете прогнозировать выручк...
13,603
Given the following text description, write Python code to implement the functionality described below step by step Description: Take the set of pings, make sure we have actual clientIds and remove duplicate pings. We collect each unique ping. Step1: Transform and sanitize the pings into arrays. Step2: Create a set ...
Python Code: def dedupe_pings(rdd): return rdd.filter(lambda p: p["meta/clientId"] is not None)\ .map(lambda p: (p["meta/documentId"], p))\ .reduceByKey(lambda x, y: x)\ .map(lambda x: x[1]) Explanation: Take the set of pings, make sure we have actual clientIds and remove d...
13,604
Given the following text description, write Python code to implement the functionality described below step by step Description: ApJdataFrames Kraus2017 Title Step1: Get all tables right away. There are 7 tables. Step2: Convert the astropy tables to pandas dataframes.
Python Code: %matplotlib inline import matplotlib.pyplot as plt import seaborn as sns import pandas as pd pd.options.display.max_columns = 150 #%config InlineBackend.figure_format = 'retina' import astropy from astropy.table import Table from astropy.io import ascii from IPython.core.display import display, HTML displa...
13,605
Given the following text description, write Python code to implement the functionality described below step by step Description: logictools WaveDrom Tutorial WaveDrom is a tool for rendering digital timing waveforms. The waveforms are defined in a simple textual format. This notebook will show how to render digital w...
Python Code: from pynq.lib.logictools.waveform import draw_wavedrom Explanation: logictools WaveDrom Tutorial WaveDrom is a tool for rendering digital timing waveforms. The waveforms are defined in a simple textual format. This notebook will show how to render digital waveforms using the pynq library. The logictools o...
13,606
Given the following text description, write Python code to implement the functionality described below step by step Description: Load in Catalogue - Limit to ISC, GCMT/HRVD, EHB, NEIC, BJI Step1: Define Rule Sets The catalogue covers the years 2005/06. To illustrate how to apply time variable hierarchies we consider ...
Python Code: parser = ISFReader("inputs/isc_test_catalogue_isf.txt", selected_origin_agencies=["ISC", "GCMT", "HRVD", "NEIC", "EHB", "BJI"], selected_magnitude_agencies=["ISC", "GCMT", "HRVD", "NEIC", "BJI"]) catalogue = parser.read_file("ISC_DB1", "ISC Global M >= 5") print("Catal...
13,607
Given the following text description, write Python code to implement the functionality described below step by step Description: Example 7 Step1: Setup an identical instance of NPTFit to Example 6 Firstly we initialize an instance of nptfit identical to that used in the previous example. Step2: Evaluate the Likeliho...
Python Code: # Import relevant modules %matplotlib inline %load_ext autoreload %autoreload 2 import numpy as np import healpy as hp import matplotlib.pyplot as plt from NPTFit import nptfit # module for performing scan from NPTFit import create_mask as cm # module for creating the mask from NPTFit import psf_correction...
13,608
Given the following text description, write Python code to implement the functionality described below step by step Description: PageRank Ways to think about SVD Data compression SVD trades a large number of features for a smaller set of better features All matrices are diagonal (if you use change of bases on the doma...
Python Code: #@title Power iteration import numpy as np def power_iteration(A, num_simulations): # Ideally choose a random vector # To decrease the chance that our vector # Is orthogonal to the eigenvector b_k = np.random.rand(A.shape[0]) for _ in range(num_simulations): # calculate the matr...
13,609
Given the following text description, write Python code to implement the functionality described below step by step Description: ProteinB Step1: Auxiliary functions Step2: Create a feature reader We create a feature reader to obtain minimal distances between all residues which are not close neighbours. Feel free to ...
Python Code: import sys import math sys.path.append("/Users/suarezalvareze2/Documents/workspace/NMpathAnalysis/nmpath") %matplotlib inline import matplotlib as mpl import matplotlib.pyplot as plt import numpy as np import pyemma import mdtraj as md from glob import glob # My modules from auxfunctions import * from mfpt...
13,610
Given the following text description, write Python code to implement the functionality described below step by step Description: <img src='https Step1: 如何使用和开发微信聊天机器人的系列教程 A workshop to develop & use an intelligent and interactive chat-bot in WeChat WeChat is a popular social media app, which has more than 800 millio...
Python Code: import IPython.display IPython.display.YouTubeVideo('YSL--3j12VA') Explanation: <img src='https://www.iss.nus.edu.sg/Sitefinity/WebsiteTemplates/ISS/App_Themes/ISS/Images/branding-iss.png' width=15% style="float: right;"> <img src='https://www.iss.nus.edu.sg/Sitefinity/WebsiteTemplates/ISS/App_Themes/ISS/I...
13,611
Given the following text description, write Python code to implement the functionality described below step by step Description: Frame The client bank XYZ is running a direct marketing campaign. It wants to identify customers who would potentially be buying their new term deposit plan. Acquire Data is obtained from UC...
Python Code: #Import the necessary libraries import numpy as np import pandas as pd #Read the train and test data train = pd.read_csv("../data/train.csv") test = pd.read_csv("../data/test.csv") Explanation: Frame The client bank XYZ is running a direct marketing campaign. It wants to identify customers who would potent...
13,612
Given the following text description, write Python code to implement the functionality described below step by step Description: TV Script Generation In this project, you'll generate your own Simpsons TV scripts using RNNs. You'll be using part of the Simpsons dataset of scripts from 27 seasons. The Neural Network y...
Python Code: import helper data_dir = './data/simpsons/moes_tavern_lines.txt' text = helper.load_data(data_dir) # Ignore notice, since we don't use it for analysing the data text = text[81:] Explanation: TV Script Generation In this project, you'll generate your own Simpsons TV scripts using RNNs. You'll be using part...
13,613
Given the following text description, write Python code to implement the functionality described below step by step Description: Preprocessing Step1: Config Automatically discover the paths to various data folders and compose the project structure. Step2: Read data Original question datasets. Step3: Load tools Step...
Python Code: from pygoose import * import nltk Explanation: Preprocessing: Unique Question Corpus Based on the training and test sets, extract a list of unique documents. Imports This utility package imports numpy, pandas, matplotlib and a helper kg module into the root namespace. End of explanation project = kg.Projec...
13,614
Given the following text description, write Python code to implement the functionality described below step by step Description: Training Hybrid Recommendation Model with the MovieLens Dataset Note Step1: Import the dataset and trained model In the previous notebook, you imported 20 million movie recommendations and ...
Python Code: import os import tensorflow as tf PROJECT = "your-project-id-here" # REPLACE WITH YOUR PROJECT ID # Do not change these os.environ["PROJECT"] = PROJECT os.environ["TFVERSION"] = '2.5' Explanation: Training Hybrid Recommendation Model with the MovieLens Dataset Note: It is recommended that you complete the ...
13,615
Given the following text description, write Python code to implement the functionality described below step by step Description: Introduction to pandas by Maxwell Margenot Part of the Quantopian Lecture Series Step1: With pandas, it is easy to store, visualize, and perform calculations on your data. With only a few l...
Python Code: import numpy as np import pandas as pd import matplotlib.pyplot as plt Explanation: Introduction to pandas by Maxwell Margenot Part of the Quantopian Lecture Series: www.quantopian.com/lectures github.com/quantopian/research_public Notebook released under the Creative Commons Attribution 4.0 License. panda...
13,616
Given the following text description, write Python code to implement the functionality described below step by step Description: The function $\texttt{toDot}(\texttt{Parent})$ takes a dictionary $\texttt{Parent}$. For every node $x$, $\texttt{Parent}[x]$ is the parent of $x$. It draws this dictionary as a family tr...
Python Code: def toDot(Parent): dot = gv.Digraph() M = Parent.keys() for x in M: p = Parent[x] if x == p: dot.node(str(x), shape='doublecircle') else: dot.node(str(x), shape='circle') dot.edge(str(x), str(p)) return dot Explanation: T...
13,617
Given the following text description, write Python code to implement the functionality described below step by step Description: Overview Use linked DMA channels to perform "scan" across multiple ADC input channels. See diagram below. Channel configuration ## DMA channel $i$ copies conesecutive SC1A configurations to ...
Python Code: from arduino_rpc.protobuf import resolve_field_values from teensy_minimal_rpc import SerialProxy import teensy_minimal_rpc.DMA as DMA import teensy_minimal_rpc.ADC as ADC # Disconnect from existing proxy (if available) try: del proxy except NameError: pass proxy = SerialProxy() Explanation: Overvie...
13,618
Given the following text description, write Python code to implement the functionality described below step by step Description: This notebook shows the how tallies can be combined (added, subtracted, multiplied, etc.) using the Python API in order to create derived tallies. Since no covariance information is obtained...
Python Code: %load_ext autoreload %autoreload 2 import glob from IPython.display import Image import numpy as np import openmc from openmc.statepoint import StatePoint from openmc.summary import Summary %matplotlib inline Explanation: This notebook shows the how tallies can be combined (added, subtracted, multiplied, e...
13,619
Given the following text description, write Python code to implement the functionality described below step by step Description: FCN-8s Tutorial Step1: This notebook walks you through how to work with this FCN-8s implementation. I will take the Cityscapes dataset as an example to train the model on in this notebook, ...
Python Code: from fcn8s_tensorflow import FCN8s from data_generator.batch_generator import BatchGenerator from helpers.visualization_utils import print_segmentation_onto_image, create_video_from_images from cityscapesscripts.helpers.labels import TRAINIDS_TO_COLORS_DICT, TRAINIDS_TO_RGBA_DICT from math import ceil impo...
13,620
Given the following text description, write Python code to implement the functionality described below step by step Description: <h1> Reading NEXRAD Level II data from Google Cloud public datasets </h1> This notebook demonstrates how to use PyART to visualize data from the Google Cloud public dataset. Step1: <h3> Ins...
Python Code: %bash rm -rf data mkdir data cd data RADAR=KIWA YEAR=2013 MONTH=07 DAY=23 HOUR=23 gsutil cp gs://gcp-public-data-nexrad-l2/$YEAR/$MONTH/$DAY/$RADAR/*_$RADAR_${YEAR}${MONTH}${DAY}${HOUR}0000_${YEAR}${MONTH}${DAY}${HOUR}5959.tar temp.tar tar xvf temp.tar rm *.tar ls Explanation: <h1> Reading NEXRAD Level II ...
13,621
Given the following text description, write Python code to implement the functionality described below step by step Description: This notebook is the reproduction of an exercise found at http Step1: We'll read the data from ZoneA.dat. Step2: We want the first, second and fourth columns of the data set, representing ...
Python Code: import sys sys.path.append('..') sys.path.append('../geostatsmodels') from geostatsmodels import utilities, variograms, model, kriging, geoplot import matplotlib.pyplot as plt import numpy as np import pandas Explanation: This notebook is the reproduction of an exercise found at http://people.ku.edu/~gbohl...
13,622
Given the following text description, write Python code to implement the functionality described below step by step Description: Deep learning for Natural Language Processing Simple text representations, bag of words Word embedding and... not just another word2vec this time 1-dimensional convolutions for text Aggregat...
Python Code: low_RAM_mode = True very_low_RAM = False #If you have <3GB RAM, set BOTH to true import pandas as pd import numpy as np import matplotlib.pyplot as plt %matplotlib inline Explanation: Deep learning for Natural Language Processing Simple text representations, bag of words Word embedding and... not just ano...
13,623
Given the following text description, write Python code to implement the functionality described below step by step Description: Algebra Lineal con Python Esta notebook fue creada originalmente como un blog post por Raúl E. López Briega en Mi blog sobre Python. El contenido esta bajo la licencia BSD. <img alt="Algebra...
Python Code: # Vector como lista de Python v1 = [2, 4, 6] v1 # Vectores con numpy import numpy as np v2 = np.ones(3) # vector de solo unos. v2 v3 = np.array([1, 3, 5]) # pasando una lista a las arrays de numpy v3 v4 = np.arange(1, 8) # utilizando la funcion arange de numpy v4 Explanation: Algebra Lineal con Python Esta...
13,624
Given the following text description, write Python code to implement the functionality described below step by step Description: DualMap plugin This plugin is using the Leaflet plugin Sync by Jieter Step1: The DualMap class accepts the same arguments as the normal Map class. Except for these Step2: You can access th...
Python Code: import folium import folium.plugins Explanation: DualMap plugin This plugin is using the Leaflet plugin Sync by Jieter: https://github.com/jieter/Leaflet.Sync The goal is to have two maps side by side. When you pan or zoom on one map, the other will move as well. End of explanation m = folium.plugins.DualM...
13,625
Given the following text description, write Python code to implement the functionality described below step by step Description: Import data from web scrawlers Here we first build a web scrawler to scrap all the trafic information from the official twitter accounts of RATP, SNCF Step1: First, have a look at the data ...
Python Code: import pandas as pd import seaborn as sns import matplotlib.pyplot as plt import numpy as np # ---- Summary of the twitter accounts -----# # RER_A # RERB # RERC_SNCF --< Infotrafic # RERD_SNCF --< Infotrafic # RERE_SNCF --< Infotrafic # Ligne12_RATP --< from 1 to 14 lines line_list = ['RER_A', 'RER_B', 'RE...
13,626
Given the following text description, write Python code to implement the functionality described below step by step Description: Sentiment Classification & How To "Frame Problems" for a Neural Network by Andrew Trask Twitter Step1: Lesson Step2: Project 1 Step3: Transforming Text into Numbers
Python Code: def pretty_print_review_and_label(i): print(labels[i] + "\t:\t" + reviews[i][:80] + "...") g = open('reviews.txt','r') # What we know! reviews = list(map(lambda x:x[:-1],g.readlines())) g.close() g = open('labels.txt','r') # What we WANT to know! labels = list(map(lambda x:x[:-1].upper(),g.readlines())...
13,627
Given the following text description, write Python code to implement the functionality described below step by step Description: Note Step1: First, we import the energy data from the sample CSV and transform it into records Step2: The records we just created look like this Step3: The energy trace data looks like th...
Python Code: # library imports from eemeter.structures import ( EnergyTrace, EnergyTraceSet, Intervention, ZIPCodeSite, Project ) from eemeter.io.serializers import ArbitraryStartSerializer from eemeter.ee.meter import EnergyEfficiencyMeter import pandas as pd import pytz Explanation: Note: Most use...
13,628
Given the following text description, write Python code to implement the functionality described below step by step Description: Building an ML App Now that we have a machine learning model to predict the defaults, let us try to build a web application to lend loans. It'll have two parts Step1: Let us run it as a se...
Python Code: %%file sq.py def square(n): return n*n Explanation: Building an ML App Now that we have a machine learning model to predict the defaults, let us try to build a web application to lend loans. It'll have two parts: a form to submit the loans admin panel to look at the submitted loans and their probabil...
13,629
Given the following text description, write Python code to implement the functionality described below step by step Description: From NumPy to Leaflet This notebook shows how to display some raster geographic data in IPyLeaflet. The data is a NumPy array, which means that you have all the power of the Python scientifi...
Python Code: import requests import os from tqdm import tqdm import zipfile import rasterio from affine import Affine import numpy as np import scipy.ndimage from rasterio.warp import reproject, Resampling import PIL import matplotlib.pyplot as plt from base64 import b64encode try: from StringIO import StringIO ...
13,630
Given the following text description, write Python code to implement the functionality described below step by step Description: <a href="https Step1: Let's begin by querying our newly transformed vcf table, containing variants for the human chromosome 21. For instructions on the BigQuery transformation see Step2: ...
Python Code: from google.colab import auth auth.authenticate_user() print('Authenticated') Explanation: <a href="https://colab.research.google.com/github/isb-cgc/examples-Python/blob/master/ISB_CGC_Query_of_the_Month_November_2018.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.sv...
13,631
Given the following text description, write Python code to implement the functionality described below step by step Description: Table of Contents <p><div class="lev1 toc-item"><a href="#A-brief-tutorial-for-the-WormBase-Enrichment-Suite,-Python-interface" data-toc-modified-id="A-brief-tutorial-for-the-WormBase-Enrich...
Python Code: # this first cell imports the libraries we typically use for data science in Python import pandas as pd import numpy as np # this is the WormBase Enrichment Suite module (previously just TEA) import tissue_enrichment_analysis as ea # plotting libraries import matplotlib.pyplot as plt import seaborn as sns ...
13,632
Given the following text description, write Python code to implement the functionality described below step by step Description: Remote WMI Wbemcomn DLL Hijack Metadata | | | | Step1: Download & Process Mordor Dataset Step2: Analytic I Look for non-system accounts SMB accessing a C Step3: Analy...
Python Code: from openhunt.mordorutils import * spark = get_spark() Explanation: Remote WMI Wbemcomn DLL Hijack Metadata | | | |:------------------|:---| | collaborators | ['@Cyb3rWard0g', '@Cyb3rPandaH'] | | creation date | 2020/10/09 | | modification date | 2020/10/09 | | playbook related...
13,633
Given the following text description, write Python code to implement the functionality described below step by step Description: Lab 4- Decision Trees This assignment uses 2012 data obtained from the Federal Election Commission on contributions to candidates from committees. The data dictionary is available at http St...
Python Code: from __future__ import division, print_function from collections import Counter, defaultdict from itertools import combinations import pandas as pd import numpy as np import itertools import sklearn from sklearn.tree import DecisionTreeClassifier from sklearn.feature_extraction import DictVectorizer #to t...
13,634
Given the following text description, write Python code to implement the functionality described below step by step Description: 200-D Multivariate Normal Let's go for broke here. Setup First, let's set up some environmental dependencies. These just make the numerics easier and adjust some of the plotting defaults to ...
Python Code: # system functions that are always useful to have import time, sys, os import pickle # basic numeric setup import numpy as np from numpy import linalg from scipy import stats # inline plotting %matplotlib inline # plotting import matplotlib from matplotlib import pyplot as plt # seed the random number gene...
13,635
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', 'cmcc', 'cmcc-cm2-hr5', 'toplevel') Explanation: ES-DOC CMIP6 Model Properties - Toplevel MIP Era: CMIP6 Institute: CMCC Source ID: CMCC-CM2-HR5 Sub-Topics: Radiative Forcings. Proper...
13,636
Given the following text description, write Python code to implement the functionality described below step by step Description: 1.4 查找最大或最小的N个元素 怎样从一个集合中获得最大或者最小的N个元素列表? Step1: 当查找的元素个数较小时(N &lt; nSum),函数nlargest and nsmalest 是很适合<br>若 仅仅想查找唯一的 最小或最大N=1的元素的话,使用max and min 更快<br>若N的大小的和集合大小接近时,通常先排序在切片更快 sorted(items...
Python Code: import heapq nums = [1,8,23,44,56,12,-2,45,23] print(heapq.nlargest(3,nums)) print(heapq.nsmallest(3,nums)) portfolio = [ {'name':'IBM','shares':100,'price':91.1}, {'name':'AAPL','shares':50,'price':543.22}, {'name': 'FB', 'shares': 200, 'price': 21.09}, {'name': 'HPQ', 'shares': 35, 'price...
13,637
Given the following text description, write Python code to implement the functionality described below step by step Description: Tutorial Part 16 Step1: For this example, we will create a data distribution consisting of a set of ellipses in 2D, each with a random position, shape, and orientation. Each class correspo...
Python Code: %tensorflow_version 1.x !curl -Lo deepchem_installer.py https://raw.githubusercontent.com/deepchem/deepchem/master/scripts/colab_install.py import deepchem_installer %time deepchem_installer.install(version='2.3.0') Explanation: Tutorial Part 16: Conditional Generative Adversarial Network Note: This exampl...
13,638
Given the following text description, write Python code to implement the functionality described below step by step Description: Lists Some methods of list Step1: <code>del</code> statement can be used to remove an item from a list given its index Step2: <code>list()</code> Step3: Sort a list <code>sorted</code><co...
Python Code: pets = ['dog', 'cat', 'pig'] print pets.index('cat') pets.insert(0, 'rabbit') print pets pets.pop(1) print pets Explanation: Lists Some methods of list: <code>list.append(x)</code>: add <code>x</code> to the end <code>list.insert(i, x)</code>: insert <code>x</code> at position <code>i</code> <code>list.ind...
13,639
Given the following text description, write Python code to implement the functionality described below step by step Description: Account for AOI reflection losses (in full mode only) In this section, we will learn Step1: Let's define a few helper functions that will help clarify the notebook Step2: Get timeseries in...
Python Code: # Import external libraries import os import numpy as np import matplotlib.pyplot as plt from datetime import datetime import pandas as pd import warnings # Settings %matplotlib inline np.set_printoptions(precision=3, linewidth=300) warnings.filterwarnings('ignore') plt.style.use('seaborn-whitegrid') plt.r...
13,640
Given the following text description, write Python code to implement the functionality described below step by step Description: Estandarizacion de datos de los Anuarios Geoestadísticos de INEGI 2017 1. Introduccion Parámetros que salen de esta fuente Step1: 2. Descarga de datos Cada entidad cuenta con una página que...
Python Code: descripciones = { 'P0610': 'Ventas de electricidad', 'P0701': 'Longitud total de la red de carreteras del municipio (excluyendo las autopistas)' } # Librerias utilizadas import pandas as pd import sys import urllib import os import csv import zipfile # Configuracion del sistema print('Python {} on ...
13,641
Given the following text description, write Python code to implement the functionality described below step by step Description: Baseline prediction for homework type The baseline prediction method we use for predicting which homework the notebook came from uses the popular plagiarism detector JPlag. We feed each note...
Python Code: # First step is to load a balanced dataset of homeworks import sys home_directory = '/dfs/scratch2/fcipollone' sys.path.append(home_directory) import numpy as np from nbminer.notebook_miner import NotebookMiner hw_filenames = np.load('../homework_names_jplag_combined_per_student.npy') min_val = min([len(te...
13,642
Given the following text description, write Python code to implement the functionality described below step by step Description: Decision Analysis The Price is Right problem On November 1, 2007, contestants named Letia and Nathaniel appeared on The Price is Right, an American game show. They competed in a game called ...
Python Code: from price import * import matplotlib.pyplot as plt player1, player2 = MakePlayers(path='../code') MakePrice1(player1, player2) plt.legend(); Explanation: Decision Analysis The Price is Right problem On November 1, 2007, contestants named Letia and Nathaniel appeared on The Price is Right, an American game...
13,643
Given the following text description, write Python code to implement the functionality described below step by step Description: Reading files The iterator notation is easiest. Step1: (The comma at the end suppresses extra newline). Can also use the object-oriented interface. Step2: Reading all of the lines at once ...
Python Code: f = open('kaiju_movies.dat') for movie in f: print movie, f.close() Explanation: Reading files The iterator notation is easiest. End of explanation f = file('kaiju_movies.dat') for movie in f: print movie, f.close() Explanation: (The comma at the end suppresses extra newline). Can also use the obje...
13,644
Given the following text description, write Python code to implement the functionality described below step by step Description: Creating STIX Content Creating STIX Domain Objects To create a STIX object, provide keyword arguments to the type's constructor Step1: Certain required attributes of all objects will be set...
Python Code: from stix2 import Indicator indicator = Indicator(name="File hash for malware variant", pattern="[file:hashes.md5 = 'd41d8cd98f00b204e9800998ecf8427e']", pattern_type="stix") print(indicator.serialize(pretty=True)) Explanation: Creating STIX Content Creating STIX...
13,645
Given the following text description, write Python code to implement the functionality described below step by step Description: How to use this Notebook The development cycle intended here is to Init an experiment Reset the model and optimizer Restart wandb Run one epoch Add any new logs for plots, as needed Then re...
Python Code: from functools import partial import torch import numpy as np import seaborn as sns import matplotlib.pyplot as plt Explanation: How to use this Notebook The development cycle intended here is to Init an experiment Reset the model and optimizer Restart wandb Run one epoch Add any new logs for plots, as ne...
13,646
Given the following text description, write Python code to implement the functionality described below step by step Description: Storage To Table Move using bucket and path prefix. License Copyright 2020 Google LLC, Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in com...
Python Code: !pip install git+https://github.com/google/starthinker Explanation: Storage To Table Move using bucket and path prefix. License Copyright 2020 Google LLC, Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy o...
13,647
Given the following text description, write Python code to implement the functionality described below step by step Description: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyri...
Python Code: import logging import random import time import matplotlib.pyplot as plt import mxnet as mx from mxnet import gluon, np, npx, autograd import numpy as onp Explanation: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with th...
13,648
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', 'mohc', 'hadgem3-gc31-ll', 'land') Explanation: ES-DOC CMIP6 Model Properties - Land MIP Era: CMIP6 Institute: MOHC Source ID: HADGEM3-GC31-LL Topic: Land Sub-Topics: Soil, Snow, Veget...
13,649
Given the following text description, write Python code to implement the functionality described below step by step Description: If we're making the fin frames with a router/2-axis mill, we need to know what angle of chamfer cutter to use. This is just the trig to make sure that the angle of the leading edge is $\leq$...
Python Code: import math as m import matplotlib.pyplot as plt %matplotlib inline import numpy as np Explanation: If we're making the fin frames with a router/2-axis mill, we need to know what angle of chamfer cutter to use. This is just the trig to make sure that the angle of the leading edge is $\leq$ the mach angle. ...
13,650
Given the following text description, write Python code to implement the functionality described below step by step Description: Introduction to Programming Paradigms In the initial days we had only one type of programming paradigms, the paradigm of the developer Step1: Functional Step2: Functional Step3: the abov...
Python Code: towns = ["Rio de Janeiro", "Bhopal", "Budd Lake", "New York", "São Paulo", "Curitib]a "] count = 0 for city in towns: print(city) count = count + 1 print() print("Total number of cities:", count) Explanation: Introduction to Programming Paradigms In the initial days we had only one type of programm...
13,651
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...
13,652
Given the following text description, write Python code to implement the functionality described below step by step Description: Doppler shifts Exploring doppler shift on precision and quality. Specifically in the Z-band. This showed the largest change with application of dopplershifts (Fegueira 2016 Fig. C.3 and C.4)...
Python Code: import matplotlib.pyplot as plt import numpy as np from tqdm import tqdm import PyAstronomy.pyasl as pyasl from astropy import constants as const import eniric from eniric import config # config.cache["location"] = None # Disable caching for these tests config.cache["location"] = ".joblib" # Enable cachi...
13,653
Given the following text description, write Python code to implement the functionality described below step by step Description: Skip-gram word2vec In this notebook, I'll lead you through using TensorFlow to implement the word2vec algorithm using the skip-gram architecture. By implementing this, you'll learn about emb...
Python Code: import time import numpy as np import tensorflow as tf import utils Explanation: Skip-gram word2vec In this notebook, I'll lead you through using TensorFlow to implement the word2vec algorithm using the skip-gram architecture. By implementing this, you'll learn about embedding words for use in natural lang...
13,654
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: Face Generation In this project, you'll use generative adversarial networks to generate new images of faces. Get the Data You'll be using two datasets in this project Step3: Explore ...
Python Code: data_dir = './data' # FloydHub - Use with data ID "R5KrjnANiKVhLWAkpXhNBe" #data_dir = '/input' DON'T MODIFY ANYTHING IN THIS CELL import helper helper.download_extract('mnist', data_dir) helper.download_extract('celeba', data_dir) Explanation: Face Generation In this project, you'll use generative adversa...
13,655
Given the following text description, write Python code to implement the functionality described below step by step Description: Crash Course In Linear Algebra For Data Scientists Preamble This notebook was made for the purposes of quickly introducing the theoretical groundwork of Linear Algebra for Data Scientists. T...
Python Code: import numpy as np Explanation: Crash Course In Linear Algebra For Data Scientists Preamble This notebook was made for the purposes of quickly introducing the theoretical groundwork of Linear Algebra for Data Scientists. To that end, we will be primarily making the computer do the hard work of doing the te...
13,656
Given the following text description, write Python code to implement the functionality described below step by step Description: Notebook Roadmap Data Generating Process Objects of Interest Processing Specification Setting up Simulation Conducting Estimation Inspection of Results Over the next couple of lectures, we w...
Python Code: %%capture # Notebook metods from IPython.core.display import HTML, Image # Unix Pattern Extensions import glob # Operating System Interfaces import os # Lexical Analysis import shlex # Copy operations import copy # Encoders and Decoders import codecs # Statistical Modeling and Econometrics import statsmo...
13,657
Given the following text description, write Python code to implement the functionality described below step by step Description: Pick one of these to explore re Step1: Run Decision Trees, Prune, and consider False Positives Step2: As a check, consider Feature selection Step3: Find the Principal Components Step4: S...
Python Code: # Look only at train IDs features = df.columns.values X = train_id_dummies y = df['ord_del'] # Non Delay Specific features = df.columns.values target_cols = ['temp','precipiation', 'visability','windspeed','humidity','cloudcover', 'is_bullet','is_limited','t_northbound', 'd_monday','...
13,658
Given the following text description, write Python code to implement the functionality described below step by step Description: H2O Tutorial Author Step1: Enable inline plotting in the Jupyter Notebook Step2: Intro to H2O Data Munging Read csv data into H2O. This loads the data into the H2O column compressed, in-me...
Python Code: import pandas as pd import numpy from numpy.random import choice from sklearn.datasets import load_boston from h2o.estimators.random_forest import H2ORandomForestEstimator import h2o h2o.init() # transfer the boston data from pandas to H2O boston_data = load_boston() X = pd.DataFrame(data=boston_data.data,...
13,659
Given the following text description, write Python code to implement the functionality described below step by step Description: Copyright 2021 Google LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the Licens...
Python Code: # Import all necessary libs from google.colab import auth import pandas as pd import numpy as np from matplotlib import pyplot as plt from IPython.display import display, HTML # Authenticate the user to query datasets in Google BigQuery auth.authenticate_user() %matplotlib inline Explanation: Copyright 20...
13,660
Given the following text description, write Python code to implement the functionality described below step by step Description: Overview Hour 1 Tuples Dictionaries Take Up Midterm Hours 2 and 3 Work Time Lists A list is an object that contains multiple data items Lists are mutable Lists can be indexed and sliced List...
Python Code: number_list = [1, 2, 4, 8, 16, 32] the_pythons = ["Graham", "Terry", "Michael", "Eric", "Terry", "John"] mixed = [1, "Terry", 4] print (mixed) Explanation: Overview Hour 1 Tuples Dictionaries Take Up Midterm Hours 2 and 3 Work Time Lists A list is an object that contains multiple data items Lists are muta...
13,661
Given the following text description, write Python code to implement the functionality described below step by step Description: Installation tips Create Anaconda virtual environment with ipython notebook support conda create -n tf ipython-notebook --yes The set up as explained in the official site failed for me. Some...
Python Code: import tensorflow as tf #---------------------------------------------------------- # Basic graph structure and operations # tf.add , tf.sub, tf.mul , tf.div , tf.mod , tf.poe # tf.less , tf.greater , tf.less_equal , tf.greater_equal # tf.logical_and , tf.logical_or , logical.xor #----------------------...
13,662
Given the following text description, write Python code to implement the functionality described below step by step Description: Precision vs Accuracy Precision is the accuracy of basic arithmetic operations used in the computation Accuracy is the absolute or relative error of the approximate quantity* NOTE Step1: Th...
Python Code: # Definition 1: Round down to p-sig. digit numberx = 0.90x1 = 0.99 # 2 correct significant digit, actual difference 0.09x2 = 0.89 # 1 correct significant digit, actual difference 0.01 # Definition 2: Round to nearest p-sig. digit numbery = 0.9951 # --> 0.10y1 = 0.9499 # --> 0.90 , only 1 correct sig. dig...
13,663
Given the following text description, write Python code to implement the functionality described below step by step Description: Machine Intelligence II - Team MensaNord Sheet 08 Nikolai Zaki Alexander Moore Johannes Rieke Georg Hoelger Oliver Atanaszov Step1: Exercise 1 Step2: Simulation with M=1 Step3: Simulation...
Python Code: from __future__ import division, print_function import matplotlib.pyplot as plt %matplotlib inline import scipy.stats import numpy as np Explanation: Machine Intelligence II - Team MensaNord Sheet 08 Nikolai Zaki Alexander Moore Johannes Rieke Georg Hoelger Oliver Atanaszov End of explanation def E(W, s): ...
13,664
Given the following text description, write Python code to implement the functionality described below step by step Description: <H1>PrimerDesign</H1> We need to define a sequence of 17 bases with the following requirements Step1: The function product is what we need to obtain a sequence of x elements with the four n...
Python Code: %pylab inline from itertools import product, permutations from math import pow Explanation: <H1>PrimerDesign</H1> We need to define a sequence of 17 bases with the following requirements: <ul> <li>Total GC content: 40-60%</li> <li>GC Clamp: < 3 in the last 5 bases at the 3' end of the primer.</li> ...
13,665
Given the following text description, write Python code to implement the functionality described below step by step Description: Copyright 2020 DeepMind Technologies Limited. ``` Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obt...
Python Code: #@title Util functions import csv import os from matplotlib import pyplot as plt import pandas as pd import seaborn as sns import tensorflow.compat.v1 as tf from tensorflow.compat.v1.io import gfile def read_csv_as_dataframe(path): with gfile.GFile(path, "r") as file: reader = csv.reader(file, delimi...
13,666
Given the following text description, write Python code to implement the functionality described below step by step Description: Annotating Public Resources Using I-Python Notebook <h2>A Linear Algebra Example</h2> Step1: Yes, you may embed Youtubes in your I-Python Notebooks, meaning you may follow up on a presentat...
Python Code: from IPython.display import YouTubeVideo YouTubeVideo("3Md5KCCQX-0") Explanation: Annotating Public Resources Using I-Python Notebook <h2>A Linear Algebra Example</h2> End of explanation import numpy as np from scipy import linalg # https://en.wikipedia.org/wiki/Hermitian_matrix A = np.matrix('2, 2+1j, 4;...
13,667
Given the following text description, write Python code to implement the functionality described below step by step Description: Kubeflow pipelines Learning Objectives Step1: Restart the kernel After you install the additional packages, you need to restart the notebook kernel so it can find the packages. Import libra...
Python Code: !pip3 install --user kfp --upgrade Explanation: Kubeflow pipelines Learning Objectives: 1. Learn how to deploy a Kubeflow cluster on GCP 1. Learn how to create a experiment in Kubeflow 1. Learn how to package you code into a Kubeflow pipeline 1. Learn how to run a Kubeflow pipeline in a repeatable ...
13,668
Given the following text description, write Python code to implement the functionality described below step by step Description: A Simple Autoencoder We'll start off by building a simple autoencoder to compress the MNIST dataset. With autoencoders, we pass input data through an encoder that makes a compressed represen...
Python Code: %matplotlib inline import numpy as np import tensorflow as tf import matplotlib.pyplot as plt from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets('MNIST_data', validation_size=0) Explanation: A Simple Autoencoder We'll start off by building a simple autoencoder to c...
13,669
Given the following text description, write Python code to implement the functionality described below step by step Description: ApJdataFrames Erickson2011 Title Step1: Table 2- Optical Properties of Candidate Young Stellar Objects Step2: Table 3 - Association Members with Optical Spectra Step3: The code to merge t...
Python Code: %pylab inline import seaborn as sns sns.set_context("notebook", font_scale=1.5) #import warnings #warnings.filterwarnings("ignore") import pandas as pd Explanation: ApJdataFrames Erickson2011 Title: THE INITIAL MASS FUNCTION AND DISK FREQUENCY OF THE Rho OPHIUCHI CLOUD: AN EXTINCTION-LIMITED SAMPLE Author...
13,670
Given the following text description, write Python code to implement the functionality described below step by step Description: 1. Abstractions for representing environments Environmental models can be represented either through a GridMeshModel or a TriMeshModel, using a grid and a triangular based representation of ...
Python Code: from pextant.mesh.abstractmesh import NpDataset import numpy as np xx,yy= np.mgrid[0:5,0:5] basic_terrain = NpDataset(0.1*(xx**2+yy**2), resolution=1) basic_terrain Explanation: 1. Abstractions for representing environments Environmental models can be represented either through a GridMeshModel or a TriMesh...
13,671
Given the following text description, write Python code to implement the functionality described below step by step Description: 9.试作下图所示电力系统的阻抗图,并将参数注载图上(不计线路和变压器的电阻和导纳)。 1.计算时取6KV电压为基本级。 2.计算时取10KV电压为基本级。 3.计算时取110KV电压为基本级。 <img src="./第9、10题图.png" /> 1.解: 先计算各参数的实际值。 Step1: 计算各变压器变比: Step2: 将实际值归算成6kv为基准的归算值: Ste...
Python Code: x1=0.4 L1=100 X_L1=x1*L1 x2=0.4 L2=80 X_L2=x2*L2 #T1 SF7-16000/110 Sn_T1=16 #MVA Uk1=10.5 #% Un_T1=121#KV X_T1=Uk1*Un_T1**2/(100*Sn_T1) #T2 S Sn_T2=31.5 #MVA Uk2=10.5 #% Un_T2=121#KV X_T2=Uk2*Un_T2**2/(100*Sn_T2) X_T1 Explanation: 9.试作下图所示电力系统的阻抗图,并将参数注载图上(不计线路和变压器的电阻和导纳)。 1.计算时取6KV电压为基本级。 2.计算时取10KV电压为基本级...
13,672
Given the following text description, write Python code to implement the functionality described below step by step Description: pandas 3 자료 안내 Step1: 분석을 위한 테스트 데이터를 만들어 보자. Step2: 위의 함수를 이용하여 테스트 데이터를 만들고, 이를 다시 데이터프레임으로 만들어보자. Step3: 위의 데이터프레임을 Excel 파일로 저장하자. 이 때 인덱스 값은 원래의 테스트 데이터셋의 일부가 아니기 때문에 저장하지 않는다. Step4...
Python Code: import pandas as pd import matplotlib.pyplot as plt import numpy.random as np # 쥬피터 노트북에서 그래프를 직접 나타내기 위해 사용하는 코드 # 파이썬 전문 에디터에서는 사용하지 않음 %matplotlib inline Explanation: pandas 3 자료 안내: pandas 라이브러리 튜토리얼에 있는 Lessons for new pandas users의 03-Lesson 내용을 담고 있다. 익명함수(lambda 함수), GroupBy, apply, transform에 대한...
13,673
Given the following text description, write Python code to implement the functionality described below step by step Description: Structure Data Example Step1: Please Download https Step2: Dealing with NaN There are many approaches possibles for NaN values in the data, here we just changing it to " " or 0 depending o...
Python Code: from __future__ import print_function from __future__ import division from __future__ import absolute_import # We're using pandas to read the CSV file. This is easy for small datasets, but for large and complex datasets, # tensorflow parsing and processing functions are more powerful import pandas as pd im...
13,674
Given the following text description, write Python code to implement the functionality described below step by step Description: The Su-Schrieffer–Heeger (SSH) model Saumya Biswas (saumyab@uoregon.edu) The celebrated SSH model is analyzed with QuTiP's lattice module below. The above figure shows a SSH model with 6 sit...
Python Code: from qutip import * import matplotlib.pyplot as plt import numpy as np val_s = ['site0','site1'] (H_cell_form,T_inter_cell_form,H_cell,T_inter_cell) = cell_structures( val_s) H_cell_form T_inter_cell_form Explanation: The Su-Schrieffer–Heeger (SSH) model Saumya Biswas (saumyab@uoregon.edu) The celebrated S...
13,675
Given the following text description, write Python code to implement the functionality described below step by step Description: Sets implemented as AVL Trees This notebook implements <em style="color Step1: Given an ordered binary tree $t$, the expression $t.\texttt{isEmpty}()$ checks whether $t$ is the empty tree. ...
Python Code: class Set: def __init__(self): self.mKey = None self.mLeft = None self.mRight = None self.mHeight = 0 Explanation: Sets implemented as AVL Trees This notebook implements <em style="color:blue;">sets</em> as <a href="https://en.wikipedia.org/wiki/AVL_tree">AVL trees...
13,676
Given the following text description, write Python code to implement the functionality described below step by step Description: Import data Step1: Set parameters Step2: Preprocessing Step6: 1. Distribution regression Kernel mean embedding Instead of fitting a model to the instances, the idea of distribution regres...
Python Code: def load_data(): full_data = pd.read_csv("Data/X.csv") train_y = pd.read_csv("Data/y_train.csv") # Rename columns to something more interpretable columns = (["reflectance_" + str(i) for i in range(7)] + ["solar_" + str(i) for i in range(5)] + ["id"]) full_data.columns = c...
13,677
Given the following text description, write Python code to implement the functionality described below step by step Description: odm2api demo with Little Bear SQLite sample DB Largely from https Step1: Read the database Step2: Run some basic sample queries Step3: Read some metadata from the database Step4: Samplin...
Python Code: import os from odm2api.ODMconnection import dbconnection odm2db_fpth = os.path.join('data', 'ODM2.sqlite') session_factory = dbconnection.createConnection('sqlite', odm2db_fpth, 2.0) Explanation: odm2api demo with Little Bear SQLite sample DB Largely from https://github.com/ODM2/ODM2PythonAPI/blob/master/E...
13,678
Given the following text description, write Python code to implement the functionality described below step by step Description: Deep Convolutional GANs In this notebook, you'll build a GAN using convolutional layers in the generator and discriminator. This is called a Deep Convolutional GAN, or DCGAN for short. The D...
Python Code: %matplotlib inline import pickle as pkl import matplotlib.pyplot as plt import numpy as np from scipy.io import loadmat import tensorflow as tf !mkdir data Explanation: Deep Convolutional GANs In this notebook, you'll build a GAN using convolutional layers in the generator and discriminator. This is called...
13,679
Given the following text description, write Python code to implement the functionality described below step by step Description: Intermediate Linear Algebra - Eigenvalues & Eigenvectors Key Equation Step1: Solving Equation $Ax=\lambda x$ Special Case Step2: 3 x 3 Matrix Let us write it in the form $$ Ax = \lambda ...
Python Code: import numpy as np import matplotlib.pyplot as plt %matplotlib inline plt.style.use('fivethirtyeight') plt.rcParams['figure.figsize'] = (10, 6) def vector_plot (vector): X,Y,U,V = zip(*vector) C = [1,1,2,2] plt.figure() ax = plt.gca() ax.quiver(X,Y,U,V,C, angles='xy',scale_units='xy',sc...
13,680
Given the following text description, write Python code to implement the functionality described below step by step Description: Sentiment Analysis of Movie Reviews In this tutorial, we will load a trained model and perform inference on a new movie review. Setup As before, we first create a computational backend to te...
Python Code: from neon.backends import gen_backend be = gen_backend(backend='gpu', batch_size=1) print be Explanation: Sentiment Analysis of Movie Reviews In this tutorial, we will load a trained model and perform inference on a new movie review. Setup As before, we first create a computational backend to tell neon on ...
13,681
Given the following text description, write Python code to implement the functionality described below step by step Description: Calculate Coverage You've defined an AOI, you've specified the image type you are interested and the search query. Great! But what is the coverage of your AOI given your search query? Wouldn...
Python Code: # Notebook dependencies from __future__ import print_function import datetime import copy from functools import partial import os from IPython.display import display, Image import matplotlib from matplotlib import cm import matplotlib.pyplot as plt import numpy as np import pandas as pd from planet import ...
13,682
Given the following text description, write Python code to implement the functionality described below step by step Description: Domestic Load Research Programme Load Profile Uncertainty Analysis This notebook requires access to a directory with hourly load profile data. The data files must be saved in /data/profiles/...
Python Code: #load support functions import observations.obs_processing as obs import features.feature_ts as ts import features.feature_socios as socios #initiate offline plotting for plotly import plotly.offline as offline import cufflinks as cf offline.init_notebook_mode() #cf.set_config_file(offline=True, world_read...
13,683
Given the following text description, write Python code to implement the functionality described below step by step Description: Insertion Sort The function sort is specified via two equations Step1: The auxiliary function insert is specified as follows
Python Code: def sort(L): if L == []: return [] x, *R = L return insert(x, sort(R)) Explanation: Insertion Sort The function sort is specified via two equations: $\mathtt{sort}([]) = []$ $\mathtt{sort}\bigl([x] + R\bigr) = \mathtt{insert}\bigl(x, \mathtt{sort}(R)\bigr)$ This is most easily im...
13,684
Given the following text description, write Python code to implement the functionality described below step by step Description: Probabilistic Programming in Python using PyMC Authors Step1: Here is what the simulated data look like. We use the pylab module from the plotting library matplotlib. Step2: Model Specific...
Python Code: import numpy as np # Intialize random number generator np.random.seed(123) # True parameter values alpha, sigma = 1, 1 beta = [1, 2.5] # Size of dataset size = 100 # Predictor variable X1 = np.linspace(0, 1, size) X2 = np.linspace(0,.2, size) # Simulate outcome variable Y = alpha + beta[0]*X1 + beta[1]*X2 ...
13,685
Given the following text description, write Python code to implement the functionality described below step by step Description: You are currently looking at version 1.0 of this notebook. To download notebooks and datafiles, as well as get help on Jupyter notebooks in the Coursera platform, visit the Jupyter Notebook ...
Python Code: import pandas as pd pd.Series? animals = ['Tiger', 'Bear', 'Moose'] pd.Series(animals) numbers = [1, 2, 3] pd.Series(numbers) animals = ['Tiger', 'Bear', None] df = pd.Series(animals) df['number_column'] = -99999 df numbers = [1, 2, None] pd.Series(numbers) import numpy as np np.nan == None np.nan == np.na...
13,686
Given the following text description, write Python code to implement the functionality described below step by step Description: Introduction Will explore aggregation framework for some analysis and then explore how we could use it for data cleaning Example of Aggregation Framework Let's find out who tweeted the most ...
Python Code: import pprint def get_client(): from pymongo import MongoClient return MongoClient('mongodb://localhost:27017/') def get_collection(): return get_client().examples.twitter collection = get_collection() def aggregate_and_show(collection, query, limit = True): _query = query[:] if limit: ...
13,687
Given the following text description, write Python code to implement the functionality described below step by step Description: Extracting Structure from Scientific Abstracts using a LSTM neural network Paul Willot This project was made for the ICADL 2015 conference. In this notebook we will go through all steps requ...
Python Code: #%install_ext https://raw.githubusercontent.com/rasbt/watermark/master/watermark.py %load_ext watermark # for reproducibility %watermark -a 'Paul Willot' -mvp numpy,scipy,spacy Explanation: Extracting Structure from Scientific Abstracts using a LSTM neural network Paul Willot This project was made for the ...
13,688
Given the following text description, write Python code to implement the functionality described below step by step Description: Copyright 2018 The TensorFlow Authors. Step1: Image Classification using tf.keras <table class="tfo-notebook-buttons" align="left"> <td> <a target="_blank" href="https Step2: TODO St...
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...
13,689
Given the following text description, write Python code to implement the functionality described below step by step Description: <img src="../../../images/qiskit-heading.gif" alt="Note Step1: Next, we create a Python dictionary to specify the problem we want to solve. There are defaults for many additional values tha...
Python Code: from qiskit_aqua_chemistry import AquaChemistry Explanation: <img src="../../../images/qiskit-heading.gif" alt="Note: In order for images to show up in this jupyter notebook you need to select File => Trusted Notebook" width="500 px" align="left"> Qiskit Aqua: Chemistry basic how to The latest version of t...
13,690
Given the following text description, write Python code to implement the functionality described below step by step Description: Further testing of the sklearn pull request Step1: Test of the warnings Testing Area calculation tests Testing in the context of modelling Step2: Test of the warnings Step3: Testing The m...
Python Code: __author__ = 'Nick Dingwall' Explanation: Further testing of the sklearn pull request End of explanation import matplotlib.pyplot as plt import matplotlib %matplotlib inline import numpy as np from sklearn.metrics.base import _average_binary_score from sklearn.metrics import precision_recall_curve import w...
13,691
Given the following text description, write Python code to implement the functionality described below step by step Description: Converting automata to strings Use to_str() to output a string representing the automaton in different formats. Step1: Saving automata to files Use save() to save the automaton into a file....
Python Code: a = spot.translate('a U b') for fmt in ('hoa', 'spin', 'dot', 'lbtt'): print(a.to_str(fmt)) Explanation: Converting automata to strings Use to_str() to output a string representing the automaton in different formats. End of explanation a.save('example.aut').save('example.aut', format='lbtt', append=Tru...
13,692
Given the following text description, write Python code to implement the functionality described below step by step Description: Pedestrian and Face Detection on Simple Azure Pedestrian and Face Detection uses OpenCV to identify people standing in a picture or a video and NIST use case in this document is built with A...
Python Code: from simpleazure import SimpleAzure saz = SimpleAzure() Explanation: Pedestrian and Face Detection on Simple Azure Pedestrian and Face Detection uses OpenCV to identify people standing in a picture or a video and NIST use case in this document is built with Apache Spark and Mesos clusters on multiple compu...
13,693
Given the following text description, write Python code to implement the functionality described below step by step Description: Truly an 11x Developer solution to the ~~world's~~ universe's premier code interview question! What is "pynads" All joking aside, I've been hacking together a collection of Haskell-esque too...
Python Code: from pynads import Container class Person(Container): __slots__ = ('name', 'age') def __init__(self, name, age): self.name = name self.age = age def _get_val(self): return {'name': self.name, 'age': self.age} def __repr__(self): return "Person(name=...
13,694
Given the following text description, write Python code to implement the functionality described below step by step Description: <header class="w3-container w3-teal"> <img src="images/utfsm.png" alt="" align="left"/> <img src="images/inf.png" alt="" align="right"/> </header> <br/><br/><br/><br/><br/> IWI131 Programaci...
Python Code: a, b = 2, 3 while b < 300: print b, a, b = b, a+b Explanation: <header class="w3-container w3-teal"> <img src="images/utfsm.png" alt="" align="left"/> <img src="images/inf.png" alt="" align="right"/> </header> <br/><br/><br/><br/><br/> IWI131 Programación de Computadores Sebastián Flores ¿Qué conte...
13,695
Given the following text description, write Python code to implement the functionality described below step by step Description: Machine Learning Engineer Nanodegree Introduction and Foundations Project 0 Step1: From a sample of the RMS Titanic data, we can see the various features present for each passenger on the s...
Python Code: import numpy as np import pandas as pd # RMS Titanic data visualization code from titanic_visualizations import survival_stats from IPython.display import display %matplotlib inline # Load the dataset in_file = 'titanic_data.csv' full_data = pd.read_csv(in_file) # Print the first few entries of the RMS Ti...
13,696
Given the following text description, write Python code to implement the functionality described below step by step Description: PyGSLIB QQ and PP plots Step1: Getting the data ready for work If the data is in GSLIB format you can use the function pygslib.gslib.read_gslib_file(filename) to import the data into a Pand...
Python Code: #general imports import pygslib Explanation: PyGSLIB QQ and PP plots End of explanation #get the data in gslib format into a pandas Dataframe cluster= pygslib.gslib.read_gslib_file('../data/cluster.dat') true= pygslib.gslib.read_gslib_file('../data/true.dat') true['Declustering Weight'] = 1 Explanati...
13,697
Given the following text description, write Python code to implement the functionality described below step by step Description: Detecting outliers in time series Step1: TL;DR Step2: STL Decomposition Seasonal and Trend decomposition using Loess (STL) was introduced by Cleveland et al. (1990). This method performs ...
Python Code: __author__ = "Ben Bernstein" Explanation: Detecting outliers in time series End of explanation from roam_outliers import * Explanation: TL;DR: We describe a method of finding outliers in time series data by combining two distinct techniques, STL decomposition and sequential Grubbs' tests. In the end, we ar...
13,698
Given the following text description, write Python code to implement the functionality described below step by step Description: Theano, Lasagne and why they matter got no lasagne? Install the bleeding edge version from here Step1: theano teaser Doing the very same thing Step2: How does it work? if you're currently ...
Python Code: import numpy as np def sum_squares(N): return <student.Implement_me()> %%time sum_squares(10**8) Explanation: Theano, Lasagne and why they matter got no lasagne? Install the bleeding edge version from here: http://lasagne.readthedocs.org/en/latest/user/installation.html Warming up Implement a function ...
13,699
Given the following text description, write Python code to implement the functionality described below step by step Description: Copyright 2019 Google LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the Licens...
Python Code: !git clone https://github.com/google-research/google-research.git import sys import os import tarfile import urllib import zipfile sys.path.append('./google-research') Explanation: Copyright 2019 Google LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in ...