Unnamed: 0 int64 0 16k | text_prompt stringlengths 110 62.1k | code_prompt stringlengths 37 152k |
|---|---|---|
7,900 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
PyQt5 QSettings Note
保存应用窗口大小和位置的例子
```
def read_settings(self)
Step1: 最简单的用法 | Python Code:
from PyQt5.QtCore import QSettings
Explanation: PyQt5 QSettings Note
保存应用窗口大小和位置的例子
```
def read_settings(self):
settings = QSettings("Dormouse", "LakeTai")
pos = settings.value("pos", QPoint(200, 200))
size = settings.value("size", QSize(400, 400))
self.resize(size)
... |
7,901 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Lesson 39
Step1: Response objects can be checked via status codes
Step2: The response object has succeded, and all values are stored within it
Step3: A typical way to deal with status is ... | Python Code:
# Test the requests module by importing it
import requests
# Store a website url in a response object that can be queried
res = requests.get('https://automatetheboringstuff.com/files/rj.txt')
Explanation: Lesson 39:
Downloading from the Web with the Requests Module
The requests module lets you easily downl... |
7,902 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Sparkling Titanic
Step1: Here, I want to find the percentance of people that survived based on their class
pclass
Step2: As expected, most of the upper class survived, while the lower clas... | Python Code:
# imports
from pyspark import SparkContext
from pyspark.sql import SQLContext
from pyspark.sql.types import *
from pyspark.sql import functions as F
from graphframes import *
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np
# make graphs beautiful
plt.style.use('... |
7,903 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Matching Market
This simple model consists of a buyer, a supplier, and a market.
The buyer represents a group of customers whose willingness to pay for a single unit of the good is captured... | Python Code:
import random as rnd
class Supplier():
def __init__(self):
self.wta = []
# the supplier has n quantities that they can sell
# they may be willing to sell this quantity anywhere from a lower price of l
# to a higher price of u
def set_quantity(self,n,l,u):
for i in r... |
7,904 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Style Transfer Tutorial
Our Changes
Step1: Imports
Step2: This was developed using Python 3.5.2 (Anaconda) and TensorFlow version
Step3: The VGG-16 model is downloaded from the internet. ... | Python Code:
from IPython.display import Image, display
Image('images/15_style_transfer_flowchart.png')
Explanation: Style Transfer Tutorial
Our Changes:
We have modified the create_denoise_loss function which denoises the mixed image. This function now shifts the input image by 50 pixels one axis at a time and then ca... |
7,905 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Example of DOV search methods for interpretations (geotechnische codering)
Use cases explained below
Get 'geotechnische codering' in a bounding box
Get 'geotechnische codering' with specific... | Python Code:
%matplotlib inline
import inspect, sys
# check pydov path
import pydov
Explanation: Example of DOV search methods for interpretations (geotechnische codering)
Use cases explained below
Get 'geotechnische codering' in a bounding box
Get 'geotechnische codering' with specific properties within a distance fro... |
7,906 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Ice - Albedo Feedback and runaway glaciation
Here we will use the 1-dimensional diffusive Energy Balance Model (EBM) to explore the effects of albedo feedback and heat transport on climate s... | Python Code:
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
import climlab
from climlab import constants as const
from climlab import legendre
Explanation: Ice - Albedo Feedback and runaway glaciation
Here we will use the 1-dimensional diffusive Energy Balance Model (EBM) to explore the effects o... |
7,907 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Example - Customize the μs-ALEX histogram
This notebook is part of smFRET burst analysis software FRETBursts.
In this notebook shows how to plot different styles of μs-ALEX histograms and $E... | Python Code:
from fretbursts import *
sns = init_notebook(apionly=True)
print('seaborn version: ', sns.__version__)
# Tweak here matplotlib style
import matplotlib as mpl
mpl.rcParams['font.sans-serif'].insert(0, 'Arial')
mpl.rcParams['font.size'] = 12
%config InlineBackend.figure_format = 'retina'
Explanation: Example... |
7,908 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<center> The effect of weather temperature on frequency of crimes </center>
In this notebook, I examine the relationship between weather temperature and frequency of crimes. This analysis is... | Python Code:
#importing libraries
import pandas as pd
import numpy as np
from datetime import datetime
import matplotlib.pyplot as plt
import seaborn as sns
import glob
import warnings
warnings.filterwarnings("ignore")
%matplotlib inline
#Compiling multiple csv files present in a folder together in one dataframe.
data ... |
7,909 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<H1>Bidirectional connections as a function of the distance </H1>
We will test whether bidirectionally connected inhibitory interneurons are over-represented as a function of the intersomati... | Python Code:
%pylab inline
import warnings
from inet import DataLoader, __version__
from inet.motifs import iicounter
from inet.utils import II_slice
print('Inet version {}'.format(__version__))
# use filenames in the dataset to read list of distances to be read
mydataset = DataLoader('../data/PV')
pvfiles = [ i for i ... |
7,910 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Creating Customer Segments
In this project we will analyze a dataset containing annual spending amounts for internal structure, to understand the variation in the different types of customer... | Python Code:
# Import libraries: NumPy, pandas, matplotlib
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# Tell iPython to include plots inline in the notebook
%matplotlib inline
# read .csv from provided dataset
csv_filename="Wholesale customers data.csv"
# df=pd.read_csv(csv_filename,index_co... |
7,911 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Sobreajuste
Les voy a mostrar algo mágico. Y después les voy a contar por qué le puse el título a este documento.
Déjenme importar primero algunas bibliotecas de manejo de datos y aprendiza... | Python Code:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
plt.style.use('seaborn-whitegrid')
from sklearn.linear_model import Ridge
from sklearn.preprocessing import PolynomialFeatures
from sklearn.pipeline import make_pipeline
Explanation: Sobreajuste
Les voy a mostrar algo mágico. Y después ... |
7,912 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
AmicalSat ShockBurst image packets processing
This notebook shows how to process ShockBurst S-band image packets to reassemble the image file
Step1: The data shockburst.u8 contains ShockBur... | Python Code:
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
from collections import Counter
Explanation: AmicalSat ShockBurst image packets processing
This notebook shows how to process ShockBurst S-band image packets to reassemble the image file
End of explanation
data = np.fromfile('/home/danie... |
7,913 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
We now have almost everything we need to process our data files, only thing missing is a library to grab files
Step1: glob contains function glob that finds files that match a pattern
* mat... | Python Code:
import glob
import numpy
import matplotlib.pyplot
Explanation: We now have almost everything we need to process our data files, only thing missing is a library to grab files
End of explanation
print(glob.glob('data/inflammation*.csv'))
Explanation: glob contains function glob that finds files that match a ... |
7,914 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Zenodo data downloads
20/07/20
Quick tests for data IO with Zenodo.
(See also epsman for Zenodo API stuff (in development) for packaging & uploading to Zenodo + ePSdata.)
Options
Step2: Wit... | Python Code:
import requests
# From doi
urlDOI = 'http://dx.doi.org/10.5281/zenodo.3629721'
r = requests.get(urlDOI)
r.ok
dir(r)
# r.json() Throws an error, not sure why!
# import json
# json.loads(r.text) # Ah, same error - seems to be formatting issue?
# JSONDecodeError: Expecting value: line 2... |
7,915 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Median Edge Coverage
Step1: Current Fuzzbench default report ranking
use the mean edges covered per benchmark
rank each fuzzer by their mean ranking for all benchmarks
Step2: Other ranking... | Python Code:
exp_snapshot_df.pivot_table(index='benchmark', columns='fuzzer', values='edges_covered', aggfunc='median')
Explanation: Median Edge Coverage
End of explanation
default_report_rank = data_utils.experiment_level_ranking(
exp_snapshot_df,
data_utils.benchmark_rank_by_mean,
data_utils.experiment_... |
7,916 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Notebook 9
Step1: Download the sequence data
Sequence data for this study are archived on the NCBI sequence read archive (SRA). Below I read in SraRunTable.txt for this project which contai... | Python Code:
### Notebook 9
### Data set 9 (Ohomopterus)
### Authors: Takahashi et al. 2014
### Data Location: DRP001067
Explanation: Notebook 9:
This is an IPython notebook. Most of the code is composed of bash scripts, indicated by %%bash at the top of the cell, otherwise it is IPython code. This notebook includes co... |
7,917 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Computation of voltage divider
It could happen that the mains voltage fluctuates because of voltage collapses. Nevertheless, the resulting signal has to be stable enough so that the fluctuat... | Python Code:
from IPython.display import Image
Image(filename='circuit.png')
# %matplotlib notebook
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as patches
from IPython.display import HTML, display
# For tables
def tableit(data):
display(HTML(
'<table><tr>{}</tr></table>'.fo... |
7,918 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Get Data
API
Step1: Load Data
Step2: Preprocessing
Step3: Transformation
Create column target with class [UP, KEEP, DOWN]
Step4: Create columns from Timestamp to Date, Year, Month, Hour,... | Python Code:
# get_data.get('data/datas.csv', period=settings.PERIOD, market=settings.MARKET)
Explanation: Get Data
API: http://bitcoincharts.com/charts
period = ['1-min', '5-min', '15-min', '30-min', 'Hourly', '2-hour', '6-hour', '12-hour', 'Daily', 'Weekly']
market = ['krakenEUR', 'bitstampUSD'] -> list of markets: h... |
7,919 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Define Global Variables and Helper Functions
Step1: Load Resources
Step2: NLTK
Step3: Pre-process comments
Step4: Replace Insults
We are going to replace any appearance of an insult with... | Python Code:
# Global Imports
import numpy as np
from sklearn import metrics
import pandas as pd
import os
import matplotlib.pyplot as plt
# Helpers
TRAIN_FILE = "resources/train/train.csv"
TEST_FILE = "resources/test/test_with_solutions.csv"
BAD_WORDS_FILE = "resources/badwords.txt"
NO_INSULT = 'NoInsult'
INSULT = 'In... |
7,920 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
数据抓取:
抓取47年政府工作报告
王成军
wangchengjun@nju.edu.cn
计算传播网 http
Step1: Inspect
<td width="274" class="bl">· <a href="./d12qgrdzfbg/201603/t20160318_369509.html" target="_blank" title="2016年政... | Python Code:
import urllib2
from bs4 import BeautifulSoup
from IPython.display import display_html, HTML
HTML('<iframe src=http://www.hprc.org.cn/wxzl/wxysl/lczf/ width=1000 height=500></iframe>')
# the webpage we would like to crawl
Explanation: 数据抓取:
抓取47年政府工作报告
王成军
wangchengjun@nju.edu.cn
计算传播网 http://computational... |
7,921 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step4: Where Am I?
Startup.ML Conference - San Francisco - Jan 20, 2017
Who Am I?
Chris Fregly
Research Scientist @ PipelineIO
Video Series Author "High Performance Tensorflow in Production"... | Python Code:
import numpy as np
import os
import tensorflow as tf
from tensorflow.contrib.session_bundle import exporter
import time
# make things wide
from IPython.core.display import display, HTML
display(HTML("<style>.container { width:100% !important; }</style>"))
from IPython.display import clear_output, Image, di... |
7,922 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
ABU量化系统使用文档
<center>
<img src="./image/abu_logo.png" alt="" style="vertical-align
Step1: 1. 参数取值范围
Grid Search实际上是蒙特卡洛方法的一种实现子集,它首先固定了几组参数取值范围,把无限个解问题先缩小到有限个解的问题,然后对排列组合的各个参数组合迭代进行运... | Python Code:
# 基础库导入
from __future__ import print_function
from __future__ import division
import warnings
warnings.filterwarnings('ignore')
warnings.simplefilter('ignore')
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline
import ipywidgets
import os
import sys
# 使用insert 0即只使用gi... |
7,923 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Recurrent Neural Networks (RNN) with Keras
Learning Objectives
Add built-in RNN layers.
Build bidirectional RNNs.
Using CuDNN kernels when available.
Build a RNN model with nested input/outp... | Python Code:
import numpy as np
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
Explanation: Recurrent Neural Networks (RNN) with Keras
Learning Objectives
Add built-in RNN layers.
Build bidirectional RNNs.
Using CuDNN kernels when available.
Build a RNN model with nested input/... |
7,924 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Index - Back - Next
Widget List
Step1: Numeric widgets
There are 10 widgets distributed with IPython that are designed to display numeric values. Widgets exist for displaying integers and ... | Python Code:
import ipywidgets as widgets
Explanation: Index - Back - Next
Widget List
End of explanation
widgets.IntSlider(
value=7,
min=0,
max=10,
step=1,
description='Test:',
disabled=False,
continuous_update=False,
orientation='horizontal',
readout=True,
readout_format='i'
)
... |
7,925 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Quandl
Step1: The data goes all the way back to 1947 and is updated quarterly.
Blaze provides us with the first 10 rows of the data for display. Just to confirm, let's just count the number... | Python Code:
# import the dataset
from quantopian.interactive.data.quandl import fred_gdpdef
# Since this data is public domain and provided by Quandl for free, there is no _free version of this
# data set, as found in the premium sets. This import gets you the entirety of this data set.
# import data operations
from o... |
7,926 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
End-To-End Example
Step1: First we need to find the latitude and longitude of Syracuse, then estimate the appropriate zoom level...
Step2: We get the data from the RoadsChallange github ac... | Python Code:
import folium
import pandas as pd
Explanation: End-To-End Example: Plotting and Mapping Potholes
Let's do a data analysis of Syracuse Potholes based on data from the civic hackathon https://cityofsyracuse.github.io/RoadsChallenge/
We will plot data and display pothole locations on a map!
End of explanatio... |
7,927 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Simple notebook pipeline
Welcome to your first steps with Kubeflow Pipelines (KFP). This notebook demos
Step1: Setup
Step2: Create pipeline component
Create a python function
Step3: Build... | Python Code:
# You may need to restart your notebook kernel after updating the kfp sdk
!python3 -m pip install kfp --upgrade --user
Explanation: Simple notebook pipeline
Welcome to your first steps with Kubeflow Pipelines (KFP). This notebook demos:
Defining a Kubeflow pipeline with the KFP SDK
Creating an experiment ... |
7,928 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Metadata
Step1: Este pequeño script muestra algunos aspectos importantes de la sintaxis de Python.
Comentarios
Los comentarios en Python empiezan con un "pound", "hash" o numeral # y cualqu... | Python Code:
# set the midpoint
midpoint = 5
# make two empty lists
lower = []; upper = []
# split the numbers into lower and upper
for i in range(10):
if (i < midpoint):
lower.append(i)
else:
upper.append(i)
print("lower:", lower)
print("upper:", upper)
Explanation: Metadata: Estos not... |
7,929 | 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 ... |
7,930 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2021 The TensorFlow Authors.
Step1: TFX Keras コンポーネントのチュートリアル
TensorFlow Extended (TFX) の各コンポーネントの紹介
注:この例は、Jupyter スタイルのノートブックで今すぐ実行できます。セットアップは必要ありません。「Google Colab で実行」をクリックするだ... | 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... |
7,931 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Simulating with FBA
Simulations using flux balance analysis can be solved using Model.optimize(). This will maximize or minimize (maximizing is the default) flux through the objective reacti... | Python Code:
import cobra.test
model = cobra.test.create_test_model("textbook")
Explanation: Simulating with FBA
Simulations using flux balance analysis can be solved using Model.optimize(). This will maximize or minimize (maximizing is the default) flux through the objective reactions.
End of explanation
solution = mo... |
7,932 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Title
Step1: Create Two Tables, Criminals And Crimes
Step2: Inner Join
Returns all rows whose merge-on id appears in both tables.
Step3: Left Join
Returns all rows from the left table but... | Python Code:
# Ignore
%load_ext sql
%sql sqlite://
%config SqlMagic.feedback = False
Explanation: Title: Merge Tables
Slug: merge_tables
Summary: Merge tables in SQL.
Date: 2016-05-01 12:00
Category: SQL
Tags: Basics
Authors: Chris Albon
Note: This tutorial was written using Catherine Devlin's SQL in Jupyter Noteboo... |
7,933 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Demonstration of the topic coherence pipeline in Gensim
Introduction
We will be using the u_mass and c_v coherence for two different LDA models
Step1: Set up logging
Step2: Set up corpus
A... | Python Code:
import numpy as np
import logging
try:
import pyLDAvis.gensim
except ImportError:
ValueError("SKIP: please install pyLDAvis")
import json
import warnings
warnings.filterwarnings('ignore') # To ignore all warnings that arise here to enhance clarity
from gensim.models.coherencemodel import Cohe... |
7,934 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Homogenization with fiber-like structures
Introduction
This example demonstrates the use of the homogenization model from pyMKS on a set of fiber-like structures. These structures are simul... | Python Code:
import numpy as np
%matplotlib inline
%load_ext autoreload
%autoreload 2
import matplotlib.pyplot as plt
Explanation: Homogenization with fiber-like structures
Introduction
This example demonstrates the use of the homogenization model from pyMKS on a set of fiber-like structures. These structures are simu... |
7,935 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Decoding sensor space data with generalization across time and conditions
This example runs the analysis described in
Step1: We will train the classifier on all left visual vs auditory tri... | Python Code:
# Authors: Jean-Remi King <jeanremi.king@gmail.com>
# Alexandre Gramfort <alexandre.gramfort@inria.fr>
# Denis Engemann <denis.engemann@gmail.com>
#
# License: BSD-3-Clause
import matplotlib.pyplot as plt
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import Standar... |
7,936 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Welcome to bruges
This page gives a quick look at some of the things bruges can do.
This library does all sorts of things so it's hard to show you a single workflow and say, "here's how to u... | Python Code:
import bruges as bg
m, top, base, ref = bg.models.wedge(width=120)
Explanation: Welcome to bruges
This page gives a quick look at some of the things bruges can do.
This library does all sorts of things so it's hard to show you a single workflow and say, "here's how to use bruges". But making a simple wedge... |
7,937 | 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="#Python-Pi-Day-2017" data-toc-modified-id="Python-Pi-Day-2017-1"><span class="toc-item-num">1 </span>Python Pi Day 2017</a... | Python Code:
print(" pi ~= 3.14 (two first digits).")
print(" pi ~= 22/7 = {} (two first digits).".format(22.0 / 7.0))
print(" pi ~= 355/113 = {} (six first digits).".format(355.0 / 113.0))
Explanation: Table of Contents
<p><div class="lev1 toc-item"><a href="#Python-Pi-Day-2017" data-toc-modified-id="Python-Pi-Day-201... |
7,938 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2019 The TensorFlow Authors.
Step1: Federated Learning for Text Generation
<table class="tfo-notebook-buttons" align="left">
<td>
<a target="_blank" href="https
Step2: Load... | 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... |
7,939 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Vectors
Create a vector
Step1: Convert it into a row vector
Step2: Convert it into a column vector
Step3: Vectors can be considered as a single feature matrix
Step4: Multiple Feature Mat... | Python Code:
import numpy as np
vector = np.array([1, 2, 3, 4, 5])
vector
Explanation: Vectors
Create a vector:
End of explanation
vector.reshape((5, 1))
Explanation: Convert it into a row vector:
End of explanation
vector.reshape((1, 5))
Explanation: Convert it into a column vector:
End of explanation
vector.reshape((... |
7,940 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<table align="left">
<td>
<a href="https
Step1: Restart the kernel
After you install the additional packages, you need to restart the notebook kernel so it can find the packages.
Step... | Python Code:
import os
# The Google Cloud Notebook product has specific requirements
IS_GOOGLE_CLOUD_NOTEBOOK = os.path.exists("/opt/deeplearning/metadata/env_version")
# Google Cloud Notebook requires dependencies to be installed with '--user'
USER_FLAG = ""
if IS_GOOGLE_CLOUD_NOTEBOOK:
USER_FLAG = "--user"
!pip3 ... |
7,941 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Getting a Python CASTable Object from an Existing CAS Table
Many of the examples in the Python series of articles here use a CASTable object to invoke actions or apply DataFrame-like syntax ... | Python Code:
import swat
conn = swat.CAS(host, port, username, password)
Explanation: Getting a Python CASTable Object from an Existing CAS Table
Many of the examples in the Python series of articles here use a CASTable object to invoke actions or apply DataFrame-like syntax to CAS tables. In those examples, the CASTa... |
7,942 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
FLIGHT TRUST
Summary
Simple python script that runs a regression to predict actual flight time and probability of delay of airlines by route. This document takes you through each of the step... | Python Code:
import pandas as pd
import statsmodels.api as sm
from sklearn.cross_validation import train_test_split
import math
import numpy as np
import matplotlib.pyplot as plt
Explanation: FLIGHT TRUST
Summary
Simple python script that runs a regression to predict actual flight time and probability of delay of airli... |
7,943 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Previous
2.6 字符串忽略大小写的搜索替换
问题
你需要以忽略大小写的方式搜索与替换文本字符串
解决方案
为了在文本操作时忽略大小写,你需要在使用 re 模块的时候给这些操作提供 re.IGNORECASE 标志参数。比如:
Step1: 最后的那个例子揭示了一个小缺陷,替换字符串并不会自动跟被匹配字符串的大小写保持一致。 为了修复这个,你可能需要一个辅助函数,就像... | Python Code:
import re
text = "UPPER PYTHON, lower python, Mixed Python"
re.findall("python", text, flags = re.IGNORECASE)
re.sub("python", "snake", text, flags = re.IGNORECASE)
Explanation: Previous
2.6 字符串忽略大小写的搜索替换
问题
你需要以忽略大小写的方式搜索与替换文本字符串
解决方案
为了在文本操作时忽略大小写,你需要在使用 re 模块的时候给这些操作提供 re.IGNORECASE 标志参数。比如:
End of expl... |
7,944 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Creating Simple TFX Pipeline for Vertex Pipelines
Learning objectives
Prepare example data.
Create a pipeline.
Run the pipeline on Vertex Pipelines.
Introduction
In this notebook, you will c... | Python Code:
# Use the latest version of pip.
!pip install --upgrade pip
!pip install --upgrade "tfx[kfp]<2"
Explanation: Creating Simple TFX Pipeline for Vertex Pipelines
Learning objectives
Prepare example data.
Create a pipeline.
Run the pipeline on Vertex Pipelines.
Introduction
In this notebook, you will create a ... |
7,945 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<a id="top"></a>
UN SDG Indicator 11.3.1
Step3: Population Growth Rate
For calculating the indicator value for this SDG, the formula is the simple average yearly change in population.
For c... | Python Code:
def sdg_11_3_1(land_consumption, population_growth_rate):
return land_consumption/population_growth_rate
Explanation: <a id="top"></a>
UN SDG Indicator 11.3.1:<br> Ratio of Land Consumption Rate to Population Growth Rate
<hr>
Notebook Summary
The United Nations have prescribed 17 "Sustainable Developm... |
7,946 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Plotting Examples
In this notebook, we demonstrate how to write a simple Model, run an SMC updater for several experiments, then plot the resulting posterior distribution.
Preamble
Before an... | Python Code:
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
try: plt.style.use('ggplot')
except: pass
Explanation: Plotting Examples
In this notebook, we demonstrate how to write a simple Model, run an SMC updater for several experiments, then plot the resulting posterior distribution.
Preamble
B... |
7,947 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
1-D
Series
Step1: x-D
Dataframes
The most important feature pandas gives us access to is the DataFrame. Dataframes are two-dimensional stucutres that you can think of very much like a spre... | Python Code:
s = pd.Series([4, 7, -5, 3])
s
s.index
s.values
s[1:3]
s2 = s**2
s2
s2+s
print(np.sum(s))
print(np.mean(s))
print(np.std(s))
s3 = pd.Series([4, 7, -5, 3], index=['d', 'b', 'a', 'c'])
s3
# !!!
s2+s3
s4 = pd.Series({'d':10, 'b':12, 'a':3, 'c':9})
s4
s3+s4
Explanation: 1-D
Series
End of explanation
# Create a... |
7,948 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Double clik to put your name(s) here
Instructions
Run the code in each cell by holding down the shift key and pushing Return (Enter)
DOWNLOAD A COPY OF THIS NOTEBOOK when you are done!
Step1... | Python Code:
from __future__ import division, print_function
import numpy as np
from ipywidgets import interact
import matplotlib.pyplot as plt
%matplotlib nbagg
Explanation: Double clik to put your name(s) here
Instructions
Run the code in each cell by holding down the shift key and pushing Return (Enter)
DOWNLOAD A C... |
7,949 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Pythonic Syntactic Sugar
The Image Basics Notebook was straight forward and closely follows ITK's C++ interface.
Sugar is great it gives your energy to get things done faster! SimpleITK has ... | Python Code:
import matplotlib.pyplot as plt
import matplotlib as mpl
mpl.rc('image', aspect='equal')
%matplotlib inline
import SimpleITK as sitk
# Download data to work on
from downloaddata import fetch_data as fdata
Explanation: Pythonic Syntactic Sugar
The Image Basics Notebook was straight forward and closely follo... |
7,950 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Multiple Inheritance
In multiple inheritance, a class can be derived from more than one base classes. The syntax for multiple inheritance is similar to single inheritance except we list all ... | Python Code:
class Base1:
pass
class Base2:
pass
class MultiDerived(Base1, Base2):
pass
Explanation: Multiple Inheritance
In multiple inheritance, a class can be derived from more than one base classes. The syntax for multiple inheritance is similar to single inheritance except we list all the base classes ... |
7,951 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
ttHbb variables preparation
Step1: variables
ATL-COM-PHYS-2017-079 (table 8, page 46)
|variable |type |n-tuple name |des... | Python Code:
import datetime
import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np
plt.rcParams["figure.figsize"] = (13, 6)
import pandas as pd
import seaborn as sns
sns.set(context = "paper", font = "monospace")
from sklearn.preprocessing import MinMaxScaler
import sqlite3
import warnings
warnings.filt... |
7,952 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: <a href="http
Step2: The figure below illustrates the terminology
Step3: We can call the function
Step4: If we call the function with a new input we get a new result
Step5: We can... | Python Code:
def add(a):
add 1 to a
b=a+1;
print(a, "if you add one" ,b)
return(b)
Explanation: <a href="http://cocl.us/topNotebooksPython101Coursera"><img src = "https://ibm.box.com/shared/static/yfe6h4az47ktg2mm9h05wby2n7e8kei3.png" width = 750, align = "center"></a>
<a href="https://w... |
7,953 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
House Prices Estimator
Note
Step1: First problem
The training and test datasets have almost the same size so it's going to be difficult to get good predictions. Worst if we want to take a p... | Python Code:
import numpy as np
import pandas as pd
#load the files
train = pd.read_csv('input/train.csv')
test = pd.read_csv('input/test.csv')
data = pd.concat([train, test])
#size of training dataset
train_samples = train.shape[0]
#print some of them
data.head()
# remove the Id feature, because is not useful for pric... |
7,954 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Introduction to Tensors and Variables
Learning Objectives
Understand Basic and Advanced Tensor Concepts
Understand Single-Axis and Multi-Axis Indexing
Create Tensors and Variables
Introducti... | Python Code:
import tensorflow as tf
import numpy as np
print("TensorFlow version: ",tf.version.VERSION)
Explanation: Introduction to Tensors and Variables
Learning Objectives
Understand Basic and Advanced Tensor Concepts
Understand Single-Axis and Multi-Axis Indexing
Create Tensors and Variables
Introduction
In this n... |
7,955 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Lab 4 - Tensorflow ANN for regression
In this lab we will use Tensorflow to build an Artificial Neuron Network (ANN) for a regression task.
As opposed to the low-level implementation from th... | Python Code:
%matplotlib inline
import math
import random
import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd
from sklearn.datasets import load_boston
import numpy as np
import tensorflow as tf
sns.set(style="ticks", color_codes=True)
Explanation: Lab 4 - Tensorflow ANN for regression
In this lab ... |
7,956 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Loading necessary library
Step1: Loading data
deleting irrelevant features
Step2: encoding catagorical features
Step3: splitting data into test and train
Step4: seperating features and c... | Python Code:
import numpy as np
import pandas as pd
from sklearn import preprocessing
from sklearn import metrics
from sklearn.metrics import accuracy_score
from sklearn.ensemble import AdaBoostClassifier
from sklearn.neighbors import KNeighborsClassifier
import xgboost as xgb
import numpy as np
Explanation: Loading ne... |
7,957 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Prediction Model
Course
Step1: Step 1
Step2: Step 2
Step3: Step 3
Step4: Our output/classification label is diagnosis(M(1)/B(0)), which is nominal categorical data.
The ratios between Be... | Python Code:
import pandas as pd
# Read CSV data into df
df = pd.read_csv('./theAwesome_PredModel.csv')
# delete id column no need
df.drop('id',axis=1,inplace=True)
# delete unnamed colum at the end
df.drop('Unnamed: 32',axis=1,inplace=True)
df.head()
# Learn the unique values in diagnosis column
df.diagnosis.unique() ... |
7,958 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Overview of Subdomains
Subdomains are a key feature of OpenPNM, but the can be a source of confusion. First, let's understand what subdomains are and why they are useful. The simplest scenar... | Python Code:
import openpnm as op
import numpy as np
import matplotlib.pyplot as plt
Explanation: Overview of Subdomains
Subdomains are a key feature of OpenPNM, but the can be a source of confusion. First, let's understand what subdomains are and why they are useful. The simplest scenario is a porous materials with 2 ... |
7,959 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<a href="https
Step1: Query the database system catalog to retrieve table metadata
You can verify that the table creation was successful by retrieving the list of all tables in your schema ... | Python Code:
%load_ext sql
# Enter the connection string for your Db2 on Cloud database instance below
# %sql ibm_db_sa://my-username:my-password@my-hostname:my-port/my-db-name
%sql ibm_db_sa://
Explanation: <a href="https://cognitiveclass.ai"><img src = "https://ibm.box.com/shared/static/ugcqz6ohbvff804xp84y4kqnvvk3bq... |
7,960 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Compute ICA on MEG data and remove artifacts
ICA is fit to MEG raw data.
The sources matching the ECG and EOG are automatically found and displayed.
Subsequently, artifact detection and reje... | Python Code:
# Authors: Denis Engemann <denis.engemann@gmail.com>
# Alexandre Gramfort <alexandre.gramfort@telecom-paristech.fr>
#
# License: BSD (3-clause)
import numpy as np
import mne
from mne.preprocessing import ICA
from mne.preprocessing import create_ecg_epochs, create_eog_epochs
from mne.datasets impor... |
7,961 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Importance of known positives versus known negatives
In this notebook we will show how to compute performance curves (ROC and PR curves to be specific) based on a data set with known positiv... | Python Code:
import random
import operator as op
import optunity.metrics
import semisup_metrics as ss
import numpy as np
from matplotlib import pyplot as plt
import pickle
import csv
import util
%matplotlib inline
Explanation: Importance of known positives versus known negatives
In this notebook we will show how to com... |
7,962 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
We'll try to desribe our loci of interest procedure with details and illustrations here.
Let's start with some modules
Step1: Then import the Codon Table for standard genetic code, with the... | Python Code:
%matplotlib inline
import os
import sys
from Bio import SeqRecord
from Bio import AlignIO
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
Explanation: We'll try to desribe our loci of interest procedure with details and illustrations here.
Let's start with some modules:
End of explan... |
7,963 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Autoencoders
What are Autoencoders?
Step1: "Autoencoding" is a data compression algorithm where the compression and decompression functions are 1) data-specific, 2) lossy, and 3) learned au... | Python Code:
PATH = "/Users/raghu/Downloads/"
Image(filename = PATH + "autoencoder_schema.jpg", width=500, height=500)
Explanation: Autoencoders
What are Autoencoders?
End of explanation
from keras.layers import Input, Dense
from keras.models import Model
# this is the size of our encoded representations
encoding_dim =... |
7,964 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
# Chapter 3
Step2: We present here the figure 3.2 in its original form in the book
Step3: Now we repeat the plot with seaborn
Step4: ## Monty Hall problem
We will simulate the Monty Hall ... | Python Code:
%pylab inline
import astroML
Explanation: # Chapter 3
End of explanation
from astroML.plotting import setup_text_plots
setup_text_plots(fontsize=8, usetex=True)
def banana_distribution(N=10000):
This generates random points in a banana shape
# create a truncated normal distribution
theta = np.r... |
7,965 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Titanic Data Science Solutions
This notebook is companion to the book Data Science Solutions. The notebook walks us through a typical workflow for solving data science competitions at sites ... | Python Code:
# data analysis and wrangling
import pandas as pd
import numpy as np
import random as rnd
# visualization
import seaborn as sns
import matplotlib.pyplot as plt
%matplotlib inline
# machine learning
from sklearn.linear_model import LogisticRegression
from sklearn.svm import SVC, LinearSVC
from sklearn.ensem... |
7,966 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<a href="https
Step1: Reformer
Step2: Setting up data and model
In this notebook, we'll be pushing the limits of just how many tokens we can fit on a single TPU device. The TPUs available ... | Python Code:
# 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
# distributed unde... |
7,967 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Implement CNN network with TensorFlow
Brief
Load a CNN implemented in TensorFlow trained before and test it's performance on MNIST dataset.
Notice
Saving checkpoints of this model demands su... | Python Code:
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
Explanation: Implement CNN network with TensorFlow
Brief
Load a CNN implemented in TensorFlow trained before and test it's performance on MNIST dataset.
Notice
Saving checkpoints of this model demands sufficient disk memory.
Import ... |
7,968 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Which morphology indicators did I settle on?
Perfect correlation with table3 above
Step1: Selecting samples for Clean Image examples
Estimated the source density for every cutout I made by ... | Python Code:
print table1.columns
print table4.columns
print len(table1), len(table4)
test = pd.merge(table1, table4, on=['OBJID'])
# What we started with - what we have after the merge
# The twelve are likely those S82 objects that snuck into the main sample :(
282350-282338
test.columns
plt.scatter(test.C_x, test.C_y... |
7,969 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Orienting Yourself
Image
Step1: If you use Python for any amount of time, you'll quickly find that there are some things it is not so good at.
In particular, performing repeated operations ... | Python Code:
from __future__ import print_function
import math
import numpy as np
Explanation: Orienting Yourself
Image: @jakevdp
How to install packages using conda
If you're using anaconda, you probably already have most (if not all) of these installed. If you installed miniconda:
conda install numpy
Conda also has c... |
7,970 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Sample Data Wrangling Project
OpenStreetMap Sample Project - Data Wrangling with MongoDB
Step1: 1 - Data Preparation
Map Area
Step2: 1.1 - Auditing Data
1.1.1 - node and way xml tags
A qui... | Python Code:
import pprint
import pandas as pd
import numpy as np
import csv
%matplotlib inline
import matplotlib
import matplotlib.pyplot as plt
from IPython.display import Image, display
Explanation: Sample Data Wrangling Project
OpenStreetMap Sample Project - Data Wrangling with MongoDB
End of explanation
Image(file... |
7,971 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Dropping PassengerId, Name and Ticket because they are unique.
Dropping Cabin because of too many null values.
Step1: Now need to take care of the missing data for Age variable. Need to app... | Python Code:
titanic_data = titanic.drop(['PassengerId','Name','Ticket'],1)
titanic_data.head()
Explanation: Dropping PassengerId, Name and Ticket because they are unique.
Dropping Cabin because of too many null values.
End of explanation
sb.boxplot(x='Pclass',y='Age',data=titanic_data)
Explanation: Now need to take ca... |
7,972 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2018 The TensorFlow Authors.
Licensed under the Apache License, Version 2.0 (the "License").
Neural Machine Translation with Attention
<table class="tfo-notebook-buttons" align="le... | Python Code:
from __future__ import absolute_import, division, print_function
# Import TensorFlow >= 1.10 and enable eager execution
import tensorflow as tf
tf.enable_eager_execution()
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
import unicodedata
import re
import numpy as np
im... |
7,973 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Creating and Manipulating Tensors
Learning Objectives
Step1: Vector Addition
You can perform many typical mathematical operations on tensors (TF API). The following code
creates and manipul... | Python Code:
import tensorflow as tf
Explanation: Creating and Manipulating Tensors
Learning Objectives:
- Initialize and assing TensorFlow Variables
- Create and manipulate tensors
- Refresh your memory about addition and multiplication in linear algebra (consult an introduction to matrix addition and multiplication i... |
7,974 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
LBYL versus EAFP
In some other languages,
one can not recover from an error,
or it is difficult to recover from an error,
so one tests input before doing something that could provoke the err... | Python Code:
numbers = (3, 1, 0, -1, -2)
def foo(x):
return 10 // x
for x in numbers:
y = foo(x)
print(f'foo({x}) --> {y}')
Explanation: LBYL versus EAFP
In some other languages,
one can not recover from an error,
or it is difficult to recover from an error,
so one tests input before doing something that co... |
7,975 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
https
Step1: Step 0 - hyperparams
vocab_size is all the potential words you could have (classification for translation case)
and max sequence length are the SAME thing
decoder RNN hidden un... | Python Code:
from __future__ import division
import tensorflow as tf
from os import path, remove
import numpy as np
import pandas as pd
import csv
from sklearn.model_selection import StratifiedShuffleSplit
from time import time
from matplotlib import pyplot as plt
import seaborn as sns
from mylibs.jupyter_notebook_help... |
7,976 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
ES-DOC CMIP6 Model Properties - Atmos
MIP Era
Step1: Document Authors
Set document authors
Step2: Document Contributors
Specify document contributors
Step3: Document Publication
Specify d... | Python Code:
# DO NOT EDIT !
from pyesdoc.ipython.model_topic import NotebookOutput
# DO NOT EDIT !
DOC = NotebookOutput('cmip6', 'miroc', 'nicam16-8s', 'atmos')
Explanation: ES-DOC CMIP6 Model Properties - Atmos
MIP Era: CMIP6
Institute: MIROC
Source ID: NICAM16-8S
Topic: Atmos
Sub-Topics: Dynamical Core, Radiat... |
7,977 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Figure 3 - noise removal
The figure in this notebook illustrates
Step1: variable definitions
figure directory
Step2: example recording 1
Step3: example recording 2
Step4: formating
Step5... | Python Code:
from matplotlib import pyplot
%matplotlib inline
from matplotlib.patches import Rectangle
from matplotlib.lines import Line2D
import numpy
from scipy.io import wavfile
from os import path
from datetime import timedelta
from django.db import connection
from database.models import Sound
from database.models ... |
7,978 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
RNA example
We take a fasta file in input and write utility functions to build a graph representation based on the structure computed by RNAfold. Finally we use the EDeN vectorizer to perfor... | Python Code:
%matplotlib inline
Explanation: RNA example
We take a fasta file in input and write utility functions to build a graph representation based on the structure computed by RNAfold. Finally we use the EDeN vectorizer to perform clustering or build a predictive model.
End of explanation
def rfam_uri(family_id):... |
7,979 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Guide to Building End-to-End Reinforcement Learning Application Pipelines using Vertex AI
<table align="left">
<td>
<a href="https
Step1: Restart the kernel
After you install the addi... | Python Code:
import os
# The Google Cloud Notebook product has specific requirements
IS_GOOGLE_CLOUD_NOTEBOOK = os.path.exists("/opt/deeplearning/metadata/env_version")
# Google Cloud Notebook requires dependencies to be installed with '--user'
USER_FLAG = ""
if IS_GOOGLE_CLOUD_NOTEBOOK:
USER_FLAG = "--user"
! pip3... |
7,980 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
HMTK Geological Tools Demonstration
This notepad demonstrates the use of the HMTK geological tools for preparing fault source models for input into OpenQuake
Construction of the Geological I... | Python Code:
#Import tools
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
from hmtk.plotting.faults.geology_mfd_plot import plot_recurrence_models
from openquake.hazardlib.scalerel.wc1994 import WC1994 # In all the following examples the Wells & Coppersmith (1994) Scaling Relation is Used
Explan... |
7,981 | 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="#Sprachübergreifende-Textalignierung" data-toc-modified-id="Sprachübergreifende-Textalignierung-1"><span class="toc-item-num">1 ... | Python Code:
import os
in_dir = "./data/constitutions/"
# we create a dictionary with our constitutions:
sources = {}
for file in sorted(os.listdir(in_dir)):
key = os.path.basename(file).split(os.extsep)[0]
with open(in_dir + '/' + file, encoding="utf-8") as f:
sources[key] = f.read()
# and a list of av... |
7,982 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
How to Efficiently Read BigQuery Data from TensorFlow 2.3
Learning Objectives
Build a benchmark model.
Find the breakoff point for Keras.
Training a TensorFlow/Keras model that reads from Bi... | Python Code:
%%bash
# create output dataset
bq mk advdata
%%bigquery
CREATE OR REPLACE MODEL advdata.ulb_fraud_detection
TRANSFORM(
* EXCEPT(Amount),
SAFE.LOG(Amount) AS log_amount
)
OPTIONS(
INPUT_LABEL_COLS=['class'],
AUTO_CLASS_WEIGHTS = TRUE,
DATA_SPLIT_METHOD='seq',
DATA_SPLIT_COL='Time',
... |
7,983 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
JupyterWorkflow3
From exploratory analysis to reproducible research
Mehmetcan Budak
Step1: SECOND PART
To make a python package so we and other people can use it for analysis.
Go to the dir... | Python Code:
%matplotlib inline
import matplotlib.pyplot as plt
plt.style.use("seaborn")
from jupyterworkflow.data import get_fremont_data
data = get_fremont_data()
data.head()
data.resample("W").sum().plot()
data.groupby(data.index.time).mean().plot()
pivoted = data.pivot_table("Total", index=data.index.time, columns=... |
7,984 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Multimodality and Resampling
This notebook tests the robustness of modified Liu-West (MLW) resampling to multimodality in the posterior distribution. We use as a test the familiar model
$$
... | Python Code:
from __future__ import division, print_function
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
try: plt.style.use('ggplot')
except: pass
Explanation: Multimodality and Resampling
This notebook tests the robustness of modified Liu-West (MLW) resampling to multimodality in the posterio... |
7,985 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Source alignment and coordinate frames
The aim of this tutorial is to show how to visually assess that the data are
well aligned in space for computing the forward solution, and understand
t... | Python Code:
import os.path as op
import numpy as np
from mayavi import mlab
import mne
from mne.datasets import sample
print(__doc__)
data_path = sample.data_path()
subjects_dir = op.join(data_path, 'subjects')
raw_fname = op.join(data_path, 'MEG', 'sample', 'sample_audvis_raw.fif')
trans_fname = op.join(data_path, 'M... |
7,986 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Executed
Step1: Notebook arguments
sigma (float)
Step2: Fitting models
Models used to fit the data.
1. Simple Exponential
In this model, we define the model function as an exponential tran... | Python Code:
sigma = 0.016
time_window = 30
time_step = 5
time_start = -900
time_stop = 900
decimation = 20
t0_vary = True
true_params = dict(
tau = 60, # time constant
init_value = 0.3, # initial value (for t < t0)
final_value = 0.8, # final value (for t -> +inf)
t0 = 0) ... |
7,987 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
\title{Counters in myHDL}
\author{Steven K Armour}
\maketitle
Counters play a vital role in Digital Hardware, ranging from Clock Dividers; (see below) to event triggers by recording the num... | Python Code:
from myhdl import *
from myhdlpeek import Peeker
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline
from sympy import *
init_printing()
import random
#https://github.com/jrjohansson/version_information
%load_ext version_information
%version_information myhdl, myhdlpee... |
7,988 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Transfer Learning
Most of the time you won't want to train a whole convolutional network yourself. Modern ConvNets training on huge datasets like ImageNet take weeks on multiple GPUs. Instea... | Python Code:
from urllib.request import urlretrieve
from os.path import isfile, isdir
from tqdm import tqdm
vgg_dir = 'tensorflow_vgg/'
# Make sure vgg exists
if not isdir(vgg_dir):
raise Exception("VGG directory doesn't exist!")
class DLProgress(tqdm):
last_block = 0
def hook(self, block_num=1, block_size=... |
7,989 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Template for test
Step1: Controlling for Random Negatve vs Sans Random in Imbalanced Techniques using S, T, and Y Phosphorylation.
Included is N Phosphorylation however no benchmarks are av... | Python Code:
from pred import Predictor
from pred import sequence_vector
from pred import chemical_vector
Explanation: Template for test
End of explanation
par = ["pass", "ADASYN", "SMOTEENN", "random_under_sample", "ncl", "near_miss"]
for i in par:
print("y", i)
y = Predictor()
y.load_data(file="Data/Train... |
7,990 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Selecting variants by number of unique barcodes
This notebook gets scores for the variants in an Experiment that are linked to multiple barcodes, and plots the relationship between each vari... | Python Code:
% matplotlib inline
from __future__ import print_function
import os.path
from collections import Counter
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from enrich2.variant import WILD_TYPE_VARIANT
import enrich2.plots as enrich_plot
pd.set_option("display.max_rows", 10) # rows show... |
7,991 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
LSTM Time Series Example
Before we get into the example, let's talk about old fashioned computer memory. Mercury delay lines are an early form of computer memory. They basically recycled e... | Python Code:
from pandas import DataFrame
from pandas import Series
from pandas import concat
from pandas import read_csv
from pandas import datetime
from sklearn.metrics import mean_squared_error
from sklearn.preprocessing import MinMaxScaler
from keras.models import Sequential
from keras.layers import Dense
from kera... |
7,992 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
VARMAX models
This is a brief introduction notebook to VARMAX models in Statsmodels. The VARMAX model is generically specified as
Step1: Model specification
The VARMAX class in Statsmodels ... | Python Code:
%matplotlib inline
import numpy as np
import pandas as pd
import statsmodels.api as sm
import matplotlib.pyplot as plt
dta = sm.datasets.webuse('lutkepohl2', 'http://www.stata-press.com/data/r12/')
dta.index = dta.qtr
endog = dta.ix['1960-04-01':'1978-10-01', ['dln_inv', 'dln_inc', 'dln_consump']]
Explanat... |
7,993 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: <div style="background
Step2: <div style="background
Step3: <div style="background
Step4: <div style="background
Step5: <div style="background
Step6: <div style="background
Step7... | Python Code:
from IPython.display import Javascript,display
from corticalmapping.ipython_lizard.html_widgets import raw_code_toggle
raw_code_toggle()
display(Javascript(var nb = IPython.notebook;
//var is_code_cell = (nb.get_selected_cell().cell_type == 'code')
//var curr_idx... |
7,994 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Transfer Learning and Fine Tuning
Train a simple convnet on the MNIST dataset the first 5 digits [0..4].
Freeze convolutional layers and fine-tune dense layers for the classification of digi... | Python Code:
import numpy as np
import datetime
np.random.seed(1337) # for reproducibility
from keras.datasets import mnist
from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation, Flatten
from keras.layers import Convolution2D, MaxPooling2D
from keras.utils import np_utils
from keras i... |
7,995 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step2: Building a Scheme Interpreter
Consider using Python to turn the string "(+ 1 2)" into the actual number 3. How does that happen? This question is really
Step4: Exercise 1
Step6: Exe... | Python Code:
def tokenizer(string):
Takes a string and segments it into parts.
We break strings up by brackets, and whitespace.
Returns a Python list of strings.
retval = []
current = ""
for i in range(len(string)):
if string[i] in ["(", "[", ")", "]"]:
if current:
... |
7,996 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Integration Exercise 1
Imports
Step2: Trapezoidal rule
The trapezoidal rule generates a numerical approximation to the 1d integral
Step3: Now use scipy.integrate.quad to integrate the f an... | Python Code:
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
from scipy import integrate
Explanation: Integration Exercise 1
Imports
End of explanation
def trapz(f, a, b, N):
Integrate the function f(x) over the range [a,b] with N points.
x = np.linspace(a,b,N+1)
h = np.diff(x)[1]
... |
7,997 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Compute power and phase lock in label of the source space
Compute time-frequency maps of power and phase lock in the source space.
The inverse method is linear based on dSPM inverse operator... | Python Code:
# Authors: Alexandre Gramfort <alexandre.gramfort@inria.fr>
#
# License: BSD (3-clause)
import numpy as np
import matplotlib.pyplot as plt
import mne
from mne import io
from mne.datasets import sample
from mne.minimum_norm import read_inverse_operator, source_induced_power
print(__doc__)
Explanation: Compu... |
7,998 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Simple unicycle model of a UAV
Step1: The Vector-Field VF(x)
based on the implicit funtion $\phi$ as taken from Goncalves2010a
Step2: Approximate Distance to Implicit Curve
Step3: Cost Fu... | Python Code:
%matplotlib inline
import pdb
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
def UAVmodel(state,u,dt):
# unpack the state vector
x = state[0]
y = state[1]
theta = state[2]
# unpack the input vectors
v = u[0]
w = u[1]
# compute deltas
dx = v*np.cos(t... |
7,999 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Plotting with matplotlib
1. Getting Started
1.1 What is matplotlib?
Matplotlib is the most popular and mature library for plotting data using
Python. It has all of the functionality you woul... | Python Code:
# In IPython or the IPython notebook, it's easiest to use the pylab magic, which
# imports matplotlib, numpy, and scipy.
# The matplotlib notebook flag means that plots will be shown interactively in the
# notebooks, rather than in pop-up windows.
%matplotlib notebook
import numpy as np
import matplotlib.p... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.