Unnamed: 0
int64
0
16k
text_prompt
stringlengths
110
62.1k
code_prompt
stringlengths
37
152k
14,600
Given the following text description, write Python code to implement the functionality described below step by step Description: Data Bootcamp 1 Step1: Example 1 Step2: The variable g (quarterly GDP growth expressed as an annual rate) is now what Python calls a DataFrame, which is a collection of data organized by v...
Python Code: x = [7, 3, 5] x.pop? Explanation: Data Bootcamp 1: Examples Python applied to economic and financial data This is an introduction to Data Bootcamp, a (prospective) course at NYU designed to give students some familiarity with (i) Python and (ii) economic and financial data. A more complete collection of ...
14,601
Given the following text description, write Python code to implement the functionality described below step by step Description: Simulating data and power analysis Tom Ellis, August 2017 Before committing to the time and cost of genotyping samples for a paternity study, it is always sensible to run simulations to test...
Python Code: import numpy as np import faps as fp import matplotlib.pylab as plt import pandas as pd from time import time, localtime, asctime np.random.seed(37) allele_freqs = np.random.uniform(0.2, 0.5, 50) adults = fp.make_parents(10, allele_freqs, family_name='adult') Explanation: Simulating data and power analysi...
14,602
Given the following text description, write Python code to implement the functionality described below step by step Description: Step2: The way you define groups affects your statistical tests This notebook is, I hope, a step towards explaining the issue and sharing some intuition about the difference between experime...
Python Code: %pylab inline from scipy import stats from ipywidgets import interact, fixed def sample_distributions(mu_neg, mu_pos, sd_neg, sd_pos, n_neg, n_pos, fnr, fpr, clip_low, clip_high): Returns subsamples and observations from two normal distributions. ...
14,603
Given the following text description, write Python code to implement the functionality described below step by step Description: Binary Data with the Beta Bernouli Distribution Let's consider one of the most basic types of data - binary data Step1: Binary data can take various forms Step2: Graphs can be represented ...
Python Code: import pandas as pd import seaborn as sns import math import cPickle as pickle import itertools as it import numpy as np import matplotlib.pyplot as plt from sklearn.datasets import fetch_mldata import itertools as it %matplotlib inline sns.set_context('talk') Explanation: Binary Data with the Beta Bernoul...
14,604
Given the following text description, write Python code to implement the functionality described below step by step Description: Handling image bytes In this notebook, we start from the checkpoints of an already trained and saved model (as in Chapter 7). For convenience, we have put this model in a public bucket in gs...
Python Code: import tensorflow as tf print('TensorFlow version' + tf.version.VERSION) print('Built with GPU support? ' + ('Yes!' if tf.test.is_built_with_cuda() else 'Noooo!')) print('There are {} GPUs'.format(len(tf.config.experimental.list_physical_devices("GPU")))) device_name = tf.test.gpu_device_name() if device_n...
14,605
Given the following text description, write Python code to implement the functionality described below step by step Description: Compare Spectral Clustering against kMeans using Similarity As there is no ground truth, the criteria used to evaluate clusters produced using Spectral and kmeans is the silhouette coefficie...
Python Code: #Compare from a silhouette_score perspective kmeans against Spectral Clustering range_n_clusters = np.arange(10)+2 for n_clusters in range_n_clusters: # The silhouette_score gives the average value for all the samples. # This gives a perspective into the density and separation of the formed # clust...
14,606
Given the following text description, write Python code to implement the functionality described below step by step Description: Word2Vec 사실 Word2vec는 noise contrastive estimator (이하 NCE) loss를 사용한다. 아직 pytorch에서는 이 부분이 구현되어 있지 않고, 간단한 vocabulary이라서 그냥 softmax를 사용해서 이 부분을 구현하였다. embedding이 2개이면, 단어에 따른 간단한 Classifiact...
Python Code: import torch from torch.autograd import Variable import torch.nn as nn import torch.nn.functional as F import torch.utils.data as data_utils Explanation: Word2Vec 사실 Word2vec는 noise contrastive estimator (이하 NCE) loss를 사용한다. 아직 pytorch에서는 이 부분이 구현되어 있지 않고, 간단한 vocabulary이라서 그냥 softmax를 사용해서 이 부분을 구현하였다. em...
14,607
Given the following text description, write Python code to implement the functionality described below step by step Description: The Most Basic-est Model of Them All They all survive Step1: The optimistic model Step2: Open a new model (.csv) file to write to Step3: Write the columns header row Step4: Take a look ...
Python Code: import csv as csv import numpy as np Explanation: The Most Basic-est Model of Them All They all survive End of explanation test_file = open('./data/test.csv', 'rb') # Open the test data test_file_object = csv.reader(test_file) header = test_file_object.next() header Explanation: The optimi...
14,608
Given the following text description, write Python code to implement the functionality described below step by step Description: modin.spreadsheet modin.spreadsheet is a Jupyter notebook widget that allows users to interact with Modin DataFrames in a spreadsheet-like fashion while taking advantage of the underlying ca...
Python Code: # Please install the required packages using `pip install -r requirements.txt` in the current directory # For all ways to install Modin see official documentation at: # https://modin.readthedocs.io/en/latest/installation.html import modin.pandas as pd import modin.spreadsheet as mss Explanation: modin.spre...
14,609
Given the following text description, write Python code to implement the functionality described below step by step Description: Web Scraping & Data Analysis with Selenium and Python Vinay Babu Github Step1: Initial Setup and Launch the browser to open the URL Step2: Getting Data Function to extract the data from We...
Python Code: %matplotlib inline from selenium import webdriver import os,time,json import pandas as pd from collections import defaultdict,Counter import matplotlib.pyplot as plt Explanation: Web Scraping & Data Analysis with Selenium and Python Vinay Babu Github: https://github.com/min2bro/WebScrapingwithSelenium Twi...
14,610
Given the following text description, write Python code to implement the functionality described below step by step Description: <!-- HTML file automatically generated from DocOnce source (https Step1: Here follows a simple example where we set up an array of ten elements, all determined by random numbers drawn accor...
Python Code: import numpy as np Explanation: <!-- HTML file automatically generated from DocOnce source (https://github.com/doconce/doconce/) doconce format html week34.do.txt --no_mako --> <!-- dom:TITLE: Week 34: Introduction to the course, Logistics and Practicalities --> Week 34: Introduction to the course, Logisti...
14,611
Given the following text description, write Python code to implement the functionality described below step by step Description: Mapwork with enlib and orphics In this short tutorial, we will Step1: It looks like white noise since we randomly put down galaxies (no clustering). Step2: Note that I'm plotting $LC_L$ he...
Python Code: from __future__ import print_function # The main mapwork module from enlib import enmap import numpy as np import matplotlib.pyplot as plt # Tools for working with enmaps, i/o, catalogs and statistics from orphics import maps as omaps,io,catalogs as cats,stats,cosmology as cosmo # Let's define a geometry c...
14,612
Given the following text description, write Python code to implement the functionality described below step by step Description: How to dynamically add functionalities to the Browser Suppose you want to add a login function to the Browser. Step1: You can define such a function at any point in your testbook. Note that...
Python Code: from marigoso import Test test = Test() browser = test.launch_browser("Firefox") data = { 'url': "http://pytest.uk", 'username': "myusername", 'password': "mysecret" } Explanation: How to dynamically add functionalities to the Browser Suppose you want to add a login function to the Browser. End...
14,613
Given the following text description, write Python code to implement the functionality described below step by step Description: Getting stretch ratios for each step Step1: Putting it all together! Step2: The sum divided by length should add up to 1... Maybe we need to subdivide it further? Or oh there's the "stretc...
Python Code: # Imports %matplotlib inline import pardir; pardir.pardir() # Allow imports from parent directory import fibonaccistretch as fib import bjorklund # Setting up basics original_rhythm = [1,0,0,1,0,0,1,0] target_rhythm = [1,0,0,0,0,1,0,0,0,0,1,0,0] fib.calculate_pulse_ratios(original_rhythm, target_rhythm) fi...
14,614
Given the following text description, write Python code to implement the functionality described below step by step Description: Q Learning and Deep Q Network Examples Step1: Game design The game the Q-agents will need to learn is made of a board with 4 cells. The agent will receive a reward of +1 every time it fills...
Python Code: import random import numpy as np import pandas as pd import tensorflow as tf import matplotlib.pyplot as plt from collections import deque from time import time seed = 23041974 random.seed(seed) print('Seed: {}'.format(seed)) Explanation: Q Learning and Deep Q Network Examples End of explanation class Game...
14,615
Given the following text description, write Python code to implement the functionality described below step by step Description: <a href="https Step1: A simple regression model using Keras with Cloud TPUs Overview This notebook demonstrates using Cloud TPUs in colab to build a simple regression model using y = sin(x)...
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...
14,616
Given the following text description, write Python code to implement the functionality described below step by step Description: Copyright 2021 The TF-Agents Authors. Step1: DQN C51/Rainbow <table class="tfo-notebook-buttons" align="left"> <td> <a target="_blank" href="https Step2: ハイパーパラメータ Step3: 環境 前回のように環...
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...
14,617
Given the following text description, write Python code to implement the functionality described below step by step Description: Make animations for webpage Create html versions of some animations to be uploaded to the webpage. Links from the pdf version of the book will go to these versions for readers who are only ...
Python Code: %matplotlib inline from IPython.display import FileLink Explanation: Make animations for webpage Create html versions of some animations to be uploaded to the webpage. Links from the pdf version of the book will go to these versions for readers who are only reading the pdf. Note that make_html_on_master.p...
14,618
Given the following text description, write Python code to implement the functionality described below step by step Description: Working with data 2017. Class 4 Contact Javier Garcia-Bernardo garcia@uva.nl 0. Structure Stats Definitions What's a p-value? One-tailed test vs two-tailed test Count vs expected count (bino...
Python Code: import pandas as pd import numpy as np import pylab as plt import seaborn as sns from scipy.stats import chi2_contingency,ttest_ind #This allows us to use R %load_ext rpy2.ipython #Visualize in line %matplotlib inline #Be able to plot images saved in the hard drive from IPython.display import Image,display...
14,619
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: TV Script Generation In this project, you'll generate your own Simpsons TV scripts using RNNs. You'll be using part of the Simpsons dataset of scripts from 27 seasons. The Neural Ne...
Python Code: DON'T MODIFY ANYTHING IN THIS CELL import helper data_dir = './data/simpsons/moes_tavern_lines.txt' text = helper.load_data(data_dir) # Ignore notice, since we don't use it for analysing the data text = text[81:] Explanation: TV Script Generation In this project, you'll generate your own Simpsons TV script...
14,620
Given the following text description, write Python code to implement the functionality described below step by step Description: Группируем по миллисекундам и усредняем Step1: Интересные нам всплески потребления кончаются где-то на 10000-ной миллисекунде (их пять подряд, мы моргали лампочкой пять раз). Step6: Функци...
Python Code: df_r1000 = df.groupby(df.index//1000).mean() fig = sns.plt.figure(figsize=(16, 6)) ax = sns.plt.subplot() df_r1000.plot(ax=ax) Explanation: Группируем по миллисекундам и усредняем: End of explanation fig = sns.plt.figure(figsize=(16, 6)) ax = sns.plt.subplot() df_r1000[:12000].plot(ax=ax) Explanation: Инте...
14,621
Given the following text description, write Python code to implement the functionality described below step by step Description: Feature Step1: Config Automatically discover the paths to various data folders and compose the project structure. Step2: Identifier for storing these features on disk and referring to them...
Python Code: from pygoose import * import math import nltk Explanation: Feature: WordNet Similarity Compute the aggregate similarity of two question token sets according to ontological graph distances in WordNet. Based on the implementation of the paper "Sentence Similarity based on Semantic Nets and Corpus Statistics"...
14,622
Given the following text description, write Python code to implement the functionality described below step by step Description: A significant portion of the checking was done in the Excel file 'manual verification.' In essence, I searched the state's site (https Step1: Five facilities did not correspond. Manual chec...
Python Code: import pandas as pd import numpy as np from IPython.core.display import display, HTML display(HTML("<style>.container { width:100% !important; }</style>")) scraped_comp = pd.read_csv('../data/scraped/scraped_complaints_3_25.csv') scraped_comp['abuse_number'] = scraped_comp['abuse_number'].apply(lambda x: x...
14,623
Given the following text description, write Python code to implement the functionality described below step by step Description: Time Series Analysis for Car Counts Guillaume Decerprit, PhD - 1 Nov. 2017 This document describes thought process and findings on data exploration & forecasting of car counts. Overview of m...
Python Code: #################### # test libraries #################### try: import mxnet except ImportError: !pip2 install mxnet try: import seaborn except ImportError: !pip2 install seaborn try: import sklearn except ImportError: !pip2 install sklearn #################### # necessary imports. ...
14,624
Given the following text description, write Python code to implement the functionality described below step by step Description: Using LAMMPS with iPython and Jupyter LAMMPS can be run interactively using iPython easily. This tutorial shows how to set this up. Installation Download the latest version of LAMMPS into a ...
Python Code: from lammps import IPyLammps L = IPyLammps() # 3d Lennard-Jones melt L.units("lj") L.atom_style("atomic") L.atom_modify("map array") L.lattice("fcc", 0.8442) L.region("box block", 0, 4, 0, 4, 0, 4) L.create_box(1, "box") L.create_atoms(1, "box") L.mass(1, 1.0) L.velocity("all create", 1.44, 87287, "loop ge...
14,625
Given the following text description, write Python code to implement the functionality described below step by step Description: Collaborative filtering on Google Analytics data This notebook demonstrates how to implement a WALS matrix refactorization approach to do collaborative filtering. Step2: Create raw dataset ...
Python Code: import os PROJECT = "cloud-training-demos" # REPLACE WITH YOUR PROJECT ID BUCKET = "cloud-training-demos-ml" # REPLACE WITH YOUR BUCKET NAME REGION = "us-central1" # REPLACE WITH YOUR BUCKET REGION e.g. us-central1 # Do not change these os.environ["PROJECT"] = PROJECT os.environ["BUCKET"] = BUCKET os.envir...
14,626
Given the following text description, write Python code to implement the functionality described. Description: Modify a given matrix by placing sorted boundary elements in clockwise manner Function to print the elements of the matrix in row - wise manner ; Function to sort boundary elements of a matrix starting from th...
Python Code: def printMatrix(a ) : for x in a : for y in x : print(y , end = "▁ ")  print()   def sortBoundaryWise(a ) : k = 0 l = 0 m = len(a ) n = len(a[0 ] ) n_k = 0 n_l = 0 n_m = m n_n = n while(k < m and l < n ) : boundary =[] for i in range(l , n ) : boundary . append(a[...
14,627
Given the following text description, write Python code to implement the functionality described below step by step Description: Import TLG http Step1: Convert TLG to Unicode http Step2: Now the TLG corpus is in now ready to use in Unicode. Some preprocesing is likely still required, as the text still has formatting...
Python Code: import datetime as dt from cltk.corpus.utils.importer import CorpusImporter corpus_importer = CorpusImporter('greek') corpus_importer.list_corpora corpus_importer.import_corpus('tlg', '/root/classics_corpora/TLG_E') Explanation: Import TLG http://docs.cltk.org/en/latest/importing_corpora.html End of explan...
14,628
Given the following text description, write Python code to implement the functionality described below step by step Description: Query for pile-up allignments at region "X" We can query the API services to obtain reads from a given readgroupset such that we are able to make a pileup for any specified region NOTE Step1...
Python Code: #Widget() Explanation: Query for pile-up allignments at region "X" We can query the API services to obtain reads from a given readgroupset such that we are able to make a pileup for any specified region NOTE: Under the "Kernel" tab above, do "Restart & Run All" then uncomment the first cell and run it indi...
14,629
Given the following text description, write Python code to implement the functionality described below step by step Description: Implementing methods Once we have a mock server, we could already provide an interface to external services mocking our replies. This is very helpful to enable clients to test our API and e...
Python Code: # connexion provides a predefined problem object from connexion import problem # Exercise: write a get_status() returning a successful response to problem. help(problem) def get_status(): return problem( status=200, title="OK", detail="The application is working properly" ...
14,630
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: Language Translation In this project, you’re going to take a peek into the realm of neural network machine translation. You’ll be training a sequence to sequence model on a dataset o...
Python Code: DON'T MODIFY ANYTHING IN THIS CELL import helper import problem_unittests as tests source_path = 'data/small_vocab_en' target_path = 'data/small_vocab_fr' source_text = helper.load_data(source_path) target_text = helper.load_data(target_path) Explanation: Language Translation In this project, you’re going ...
14,631
Given the following text description, write Python code to implement the functionality described below step by step Description: Processing in IPython This notebook shows the ability to use the Processing library (based on Java). There is also a full Processing kernel that does a Java-compile (showing any errors) with...
Python Code: ! pip install metakernel --user Explanation: Processing in IPython This notebook shows the ability to use the Processing library (based on Java). There is also a full Processing kernel that does a Java-compile (showing any errors) with additional benefits. This magic does no error checking. Requirements: I...
14,632
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: ABC Abstract base classes are a form of interface checking more strict than individual hasattr() checks for particular methods. By defining an abstract base class, you can define a co...
Python Code: from abc import ABCMeta, abstractmethod class Mammal(metaclass=ABCMeta): ## version 2.x ## __metaclass__=ABCMeta @abstractmethod def eyes(self, val): pass # @abstractmethod # def hand(self): # pass def hair(self): print("hair") def neocorte...
14,633
Given the following text description, write Python code to implement the functionality described below step by step Description: Examples and Exercises from Think Stats, 2nd Edition http Step1: Time series analysis Load the data from "Price of Weed". Step3: The following function takes a DataFrame of transactions an...
Python Code: from __future__ import print_function, division %matplotlib inline import warnings warnings.filterwarnings('ignore', category=FutureWarning) import numpy as np import pandas as pd import random import thinkstats2 import thinkplot Explanation: Examples and Exercises from Think Stats, 2nd Edition http://thin...
14,634
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="#Building-an-ANN" data-toc-modified-id="Building-an-ANN-1"><span class="toc-item-num">1&nbsp;&nbsp;</span>Building an ANN</a></div><d...
Python Code: # Installing Theano # pip install --upgrade --no-deps git+git://github.com/Theano/Theano.git # Installing Tensorflow # pip install tensorflow # Installing Keras # pip install --upgrade keras Explanation: Table of Contents <p><div class="lev1 toc-item"><a href="#Building-an-ANN" data-toc-modified-id="Buildi...
14,635
Given the following text description, write Python code to implement the functionality described below step by step Description: <img src="../artworks/matchzoo-logo.png" alt="logo" style="width Step1: Define Task There are two types of tasks available in MatchZoo. mz.tasks.Ranking and mz.tasks.Classification. We will...
Python Code: import matchzoo as mz print(mz.__version__) Explanation: <img src="../artworks/matchzoo-logo.png" alt="logo" style="width:600px;float: center"/> MatchZoo Quick Start End of explanation task = mz.tasks.Ranking() print(task) Explanation: Define Task There are two types of tasks available in MatchZoo. mz.task...
14,636
Given the following text description, write Python code to implement the functionality described below step by step Description: ES-DOC CMIP6 Model Properties - Landice 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', 'nerc', 'sandbox-3', 'landice') Explanation: ES-DOC CMIP6 Model Properties - Landice MIP Era: CMIP6 Institute: NERC Source ID: SANDBOX-3 Topic: Landice Sub-Topics: Glaciers, Ice. Prop...
14,637
Given the following text description, write Python code to implement the functionality described below step by step Description: <h1 align="center">TensorFlow Neural Network Lab</h1> <img src="image/notmnist.png"> In this lab, you'll use all the tools you learned from Introduction to TensorFlow to label images of Engl...
Python Code: import hashlib import os import pickle from urllib.request import urlretrieve import numpy as np from PIL import Image from sklearn.model_selection import train_test_split from sklearn.preprocessing import LabelBinarizer from sklearn.utils import resample from tqdm import tqdm from zipfile import ZipFile p...
14,638
Given the following text description, write Python code to implement the functionality described below step by step Description: In this little demo we'll have a look at using the HoloViews DataFrame support and Bokeh backend to explore some real world data. This demo first appeared on Philipp Rudiger's blog, but this...
Python Code: basemap = Basemap() kdims = ['Longitude', 'Latitude'] continents = hv.Polygons([poly.get_coords() for poly in basemap.landpolygons], group='Continents', kdims=kdims) countries = hv.Contours([np.array(country) for path in basemap._readboundarydata('countries') ...
14,639
Given the following text description, write Python code to implement the functionality described below step by step Description: Imports and configuration Note Step1: Specify the path to your JCMsuite installation directory here. You can skip this later if you have a configuration file. Step2: Prepare Creating a JCM...
Python Code: import sys sys.path.append('..') import os import numpy as np Explanation: Imports and configuration Note: It is assumed that impatient people do not have a configuration file yet. You can learn on configuration files in the Setting up a configuration file notebook. Since the parent directory, which conta...
14,640
Given the following text description, write Python code to implement the functionality described below step by step Description: Getting first and last date of tweets for each twitter user The purpose of this notebook is to extract unique user id, screen name, date user created, date of first tweet in dataset, date of...
Python Code: # For users: Change the filenames as you like. INPUTFILE = "POE_json2.json" OUTPUTFILE = "results.csv" Explanation: Getting first and last date of tweets for each twitter user The purpose of this notebook is to extract unique user id, screen name, date user created, date of first tweet in dataset, date of ...
14,641
Given the following text description, write Python code to implement the functionality described below step by step Description: Copyright 2019 The TensorFlow Probability Authors. Licensed under the Apache License, Version 2.0 (the "License"); Step1: TFP 確率的レイヤー:変分オートエンコーダー <table class="tfo-notebook-buttons" align="...
Python Code: #@title Licensed under the Apache License, Version 2.0 (the "License"); { display-mode: "form" } # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in...
14,642
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: TV Script Generation In this project, you'll generate your own Simpsons TV scripts using RNNs. You'll be using part of the Simpsons dataset of scripts from 27 seasons. The Neural Ne...
Python Code: DON'T MODIFY ANYTHING IN THIS CELL import helper data_dir = './data/simpsons/moes_tavern_lines.txt' text = helper.load_data(data_dir) # Ignore notice, since we don't use it for analysing the data text = text[81:] Explanation: TV Script Generation In this project, you'll generate your own Simpsons TV script...
14,643
Given the following text description, write Python code to implement the functionality described below step by step Description: EDA with Teton avalanche observations and hazard forecasts I've already preprocessed the avalanche events and forecasts, so we'll just load them into dataframes here Step1: Since we dont't ...
Python Code: events_df = pd.read_csv('btac_events.csv.gz', compression='gzip', index_col=[0], parse_dates = [2]) hzrd_df = pd.read_csv('btac_nowcast_teton.csv.gz', compression='gzip', index_col=[0], parse_dates=[0]) Explanation: EDA with Teton avalanche observations and h...
14,644
Given the following text description, write Python code to implement the functionality described below step by step Description: Calculate $f_{sat}$ for the Entire MultiDark Volume Step1: Note that changing the PBC condition enforce_PBC option does not change the $f_{sat}$ value. Calculate $f_{sat}$ for MultiDark Su...
Python Code: # initialize hod model model = PrebuiltHodModelFactory('zheng07', threshold=-21) halocat = CachedHaloCatalog(simname='multidark', redshift=0, halo_finder='rockstar') model.populate_mock(halocat, enforce_PBC=False) N_sat = len(np.where(model.mock.galaxy_table['gal_type'] == 'satellites')[0]) N_gal = len(mod...
14,645
Given the following text description, write Python code to implement the functionality described below step by step Description: Residual bias correction of Mean-field GF This is the full computation of the residual bias correction for our (mean-field) GF solution for the percolation problem (immobile "solute" with va...
Python Code: import sys sys.path.extend(['.','./Vacancy']) import numpy as np import matplotlib.pyplot as plt plt.style.use('seaborn-whitegrid') %matplotlib inline import scipy.sparse import itertools from numba import jit, njit, prange, guvectorize # faster runtime with update routines from scipy.misc import comb # f...
14,646
Given the following text description, write Python code to implement the functionality described below step by step Description: A final exercise This exercise puts together many of the topics covered in this session. 1. Load the single cube from the file iris.sample_data_path('SOI_Darwin.nc'). This contains monthly v...
Python Code: import iris soi = iris.load_cube(iris.sample_data_path('SOI_Darwin.nc')) print(soi) Explanation: A final exercise This exercise puts together many of the topics covered in this session. 1. Load the single cube from the file iris.sample_data_path('SOI_Darwin.nc'). This contains monthly values of the Souther...
14,647
Given the following text description, write Python code to implement the functionality described below step by step Description: Bayesian Data Analysis, 3rd ed Chapter 4, demo 1 Normal approximaton for Bioassay model. Step1: Find the mode by minimising negative log posterior. Compute gradients and Hessian analyticall...
Python Code: import numpy as np from scipy import optimize, stats %matplotlib inline import matplotlib.pyplot as plt import os, sys # add utilities directory to path util_path = os.path.abspath(os.path.join(os.path.pardir, 'utilities_and_data')) if util_path not in sys.path and os.path.exists(util_path): sys.path.i...
14,648
Given the following text description, write Python code to implement the functionality described below step by step Description: Creating a 2 Layer Neural Network in 30 Lines of Python Modified from an existing exercise. Credit for the original code to Stanford CS 231n To demonstrate with code the math we went over ea...
Python Code: import numpy as np import matplotlib.pyplot as plt Explanation: Creating a 2 Layer Neural Network in 30 Lines of Python Modified from an existing exercise. Credit for the original code to Stanford CS 231n To demonstrate with code the math we went over earlier, we're going to generate some data that is not ...
14,649
Given the following text description, write Python code to implement the functionality described below step by step Description: Numpy 介紹 Step1: 建立 ndarray Step2: 看 ndarray 的第一件事情: shape , dtype Step3: 有時候,可以看圖 Step4: 有很多其他建立的方式 Step5: 這是一堆資料 * 資料有什麼資訊? * 資料有什麼限制? * 這些限制有什麼意義?好處? * 以前碰過什麼類似的東西? * 可以套用在哪些東西上面? * ...
Python Code: # 起手式 import numpy as np Explanation: Numpy 介紹 End of explanation np.array([1,2,3,4]) x = _ y = np.array([[1.,2,3],[4,5,6]]) y Explanation: 建立 ndarray End of explanation x.shape y.shape x.dtype y.dtype Explanation: 看 ndarray 的第一件事情: shape , dtype End of explanation # import matplotlib %matplotlib inline i...
14,650
Given the following text description, write Python code to implement the functionality described below step by step Description: Building word vectors Setup Step1: Data load corpus vocab and wordidx Step2: load data Step3: Word Vectors Pre Trained collecting biolab words Step4: dont need word to id dict since this...
Python Code: import sys import os import re import collections import itertools import bcolz import pickle sys.path.append('../lib') import gc import random import smart_open import h5py import csv import tensorflow as tf import gensim import datetime as dt from tqdm import tqdm_notebook as tqdm import numpy as np impo...
14,651
Given the following text description, write Python code to implement the functionality described below step by step Description: CNTK 206 Part A Step1: Select the notebook runtime environment devices / settings Set the device to cpu / gpu for the test environment. If you have both CPU and GPU on your machine, you can...
Python Code: import matplotlib as mpl import matplotlib.pyplot as plt import numpy as np import os import cntk as C from cntk import Trainer from cntk.device import try_set_default_device, gpu, cpu from cntk.initializer import xavier from cntk.io import (MinibatchSource, CTFDeserializer, StreamDef, StreamDefs, ...
14,652
Given the following text description, write Python code to implement the functionality described below step by step Description: Python Pero la estrella indiscutible de Jupyter es Python, que se está convirtiendo poco a poco en el lenguaje de facto para el análisis de datos, decantando lentamente R, SAS, Matlab... Lo ...
Python Code: import pandas as pd import numpy as np from sklearn import linear_model from matplotlib import pylab as plt plt.style.use('bmh') %matplotlib notebook wine = pd.read_csv('data/winequality-white.csv',delimiter=';') wine.describe() fig = plt.figure(2) ax = [fig.add_subplot(3,4,i) for i in range(1,12)] models ...
14,653
Given the following text description, write Python code to implement the functionality described below step by step Description: Copyright 2021 The TensorFlow Authors. Step1: Extension types <table class="tfo-notebook-buttons" align="left"> <td> <a target="_blank" href="https Step5: Extension types User-define...
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...
14,654
Given the following text description, write Python code to implement the functionality described below step by step Description: 201 Step1: In this example notebook, we will walk through the creation of a tour mode choice model. To begin, we'll re-load the tours and skims data from the data setup example. Step2: Pr...
Python Code: # HIDDEN import larch.numba as lx from pytest import approx import os import numpy as np import pandas as pd import larch.numba as lx from larch import P, X Explanation: 201: Exampville Mode Choice Welcome to Exampville, the best simulated town in this here part of the internet! Exampville is a demonstrat...
14,655
Given the following text description, write Python code to implement the functionality described below step by step Description: https Step1: http Step2: http
Python Code: import quandl print quandl.get("SOCSEC/RETIRED") ! apt-get install curl Explanation: https://www.quandl.com/data/SOCSEC/RETIRED-Social-Security-Beneficiary-Data-Retired-Workers-and-Dependants End of explanation ! curl http://data.edwardsaquifer.org/csv_j17.php > csv_j17 ! curl http://data.edwardsaquifer.or...
14,656
Given the following text description, write Python code to implement the functionality described below step by step Description: Asyncio Examples All commands are coroutine functions. Connecting and Disconnecting Utilizing asyncio Redis requires an explicit disconnect of the connection since there is no asyncio decons...
Python Code: import redis.asyncio as redis connection = redis.Redis() print(f"Ping successful: {await connection.ping()}") await connection.close() Explanation: Asyncio Examples All commands are coroutine functions. Connecting and Disconnecting Utilizing asyncio Redis requires an explicit disconnect of the connection s...
14,657
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: Modeling and Simulation in Python Case study Step3: Testing make_system Step4: Testing slope_func Step5: Now we can run the simulation. Step6: Plotting r Step7: We can also see t...
Python Code: # If you want the figures to appear in the notebook, # and you want to interact with them, use # %matplotlib notebook # If you want the figures to appear in the notebook, # and you don't want to interact with them, use # %matplotlib inline # If you want the figures to appear in separate windows, use # %m...
14,658
Given the following text description, write Python code to implement the functionality described below step by step Description: Branching GP Regression Step1: Create the tree Specify where the branching point is Step2: Specify where to evaluate the kernel Step3: Specify the kernel and its hyperparameters These det...
Python Code: import pickle import gpflow import numpy as np import pandas as pd from matplotlib import pyplot as plt from BranchedGP import BranchingTree as bt from BranchedGP import VBHelperFunctions as bplot from BranchedGP import branch_kernParamGPflow as bk plt.style.use("ggplot") %matplotlib inline Explanation: Br...
14,659
Given the following text description, write Python code to implement the functionality described below step by step Description: Language Model Reports Since my local machine does not have GPU support and thus can't perform many model training and evaluation tasks in a reasonable amount of time, I have created a scrip...
Python Code: # load some requirements import json import matplotlib.pyplot as plt with open('reports/unweightednoavg_one_layer_12.json', 'r') as f: first_report = json.loads(f.read()) with open('reports/unweightednoavg_7.json', 'r') as f: second_report = json.loads(f.read()) with open('reports/unweightednoavg_4...
14,660
Given the following text description, write Python code to implement the functionality described below step by step Description: Sebastian Raschka, 2015 https Step1: <br> <br> Overview Unsupervised dimensionality reduction via principal component analysis 128 Total and explained variance Feature transformation Princi...
Python Code: %load_ext watermark %watermark -a 'Sebastian Raschka' -u -d -v -p numpy,scipy,matplotlib,scikit-learn # to install watermark just uncomment the following line: #%install_ext https://raw.githubusercontent.com/rasbt/watermark/master/watermark.py Explanation: Sebastian Raschka, 2015 https://github.com/rasbt/p...
14,661
Given the following text description, write Python code to implement the functionality described below step by step Description: Copyright 2019 The TensorFlow Authors. Step1: 시계열 예측 <table class="tfo-notebook-buttons" align="left"> <td><a target="_blank" href="https Step2: 날씨 데이터세트 이 튜토리얼은 <a class="external" href...
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...
14,662
Given the following text description, write Python code to implement the functionality described below step by step Description: Reading and plotting LMA data In a previous module we learned about LMA VHF source files - their structure, and principles of data quality control using the station mask and $\chi_{\nu}^2$. ...
Python Code: # We could tediously build a list … # filenames = ['/data/Houston/realtime-tracer/LYLOUT_200524_210000_0600.dat.gz',] # Instead, let's read a couple hours at the same time. import sys, glob filenames = glob.glob('/data/Houston/130619/LYLOUT_130619_2[0-1]*.dat.gz') for filename in filenames: print(filen...
14,663
Given the following text description, write Python code to implement the functionality described below step by step Description: W12 lab assignment Step1: Choropleth map Let's make a choropleth map with Pokemon statistics. The color of a county should correspond to the number of Pokemons found there. You can download...
Python Code: import pandas as pd from urllib.request import urlopen import json import warnings warnings.filterwarnings("ignore") Explanation: W12 lab assignment End of explanation pokemon = pd.read_csv('pokemon.csv') pokemon.head() Explanation: Choropleth map Let's make a choropleth map with Pokemon statistics. The co...
14,664
Given the following text description, write Python code to implement the functionality described below step by step Description: This notebook plots the number of origins of viviparity and reversions to oviparity, broken down by tree. The result is a grouped histogram. Step1: Read data using pandas. Step2: Pivot the...
Python Code: import pandas as pd from pandas import * import matplotlib.pyplot as plt %matplotlib inline from ggplot import * from numpy import random plt.style.use('ggplot') Explanation: This notebook plots the number of origins of viviparity and reversions to oviparity, broken down by tree. The result is a grouped h...
14,665
Given the following text description, write Python code to implement the functionality described below step by step Description: Welcome to the PyGraphML Documentation PyGraphML is a Python library designed to parse GraphML file. Overview GraphML GraphML is a comprehensive and easy-to-use file format for graphs. It co...
Python Code: %matplotlib inline import tempfile import os import sys sys.path.append("../") from pygraphml import GraphMLParser from pygraphml import Graph Explanation: Welcome to the PyGraphML Documentation PyGraphML is a Python library designed to parse GraphML file. Overview GraphML GraphML is a comprehensive and ea...
14,666
Given the following text description, write Python code to implement the functionality described below step by step Description: <p style="text-align Step2: 1. Implementar o algoritmo K-means Nesta etapa você irá implementar as funções que compõe o algoritmo do KMeans uma a uma. É importante entender e ler a document...
Python Code: # import libraries # linear algebra import numpy as np # data processing import pandas as pd # data visualization from matplotlib import pyplot as plt # sys - to get maximum float value import sys # load the data with pandas url = 'https://raw.githubusercontent.com/InsightLab/data-science-cookbook/maste...
14,667
Given the following text description, write Python code to implement the functionality described below step by step Description: Image data The goal of this notebook is to detail how to interact with, and compute statistics on the images associated to the set of ads provided for the CP1 during the MEMEX Winter QPR 201...
Python Code: import os import csv import json # set some parameters data_dir = "../data" prefix = "test" if prefix=="train": input_file = "train_adjusted.json" else: input_file = "test_adjusted_unlabelled.json" images_dir = os.path.join(data_dir,prefix+"_images") url_sha1_file = os.path.join(data_dir,prefix+"_i...
14,668
Given the following text description, write Python code to implement the functionality described below step by step Description: Executing JavaScript Code Directly in SQL Queries Using the jseval Function Tutorial MLDB provides a complete implementation of the SQL SELECT statement. Most of the functions you are used t...
Python Code: from pymldb import Connection mldb = Connection("http://localhost") Explanation: Executing JavaScript Code Directly in SQL Queries Using the jseval Function Tutorial MLDB provides a complete implementation of the SQL SELECT statement. Most of the functions you are used to using are available in your querie...
14,669
Given the following text description, write Python code to implement the functionality described below step by step Description: 机器学习工程师纳米学位 模型评价与验证 项目 1 Step1: 分析数据 在项目的第一个部分,你会对波士顿房地产数据进行初步的观察并给出你的分析。通过对数据的探索来熟悉数据可以让你更好地理解和解释你的结果。 由于这个项目的最终目标是建立一个预测房屋价值的模型,我们需要将数据集分为特征(features)和目标变量(target variable)。特征 'RM', 'LSTA...
Python Code: # Import libraries necessary for this project # 载入此项目所需要的库 import numpy as np import pandas as pd import visuals as vs # Supplementary code from sklearn.model_selection import ShuffleSplit # Pretty display for notebooks # 让结果在notebook中显示 %matplotlib inline # Load the Boston housing dataset # 载入波士顿房屋的数据集 da...
14,670
Given the following text description, write Python code to implement the functionality described below step by step Description: Content under Creative Commons Attribution license CC-BY 4.0, code under BSD 3-Clause License © 2018 by D. Koehn, notebook style sheet by L.A. Barba, N.C. Clementi Step1: 1D viscoelastic SH...
Python Code: # Execute this cell to load the notebook's style sheet, then ignore it from IPython.core.display import HTML css_file = '../style/custom.css' HTML(open(css_file, "r").read()) Explanation: Content under Creative Commons Attribution license CC-BY 4.0, code under BSD 3-Clause License © 2018 by D. Koehn, noteb...
14,671
Given the following text description, write Python code to implement the functionality described below step by step Description: Visual Comparison Between Different Classification Methods in Shogun Notebook by Youssef Emad El-Din (Github ID Step1: <a id = "section1">Data Generation and Visualization</a> Transformatio...
Python Code: import numpy as np import matplotlib.pyplot as plt import os import shogun as sg %matplotlib inline SHOGUN_DATA_DIR=os.getenv('SHOGUN_DATA_DIR', '../../../data') #Needed lists for the final plot classifiers_linear = []*10 classifiers_non_linear = []*10 classifiers_names = []*10 fadings = []*10 Explanation:...
14,672
Given the following text description, write Python code to implement the functionality described below step by step Description: Step3: Mini-Assignment 3 Step4: Stemming As we could see from the results of the last assignment, our simple index doesn't handle punctuation and the difference between singular and plural ...
Python Code: import pickle, bz2, re from collections import namedtuple, defaultdict, Counter from IPython.display import display, HTML from math import log10, sqrt Summaries_file = 'data/malaria__Summaries.pkl.bz2' Abstracts_file = 'data/malaria__Abstracts.pkl.bz2' Summaries = pickle.load( bz2.BZ2File( Summaries_file, ...
14,673
Given the following text description, write Python code to implement the functionality described below step by step Description: <a href='http Step1: The Data Let's work with the cancer data set again since it had so many features. Step2: PCA Visualization As we've noticed before it is difficult to visualize high di...
Python Code: import matplotlib.pyplot as plt import pandas as pd import numpy as np import seaborn as sns %matplotlib inline Explanation: <a href='http://www.pieriandata.com'> <img src='../Pierian_Data_Logo.png' /></a> Principal Component Analysis Let's discuss PCA! Since this isn't exactly a full machine learning algo...
14,674
Given the following text description, write Python code to implement the functionality described below step by step Description: 以下の論文のPSOアルゴリズムに従った。 http Step1: 10都市で行う。パラメータは左から順に、(都市の数、粒子の数、前期の速度の影響率、localベストの影響率、globalベストの影響率)である。 Step2: 都市の座標とプロット。 Step3: 粒子の初期化。 Step4: 100回シミュレーションした。
Python Code: %matplotlib inline import numpy as np import pylab as pl import math from sympy import * import matplotlib.pyplot as plt import matplotlib.animation as animation from mpl_toolkits.mplot3d import Axes3D def TSP_map(N): #100×100の正方格子内にN個の点を配置する関数 TSP_map = [] X = [i for i in range(100)] Y = [i f...
14,675
Given the following text description, write Python code to implement the functionality described below step by step Description: Getting started with concise Become familiar with Keras In order to successfully use Concise, please make sure you are familiar with Keras. I strongly advise everyone to read the excellent K...
Python Code: %matplotlib inline import matplotlib.pyplot as plt import concise.layers as cl import keras.layers as kl import concise.initializers as ci import concise.regularizers as cr from keras.callbacks import EarlyStopping from concise.preprocessing import encodeDNA from keras.models import Model, load_model # get...
14,676
Given the following text description, write Python code to implement the functionality described below step by step Description: Lab Exercise Step1: Complete the TODOs before executing the next cell to train the model in your local environment Modify the model.py file containing the convolutional neural network layer...
Python Code: import os PROJECT = 'my-project-id' # REPLACE WITH YOUR PROJECT ID BUCKET = 'my-bucket-name' # REPLACE WITH YOUR BUCKET NAME REGION = 'us-central1' # REPLACE WITH YOUR BUCKET REGION e.g. us-central1 MODEL_TYPE='cnn' # 'dnn' or 'cnn' # do not change these os.environ['PROJECT'] = PROJECT os.environ['BUCKET...
14,677
Given the following text description, write Python code to implement the functionality described below step by step Description: In this exercise, you'll apply what you learned in the Scaling and normalization tutorial. Setup The questions below will give you feedback on your work. Run the following cell to set up the...
Python Code: from learntools.core import binder binder.bind(globals()) from learntools.data_cleaning.ex2 import * print("Setup Complete") Explanation: In this exercise, you'll apply what you learned in the Scaling and normalization tutorial. Setup The questions below will give you feedback on your work. Run the followi...
14,678
Given the following text description, write Python code to implement the functionality described below step by step Description: Visualizing EQTransformer comes with a few visualization tools to get a better sense of data that is beinig processed and the results. 1) continouty of the seismic data being processed Step...
Python Code: from EQTransformer.utils.plot import plot_data_chart plot_data_chart('preproc/time_tracks.pkl', time_interval=10) Explanation: Visualizing EQTransformer comes with a few visualization tools to get a better sense of data that is beinig processed and the results. 1) continouty of the seismic data being pro...
14,679
Given the following text description, write Python code to implement the functionality described below step by step Description: <a href="https Step1: GRU RNNs Step2: How does this work on anything that is not a real movie review?
Python Code: # Based on # https://github.com/fchollet/deep-learning-with-python-notebooks/blob/master/6.2-understanding-recurrent-neural-networks.ipynb import warnings warnings.filterwarnings('ignore') %matplotlib inline %pylab inline import matplotlib.pyplot as plt import pandas as pd import tensorflow as tf from tens...
14,680
Given the following text description, write Python code to implement the functionality described below step by step Description: 101 Step1: This example is a mode choice model built using the Swissmetro example dataset. First we can create a Model object Step2: We can attach a title to the model. The title does not ...
Python Code: # TEST import os import pandas as pd pd.set_option("display.max_columns", 999) pd.set_option('expand_frame_repr', False) pd.set_option('display.precision', 3) import larch larch._doctest_mode_ = True from pytest import approx import larch.numba as lx import larch.numba as lx Explanation: 101: Swissmetro MN...
14,681
Given the following text description, write Python code to implement the functionality described below step by step Description: Set weather data datetime This notebook formats a date and a time column for weather data measurements with a unix timestamp. Each measurement is then inserted into a pumilio database. Requi...
Python Code: weather_filepath = "" Explanation: Set weather data datetime This notebook formats a date and a time column for weather data measurements with a unix timestamp. Each measurement is then inserted into a pumilio database. Required packages <a href="https://github.com/pydata/pandas">pandas</a> <br /> <a href=...
14,682
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', 'snu', 'sam0-unicon', 'land') Explanation: ES-DOC CMIP6 Model Properties - Land MIP Era: CMIP6 Institute: SNU Source ID: SAM0-UNICON Topic: Land Sub-Topics: Soil, Snow, Vegetation, Ene...
14,683
Given the following text description, write Python code to implement the functionality described below step by step Description: Working from Remote Geophysical data Examples of accessing Netcdf data via TRHEDDS/OPENDAP services in Python, and plotting in Basemaps First, import libraries Important note It looks like f...
Python Code: from mpl_toolkits.basemap import Basemap, shiftgrid from netCDF4 import Dataset, date2index import time import sys import numpy as np import matplotlib.pyplot as plt import matplotlib.cm as cm from datetime import datetime, timedelta %matplotlib notebook Explanation: Working from Remote Geophysical data Ex...
14,684
Given the following text description, write Python code to implement the functionality described below step by step Description: Experiment for the paper "Identification of singleton mentions in Russian" Replication of CLLS-2016 paper (Ionov and Toldova 2016) To reproduce this experiment you will need Step1: Reading ...
Python Code: %cd '/Users/max/Projects/Coreference/' %cd 'rucoref' from anaphoralib.corpora import rueval from anaphoralib.tagsets import multeast from anaphoralib.experiments.base import BaseClassifier from anaphoralib import utils from anaphoralib.experiments import utils as exp_utils %cd '..' from sklearn.ensemble im...
14,685
Given the following text description, write Python code to implement the functionality described below step by step Description: Hashing Hashing can be useful in speeding up the search process for a specific item that is part of a larger collection of items. Depending on the implementation of the hashing algorithm, th...
Python Code: items = [25,54,34,67,75,21,77,31] def hash(item_list, table_size): hash_table = dict([(i,None) for i,x in enumerate(range(table_size))]) for item in item_list: i = item % table_size print("The hash for %s is %s" % (item, i)) hash_table[i] = item return hash_table # ...
14,686
Given the following text description, write Python code to implement the functionality described below step by step Description: This notebook will demonstrate how to do basic SuperDARN data plotting. Step1: Remote File RTI Plots Step2: Local File RTI Plot You can also plot data stored in a local file. Just change ...
Python Code: %pylab inline import datetime import os import matplotlib.pyplot as plt from davitpy import pydarn sTime = datetime.datetime(2008,2,22) eTime = datetime.datetime(2008,2,23) radar = 'bks' beam = 7 Explanation: This notebook will demonstrate how to do basic SuperDARN data plotting. End of explanation #The f...
14,687
Given the following text description, write Python code to implement the functionality described below step by step Description: Euler Equations The Euler equations in primitive variable form, $q = (\rho, u, p)^\intercal$ appear as Step1: The eigenvalues are the speeds at which information propagates with. SymPy ret...
Python Code: from sympy.abc import rho rho, u, c = symbols('rho u c') A = Matrix([[u, rho, 0], [0, u, rho**-1], [0, c**2 * rho, u]]) A Explanation: Euler Equations The Euler equations in primitive variable form, $q = (\rho, u, p)^\intercal$ appear as: $$q_t + A(q) q_x = 0$$ with the matrix $A(q)$: $$A(q) = \left ( \beg...
14,688
Given the following text description, write Python code to implement the functionality described below step by step Description: You are almost done with the course. Nice job! We have a couple more interesting problems for you before you go. As always, run the setup code below before working on the questions. Step1: ...
Python Code: from learntools.core import binder; binder.bind(globals()) from learntools.python.ex6 import * print('Setup complete.') Explanation: You are almost done with the course. Nice job! We have a couple more interesting problems for you before you go. As always, run the setup code below before working on the qu...
14,689
Given the following text description, write Python code to implement the functionality described. Description: Minimize cost to split an array into K subsets such that the cost of each element is its product with its position in the subset Function to find the minimum cost to split array into K subsets ; Sort the array...
Python Code: def getMinCost(arr , n , k ) : arr . sort(reverse = True ) min_cost = 0 ; X = 0 ; for i in range(0 , n , k ) : for j in range(i , n , 1 ) : if(j < i + k ) : min_cost += arr[j ] *(X + 1 ) ;   X += 1 ;  return min_cost ;  if __name__== ' __main __' : arr =[9 , 20 , 7 , 8 ] ; ...
14,690
Given the following text description, write Python code to implement the functionality described below step by step Description: Импортируем все необходимые библиотеки Step1: Загружаем наши данные и смотрим на их состояние Step2: Легко заметить, что в тренировочном датасете у нас не хватает данных о возрасте, каюте ...
Python Code: # pandas import pandas as pd from pandas import DataFrame import re import numpy as np import matplotlib.pyplot as plt import seaborn as sns sns.set_style('whitegrid') %matplotlib inline # machine learning from sklearn.linear_model import LogisticRegression from sklearn.ensemble import RandomForestClassifi...
14,691
Given the following text description, write Python code to implement the functionality described below step by step Description: An old FiPy solution to 1D BL I'm not really sure if the result is correct. The results is indeed incorrect. See the updated code a few cells below that might work slightly better. Step1: U...
Python Code: from fipy import * u = 1.e-3 L = 100. nx = 200 dt = 200. dx = L/nx muo = 0.002 muw = 0.001 mesh = Grid1D(dx = L/nx, nx = nx) x = mesh.cellCenters sw = CellVariable(mesh=mesh, name="saturation", hasOld=True, value = 0.) sw.setValue(1,where = x<=dx) sw.constrain(1.,mesh.facesLeft) #sw.constrain(0., mesh.face...
14,692
Given the following text description, write Python code to implement the functionality described below step by step Description: Default Behavior of BTE Step1: As you can see above, by default, BTE will query all APIs integrated. Remove a specific API or a list of APIs from BTE Step2: The Registry class stores all A...
Python Code: from biothings_explorer.user_query_dispatcher import FindConnection from biothings_explorer.hint import Hint ht = Hint() # find all potential representations of CML cml_hint = ht.query("MONDO:0011996") # select the correct representation of CML cml = cml_hint['Disease'][0] cml # find all potential represen...
14,693
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', 'noaa-gfdl', 'sandbox-2', 'toplevel') Explanation: ES-DOC CMIP6 Model Properties - Toplevel MIP Era: CMIP6 Institute: NOAA-GFDL Source ID: SANDBOX-2 Sub-Topics: Radiative Forcings. Pr...
14,694
Given the following text description, write Python code to implement the functionality described below step by step Description: Graph Analyses Here, we'll perform various analysis by constructing graphs and measure properties of those graphs to learn more about the data Step1: We'll start with just looking at analys...
Python Code: import csv from scipy.stats import kurtosis from scipy.stats import skew from scipy.spatial import Delaunay import numpy as np import math import skimage import matplotlib.pyplot as plt import seaborn as sns from skimage import future import networkx as nx %matplotlib inline # Read in the data data = open(...
14,695
Given the following text description, write Python code to implement the functionality described below step by step Description: Forecast Tutorial This tutorial will walk through forecast data from Unidata forecast model data using the forecast.py module within pvlib. Table of contents Step1: GFS (0.5 deg) Step2: GF...
Python Code: %matplotlib inline import matplotlib.pyplot as plt # built in python modules import datetime import os # python add-ons import numpy as np import pandas as pd # for accessing UNIDATA THREDD servers from siphon.catalog import TDSCatalog from siphon.ncss import NCSS import pvlib from pvlib.forecast import GF...
14,696
Given the following text description, write Python code to implement the functionality described below step by step Description: VecLib A Python library for playing with and visualizing vectors in Jupyter notebooks. For personal learning purposes. Step3: Roadmap <s>Addition and subtraction</s> <s>Scaling (multiplicat...
Python Code: import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D from IPython.display import display_png %matplotlib inline plt.style.use('seaborn-whitegrid') Explanation: VecLib A Python library for playing with and visualizing vectors in Jupyter notebooks. For personal learning ...
14,697
Given the following text description, write Python code to implement the functionality described below step by step Description: Numpy Step1: 1.2 Creating Arrays Step2: 1.3 Basic Data Types Step3: 1.4 Basic Visualization Step4: 1.5 Indexing and Slicing Step5: 1.6 Copies and views Step6: 1.7 Fancy Indexing Step7:...
Python Code: # import numpy by following the convention import numpy as np Explanation: Numpy: Creating and Manipulating Numerical Data 1. The Numpy Array Object 1.1 What are Numpy and Numpy Arrays? Numpy: the core tool for performance numerical computing with Python Numpy arrays: multi-dimentional data structures in N...
14,698
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: The sqlite3 module implements a Python DB-API 2.0 compliant interface to SQLite, an in-process relational database. SQLite is designed to be embedded in applications, instead of using...
Python Code: import os import sqlite3 db_filename = 'todo.db' db_is_new = not os.path.exists(db_filename) conn = sqlite3.connect(db_filename) if db_is_new: print('Need to create schema') else: print('Database exists, assume schme does, too.') conn.close() %ls *.db %rm -rf todo.db import os import sqlite3 db_fil...
14,699
Given the following text description, write Python code to implement the functionality described below step by step Description: Name Data preparation using Apache Pig on YARN with Cloud Dataproc Label Cloud Dataproc, GCP, Cloud Storage, YARN, Pig, Apache, Kubeflow, pipelines, components Summary A Kubeflow Pipeline co...
Python Code: %%capture --no-stderr !pip3 install kfp --upgrade Explanation: Name Data preparation using Apache Pig on YARN with Cloud Dataproc Label Cloud Dataproc, GCP, Cloud Storage, YARN, Pig, Apache, Kubeflow, pipelines, components Summary A Kubeflow Pipeline component to prepare data by submitting an Apache Pig jo...