Unnamed: 0 int64 0 16k | text_prompt stringlengths 110 62.1k | code_prompt stringlengths 37 152k |
|---|---|---|
8,300 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
ES-DOC CMIP6 Model Properties - Land
MIP Era
Step1: Document Authors
Set document authors
Step2: Document Contributors
Specify document contributors
Step3: Document Publication
Specify do... | Python Code:
# DO NOT EDIT !
from pyesdoc.ipython.model_topic import NotebookOutput
# DO NOT EDIT !
DOC = NotebookOutput('cmip6', 'mohc', 'hadgem3-gc31-mm', 'land')
Explanation: ES-DOC CMIP6 Model Properties - Land
MIP Era: CMIP6
Institute: MOHC
Source ID: HADGEM3-GC31-MM
Topic: Land
Sub-Topics: Soil, Snow, Veget... |
8,301 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Univariate plotting with pandas 单一变量
df.plot.bar() df.plot.line() df.plot.area() df.plot.hist()
Step1: 三分之一的酒来自加尼福尼亚
得分['points']分数越高越好 | Python Code:
reviews['province'].value_counts().head(10).plot.bar()
plt.show()
(reviews['province'].value_counts().head(10) / len(reviews)).plot.bar()
plt.show()
Explanation: Univariate plotting with pandas 单一变量
df.plot.bar() df.plot.line() df.plot.area() df.plot.hist()
End of explanation
reviews['points'].value_co... |
8,302 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: TV Script Generation
In this project, you'll generate your own Simpsons TV scripts using RNNs. You'll be using part of the Simpsons dataset of scripts from 27 seasons. The Neural Ne... | Python Code:
DON'T MODIFY ANYTHING IN THIS CELL
import helper
data_dir = './data/simpsons/moes_tavern_lines.txt'
text = helper.load_data(data_dir)
# Ignore notice, since we don't use it for analysing the data
text = text[81:]
Explanation: TV Script Generation
In this project, you'll generate your own Simpsons TV script... |
8,303 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
First, here's the SPA power function
Step1: Here are two helper functions for computing the dot product over space, and for plotting the results
Step2: Let's do a quick example of using th... | Python Code:
def power(s, e):
x = np.fft.ifft(np.fft.fft(s.v) ** e).real
return spa.SemanticPointer(data=x)
Explanation: First, here's the SPA power function:
End of explanation
def spatial_dot(v, X, Y, xs, ys, transform=1):
if isinstance(v, spa.SemanticPointer):
v = v.v
vs = np.zeros((len(ys),l... |
8,304 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Locality Sensitive Hashing
Locality Sensitive Hashing (LSH) provides for a fast, efficient approximate nearest neighbor search. The algorithm scales well with respect to the number of data p... | Python Code:
import numpy as np
import graphlab
from scipy.sparse import csr_matrix
from scipy.sparse.linalg import norm
from sklearn.metrics.pairwise import pairwise_distances
import time
from copy import copy
import matplotlib.pyplot as plt
%matplotlib inline
Explanation: Locality Sensitive Hashing
Locality Sensitive... |
8,305 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Setting the EEG reference
This tutorial describes how to set or change the EEG reference in MNE-Python.
Step1: Background
EEG measures a voltage (difference in electric potential) betwe... | Python Code:
import os
import mne
sample_data_folder = mne.datasets.sample.data_path()
sample_data_raw_file = os.path.join(sample_data_folder, 'MEG', 'sample',
'sample_audvis_raw.fif')
raw = mne.io.read_raw_fif(sample_data_raw_file, verbose=False)
raw.crop(tmax=60).load_data()
raw.pi... |
8,306 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Title
Step1: Create Dictionary
Step2: Feature Matrix From Dictionary
Step3: View column names | Python Code:
# Load library
from sklearn.feature_extraction import DictVectorizer
Explanation: Title: Converting A Dictionary Into A Matrix
Slug: converting_a_dictionary_into_a_matrix
Summary: How to convert a dictionary into a feature matrix for machine learning in Python.
Date: 2016-09-06 12:00
Category: Machine Le... |
8,307 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
1A.soft - Calcul numérique et Cython - correction
Step1: Exercice
Step2: solution avec notebook
Les préliminaires
Step3: Puis
Step6: solution sans notebook
Step7: La version Cython e... | Python Code:
from jyquickhelper import add_notebook_menu
add_notebook_menu()
Explanation: 1A.soft - Calcul numérique et Cython - correction
End of explanation
def distance_edition(mot1, mot2):
dist = { (-1,-1): 0 }
for i,c in enumerate(mot1) :
dist[i,-1] = dist[i-1,-1] + 1
dist[-1,i] = dist[-1,i... |
8,308 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Chapter 2
Step1: In this chapter, we show an example of image clustering. A deep feature (VGG16 fc6 activation) is extracted from each image using Keras, then the features are clustered usi... | Python Code:
import numpy
import pqkmeans
import tqdm
import matplotlib.pyplot as plt
%matplotlib inline
Explanation: Chapter 2: Image clustering
This chapter contains the followings:
Read images from the CIFAR10 dataset
Extract a deep feature (VGG16 fc6 activation) from each image using Keras
Run clustering on deep fe... |
8,309 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Problème 1
Visualiser les isothermes de Freundlich et de Langmuir
Step1: Problème 2
Lisser des données simulées avec la fonction d'isotherme de Langmuir.
Créer des données simulées
Step2: ... | Python Code:
%pylab inline
def freundlich(C, kp, b):
S = kp*C**b
return(S)
def langmuir(C, Smax, kp):
S = C*kp*Smax/(1+kp*C)
return(S)
conc = linspace(num = 11, start = 0, stop = 10, endpoint=True)
S_freundlich1 = freundlich(C = conc, kp = 1, b = 0.1)
S_freundlich2 = freundlich(C = conc, kp = 1, b = 0.5... |
8,310 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Datenmodell
Beschreibung der Domäne, die auf Basis der relationalen DB gewünscht wird
Step1: Lesen der Tarif-Informationen
Step2: Die Tarif-Informationen aufnehmen
Vorgehensweise
Step3: H... | Python Code:
import pandas as pd
import numpy as np
def writeDsvFile(df, typeName, delimiter, columnsList, headerList):
filename = './output/' + typeName + '.dsv'
df.to_csv(filename, index = False, sep = delimiter, columns = columnsList, header = headerList)
def trimName(longName):
trimmedName = ''
... |
8,311 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2019 The TensorFlow Authors.
Step1: 预创建的 Estimators
<table class="tfo-notebook-buttons" align="left">
<td>
<a target="_blank" href="https
Step2: 数据集
本文档中的示例程序构建并测试了一个模型,该模型... | Python Code:
#@title Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# dist... |
8,312 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Vector Math
In this notebook we'll demo that word2vec-like properties are kept. You can download the vectors, follow along at home, and make your own queries if you'd like.
Sums
Step1: You ... | Python Code:
!wget https://zenodo.org/record/49903/files/vocab.npy
!wget https://zenodo.org/record/49903/files/word_vectors.npy
Explanation: Vector Math
In this notebook we'll demo that word2vec-like properties are kept. You can download the vectors, follow along at home, and make your own queries if you'd like.
Sums:
... |
8,313 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: Tutorial "Algorithmic Methods for Network Analysis with NetworKit" (Part 3)
Determining Important Nodes
There are a number of ways to measure the importance of nodes in a network. Pos... | Python Code:
%matplotlib inline
from networkit import *
import matplotlib.pyplot as plt
cd ~/Documents/workspace/NetworKit
%matplotlib inline
G = readGraph("input/MIT8.edgelist", Format.EdgeListTabZero)
def avgFriendDegree(v):
Calculate the average degree of the neighbors of a node
degSum = 0
for u in G.ne... |
8,314 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Vector Space Model
Adapted from this blog post, written by Allen Riddell.
One of the benefits of the DTM is that it allows us to think about text within the bounds of geometry, which then al... | Python Code:
import numpy as np
from sklearn.feature_extraction.text import CountVectorizer
filenames = ['../Data/Alcott_GarlandForGirls.txt',
'../Data/Austen_PrideAndPrejudice.txt',
'../Data/Machiavelli_ThePrince.txt',
'../Data/Marx_CommunistManifesto.txt']
vectorizer = CountVector... |
8,315 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Introduction
This example demonstraites how to convert Caffe pretrained ResNet-50 model from https
Step1: We need a lot of building blocks from Lasagne to build network
Step2: Helper modul... | Python Code:
import caffe
Explanation: Introduction
This example demonstraites how to convert Caffe pretrained ResNet-50 model from https://github.com/KaimingHe/deep-residual-networks (firstly described in http://arxiv.org/pdf/1512.03385v1.pdf) into Theano/Lasagne format.
We will create a set of Lasagne layers correspo... |
8,316 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Sveučilište u Zagrebu
Fakultet elektrotehnike i računarstva
Strojno učenje 2018/2019
http
Step1: 1. Klasifikator stroja potpornih vektora (SVM)
(a)
Upoznajte se s razredom svm.SVC, koja u... | Python Code:
import numpy as np
import scipy as sp
import pandas as pd
import mlutils
import matplotlib.pyplot as plt
%pylab inline
Explanation: Sveučilište u Zagrebu
Fakultet elektrotehnike i računarstva
Strojno učenje 2018/2019
http://www.fer.unizg.hr/predmet/su
Laboratorijska vježba 3: Stroj potpornih vektora i al... |
8,317 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Homework #4
These problem sets focus on list comprehensions, string operations and regular expressions.
Problem set #1
Step1: In the following cell, complete the code with an expression tha... | Python Code:
numbers_str = '496,258,332,550,506,699,7,985,171,581,436,804,736,528,65,855,68,279,721,120'
Explanation: Homework #4
These problem sets focus on list comprehensions, string operations and regular expressions.
Problem set #1: List slices and list comprehensions
Let's start with some data. The following cell... |
8,318 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Tokenize the text using nltk
Step1: Assign POS tags to the words in the text
Step3: Normalize - return a list of tuples with the first item's periods removed.
Step4: This will be used to ... | Python Code:
word_tokens = nltk.word_tokenize(fread)
Explanation: Tokenize the text using nltk
End of explanation
tagged = nltk.pos_tag(word_tokens)
textlist = [x[0] for x in tagged]
# filter_for_tags
defaulttags = ['NN','JJ','NNP']
tagged_filtered = [item for item in tagged if item[1] in defaulttags]
tagged_filtered
E... |
8,319 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Interact Exercise 3
Imports
Step2: Using interact for animation with data
A soliton is a constant velocity wave that maintains its shape as it propagates. They arise from non-linear wave eq... | Python Code:
%matplotlib inline
from matplotlib import pyplot as plt
import numpy as np
from IPython.html.widgets import interact, interactive, fixed
from IPython.display import display
Explanation: Interact Exercise 3
Imports
End of explanation
def soliton(x, t, c, a):
Return phi(x, t) for a soliton wave with cons... |
8,320 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
webpages module
author
Step1: field setting
invalid attribute
raises Attribute error
Step2: set pagefilename
the filename concatenates the basepath, relpaths, pagefilename, and pagefileext... | Python Code:
%load_ext autoreload
%autoreload 2
import os, sys
path = os.path.abspath('../..'); sys.path.insert(0, path) if path not in sys.path else None
from IPython.display import HTML
from pywebify import webpage
Page = webpage.Webpage
Explanation: webpages module
author: kevin.tetz
description: webpages module tes... |
8,321 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Sinusoidal Steady State Voltage on a Transmission Line
The voltage on a lossless transmission line is given by
\begin{aligned} v(z,t) & = v_0 cos(\omega t - \beta z) + \left|{\Gamma_L}\right... | Python Code:
import numpy as np
from matplotlib import pyplot as plt
from matplotlib import animation
# Switch to a backend that supports FuncAnimation
plt.switch_backend('tkagg')
print 'Matplotlib graphics backend in use:',plt.get_backend()
Explanation: Sinusoidal Steady State Voltage on a Transmission Line
The voltag... |
8,322 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<div align="center"><h1>Image Processing with Hybridizer</h1></div>
Image processing is most often an embarassingly parallel problem. It naturally fits on the GPU.
In this lab, we will stud... | Python Code:
import platform
if platform.system() == "Windows" : # create directory on Windows
!mkdir output-01-naive
if platform.system() == "Linux" : # create directory on Linux
!mkdir -p ./output-01-naive
!hybridizer-cuda ./01-naive/01-naive-csharp.cs graybitmap.cs -o ./01-naive/01-naive-csharp.exe -run
# ... |
8,323 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Inference
Think Bayes, Second Edition
Copyright 2020 Allen B. Downey
License
Step1: Whenever people compare Bayesian inference with conventional approaches, one of the questions that comes ... | Python Code:
# If we're running on Colab, install empiricaldist
# https://pypi.org/project/empiricaldist/
import sys
IN_COLAB = 'google.colab' in sys.modules
if IN_COLAB:
!pip install empiricaldist
# Get utils.py
from os.path import basename, exists
def download(url):
filename = basename(url)
if not exists(... |
8,324 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
PyQuiver
This is an IPython Notebook interface for the PyQuiver package. The code below will guide you through using PyQuiver through a native Python interface. The same steps could be repro... | Python Code:
# import the necessary package elements
import numpy as np
import sys
sys.path.append("../src")
from kie import KIE_Calculation
Explanation: PyQuiver
This is an IPython Notebook interface for the PyQuiver package. The code below will guide you through using PyQuiver through a native Python interface. The s... |
8,325 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Compute MxNE with time-frequency sparse prior
The TF-MxNE solver is a distributed inverse method (like dSPM or sLORETA)
that promotes focal (sparse) sources (such as dipole fitting technique... | Python Code:
# Author: Alexandre Gramfort <alexandre.gramfort@inria.fr>
# Daniel Strohmeier <daniel.strohmeier@tu-ilmenau.de>
#
# License: BSD-3-Clause
import numpy as np
import mne
from mne.datasets import sample
from mne.minimum_norm import make_inverse_operator, apply_inverse
from mne.inverse_sparse import t... |
8,326 | 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... |
8,327 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
From Command Line - Import CSV file (Raw Data) into MongoDB
mongoimport --db airbnb --type csv --file listings_new.csv -c listings_new
mongoimport --db airbnb --type csv --file barcelona_att... | Python Code:
import pymongo
from pymongo import MongoClient
Explanation: From Command Line - Import CSV file (Raw Data) into MongoDB
mongoimport --db airbnb --type csv --file listings_new.csv -c listings_new
mongoimport --db airbnb --type csv --file barcelona_attractions.csv -c attractions
End of explanation
client = M... |
8,328 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Regression Week 2
Step1: Load in house sales data
Dataset is from house sales in King County, the region where the city of Seattle, WA is located.
Step2: Split data into training and testi... | Python Code:
import graphlab
Explanation: Regression Week 2: Multiple Regression (Interpretation)
The goal of this first notebook is to explore multiple regression and feature engineering with existing graphlab functions.
In this notebook you will use data on house sales in King County to predict prices using multiple ... |
8,329 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Hadoop Short Course
1. Hadoop Distributed File System
Hadoop Distributed File System (HDFS)
HDFS is the primary distributed storage used by Hadoop applications. A HDFS cluster primarily cons... | Python Code:
hadoop_root = '/home/ubuntu/shortcourse/hadoop-2.7.1/'
hadoop_start_hdfs_cmd = hadoop_root + 'sbin/start-dfs.sh'
hadoop_stop_hdfs_cmd = hadoop_root + 'sbin/stop-dfs.sh'
# start the hadoop distributed file system
! {hadoop_start_hdfs_cmd}
# show the jave jvm process summary
# You should see NamenNode, Secon... |
8,330 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Lake Model Solutions
Excercise 1
We begin by initializing the variables and import the necessary modules
Step1: Now construct the class containing the initial conditions of the problem
Step... | Python Code:
%pylab inline
import LakeModel
alpha = 0.012
lamb = 0.2486
b = 0.001808
d = 0.0008333
g = b-d
N0 = 100.
e0 = 0.92
u0 = 1-e0
T = 50
Explanation: Lake Model Solutions
Excercise 1
We begin by initializing the variables and import the necessary modules
End of explanation
LM0 = LakeModel.LakeModel(lamb,alpha,b,... |
8,331 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Detrending, Stylized Facts and the Business Cycle
In an influential article, Harvey and Jaeger (1993) described the use of unobserved components models (also known as "structural time series... | Python Code:
%matplotlib inline
import numpy as np
import pandas as pd
import statsmodels.api as sm
import dismalpy as dp
import matplotlib.pyplot as plt
from IPython.display import display, Latex
Explanation: Detrending, Stylized Facts and the Business Cycle
In an influential article, Harvey and Jaeger (1993) describe... |
8,332 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
What does the following code do?
Step1: What does the following code do?
Step2: What does the following code do?
Step3: What does the following code do?
Step4: What does the following co... | Python Code:
d = pd.read_csv("data/dataset_0.csv")
fig, ax = plt.subplots()
ax.plot(d.x,d.y,'o')
Explanation: What does the following code do?
End of explanation
def linear(x,a,b):
return a + b*x
Explanation: What does the following code do?
End of explanation
def linear(x,a,b):
return a + b*x
def linear_r(para... |
8,333 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Prevalence of Personal Attacks
In this notebook, we do some basic investigation into the frequency of personal attacks on Wikipedia. We will attempt to provide some insight into the followin... | Python Code:
%load_ext autoreload
%autoreload 2
%matplotlib inline
import warnings
warnings.filterwarnings('ignore')
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
import pandas as pd
from load_utils import *
from analysis_utils import compare_groups
d = load_diffs()
df_events, df_blocked_user... |
8,334 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
circle()
The following function, circle(xy, radius, kwargs=None), is a customised wrapper for patches.Ellipse to draw nice circles on a figure even if the axes have very different dimensions... | Python Code:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import rc, patches
# Increase font size, set CM as default text, and use LaTeX
rc('font', **{'size': 16, 'family': 'serif', 'serif': ['Computer Modern Roman']})
rc('text', usetex=True)
# Define colours (taken from http://colorbrewer2.org)
c... |
8,335 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Introduction to Dynamic Programming
We have studied the theory of dynamic programming in discrete time under certainty. Let's review what we know so far, so that we can start thinking about ... | Python Code:
from __future__ import division
%pylab --no-import-all
%matplotlib inline
from numpy import interp
interp?
x = np.linspace(0, np.pi, 100)
plt.figure(1)
plt.plot(x, np.sin(x), label='Actual Function')
for i in np.arange(3,11,2):
fig1 = plt.figure(1)
xp = np.linspace(0, np.pi, i)
yp = np.sin(xp)... |
8,336 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Gather precovery imaging
This notebook shows how to get precovery imaging for objects found with KBMOD. Once we have an object
identified we can record the observations we used in MPC format... | Python Code:
from precovery_utils import ssoisPrecovery
Explanation: Gather precovery imaging
This notebook shows how to get precovery imaging for objects found with KBMOD. Once we have an object
identified we can record the observations we used in MPC format and use the following tools to search
other telescope data f... |
8,337 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<h1 align="center"> Introdução ao Processamento de Linguagem Natural (PLN) Usando Python </h1>
<h3 align="center"> Professor Fernando Vieira da Silva MSc.</h3>
<h2>Problema de Classificação<... | Python Code:
import nltk
nltk.download('nps_chat')
from nltk.corpus import nps_chat
print(nps_chat.fileids())
Explanation: <h1 align="center"> Introdução ao Processamento de Linguagem Natural (PLN) Usando Python </h1>
<h3 align="center"> Professor Fernando Vieira da Silva MSc.</h3>
<h2>Problema de Classificação</h2>
<p... |
8,338 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Combining different machine learning algorithms into an ensemble model
Model ensembling is a class of techniques for aggregating together multiple different predictive algorithm into a sort ... | Python Code:
import pandas as pd
import numpy as np
# Import the dataset
dataset_path = "spam_dataset.csv"
dataset = pd.read_csv(dataset_path, sep=",")
# Take a peak at the data
dataset.head()
Explanation: Combining different machine learning algorithms into an ensemble model
Model ensembling is a class of techniques f... |
8,339 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Read CA CSV
Import directives
Step1: Export/import data (write/read files)
See http
Step2: CSV files
See http
Step3: Setting more options
Step4: Read CSV files
See http
Step5: Setting m... | Python Code:
%matplotlib inline
#%matplotlib notebook
from IPython.display import display
import matplotlib
matplotlib.rcParams['figure.figsize'] = (9, 9)
import pandas as pd
import numpy as np
!head -n30 /Users/jdecock/Downloads/CA20170725_1744.CSV
#df = pd.read_csv("/Users/jdecock/Downloads/CA20170725_1744.CSV")
df =... |
8,340 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
|S.No| Package | Comments |
|---|---|---|
|1| pandas | provides data structures (such as DataFrame) to <span style="color
Step1: Read input tables
Step2: Block tables to get candidate ... | Python Code:
import py_entitymatching as em
import profiler
import pandas as pd
Explanation: |S.No| Package | Comments |
|---|---|---|
|1| pandas | provides data structures (such as DataFrame) to <span style="color:red;">store and manage relational data</span>. Specifically, DataFrame is used to represent input tab... |
8,341 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Equation of motion - SDE to be solved
$\ddot{q}(t) + \Gamma_0\dot{q}(t) + \Omega_0^2 q(t) - \dfrac{1}{m} F(t) = 0 $
where q = x, y or z
Where $F(t) = \mathcal{F}{fluct}(t) + F{feedback}(t)$... | Python Code:
def a_q(t, v, q):
return v
def a_v(t, v, q):
return -(Gamma0 - Omega0*eta*q**2)*v - Omega0**2*q
def b_v(t, v, q):
return np.sqrt(2*Gamma0*k_b*T_0/m)
Explanation: Equation of motion - SDE to be solved
$\ddot{q}(t) + \Gamma_0\dot{q}(t) + \Omega_0^2 q(t) - \dfrac{1}{m} F(t) = 0 $
where q = x, y o... |
8,342 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Use logical constraints with decision optimization
This tutorial includes everything you need to set up decision optimization engines, build a mathematical programming model, leveraging logi... | Python Code:
import sys
try:
import docplex.mp
except:
raise Exception('Please install docplex. See https://pypi.org/project/docplex/')
Explanation: Use logical constraints with decision optimization
This tutorial includes everything you need to set up decision optimization engines, build a mathematical program... |
8,343 | Given the following text problem statement, write Python code to implement the functionality described below in problem statement
Problem:
Let X be a M x N matrix. Denote xi the i-th column of X. I want to create a 3 dimensional N x M x M array consisting of M x M matrices xi.dot(xi.T). | Problem:
import numpy as np
X = np.random.randint(2, 10, (5, 6))
result = X.T[:, :, None] * X.T[:, None] |
8,344 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Start here to begin with Stingray.
Step1: Creating a light curve
Step2: A Lightcurve object can be created in two ways
Step3: Create 1000 random Poisson-distributed counts
Step4: Create... | Python Code:
import numpy as np
%matplotlib inline
import warnings
warnings.filterwarnings('ignore')
Explanation: Start here to begin with Stingray.
End of explanation
from stingray import Lightcurve
Explanation: Creating a light curve
End of explanation
times = np.arange(1000)
times[:10]
Explanation: A Lightcurve obje... |
8,345 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Benchmarks of different version of Cross Correlations
Author
Step1: Table of Values
In the below table, I compare four different methods for implementing cross correlation.
NoGpuSupport - ... | Python Code:
from __future__ import print_function
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
%matplotlib inline
Explanation: Benchmarks of different version of Cross Correlations
Author: Cody W. Eilar
In this notebook, I explore speed comparisons of several different methods of implementing... |
8,346 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
For high dpi displays.
Step1: 0. General note
This example compares pressure calculated from pytheos and original publication for the gold scale by Speiale 2001.
1. Global setup
Step2: 3. ... | Python Code:
%config InlineBackend.figure_format = 'retina'
Explanation: For high dpi displays.
End of explanation
import matplotlib.pyplot as plt
import numpy as np
from uncertainties import unumpy as unp
import pytheos as eos
Explanation: 0. General note
This example compares pressure calculated from pytheos and orig... |
8,347 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: Lesson 2
Step2: <img src = "funsyn.jpg">
Modules
A set of related functions can be grouped together as module
A module is nothing but a python file
The open source community continuo... | Python Code:
# FUNCTION DEFINITION
def check_if_5(user_number):
This function just checks if the number passed to it is equal
to 5. It returns 1 if the number is 5 and returns 0 if the number is not 5
if user_number == 5:
return 1
else:
return 0
#FUNCTION CALL
return_val = check_if_5(5)... |
8,348 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Get Notebook from github.com and other source.
by openthings@163.com, 2016-04.
通用的Notebook更新维护的工具。
原始URL列表保存在文本文件git_list.txt中。
git_list.txt转为git_list.md,在GitBook中使用。
git_list.txt转为git_lis... | Python Code:
from pprint import *
Explanation: Get Notebook from github.com and other source.
by openthings@163.com, 2016-04.
通用的Notebook更新维护的工具。
原始URL列表保存在文本文件git_list.txt中。
git_list.txt转为git_list.md,在GitBook中使用。
git_list.txt转为git_list.ipynb,在Jupyter中使用。
End of explanation
url_str = open("git_list.txt").read()
print... |
8,349 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
La Magia de la television
Capitulo 3
Step1: En la realidad, todos sabemos que los premios se eligen no en base a la realidad y los votos, sino en base a quien pone mas plata para comprarlos... | Python Code:
Image(filename='./clase-16-04_images/img1.jpg')
Explanation: La Magia de la television
Capitulo 3: Todo termina con un premio
Parte 1: Los premios son toda una mentira
End of explanation
PRIMER_NOMINADO = 0
SEGUNDO_NOMINADO = 1
TERCER_NOMINADO = 2
CUARTO_NOMINADO = 3
ANIME = 0
NOVELA_ARGENTINA = 1
NOVELA_K... |
8,350 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<font color='blue'>Data Science Academy - Python Fundamentos - Capítulo 7</font>
Download
Step1: Missão
Step2: Informações Sobre os Consumidores
Step3: Análise Geral de Compras
Step4: An... | Python Code:
# Versão da Linguagem Python
from platform import python_version
print('Versão da Linguagem Python Usada Neste Jupyter Notebook:', python_version())
Explanation: <font color='blue'>Data Science Academy - Python Fundamentos - Capítulo 7</font>
Download: http://github.com/dsacademybr
End of explanation
# Imp... |
8,351 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Defining inputs
Need to define some heterogenous factors of production...
Step1: Note that we are shifting the distributions of worker skill and firm productivity to the right by 1.0 in ord... | Python Code:
# define some workers skill
x, loc1, mu1, sigma1 = sym.var('x, loc1, mu1, sigma1')
skill_cdf = 0.5 + 0.5 * sym.erf((sym.log(x - loc1) - mu1) / sym.sqrt(2 * sigma1**2))
skill_params = {'loc1': 1e0, 'mu1': 0.0, 'sigma1': 1.0}
workers = pyam.Input(var=x,
cdf=skill_cdf,
... |
8,352 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
MECA653
Step1: 2 - Quelle est la poportion Homme/Femme impliquée dans les accidents ? Représenter le résultat sous forme graphique.
Step2: 2 - Quelle est la poportion des accidents ayant e... | Python Code:
dfc = pd.read_csv('./DATA/caracteristiques_2016.csv')
dfu = pd.read_csv('./DATA/usagers_2016.csv')
dfl = pd.read_csv('./DATA/lieux_2016.csv')
df = pd.concat([dfu, dfc, dfl], axis=1)
dfc.tail()
dfu.head()
dfl.tail()
df.head()
df = pd.concat([df, dfl], axis=1)
df.head()
Explanation: MECA653: Traitement de d... |
8,353 | Given the following text description, write Python code to implement the functionality described.
Description:
Given an array arr of integers, find the minimum number of elements that
need to be changed to make the array palindromic. A palindromic array is an array that
is read the same backwards and forwar... | Python Code:
def smallest_change(arr):
ans = 0
for i in range(len(arr) // 2):
if arr[i] != arr[len(arr) - i - 1]:
ans += 1
return ans |
8,354 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
字典中 to yield 表示产出和让步,对于 Python 生成器中的 yield 来说,这是成立的,yield item 这行代码会产生一个值,提供给 next(...) 调用方,此外,还会做出让步,暂停执行生成器,让调用方继续工作,直到需要使用另一个值再调用 next()。调用方会从生成器中拉取值
语法上来说,协程和生成器类似,都是定义体中包含 yield 关键字的函数,... | Python Code:
def simple_coroutine():
print('-> coroutine started')
# 如果协程只需要从客户那里接收数据,那么产出的值是 None
# 这个值是隐式指定的,因为 yield 关键字右面没有表达式
x = yield
print('-> croutine received:', x)
my_coro = simple_coroutine()
my_coro
# 先调用 next(...) 函数,因为生成器还没启动,没在 yield 语句暂停,所以无法发送数据
next(my_coro)
# 协程定义体中的 yield 表... |
8,355 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2019 The TensorFlow Authors.
Licensed under the Apache License, Version 2.0 (the "License");
Step1: Adversarial example using FGSM
<table class="tfo-notebook-buttons" align="left"... | 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... |
8,356 |
Given the following text problem statement, write Python code to implement the functionality described below in problem statement
Problem:
The function below named create_sequences(), given the tokenizer, a maximum sequence length, and the dictionary of all descriptions and photos, will transform the data into input-o... | Python Code::
# create sequences of images, input sequences and output words for an image
def create_sequences(tokenizer, max_length, descriptions, photos, vocab_size):
X1, X2, y = list(), list(), list()
# walk through each image identifier
for key, desc_list in descriptions.items():
# walk through each descriptio... |
8,357 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<a href="https
Step1: Data Generation
Data is generated from a 2D mixture of Gaussians.
Step2: Plotting
Step3: Models and Training
A multilayer perceptron with the ReLU activation functio... | Python Code:
!pip install -q flax
from typing import Sequence
import matplotlib.pyplot as plt
import jax
import jax.numpy as jnp
import flax.linen as nn
from flax.training import train_state
import optax
import functools
import scipy as sp
import math
rng = jax.random.PRNGKey(0)
Explanation: <a href="https://colab.rese... |
8,358 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Практическое задание к уроку 1 (2 неделя).
Линейная регрессия
Step1: Мы будем работать с датасетом "bikes_rent.csv", в котором по дням записаны календарная информация и погодные условия, ха... | Python Code:
import pandas as pd
import numpy as np
from matplotlib import pyplot as plt
%matplotlib inline
Explanation: Практическое задание к уроку 1 (2 неделя).
Линейная регрессия: переобучение и регуляризация
В этом задании мы на примерах увидим, как переобучаются линейные модели, разберем, почему так происходит, и... |
8,359 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Skip-gram word2vec
In this notebook, I'll lead you through using TensorFlow to implement the word2vec algorithm using the skip-gram architecture. By implementing this, you'll learn about emb... | Python Code:
import time
import numpy as np
import tensorflow as tf
import utils
Explanation: Skip-gram word2vec
In this notebook, I'll lead you through using TensorFlow to implement the word2vec algorithm using the skip-gram architecture. By implementing this, you'll learn about embedding words for use in natural lang... |
8,360 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: Probability theory
Motivation
In machine learning, as in life in general, we deal with uncertainty. This is probably why probability theory has overtaken logic as the leading system... | Python Code:
# Copyright (c) Thalesians Ltd, 2017-2019. All rights reserved
# Copyright (c) Paul Alexander Bilokon, 2017-2019. All rights reserved
# Author: Paul Alexander Bilokon <paul@thalesians.com>
# Version: 1.0 (2019.08.03)
# Email: education@thalesians.com
# Platform: Tested on Windows 10 with Python 3.6
Explana... |
8,361 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Import
Step1: Reading initial data
Step2: Remove rows with NAN from data
Step3: Add diff_pt and cos(diff_phi)
Step4: Add max, sum among PIDs
Step5: define label = signB * signTrack
if >... | Python Code:
import pandas
import numpy
from folding_group import FoldingGroupClassifier
from rep.data import LabeledDataStorage
from rep.report import ClassificationReport
from rep.report.metrics import RocAuc
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import roc_curve, roc_auc_score
from... |
8,362 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
WPS call for analogs detection and visualisation
Step1: There are different ways to call a WPS service. The following cells are examples of the same process execution with different executi... | Python Code:
##############################
# load the required libraries
#############################
from owslib.wps import WebProcessingService, monitorExecution, printInputOutput
from os import system
import time
#################################################
# connect to the compute provider hosting the WPS
#... |
8,363 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Adding new passbands to PHOEBE
In this tutorial we will show you how to add your own passband to PHOEBE. Adding a custom passband involves
Step1: If you plan on computing model atmosphere i... | Python Code:
#!pip install -I "phoebe>=2.3,<2.4"
Explanation: Adding new passbands to PHOEBE
In this tutorial we will show you how to add your own passband to PHOEBE. Adding a custom passband involves:
downloading and setting up model atmosphere tables;
providing a passband transmission function;
defining and registeri... |
8,364 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
ES-DOC CMIP6 Model Properties - Seaice
MIP Era
Step1: Document Authors
Set document authors
Step2: Document Contributors
Specify document contributors
Step3: Document Publication
Specify ... | Python Code:
# DO NOT EDIT !
from pyesdoc.ipython.model_topic import NotebookOutput
# DO NOT EDIT !
DOC = NotebookOutput('cmip6', 'messy-consortium', 'emac-2-53-aerchem', 'seaice')
Explanation: ES-DOC CMIP6 Model Properties - Seaice
MIP Era: CMIP6
Institute: MESSY-CONSORTIUM
Source ID: EMAC-2-53-AERCHEM
Topic: Se... |
8,365 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Hyperparameters and Model Validation
Previously, we saw the basic recipe for applying a supervised machine learning model
Step1: Next we choose a model and hyperparameters
Step2: Then we t... | Python Code:
from sklearn.datasets import load_iris
iris = load_iris()
X = iris.data
y = iris.target
Explanation: Hyperparameters and Model Validation
Previously, we saw the basic recipe for applying a supervised machine learning model:
Choose a class of model
Choose model hyperparameters
Fit the model to the training ... |
8,366 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Visualising Clustering with Voronoi Tesselations
When experimenting with using the Voronoi Tesselation to identify which machines are picked up by certain points, it was easy to extend the i... | Python Code:
%matplotlib inline
import numpy as np
from pycobra.cobra import Cobra
from pycobra.visualisation import Visualisation
from pycobra.diagnostics import Diagnostics
import matplotlib.pyplot as plt
from sklearn import cluster
Explanation: Visualising Clustering with Voronoi Tesselations
When experimenting with... |
8,367 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Late night 1 hour hack of the freshly released dataset on train time tables by IRCTC.
Source
Step1: Distribution of Arrival and Departure Times
Lets analyze the arrival and departure time d... | Python Code:
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
# Load the data into a dataframe
df = pd.read_csv("data/isl_wise_train_detail_03082015_v1.csv")
sns.set_context("poster")
# Show some rows
df.head()
df.columns
# Convert time columns to datetime ... |
8,368 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Notes for Machine Learning for Trading
Udacity - ud501
Part 1
Step1: You can download the csv files with the stock data in it from Yahoo Finance (Historical Data)
using your browser, the pa... | Python Code:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from util import get_data, plot_data, fill_missing_values
%matplotlib inline
Explanation: Notes for Machine Learning for Trading
Udacity - ud501
Part 1
End of explanation
dates = pd.date_range('2014-01-01', '2014-12-31')
symbols = ['V']... |
8,369 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<a href="http
Step1: First we will make a default NormalFault.
Step2: This fault has a strike of NE and dips to the SE. Thus the uplifted nodes (shown in yellow) are in the NW half of the ... | Python Code:
# start by importing necessary modules
import matplotlib.pyplot as plt
import numpy as np
from landlab import HexModelGrid, RasterModelGrid
from landlab.components import (
FastscapeEroder,
FlowAccumulator,
NormalFault,
StreamPowerEroder,
)
from landlab.plot import imshow_grid
%matplotlib i... |
8,370 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Gensim Tutorial on Online Non-Negative Matrix Factorization
This notebooks explains basic ideas behind the open source NMF implementation in Gensim, including code examples for applying NMF ... | Python Code:
import logging
import time
from contextlib import contextmanager
import os
from multiprocessing import Process
import psutil
import numpy as np
import pandas as pd
from numpy.random import RandomState
from sklearn import decomposition
from sklearn.cluster import MiniBatchKMeans
from sklearn.datasets import... |
8,371 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Cu-Mg workflows
Goal
Step1: Get your structures
Three ways main ways you'll use to get structures
1. From the Materials Project via the MPRester API
Step2: 2. From a POSCAR file
Step3: 3.... | Python Code:
from fireworks import LaunchPad
# lpad = LaunchPad.auto_load()
lpad = LaunchPad.from_file('/Users/brandon/.fireworks/my_launchpad.yaml')
Explanation: Cu-Mg workflows
Goal: fully describe the Cu-Mg system with DFT calculations
Phases
There are 5 phases in Cu-Mg that will be described with the following mode... |
8,372 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Summary of Data (Part 2)
This post suggests the revised functionalites offered by the summary function described previously in the Summary of Data. The functions are mainly available at the ... | Python Code:
# Import functions and load data into a dataframe
import sys
sys.path.append("../")
import pandas as pd
from script.preprocess import summary, warn_missing
kwargs = {"parse_dates": ["utc_time"]}
bj_aq_df = pd.read_csv("beijing_201802_201803_aq.csv", **kwargs)
warn_missing(bj_aq_df, "beijing_201802_201803_a... |
8,373 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Cerebral Cortex Data Analysis Algorithms
Cerebral Cortex contains a library of algorithms that are useful for processing data and converting it into features or biomarkers. This page demons... | Python Code:
%reload_ext autoreload
from util.dependencies import *
CC = Kernel("/home/jovyan/cc_conf/", study_name="default")
Explanation: Cerebral Cortex Data Analysis Algorithms
Cerebral Cortex contains a library of algorithms that are useful for processing data and converting it into features or biomarkers. This p... |
8,374 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Modeling Competitive Binding
We will model binding of two ligands, one is fluorescent (L), the other competing ligand (A) is not. Kd of both of their binding to protein (P) are known.
Compl... | Python Code:
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
from IPython.display import display, Math, Latex #Do we even need this anymore?
%pylab inline
Explanation: Modeling Competitive Binding
We will model binding of two ligands, one is fluorescent (L), the other competing ligand (A) is no... |
8,375 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
This notebook explores the PHAT v2 artificial star test (AST) results, and how to use them in m31hst.
Step1: Assuming that the Williams et al 2014 Table 6 file was downloaded to the correct... | Python Code:
%matplotlib inline
import numpy as np
from sklearn.cluster import KMeans
from astroML.stats import binned_statistic
import matplotlib.pyplot as plt
Explanation: This notebook explores the PHAT v2 artificial star test (AST) results, and how to use them in m31hst.
End of explanation
from m31hst.phatast impor... |
8,376 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Initial_t_rad Bug
The purpose of this notebook is to demonstrate the bug associated with setting the initial_t_rad tardis.plasma property.
Step1: Density and Abundance test files
Below are ... | Python Code:
pwd
import tardis
import numpy as np
Explanation: Initial_t_rad Bug
The purpose of this notebook is to demonstrate the bug associated with setting the initial_t_rad tardis.plasma property.
End of explanation
density_dat = np.loadtxt('data/density.txt',skiprows=1)
abund_dat = np.loadtxt('data/abund.dat', sk... |
8,377 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
A socket is one endpoint of a communication channel used by programs to pass data back and forth locally or across the Internet. Sockets have two primary properties controlling the way they ... | Python Code:
import socket
print(socket.gethostname())
Explanation: A socket is one endpoint of a communication channel used by programs to pass data back and forth locally or across the Internet. Sockets have two primary properties controlling the way they send data: the address family controls the OSI network ... |
8,378 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Python 2.7 compatibility
To achieve Python 2.7 compatibility we will import the "_winreg" module
from six.moves, since it has been renamed to winreg in Python 3.
Step1: The relevant keys in... | Python Code:
import re, six
from six.moves import winreg
Explanation: Python 2.7 compatibility
To achieve Python 2.7 compatibility we will import the "_winreg" module
from six.moves, since it has been renamed to winreg in Python 3.
End of explanation
if six.PY2:
FileNotFoundError = WindowsError
Explanation: The rel... |
8,379 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Links zu Dokumentationen/Tutorials für IPython/Python/numpy/matplotlib/git sowie die Sourcodes findet ihr im GitHub Repo.
Step1: Modellierung mit Newtonschem Gesetz
Step2: $H(q(t), p(t))$ ... | Python Code:
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
Explanation: Links zu Dokumentationen/Tutorials für IPython/Python/numpy/matplotlib/git sowie die Sourcodes findet ihr im GitHub Repo.
End of explanation
values = np.loadtxt('values')
alpha = values[:,0]
alpha_dot = values[:,1]
plt.plot(... |
8,380 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Fitzhugh-Nagumo simplified action-potential model
This example shows how the Fitzhugh-Nagumo simplified action potential (AP) model can be used.
The model is based on a simplification and st... | Python Code:
import matplotlib.pyplot as plt
import numpy as np
import pints
import pints.toy
# Create a model
model = pints.toy.FitzhughNagumoModel()
# Run a simulation
parameters = [0.1, 0.5, 3]
times = np.linspace(0, 20, 200)
values = model.simulate(parameters, times)
# Plot the results
plt.figure()
plt.xlabel('Time... |
8,381 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
PraatIO - doing speech analysis with Python
An introduction and tutorial
<hr>
TABLE OF CONTENTS
An introduction
- <a href="#what_is_praat">What is Praat?</a>
- <a href="#textgrids_and_tiers"... | Python Code:
!pip install praatio --upgrade
Explanation: PraatIO - doing speech analysis with Python
An introduction and tutorial
<hr>
TABLE OF CONTENTS
An introduction
- <a href="#what_is_praat">What is Praat?</a>
- <a href="#textgrids_and_tiers">TextGrids, IntervalTiers, and PointTiers</a>
- <a href="#physical_textgr... |
8,382 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
My notebook to practics Pandas
This is some notes
Step1: Working with series
loc uses the specified index and it is inclusive
iloc uses the python index and is exclusive
Step2: Working wit... | Python Code:
import pandas as pd
Explanation: My notebook to practics Pandas
This is some notes
End of explanation
## difference between loc and iloc
vals = [0, 1, 2]
idx = [10, 11, 12]
ser = pd.Series(vals, index=idx)
print("...using loc")
print(ser.loc[10:11])
print("\n...using iloc")
print(ser.iloc[0:2])
## creating... |
8,383 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Algo - TSP - Traveling Salesman Problem
TSP, Traveling Salesman Problem ou Problème du Voyageur de Commerce est un problème classique. Il s'agit de trouver le plus court chemin passant par d... | Python Code:
from jyquickhelper import add_notebook_menu
add_notebook_menu()
%matplotlib inline
Explanation: Algo - TSP - Traveling Salesman Problem
TSP, Traveling Salesman Problem ou Problème du Voyageur de Commerce est un problème classique. Il s'agit de trouver le plus court chemin passant par des villes en supposan... |
8,384 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
熟悉Pandas Sklearn
CSV to DataFrame
Step1: 可视化数据对于识别模型中潜在的模式十分重要
Step2: 特征转换
除了'sex'特征之外,'age'是其次重要的特征,如果按照数据集中age的原始值来搞显然太离散了容易降低泛化能力导致过拟合,所以需要处理age将people划分到不同的年龄段组成的组中
Cabin特征每行记录都是以一个字母开... | Python Code:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
%matplotlib inline
data_train = pd.read_csv('./input/titanic/train.csv')
data_test = pd.read_csv('./input/titanic/test.csv')
data_train.sample(20)
Explanation: 熟悉Pandas Sklearn
CSV to DataFrame
End of explanation
s... |
8,385 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Tah hráče
Je tam opravdu vše potřeba?
Step1: Není
Step2: Vyhodnocení piškvorek
Co by se tady dalo udělat jednodušeji?
Step3: Upravená varianta
Step4: Piškvorky
Step5: Chyby v programu a... | Python Code:
def tah_hrace (pole):
'Vrátí herní pole se zaznamenaným tahem hráče'
t = 0
while t == 0:
pozice = int(input('Na které políčko chceš hrát? '))
if (pozice > 0) and (pozice<=20) and (pole[pozice-1] == '-'):
return tah(pole,pozice,'x')
t = 1
else:
... |
8,386 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Description
Step1: Init
Step2: Determining the probability of detecting the taxa across the entire gradient
Step3: skewed normal distribution
Step4: small uniform distribution
Step5: No... | Python Code:
workDir = '/home/nick/notebook/SIPSim/dev/bac_genome3/validation/'
R_dir = '/home/nick/notebook/SIPSim/lib/R/'
figDir = '/home/nick/notebook/SIPSim/figures/'
nprocs = 3
Explanation: Description:
For emperical data, most taxa (>0.1% abundance) are detected across the entire gradient.
Checking whether a simi... |
8,387 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Porting Bike-Sharing project-1 to RNN
Step1: Load and prepare the data
A critical step in working with neural networks is preparing the data correctly. Variables on different scales make it... | Python Code:
%matplotlib inline
%config InlineBackend.figure_format = 'retina'
import sys
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
Explanation: Porting Bike-Sharing project-1 to RNN
End of explanation
data_path = 'Bike-Sharing-Dataset/hour.csv'
rides = pd.read_csv(data_path)
rides.head()
E... |
8,388 | 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', 'bnu', 'sandbox-1', 'atmos')
Explanation: ES-DOC CMIP6 Model Properties - Atmos
MIP Era: CMIP6
Institute: BNU
Source ID: SANDBOX-1
Topic: Atmos
Sub-Topics: Dynamical Core, Radiation, T... |
8,389 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
make the train_pivot, duplicate exist when index = ['Cliente','Producto']
for each cliente & producto, first find its most common Agencia_ID, Canal_ID, Ruta_SAK
Step1: make pivot table of t... | Python Code:
agencia_for_cliente_producto = train_dataset[['Cliente_ID','Producto_ID'
,'Agencia_ID']].groupby(['Cliente_ID',
'Producto_ID']).agg(lambda x:x.value_counts().index[0]).reset_index()
canal_f... |
8,390 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Import modules
Step1: Enter your details for twitter API
Step2: Set up details for PostGIS DB, run in terminal
Step3: Function which connects to PostGis database and inserts data
Step4: ... | Python Code:
from twython import TwythonStreamer
import string, json, pprint
import urllib
from datetime import datetime
from datetime import date
from time import *
import string, os, sys, subprocess, time
import psycopg2
import re
from osgeo import ogr
Explanation: Import modules
End of explanation
# get access to th... |
8,391 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
06 - For JLab Submission
I was invited to send over my trained model for evaluation!
The model needs changing to be compliant with the rules
Submitted models will be
loaded as-is from a sing... | Python Code:
%matplotlib inline
Explanation: 06 - For JLab Submission
I was invited to send over my trained model for evaluation!
The model needs changing to be compliant with the rules
Submitted models will be
loaded as-is from a single submitted HDF5 compatible with keras.models.load model(). The loaded model
will th... |
8,392 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Self-Driving Car Engineer Nanodegree
Deep Learning
Project
Step1: Step 1
Step2: 3. Include an exploratory visualization of the dataset
Visualize the German Traffic Signs Dataset using the ... | Python Code:
# Load pickled data
import pickle
# TODO: Fill this in based on where you saved the training and testing data
training_file = './traffic-signs-data/train.p'
validation_file = './traffic-signs-data/valid.p'
testing_file = './traffic-signs-data/test.p'
with open(training_file, mode='rb') as f:
train... |
8,393 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Probability tables and the categorical distribution
The following cell illustrates drawing from a categorical distribution with on an alphabet, not necessarly $0\dots K-1$.
Step1: Often we ... | Python Code:
import numpy as np
# Sampling from a Categorical Distribution
a = np.array(sorted(['blue', 'red', 'black', 'yellow']))
pr = np.array([0.2, 0.55, 0.15, 0.1])
N = 100
x = np.random.choice(a, size=N, replace=True, p=pr)
print('Symbols:')
print(a)
print('Probabilities:')
print(pr)
print('{N} realizations:'.for... |
8,394 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
DataFrame
Step1: This is to get a tree from test data called cernstaff.root
Step2: Here we create the DataFrame object
Step3: As you can see, it also creates a PyTreeReader. This is why P... | Python Code:
import ROOT
from PyTreeReader import PyTreeReader
from functional import DataFrame
from ROOT import TFile
Explanation: DataFrame: Functional Chains for TTrees in Python.
<hr style="border-top-width: 4px; border-top-color: #359C38;">
The DataFrame class brings the feature called functional chains with cachi... |
8,395 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Meta Analysis of the Datasets for the Epi² pilot project
RNA PTM DATASETS
PYTHON 3 Notebook
Adrien Leger / EMBL EBI
Starting date 23/05/2016
Import general package and definition of specific... | Python Code:
# pycl imports
from pycl import *
#Std lib imports
import datetime
from glob import glob
from pprint import pprint as pp
from os.path import basename
from os import listdir, remove, rename
from os.path import abspath, basename, isdir
from collections import OrderedDict
# Third party import
import numpy as ... |
8,396 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2018 The TensorFlow Authors.
Step1: 基本分类:对服装图像进行分类
<table class="tfo-notebook-buttons" align="left">
<td><a target="_blank" href="https
Step2: 导入 Fashion MNIST 数据集
本指南使用 Fashio... | 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... |
8,397 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Lab 1
Step1: Let's take a cursory glance at the data to see what we're working with.
Step2: There's a lot of data that we don't care about. For example, 'PassAttempt' is a binary attribute... | Python Code:
import pandas as pd
import numpy as np
df = pd.read_csv('data/data.csv') # read in the csv file
Explanation: Lab 1: Exploring NFL Play-By-Play Data
Data Loading and Preprocessing
To begin, we load the data into a Pandas data frame from a csv file.
End of explanation
df.head()
Explanation: Let's take a curs... |
8,398 | 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 2001 and is updated monthly.
Blaze provides us with the first 10 rows of the data for display. Just to confirm, let's just count the number o... | Python Code:
# import the dataset
from quantopian.interactive.data.quandl import adp_empl_sec
# 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... |
8,399 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Bayesian inference tutorial
Step1: Deciding a model
The first thing once we've got some data is decide which is the model that generated the data. In this case we decide that the height of ... | Python Code:
x = [183, 168, 177, 170, 175, 177, 178, 166, 174, 178]
Explanation: Bayesian inference tutorial: a hello world example
The goal is to find a statistical model with its parameters that explains the data.
So, let's assume we've got some data, regarding the height of Python developers.
This is our data:
End o... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.