Unnamed: 0 int64 0 16k | text_prompt stringlengths 110 62.1k | code_prompt stringlengths 37 152k |
|---|---|---|
700 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
26/May/2016
Step1: What's going on in cells 11 & 14 ? | Python Code:
import functools
def hello_doctor(greet_msg, greet_whom):
return "%s %s, Welcome to the world of robots." %(greet_msg, greet_whom)
## this line works
# hello_doctor = functools.partial(hello_doctor, "R2-D2")
# hello_doctor("Dr.Susan Calvin")
Explanation: 26/May/2016:
** Hey, what's this 'functools' thi... |
701 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
ケモインフォマティクス入門講座初級編
Python基礎 2017年9月30日
講師:久保 竜一(株式会社DeNAライフサイエンス)
WHO ARE YOU??
<img width="309" alt="2017-09-06 16 05 42" src="https
Step1: 破壊的代入
既に代入済みの変数に再代入すると新しい値に置き換わる(破壊的代入)
Step2: ... | Python Code:
a = 1
a
Explanation: ケモインフォマティクス入門講座初級編
Python基礎 2017年9月30日
講師:久保 竜一(株式会社DeNAライフサイエンス)
WHO ARE YOU??
<img width="309" alt="2017-09-06 16 05 42" src="https://user-images.githubusercontent.com/7918702/30098549-5013838e-931d-11e7-8b9c-01dd1a30ccfd.png">
一般的には
@kubor_
ソーシャル創薬美少女
いろんなイベントやってます
Genome Biz Meetu... |
702 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<font color='#A52A2A'>Enhancing ZOS API using PyZOS library</font>
Step1: <font color='#008000'>Reference</font>
We will use the following two Zemax knowledgebase articles as base material ... | Python Code:
from __future__ import print_function
import os
import sys
import numpy as np
from IPython.display import display, Image, YouTubeVideo
import matplotlib.pyplot as plt
# Imports for using ZOS API in Python directly with pywin32
# (not required if using PyZOS)
from win32com.client.gencache import EnsureDispa... |
703 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Class Python Demos
I will be using this Notebook for class demos. To use at home, load Anaconda (https
Step1: Let's look at what set() does!
Step2: Let's create a 2nd list and set.
Step3: ... | Python Code:
import numpy as np
nums1 = np.random.randint(1,11, 15)
nums1
Explanation: Class Python Demos
I will be using this Notebook for class demos. To use at home, load Anaconda (https://www.continuum.io/downloads) or WinPython (https://winpython.github.io/)
Set() demo
First let's create a random list using the nu... |
704 | Given the following text problem statement, write Python code to implement the functionality described below in problem statement
Problem:
Does Python have a function to reduce fractions? | Problem:
import numpy as np
numerator = 98
denominator = 42
gcd = np.gcd(numerator, denominator)
result = (numerator//gcd, denominator//gcd) |
705 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
In this notebook, we'll study the relation between dimensions and the semantic field of concepts.
To do so, we'll study for a domain specific corpus the repartition of dimensions.
Workflow
b... | Python Code:
domainWordList = [open('../../data/domain/luu_animal.txt').read().splitlines(),
open('../../data/domain/luu_plant.txt').read().splitlines(),
open('../../data/domain/luu_vehicle.txt').read().splitlines()]
def buildCptDf(d, domain, polar=False):
cptList = cpe.buildConc... |
706 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Deep Autoencoders
by Khaled Nasr as a part of a <a href="https
Step1: Creating the autoencoder
Similar to regular neural networks in Shogun, we create a deep autoencoder using an array of N... | Python Code:
%pylab inline
%matplotlib inline
import os
SHOGUN_DATA_DIR=os.getenv('SHOGUN_DATA_DIR', '../../../data')
from scipy.io import loadmat
from shogun import RealFeatures, MulticlassLabels, Math
# load the dataset
dataset = loadmat(os.path.join(SHOGUN_DATA_DIR, 'multiclass/usps.mat'))
Xall = dataset['data']
# t... |
707 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2019 The TensorFlow Authors.
Step1: 훈련 후 float16 양자화
<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... |
708 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
BandsPlot
Step1: Let's get a bands_plot from a .bands file
Step2: and see what we've got
Step3: Getting the bands that you want
By default, BandsPlot gives you the 15 bands below and abov... | Python Code:
import sisl
import sisl.viz
# This is just for convenience to retreive files
siesta_files = sisl._environ.get_environ_variable("SISL_FILES_TESTS") / "sisl" / "io" / "siesta"
Explanation: BandsPlot
End of explanation
bands_plot = sisl.get_sile( siesta_files / "SrTiO3.bands").plot()
Explanation: Let's get a ... |
709 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Interact Exercise 4
Imports
Step2: Line with Gaussian noise
Write a function named random_line that creates x and y data for a line with y direction random noise that has a normal distribut... | Python Code:
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
from IPython.html.widgets import interact, interactive, fixed
from IPython.display import display
Explanation: Interact Exercise 4
Imports
End of explanation
def random_line(m, b, sigma, size=10):
Create a line y = m*x + b + N(0,sigm... |
710 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
More SQL DML and DDL
Data and environment setup
Step1: SQL JOINs
Note first that a simple JOIN without further specification of common attributes will result in a cross product relation. W... | Python Code:
!wget http://files.software-carpentry.org/survey.db
!pip install ipython-sql
%load_ext sql
%sql sqlite:///survey.db
Explanation: More SQL DML and DDL
Data and environment setup
End of explanation
%%sql
SELECT *
FROM Site;
%%sql
SELECT *
FROM Visited;
Explanation: SQL JOINs
Note first that a simple JOIN wit... |
711 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Feedback k domácím projektům
Najdi chybu 1
Tento kousek kódu, který se stará o výběr tahu počítače na základě náhodně vygenerovaného čísla, může vypada na první pohled správně, ale ve skuteč... | Python Code:
from random import randrange
cislo = randrange(2)
if cislo == 0:
tah_pocitace = "kámen"
print("Počítač vybral kámen.")
if cislo == 1:
print("Počítač vybral nůžky.")
tah_pocitace = "nůžky"
else:
tah_pocitace = "papír"
print("Počítač vybral papír.")
Explanation: Feedback k domácím pro... |
712 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Integration and derivatives
Step1: Derivatives and Integrals
Step2: Numerical Derivatives
Step3: Note that the values are pretty close, and we can use a print('{0
Step4: First Order Ordi... | Python Code:
# Python imports
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
from scipy.misc import derivative
from scipy import integrate
Explanation: Integration and derivatives:
Many systems are represented dynamically and present the need for some simple calculus. Derivatives and integrals ar... |
713 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
^ gor
Step1: Videti je, da zaporedje konvergira in sicer natanko k rešitvi enačbe. Opazimo tudi, da za vsako pravilno decimalko potrebujemo približno 3 korake rekurzije.
Konvergenca
Zdi se,... | Python Code:
g = lambda x: 2**(-x)
xp = 1 # začetni približek
for i in range(15):
xp = g(xp)
print(xp)
print("Razlika med desno in levo stranjo enačbe je", xp-2**(-xp))
Explanation: ^ gor: Uvod
Reševanje enačb z navadno iteracijo
Pri rekurzivnih zaporedjih smo videli, da za zaporedje, ki zadošča rekurzivni for... |
714 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: Clean the data
First, import packages for data cleaning and read the data
Step2: Combine the train and test set for cleaning
Step3: Convert all ints to floats for XGBoost
Step4: Sa... | Python Code:
from scipy.stats.mstats import mode
import pandas as pd
import numpy as np
import time
from sklearn.preprocessing import LabelEncoder
Read Data
train = pd.read_csv('data/train.csv')
test = pd.read_csv('data/test.csv')
target = train['SalePrice']
train = train.drop(['SalePrice'],axis=1)
trainlen = train.sha... |
715 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
分类和逻辑回归 Classification and Logistic Regression
引入科学计算和绘图相关包:
Step1: 分类和回归的唯一区别在于,分类问题中我们希望预测的目标变量 $y$ 只会取少数几个离散值。本节我们将主要关注二元分类 binary classification问题,$y$ 在二元分类中只会取 $0, 1$ 两个值。$0$ 也被称为反类 ne... | Python Code:
import numpy as np
from sklearn import linear_model, datasets
import matplotlib.pyplot as plt
import seaborn as sns
sns.set_style('whitegrid')
%matplotlib inline
Explanation: 分类和逻辑回归 Classification and Logistic Regression
引入科学计算和绘图相关包:
End of explanation
x = np.arange(-10., 10., 0.2)
y = 1 / (1 + np.e ** (... |
716 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2018 Google LLC.
Step1: Case Study
Step2: Check Correlation Matrix
Before developing your ML model, you need to select features. To find informative features, check the correlati... | 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
# distribute... |
717 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Previous
1.17 从字典中提取子集
问题
你想构造一个字典,它是另外一个字典的子集。
解决方案
最简单的方式是使用字典推导。比如:
Step1: 讨论
大多数情况下字典推导能做到的,通过创建一个元组序列然后把它传给 dict() 函数也能实现。比如:
Step2: 但是,字典推导方式表意更清晰,并且实际上也会运行的更快些 (在这个例子中,实际测试几乎比 dcit(... | Python Code:
prices = {
'ACME': 45.23,
'AAPL': 612.78,
'IBM': 205.55,
'HPQ': 37.20,
'FB': 10.75
}
# Make a dictionary of all prices over 200
p1 = {key: value for key, value in prices.items() if value > 200}
p1
# Make a dictionary of tech stocks
tech_names = {'AAPL', 'IBM', 'HPQ', 'MSFT'}
p2 = {key: ... |
718 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2019 The TensorFlow Hub Authors.
Licensed under the Apache License, Version 2.0 (the "License");
Step3: 任意画風の高速画風変換
<table class="tfo-notebook-buttons" align="left">
<td><a targ... | Python Code:
# Copyright 2019 The TensorFlow Hub Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless re... |
719 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Sparse GP Regression
14th January 2014 James Hensman
29th September 2014 Neil Lawrence (added sub-titles, notes and some references).
This example shows the variational compression effect of... | Python Code:
%matplotlib inline
%config InlineBackend.figure_format = 'svg'
import GPy
import numpy as np
np.random.seed(101)
Explanation: Sparse GP Regression
14th January 2014 James Hensman
29th September 2014 Neil Lawrence (added sub-titles, notes and some references).
This example shows the variational compression ... |
720 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Coding in Python3
So now that PmagPy has made the conversion to python3, for at least a short time the command line programs will be supported in both Python2 and Python3 using the library f... | Python Code:
#python2 syntax, now throws an error
print "hello world"
#python3 syntax, this also works in python2 (2.5+) though in python3 this is the only option
print("hello world")
#documentation on the python3 print function
help(print)
Explanation: Coding in Python3
So now that PmagPy has made the conversion to py... |
721 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
A genertor function, which acts as an iterator, provides memory-efficient way to generate a large sequence of data, such as an array with size of 100,000. We have 3 different methods to invo... | Python Code:
def firstn(n):
num = 0
while num < n:
yield num
num += 1
print(sum(firstn(1000000)))
Explanation: A genertor function, which acts as an iterator, provides memory-efficient way to generate a large sequence of data, such as an array with size of 100,000. We have 3 different m... |
722 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Example
Step1: A simple bottleneck
In order to change population size, one simply has to change the values in the "nlist". For example, here is a population bottleneck
Step2: Please note... | Python Code:
%matplotlib inline
%pylab inline
from __future__ import print_function
import numpy as np
import array
import matplotlib.pyplot as plt
#population size
N=1000
#nlist corresponds to a constant population size for 10N generations
#note the "dtype" argument. Without it, we'd be defaulting to int64,
#which is... |
723 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Questions
Step1: For the purpose of cleaning up the data I determined that the Name and Ticket columns were not necessary for my future analysis.
Step2: Using .info and .describe, I am abl... | Python Code:
##import everything
import numpy as np
import pandas as pd
import scipy as sp
import matplotlib.pyplot as plt
import seaborn as sea
%matplotlib inline
sea.set(style="whitegrid")
titanic_ds = pd.read_csv('titanic-data.csv')
Explanation: Questions:
1: What sex has a higher probability of surviving?
2: What w... |
724 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Translation of products
This is the code for translation of products. In Prestashop, we have products in Thai and English description. We need to move the translation database to Woocommerce... | Python Code:
import pandas as pd
import numpy as np
Explanation: Translation of products
This is the code for translation of products. In Prestashop, we have products in Thai and English description. We need to move the translation database to Woocommerce. Woocommerce uses "WPML Multilingual CMS" plugin. After activate... |
725 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
오류 및 예외 처리
개요
코딩할 때 발생할 수 있는 다양한 오류 살펴 보기
오류 메시지 정보 확인 방법
예외 처리, 즉 오류가 발생할 수 있는 예외적인 상황을 미리 고려하는 방법 소개
오늘의 주요 예제
아래 코드는 input() 함수를 이용하여 사용자로부터 숫자를 입력받아
그 숫자의 제곱을 리턴하는 내용을 담고 있다.
코드를 실행하면 ... | Python Code:
input_number = input("A number please: ")
number = int(input_number)
print("제곱의 결과는", number**2, "입니다.")
input_number = input("A number please: ")
number = int(input_number)
print("제곱의 결과는", number**2, "입니다.")
Explanation: 오류 및 예외 처리
개요
코딩할 때 발생할 수 있는 다양한 오류 살펴 보기
오류 메시지 정보 확인 방법
예외 처리, 즉 오류가 발생할 수 있는 예외적인... |
726 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Testing TFNoiseAwareModel
We'll start by testing the textRNN model on a categorical problem from tutorials/crowdsourcing. In particular we'll test for (a) basic performance and (b) proper c... | Python Code:
%load_ext autoreload
%autoreload 2
%matplotlib inline
import os
os.environ['SNORKELDB'] = 'sqlite:///{0}{1}crowdsourcing.db'.format(os.getcwd(), os.sep)
from snorkel import SnorkelSession
session = SnorkelSession()
Explanation: Testing TFNoiseAwareModel
We'll start by testing the textRNN model on a categor... |
727 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Linear control flow between a series of coroutines is easy to manage with the built-in language keyword await. More complicated structures allowing one coroutine to wait for several others t... | Python Code:
# %load asyncio_wait.py
import asyncio
async def phase(i):
print('in phase {}'.format(i))
await asyncio.sleep(0.1 * i)
print('done with phase {}'.format(i))
return 'phase {} result'.format(i)
async def main(num_phases):
print('starting main')
phases = [
phase(i)
for ... |
728 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Multi-Dimensional Integration with MCMC
By Megan Bedell (Flatiron Institute)
10 September 2019
Problem 1
Step1: Problem 1a
Plot the data. Let's take a look at what we're working with!
Step2... | Python Code:
datafile = 'https://exoplanetarchive.ipac.caltech.edu/data/ExoData/0108/0108859/data/UID_0108859_RVC_001.tbl'
data = pd.read_fwf(datafile, header=0, names=['t', 'rv', 'rv_err'], skiprows=22)
data['t'] -= data['t'][0]
Explanation: Multi-Dimensional Integration with MCMC
By Megan Bedell (Flatiron Institute)
... |
729 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Advanced tour of the Bayesian Optimization package
Step1: 1. Suggest-Evaluate-Register Paradigm
Internally the maximize method is simply a wrapper around the methods suggest, probe, and reg... | Python Code:
from bayes_opt import BayesianOptimization
Explanation: Advanced tour of the Bayesian Optimization package
End of explanation
# Let's start by defining our function, bounds, and instanciating an optimization object.
def black_box_function(x, y):
return -x ** 2 - (y - 1) ** 2 + 1
Explanation: 1. Suggest... |
730 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
project bonhomie ${t\bar{t}H}$ and ${t\bar{t}b\bar{b}}$ classification variables preparation
This notebook takes ROOT files of ${t\bar{t}H}$ and ${t\bar{t}b\bar{b}}$ samples, applies a selec... | Python Code:
import datetime
import keras
from keras import activations
from keras.datasets import mnist
from keras.layers import Dense, Flatten
from keras.layers import Conv1D, Conv2D, MaxPooling1D, MaxPooling2D, Dropout
from keras.models import Sequential
from keras.utils import plot_model
from matplotlib import grid... |
731 | 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... |
732 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
The ultimate objective of this portion of the hack it to create Metric Analysis Framework metrics to determine the value of a given opsim run for the intermediate mass MACHO science.
Note t... | Python Code:
import numpy as np
import matplotlib.pyplot as plt
# import lsst sims maf modules
import lsst.sims.maf
import lsst.sims.maf.db as db
import lsst.sims.maf.metrics as lsst_metrics
import lsst.sims.maf.slicers as slicers
import lsst.sims.maf.stackers as stackers
import lsst.sims.maf.plots as plots
import lsst... |
733 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Bio.Pairwise2 optimization
This project aims to optimize alignment algorithms from pairwise2 module of BioPython library.
Especially algorithms for local alignments of this library are consi... | Python Code:
from generate_samples import generate_sample, PROTEIN_ALPHABET
# Let's generate two sample sequences of proteins. Length of first sequence will be 50.
seq1, seq2 = generate_sample(PROTEIN_ALPHABET, 50)
print "Sequence 1: " + seq1
print "Sequence 2: " + seq2
Explanation: Bio.Pairwise2 optimization
This proj... |
734 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
A Simple Autoencoder
We'll start off by building a simple autoencoder to compress the MNIST dataset. With autoencoders, we pass input data through an encoder that makes a compressed represen... | Python Code:
import torch
import numpy as np
from torchvision import datasets
import torchvision.transforms as transforms
# convert data to torch.FloatTensor
transform = transforms.ToTensor()
# load the training and test datasets
train_data = datasets.MNIST(root='data', train=True,
do... |
735 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Blockade Interaction in a Magnetic Field
The interaction between Rydberg atoms is strongly influenced by external electric and magnetic fields. A small magnetic field for instance lifts the ... | Python Code:
%matplotlib inline
# Arrays
import numpy as np
# Plotting
import matplotlib.pyplot as plt
# Operating system interfaces
import os, sys
# Parallel computing
if sys.platform != "win32": from multiprocessing import Pool
from functools import partial
# pairinteraction :-)
from pairinteraction import pireal as ... |
736 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Python Training - Lession 2 - classes in Object Oriented Programming
In Python, pretty much every variable is an object, and therefore an instance of some class. But what is a class? A first... | Python Code:
class Example:
a = 1
print type(Example)
Explanation: Python Training - Lession 2 - classes in Object Oriented Programming
In Python, pretty much every variable is an object, and therefore an instance of some class. But what is a class? A first, basic understanding of a class should be:
A data stru... |
737 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Title
Step1: Create Matrix
Step2: Flatten Matrix | Python Code:
# Load library
import numpy as np
Explanation: Title: Flatten A Matrix
Slug: flatten_a_matrix
Summary: How to flatten a matrix in Python.
Date: 2017-09-02 12:00
Category: Machine Learning
Tags: Vectors Matrices Arrays
Authors: Chris Albon
Preliminaries
End of explanation
# Create matrix
matrix = np... |
738 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: Image Classification
In this project, you'll classify images from the CIFAR-10 dataset. The dataset consists of airplanes, dogs, cats, and other objects. You'll preprocess the images... | Python Code:
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
from urllib.request import urlretrieve
from os.path import isfile, isdir
from tqdm import tqdm
import problem_unittests as tests
import tarfile
cifar10_dataset_folder_path = 'cifar-10-batches-py'
class DLProgress(tqdm):
last_block = 0
def h... |
739 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Lesson 1
Step1: 11 - Using CSV Module
But there are many small things that will cause us problems if we try and write the CSV reader by ourselves. So we will re write the above using python... | Python Code:
import os
DATA_FILE_CSV = "beatles-diskography.csv"
def parse_file(data_file):
data = []
row_count = 0
with open(data_file) as f:
header = f.readline().split(',')
for line in f:
if row_count >= 10:
break
fields = line.stri... |
740 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Modeling and Simulation in Python
Rabbit example
Copyright 2017 Allen Downey
License
Step1: Rabbit is Rich
This notebook starts with a version of the rabbit population growth model. You wi... | Python Code:
%matplotlib inline
from modsim import *
Explanation: Modeling and Simulation in Python
Rabbit example
Copyright 2017 Allen Downey
License: Creative Commons Attribution 4.0 International
End of explanation
system = System(t0 = 0,
t_end = 20,
juvenile_pop0 = 0,
... |
741 | 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', 'mohc', 'hadgem3-gc31-ll', 'atmos')
Explanation: ES-DOC CMIP6 Model Properties - Atmos
MIP Era: CMIP6
Institute: MOHC
Source ID: HADGEM3-GC31-LL
Topic: Atmos
Sub-Topics: Dynamical Core... |
742 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<center>
<img src="img/scikit-learn-logo.png" width="40%" />
<br />
<h1>Robust and calibrated estimators with Scikit-Learn</h1>
<br /><br />
Gilles Louppe (<a href="https... | Python Code:
# Global imports and settings
# Matplotlib
%matplotlib inline
from matplotlib import pyplot as plt
plt.rcParams["figure.figsize"] = (8, 8)
plt.rcParams["figure.max_open_warning"] = -1
# Print options
import numpy as np
np.set_printoptions(precision=3)
# Slideshow
from notebook.services.config import Config... |
743 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Train a Neural Network Model to Classify Images
Learning Objectives
Undersand how to read and display image data
Pre-process image data
Build, compile, and train a neural network model
Make ... | Python Code:
# TensorFlow and tf.keras
import tensorflow as tf
from tensorflow import keras
# Helper libraries
import numpy as np
import matplotlib.pyplot as plt
print(tf.__version__)
Explanation: Train a Neural Network Model to Classify Images
Learning Objectives
Undersand how to read and display image data
Pre-proces... |
744 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Applying classifiers to Shalek2013 and Macaulay2016
We're going to use the classifier knowledge that we've learned so far and apply it to the shalek2013 and macaulay2016 datasets.
For the GO... | Python Code:
# Alphabetical order is standard
# We're doing "import superlongname as abbrev" for our laziness - this way we don't have to type out the whole thing each time.
# From python standard library
import collections
# Python plotting library
import matplotlib.pyplot as plt
# Numerical python library (pronounced... |
745 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Comparing test-statistics
Step1: First, data following a (zero-inflated) negative binomial (ZINB) distribution is created for testing purposes. Test size and distribution parameters can be ... | Python Code:
import numpy as np
import scanpy.api as sc
from anndata import AnnData
from numpy.random import negative_binomial, binomial, seed
Explanation: Comparing test-statistics: T-Test and Wilcoxon rank sum test for generic Zero-Inflated Negative Binomial Distribution
End of explanation
seed(1234)
# n_cluster nee... |
746 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Kaggle's Predicting Red Hat Business Value
This is a follow up attempt at Kaggle's Predicting Red Hat Business Value competition.
See my notebooks section for links to the first attempt and ... | Python Code:
import pandas as pd
people = pd.read_csv('people.csv.zip')
people.head(3)
actions = pd.read_csv('act_train.csv.zip')
actions.head(3)
Explanation: Kaggle's Predicting Red Hat Business Value
This is a follow up attempt at Kaggle's Predicting Red Hat Business Value competition.
See my notebooks section for li... |
747 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
ScrapyDo Overview
ScrapyDo is a crochet-based blocking API for Scrapy. It allows the usage of Scrapy as a library, mainly aimed to be used in spiders prototyping and data exploration in IPyt... | Python Code:
import scrapydo
scrapydo.setup()
Explanation: ScrapyDo Overview
ScrapyDo is a crochet-based blocking API for Scrapy. It allows the usage of Scrapy as a library, mainly aimed to be used in spiders prototyping and data exploration in IPython notebooks.
In this notebook we are going to show how to use scrapyd... |
748 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Your first neural network
In this project, you'll build your first neural network and use it to predict daily bike rental ridership. We've provided some of the code, but left the implementat... | Python Code:
%matplotlib inline
%config InlineBackend.figure_format = 'retina'
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
Explanation: Your first neural network
In this project, you'll build your first neural network and use it to predict daily bike rental ridership. We've provided some of t... |
749 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Fantasy Football Scoring System
| Stat Category | Point Value |
|---------------------|---------------------------|
|Passing Yards | 1 point for every 25 yards|
|P... | Python Code:
%matplotlib inline
import pandas as pd
import matplotlib as mp
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
qb_games = pd.read_csv('qb_games.csv')
qb_games.columns.values
Explanation: Fantasy Football Scoring System
| Stat Category | Point Value ... |
750 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
BEM method
Step5: Boundary Discretization
we will create a discretization of the body geometry into panels (line segments in 2D). A panel's attributes are
Step6: We create a node distribut... | Python Code:
#Q = 2000/3 #strength of the source-sheet,stb/d
h=25.26 #thickness of local gridblock,ft
phi=0.2 #porosity
kx=200 #pemerability in x direction,md
ky=200 #pemerability in y direction,md
kr=kx/ky #pemerability ratio
miu=1 #viscosity,cp
Nw=1 #Number o... |
751 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Homework 2 (DUE
Step1: Question 2
For each of the following first-difference processes, compute the values of $y$ from $t=0$ through $t = 12$. For each, assume that $y_0 = 0$.
$y_t = 1 + 0... | Python Code:
# Question 1
T = 20
w = np.zeros(T)
w[0] = 1
def firstDiff(mu,rho,w,y0,T):
y = np.zeros(T+1)
y[0] = y0
for t in range(T):
y[t+1] = (1-rho)*mu + rho*y[t] + w[t]
return y
y1 = firstDiff(mu=0,rho=0.99,w=w,y0=0,T=T)
y2 = firstDiff(mu=0,rho=1,w=w,y0=0,T=T)
y3 = firstDiff(mu=0,r... |
752 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
In the tutorial, you learned about human-centered design (HCD) and became familiar with six general steps to apply it to AI systems. In this exercise, you will identify and address design is... | Python Code:
# Set up feedback system
from learntools.core import binder
binder.bind(globals())
from learntools.ethics.ex2 import *
print("Setup Complete")
Explanation: In the tutorial, you learned about human-centered design (HCD) and became familiar with six general steps to apply it to AI systems. In this exercise, ... |
753 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
TensorFlow Tutorial On Simple Linear Model
Introduction
This tutorial demonstrates the basic workflow of using TensorFlow with a simple linear model. After loading the MNIST data-set with im... | Python Code:
%matplotlib inline
import matplotlib.pyplot as plt
import tensorflow as tf
import numpy as np
from sklearn.metrics import confusion_matrix
Explanation: TensorFlow Tutorial On Simple Linear Model
Introduction
This tutorial demonstrates the basic workflow of using TensorFlow with a simple linear model. After... |
754 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Logistic Regression with a Neural Network mindset
Welcome to your first (required) programming assignment! You will build a logistic regression classifier to recognize cats. This assignment... | Python Code:
import numpy as np
import matplotlib.pyplot as plt
import h5py
import scipy
from PIL import Image
from scipy import ndimage
from lr_utils import load_dataset
%matplotlib inline
Explanation: Logistic Regression with a Neural Network mindset
Welcome to your first (required) programming assignment! You will b... |
755 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Build Experiment from keras model
Embeds a 3 layer FCN model to predict MNIST handwritten digits in a Tensorflow Experiment. The Estimator here is a Keras model.
DOES NOT WORK CURRENTLY with... | Python Code:
from __future__ import division, print_function
from tensorflow.contrib.learn.python.learn.estimators import model_fn as model_fn_lib
from tensorflow.contrib import keras
import matplotlib.pyplot as plt
import numpy as np
import os
import shutil
import tensorflow as tf
DATA_DIR = "../../data"
TRAIN_FILE = ... |
756 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<a href="https
Step1: Predict Shakespeare with Cloud TPUs and TPUEstimator
Overview
This example uses TPUEstimator to build a language model and train it on a Cloud TPU. This language model... | 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... |
757 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
1. What country are most billionaires from? For the top ones, how many billionaires per billion people?
Step1: 2. What's the average wealth of a billionaire? Male? Female?
Step2: 3. Most c... | Python Code:
print("Most billionaires are from the following countries in descending order:")
df['countrycode'].value_counts().head(5)
us = 903 / 1000000000
ger = 160 / 1000000000
china = 153 / 1000000000
russia = 119 / 1000000000
japan = 96 / 1000000000
print("per billion for us is", us, "for germany is", ger, "for ch... |
758 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Lending Club Default Rate Analysis
Step1: Columns Interested
loan_status -- Current status of the loan<br/>
loan_amnt -- The listed amount of the loan applied for by the borrower. If at som... | Python Code:
import pandas as pd
import numpy as np
from sklearn import preprocessing
from sklearn.model_selection import train_test_split
from sklearn.model_selection import cross_val_score
from sklearn.feature_selection import RFE
from sklearn.svm import SVR
from sklearn.svm import LinearSVC
from sklearn.svm import L... |
759 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Problema 3.7
El tensor de tensiones en el punto P esta definido como
Step1: Solución
Step2: Se calcula el vector normal de acuerdo con
Step3: con lo cual es posible calcular el vector de ... | Python Code:
import numpy as np
from numpy import array, cross, dot , sqrt
from sympy import *
from IPython.display import Image,Latex
Image(filename='FIGURES/Ejer3_7.png',width=250)
Explanation: Problema 3.7
El tensor de tensiones en el punto P esta definido como:
$$\left[ {\begin{array}{*{20}{c}}
8&{ - 4}&1\
{ - 4}&3... |
760 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
The Marmousi model
The Marmousi model developped by Versteeg, 1994 is perhaps the most known benchmark model used for seismic imaging and inversion. Let's first download it from a public rep... | Python Code:
import os
from urllib.request import urlretrieve
import numpy as np
import matplotlib.pyplot as plt
from SeisCL import SeisCL
url = "http://sw3d.cz/software/marmousi/little.bin/velocity.h@"
if not os.path.isfile("velocity.h@"):
urlretrieve(url, filename="velocity.h@")
vel = np.fromfile("velocity.h@", d... |
761 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Exercises
Step1: Exercise 1
Step2: Exercise 2
Step3: b. Checking for Normality
Use the jarque_bera function to conduct a Jarque-Bera test on $X$, $Y$, and $Z$ to determine whether their d... | Python Code:
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from statsmodels.stats.stattools import jarque_bera
# Set a seed so we can play with the data without generating new random numbers every time
np.random.seed(321)
Explanation: Exercises: Instability of Parameter Estimates - Answer Key
L... |
762 | Given the following text description, write Python code to implement the functionality described.
Description:
Reduce the array to a single element with the given operation
Function to return the final element ; Driver code
| Python Code:
def getFinalElement(n ) :
finalNum = 2
while finalNum * 2 <= n :
finalNum *= 2
return finalNum
if __name__== "__main __":
N = 12
print(getFinalElement(N ) )
|
763 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Introduction to NLP with NLTK
Natural Language Processing (NLP) is often taught at the academic level from the perspective of computational linguists. However, as data scientists, we have a ... | Python Code:
import nltk
nltk.download()
Explanation: Introduction to NLP with NLTK
Natural Language Processing (NLP) is often taught at the academic level from the perspective of computational linguists. However, as data scientists, we have a richer view of the natural language world - unstructured data that by its ve... |
764 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<center> Hofstadter Butterfly </center>
We generate a fractal like-structure, called the Hofstadter Butterfly, which represents the energy
levels of an electron travelling through a periodi... | Python Code:
import platform
print(f'Python version: {platform.python_version()}')
import plotly
plotly.__version__
import plotly.graph_objs as go
import numpy as np
from numpy import pi
Explanation: <center> Hofstadter Butterfly </center>
We generate a fractal like-structure, called the Hofstadter Butterfly, which rep... |
765 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Working with IUCN data in shapefiles
just some logging/plotting magic to output in this notebook, nothing to care about.
Step1: 1. Load a shapefile with all turtles data. At this point no d... | Python Code:
import logging
root = logging.getLogger()
root.addHandler(logging.StreamHandler())
%matplotlib inline
Explanation: Working with IUCN data in shapefiles
just some logging/plotting magic to output in this notebook, nothing to care about.
End of explanation
# download http://bit.ly/1R8pt20 (zipped Turtles sha... |
766 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
author
Step1: Remove eukaryotic sequences from Silva DB
Also change 'U' to 'T' to match DNA sequences from EMP
Step2: Search deblur against all (or at least a max of 1000 identical) hits
C... | Python Code:
!source activate qiime
import re
import sys
Explanation: author: jonsan@gmail.com<br>
date: 9 Oct 2017<br>
language: Python 3.5<br>
license: BSD3<br>
matches_deblur_to_gg_silva.ipynb
End of explanation
def fix_silva(silva_fp, output_fp):
with open(output_fp, 'w') as f_o:
with open(silva_fp, 'r'... |
767 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Getting ready to implement the Schelling model
Goal for this assignment
The goal of this assignment is to finish up the two functions that you started in class on the first day of this proje... | Python Code:
# Put your code here, using additional cells if necessary.
Explanation: Getting ready to implement the Schelling model
Goal for this assignment
The goal of this assignment is to finish up the two functions that you started in class on the first day of this project, to ensure that you're ready to hit the gr... |
768 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Esercizio 1
Si consideri il dataset delle precipitazioni mensili (mm) nei sette anni dal 2009 al 2015, che ha il seguente formato
Step1: 2) Definizione della funzione compute_mean()
Step2: ... | Python Code:
import numpy as np
Explanation: Esercizio 1
Si consideri il dataset delle precipitazioni mensili (mm) nei sette anni dal 2009 al 2015, che ha il seguente formato: 13 record di campi separati da tabulazione di cui il primo è il record di intestazione degli anni (composto da 7 campi) e gli altri 12 sono i re... |
769 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<a href="https
Step1: 1. Define the Sweep
Weights & Biases sweeps give you powerful levers to configure your sweeps exactly how you want them, with just a few lines of code. The sweeps conf... | Python Code:
# WandB – Install the W&B library
%pip install wandb -q
import wandb
from wandb.keras import WandbCallback
!pip install wandb -qq
from keras.datasets import fashion_mnist
from keras.models import Sequential
from keras.layers import Conv2D, MaxPooling2D, Dropout, Dense, Flatten
from keras.utils import np_ut... |
770 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Comparing color-color tracks of the stellar templates
The goal of this notebook is to compare the stellar loci (in various color-color spaces) of the (theoretical) templates to the observed ... | Python Code:
import os
import numpy as np
import fitsio
import matplotlib.pyplot as plt
from speclite import filters
from astropy import constants
import astropy.units as u
from desisim.io import read_basis_templates
import seaborn as sns
%pylab inline
sns.set(style='white', font_scale=1.8, font='sans-serif', palette='... |
771 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
AFM-MINER
Tech Review
Garrett, Jessica, and Wesley
Step1: <a id='visualize'></a>
Finding objects in the data
Step2: Cons of the edge-based method and the OpenCV Canny edge dector
Step3: C... | Python Code:
import cv2
import numpy as np
import scipy.io
import scipy.optimize
from scipy import stats
import matplotlib.pyplot as plt
from matplotlib import gridspec
import pandas
#import magni
import math
from PIL import Image
#import seaborn as sns; sns.set()
from sklearn.cross_validation import train_test_split
... |
772 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
3. Imagined movement
In this tutorial we will look at imagined movement. Our movement is controlled in the motor cortex where there is an increased level of mu activity (8–12 Hz) when we per... | Python Code:
%pylab inline
import numpy as np
import scipy.io
m = scipy.io.loadmat('data_set_IV/BCICIV_calib_ds1d.mat', struct_as_record=True)
# SciPy.io.loadmat does not deal well with Matlab structures, resulting in lots of
# extra dimensions in the arrays. This makes the code a bit more cluttered
sample_rate = m['nf... |
773 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
DV360 Report To Storage
Move existing DV360 report into a Storage bucket.
License
Copyright 2020 Google LLC,
Licensed under the Apache License, Version 2.0 (the "License");
you may not use t... | Python Code:
!pip install git+https://github.com/google/starthinker
Explanation: DV360 Report To Storage
Move existing DV360 report into a Storage bucket.
License
Copyright 2020 Google LLC,
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
Y... |
774 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Building an ARIMA Model for a Financial Dataset
In this notebook, you will build an ARIMA model for AAPL stock closing prices. The lab objectives are
Step1: Import data from Google Clod Sto... | Python Code:
!pip install --user statsmodels
%matplotlib inline
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import datetime
%config InlineBackend.figure_format = 'retina'
Explanation: Building an ARIMA Model for a Financial Dataset
In this notebook, you will build an ARIMA model for AAPL stoc... |
775 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Interact Exercise 4
Imports
Step2: Line with Gaussian noise
Write a function named random_line that creates x and y data for a line with y direction random noise that has a normal distribut... | Python Code:
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
from IPython.html.widgets import interact, interactive, fixed
from IPython.display import display
Explanation: Interact Exercise 4
Imports
End of explanation
def random_line(m, b, sigma, size=10):
Create a line y = m*x + b + N(0,sigm... |
776 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
TFX pipeline example - Chicago Taxi tips prediction
Overview
Tensorflow Extended (TFX) is a Google-production-scale machine
learning platform based on TensorFlow. It provides a configuration... | Python Code:
!python3 -m pip install pip --upgrade --quiet --user
!python3 -m pip install kfp --upgrade --quiet --user
!python3 -m pip install tfx==0.21.2 --quiet --user
Explanation: TFX pipeline example - Chicago Taxi tips prediction
Overview
Tensorflow Extended (TFX) is a Google-production-scale machine
learning plat... |
777 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Python 문자열 인코딩
문자와 인코딩
문자의 구성
바이트 열 Byte Sequence
Step1: 유니코드 리터럴(Literal)
따옴표 앞에 u자를 붙이면 unicode 문자열로 인식
내부적으로 유니코드 포인트로 저장
Step2: 유니코드 인코딩(Encoding) / 디코딩(Decoding)
encode
unicode 타입의 메소... | Python Code:
c = "a"
c
print(c)
x = "가"
x
print(x)
print(x.__repr__())
x = ["가"]
print(x)
x = "가"
len(x)
x = "ABC"
y = "가나다"
print(len(x), len(y))
print(x[0], x[1], x[2])
print(y[0], y[1], y[2])
print(y[0], y[1], y[2], y[3])
Explanation: Python 문자열 인코딩
문자와 인코딩
문자의 구성
바이트 열 Byte Sequence: 컴퓨터에 저장되는 자료. 각 글자에 바이트 열을 지정
글... |
778 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Deep Learning with TensorFlow
Credits
Step2: First, we'll download the dataset to our local machine. The data consists of characters rendered in a variety of fonts on a 28x28 image. The lab... | Python Code:
print 'xxxx'
# These are all the modules we'll be using later. Make sure you can import them
# before proceeding further.
import matplotlib.pyplot as plt
import numpy as np
import os
import tarfile
import urllib
from IPython.display import display, Image
from scipy import ndimage
from sklearn.linear_model ... |
779 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Starman
This notebook integrates the orbit of Elon Musk's Tesla and Starman.
Step1: We start by querying NASA Horizons for the Solar System planets around the time of the orbit injection.
S... | Python Code:
import rebound
import numpy as np
%matplotlib inline
Explanation: Starman
This notebook integrates the orbit of Elon Musk's Tesla and Starman.
End of explanation
sim = rebound.Simulation()
sim.add(["Sun","Mercury","Venus","Earth","Mars","Jupiter","Saturn","Uranus","Neptune"],date="2018-02-10 00:00")
sim.sa... |
780 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
0. random init
for initial centroids
Step1: 1. cluster assignment
http
Step2: 1 epoch cluster assigning
Step3: See the first round clustering result
Step4: 2. calculate new centroid
Step... | Python Code:
km.random_init(data2, 3)
Explanation: 0. random init
for initial centroids
End of explanation
init_centroids = km.random_init(data2, 3)
init_centroids
x = np.array([1, 1])
fig, ax = plt.subplots(figsize=(6,4))
ax.scatter(x=init_centroids[:, 0], y=init_centroids[:, 1])
for i, node in enumerate(init_centroid... |
781 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Testing the non-Markovian Path Analysis Package
Step1: 2D Toy model
Step2: MC simulation
Step3: 1 - Ensemble class (analysis of continuos trajectories)
Stores an esemble (list) of traject... | Python Code:
import sys
sys.path.append("../nmpath/")
from tools_for_notebook0 import *
%matplotlib inline
from mappers import rectilinear_mapper
from ensembles import Ensemble, DiscreteEnsemble, PathEnsemble, DiscretePathEnsemble
Explanation: Testing the non-Markovian Path Analysis Package
End of explanation
plot_traj... |
782 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Photometric Inference
This notebook outlines the basics of how to conduct basic redshift inference (i.e. a set of intrinsic labels) using photometry (i.e. a set of observed features).
Setup
... | Python Code:
from __future__ import print_function, division
import sys
import pickle
import numpy as np
import scipy
import matplotlib
from matplotlib import pyplot as plt
from six.moves import range
# import frankenz code
import frankenz as fz
# plot in-line within the notebook
%matplotlib inline
np.random.seed(83481... |
783 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Welcome to the MXCuBE jupyter Notebook service!
Press "Shift + Enter" to proceed
Step1: Try to load some hardware objects defined in the xml-qt
Step2: Use dir to see available methods and ... | Python Code:
import os
import sys
cwd = os.getcwd()
print cwd
mxcube_root = cwd[:-4]
print mxcube_root
sys.path.insert(0, mxcube_root)
from HardwareRepository import HardwareRepository
#print "MXCuBE home directory: %s" % cwd
hwr_server = mxcube_root + "/HardwareRepository/configuration/xml-qt"
HardwareRepository.setH... |
784 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Introduction to Non-Personalized Recommenders
The recommendation problem
Recommenders have been around since at least 1992. Today we see different flavours of recommenders, deployed across d... | Python Code:
from IPython.core.display import Image
Image(filename='/Users/chengjun/GitHub/cjc2016/figure/recsys_arch.png')
Explanation: Introduction to Non-Personalized Recommenders
The recommendation problem
Recommenders have been around since at least 1992. Today we see different flavours of recommenders, deployed ... |
785 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Simulate the model and make Figure SI-1
Imports
First run all of the code in this section to import the necessary packages.
First we load some magic commands
Step1: Next load some standard... | Python Code:
%load_ext autoreload
%autoreload 2
%matplotlib inline
Explanation: Simulate the model and make Figure SI-1
Imports
First run all of the code in this section to import the necessary packages.
First we load some magic commands:
End of explanation
import numpy as np
import matplotlib.pyplot as plt
import mat... |
786 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Hazard Curves and Uniform Hazard Spectra
This IPython notebook allows the user to visualise the hazard curves for individual sites generated from a probabilistic event-based hazard analysis ... | Python Code:
%matplotlib inline
import matplotlib.pyplot as plt
from plot_hazard_outputs import HazardCurve, UniformHazardSpectra
hazard_curve_file = "../sample_outputs/hazard/hazard_curve.xml"
hazard_curves = HazardCurve(hazard_curve_file)
Explanation: Hazard Curves and Uniform Hazard Spectra
This IPython notebook all... |
787 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Summary of Available Sensorimotor and Interest Models
In this notebook, we summarize the different sensorimotor and interest models available in the Explauto library, and give some explanati... | Python Code:
from explauto.environment.environment import Environment
environment = Environment.from_configuration('simple_arm', 'mid_dimensional')
Explanation: Summary of Available Sensorimotor and Interest Models
In this notebook, we summarize the different sensorimotor and interest models available in the Explauto l... |
788 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Interactions and ANOVA
Note
Step1: Take a look at the data
Step2: Fit a linear model
Step3: Have a look at the created design matrix
Step4: Or since we initially passed in a DataFrame, w... | Python Code:
%matplotlib inline
from urllib.request import urlopen
import numpy as np
np.set_printoptions(precision=4, suppress=True)
import pandas as pd
pd.set_option("display.width", 100)
import matplotlib.pyplot as plt
from statsmodels.formula.api import ols
from statsmodels.graphics.api import interaction_plot, abl... |
789 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Using Tensorboard in DeepChem
DeepChem Neural Networks models are built on top of tensorflow. Tensorboard is a powerful visualization tool in tensorflow for viewing your model architecture ... | Python Code:
from IPython.display import Image, display
import deepchem as dc
from deepchem.molnet import load_tox21
from deepchem.models.graph_models import GraphConvModel
# Load Tox21 dataset
tox21_tasks, tox21_datasets, transformers = load_tox21(featurizer='GraphConv')
train_dataset, valid_dataset, test_dataset = to... |
790 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Introduction to Python
(via xkcd)
What is Python?
Python is a modern, open source, object-oriented programming language, created by a Dutch programmer, Guido van Rossum. Officially, it is an... | Python Code:
# Import modules you might use
import numpy as np
# Some data, in a list
my_data = [12, 5, 17, 8, 9, 11, 21]
# Function for calulating the mean of some data
def mean(data):
# Initialize sum to zero
sum_x = 0.0
# Loop over data
for x in data:
# Add to sum
sum_x += x
... |
791 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step5: Encapsulation, part 2
Step6: 2. Instantiating objects
We can now instantiate a music-maker object. We do this by calling the music-maker's initializer, to which we pass counts, denom... | Python Code:
class MusicMaker:
def __init__(
self,
counts,
denominator,
pitches,
clef,
):
self.counts = counts
self.denominator = denominator
self.pitches = pitches
self.clef = clef
def make_notes_and_rests(self, counts, denomina... |
792 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Get the list of motifsets that are available
Step1: We have two urls for getting a motifset | Python Code:
output = requests.get(server_url + '/motifdb/list_motifsets')
motifset_list = output.json()
print(motifset_list)
Explanation: Get the list of motifsets that are available
End of explanation
url = server_url + '/motifdb/initialise_api'
client = requests.session()
token = client.get(url).json()['token']
url ... |
793 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Experimental
Step1: 1. Write Eager code that is fast and scalable
TF.Eager gives you more flexibility while coding, but at the cost of losing the benefits of TensorFlow graphs. For example,... | Python Code:
# Install TensorFlow; note that Colab notebooks run remotely, on virtual
# instances provided by Google.
!pip install -U -q tf-nightly
import os
import time
import tensorflow as tf
from tensorflow.contrib import autograph
import matplotlib.pyplot as plt
import numpy as np
import six
from google.colab impor... |
794 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
This notebook is to get myself to be familair with the pybedtools
import the pybedtools module
Step1: get the working directory and you can change to the directory you want by os.chdir(path... | Python Code:
import pybedtools
import sys
import os
Explanation: This notebook is to get myself to be familair with the pybedtools
import the pybedtools module
End of explanation
os.getcwd()
# use a pre-shipped bed file as an example
a = pybedtools.example_bedtool('a.bed')
Explanation: get the working directory and you... |
795 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step2: Bonus1
Step4: Bonus2
Step6: Bonus3
Step8: We may use lambda when no key is provided like so
Step10: Unit Tests | Python Code:
multimax([])
def multimax(iterable):
Return a list of all maximum values
try:
max_item = max(iterable)
except ValueError:
return []
return [
item
for item in iterable
if item == max_item
]
multimax([])
def multimax(iterable):
Return a ... |
796 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Twitter Sentiment analysis with Watson Tone Analyzer and Watson Personality Insights
<img style="max-width
Step1: Install latest pixiedust
Make sure you are running the latest pixiedust ver... | Python Code:
!pip install --user python-twitter
!pip install --user watson-developer-cloud
Explanation: Twitter Sentiment analysis with Watson Tone Analyzer and Watson Personality Insights
<img style="max-width: 800px; padding: 25px 0px;" src="https://ibm-watson-data-lab.github.io/spark.samples/Twitter%20Sentiment%20wi... |
797 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Time Series Database
This notebook demonstrates the persistent behavior of the database.
Initialization
Clear the file system for demonstration purposes.
Step1: Load the database server.
St... | Python Code:
# database parameters
ts_length = 100
data_dir = '../db_files'
db_name = 'default'
dir_path = data_dir + '/' + db_name + '/'
# clear file system for testing
if not os.path.exists(dir_path):
os.makedirs(dir_path)
filelist = [dir_path + f for f in os.listdir(dir_path)]
for f in filelist:
os.remove(f)... |
798 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
L'objectif est de réaliser des graphiques décrivant l'évolution mensuelle des prix des carburants depuis 1990.
Import de modules spécifiques à Openfisca, et import des données de prix des ca... | Python Code:
%matplotlib inline
from ipp_macro_series_parser.agregats_transports.parser_cleaner_prix_carburants import prix_mensuel_carburants_90_15
from openfisca_france_indirect_taxation.examples.utils_example import graph_builder_carburants
Explanation: L'objectif est de réaliser des graphiques décrivant l'évolution... |
799 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
A Network Tour of Data Science
Xavier Bresson, Winter 2016/17
Exercise 4 - Code 2
Step1: Question 1a
Step2: Question 1b
Step3: Question 1c | Python Code:
# Load libraries
# Math
import numpy as np
# Visualization
%matplotlib notebook
import matplotlib.pyplot as plt
plt.rcParams.update({'figure.max_open_warning': 0})
from mpl_toolkits.axes_grid1 import make_axes_locatable
from scipy import ndimage
# Print output of LFR code
import subprocess
# Sparse matri... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.