Unnamed: 0 int64 0 16k | text_prompt stringlengths 110 62.1k | code_prompt stringlengths 37 152k |
|---|---|---|
1,800 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
JUPYTER NOTEBOOK
http
Step1: Observações
Step2: Plotando o resultado dos mínimos quadrados para polinômios de graus 0 a 9. Qual é um bom modelo? | Python Code:
%matplotlib inline
import numpy as np
import matplotlib.pylab as plt
from ipywidgets import *
#Variância do ruído
var = 0.3
#Conjunto de treino
train_size = 10
x_train = np.linspace(0,1,train_size)
y_train = np.sin(2*np.pi*x_train) + np.random.normal(0,var,train_size) #sinal + ruido
#Conjunto de teste
test... |
1,801 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<figure>
<IMG SRC="../logo/logo.png" WIDTH=250 ALIGN="right">
</figure>
Strip of land with same rise at both sides
@Theo Olsthoorn
2019-12-21
This exercise was done in class on 2019-01-10
... | Python Code:
# import modules we need
import matplotlib.pyplot as plt
import numpy as np
from scipy.special import erfc
Explanation: <figure>
<IMG SRC="../logo/logo.png" WIDTH=250 ALIGN="right">
</figure>
Strip of land with same rise at both sides
@Theo Olsthoorn
2019-12-21
This exercise was done in class on 2019-01-... |
1,802 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Certamen 2A, TI 2, 2017-1
Leo Ferres & Rodrigo Trigo
UDD
Pregunta 1
Cree la función fechaValida(fecha) que devuelva True si el argumento es una fecha real, o False si no. Ejemplo, "32 de ene... | Python Code:
##escriba la función aqui##
fechaValida('02/06/2017')
Explanation: Certamen 2A, TI 2, 2017-1
Leo Ferres & Rodrigo Trigo
UDD
Pregunta 1
Cree la función fechaValida(fecha) que devuelva True si el argumento es una fecha real, o False si no. Ejemplo, "32 de enero" no es válida (no considere bisiestos). La fech... |
1,803 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Introduction
This is a live IPython notebook. You can write and test code, annotate it with text (including equations $\hat x = \frac{1}{n}\sum_{i=0}^n x_i$), plot graphs and start external ... | Python Code:
# note that this is a code cell -- you can execute it with Shift-ENTER
%matplotlib inline
Explanation: Introduction
This is a live IPython notebook. You can write and test code, annotate it with text (including equations $\hat x = \frac{1}{n}\sum_{i=0}^n x_i$), plot graphs and start external processes. Yo... |
1,804 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Cookbook
Step1: Create a raxml Class object
Create a raxml object which has a bunch of default parameters associated with it. The only required argument to initialize the object is a phylip... | Python Code:
## conda install ipyrad -c ipyrad
## conda install toytree -c eaton-lab
## conda install raxml -c bioconda
Explanation: Cookbook: RAxML analyses in a notebook
As part of the ipyrad.analysis toolkit we've created convenience functions for easily running common RAxML commands. This can be useful when you wan... |
1,805 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<table align="left">
<td>
<a href="https
Step1: Restart the kernel
After you install the additional packages, you need to restart the notebook kernel so it can find the packages.
Step... | Python Code:
import os
# The Google Cloud Notebook product has specific requirements
IS_GOOGLE_CLOUD_NOTEBOOK = os.path.exists("/opt/deeplearning/metadata/env_version")
# Google Cloud Notebook requires dependencies to be installed with '--user'
USER_FLAG = ""
if IS_GOOGLE_CLOUD_NOTEBOOK:
USER_FLAG = "--user"
! pip3... |
1,806 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Implementing a Stack Class
First, we define an empty class Stack.
Step1: Next we define a constructor for this class. The function stack(S) takes an uninitialized, empty object S
and init... | Python Code:
class Stack:
pass
S = Stack()
S
Explanation: Implementing a Stack Class
First, we define an empty class Stack.
End of explanation
def stack(S):
S.mStackElements = []
Explanation: Next we define a constructor for this class. The function stack(S) takes an uninitialized, empty object S
and initiali... |
1,807 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Gaia DR2 variability lightcurves
Part III
Step1: Ok, this flat file is just what we want. It contains the flux as a function of time for unique sources, with additional metadata flags.
Ste... | Python Code:
# %load /Users/obsidian/Desktop/defaults.py
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
%config InlineBackend.figure_format = 'retina'
! du -hs ../data/dr2/Gaia/gdr2/light_curves/csv/
df0 = pd.read_csv('../data/dr2/Gaia/gdr2/light_curves/csv/light_curves_104250... |
1,808 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
MNIST handwritten digits recognition
Written by Yujun Lin
Preparation
Follow the instructions on notebook for training a binary single-layer perception and saving weights and images to local... | Python Code:
image_id = 9
filename = 'nn_train/BNN.pkl'
Explanation: MNIST handwritten digits recognition
Written by Yujun Lin
Preparation
Follow the instructions on notebook for training a binary single-layer perception and saving weights and images to local file.
change image_id for other pictures. There are 10 pictu... |
1,809 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Next
I want to write code -- or, find an existing module! -- that reloads
Step1: Add D3 Visualization showing MCMC over two different methods
Add PS (I'm looking for a job in NYC)
WHEREAMI?... | Python Code:
%%html
<div align="center"><blockquote class="twitter-tweet" lang="en"><p lang="en" dir="ltr">When I’m trying to fix a tiny bug. <a href="https://t.co/nml6ZS5quW">pic.twitter.com/nml6ZS5quW</a></p>— Mike Bostock (@mbostock) <a href="https://twitter.com/mbostock/status/661650359069208576">November 3,... |
1,810 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Lecture 3
I/O and exceptions
About Files
RAM and volatility.
Files and non-volatility
Writing a file
file handle
mode
Step1: Reading a whole file at once
Step2: A better way to read files
... | Python Code:
myfile = open("test.txt", "w")
myfile.write("My first file written from Python\n")
myfile.write("---------------------------------\n")
myfile.write("Hello, world!\n")
myfile.write("Did it work?\n")
myfile.close()
Explanation: Lecture 3
I/O and exceptions
About Files
RAM and volatility.
Files and non-volati... |
1,811 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Orbital Elements
We can add particles to a simulation by specifying cartesian components
Step1: Any components not passed automatically default to 0. REBOUND can also accept orbital elemen... | Python Code:
import rebound
sim = rebound.Simulation()
sim.add(m=1., x=1., vz = 2.)
Explanation: Orbital Elements
We can add particles to a simulation by specifying cartesian components:
End of explanation
sim.add(m=1., a=1.)
sim.status()
Explanation: Any components not passed automatically default to 0. REBOUND can a... |
1,812 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Variational Autoencoder
Step5: Task
Step6: Visualize reconstruction quality
Step7: Illustrating latent space
Next, we train a VAE with 2d latent space and illustrates how the encoder (the... | Python Code:
import numpy as np
import tensorflow as tf
import tensorflow.contrib.slim as slim
from tensorflow.contrib.learn.python.learn.datasets.mnist import read_data_sets
import matplotlib.pyplot as plt
%matplotlib inline
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets('... |
1,813 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<h1> Preprocessing using Dataflow </h1>
This notebook illustrates
Step1: Run the command again if you are getting oauth2client error.
Note
Step2: You may receive a UserWarning about the Ap... | Python Code:
pip install --user apache-beam[gcp]
Explanation: <h1> Preprocessing using Dataflow </h1>
This notebook illustrates:
<ol>
<li> Creating datasets for Machine Learning using Dataflow
</ol>
<p>
While Pandas is fine for experimenting, for operationalization of your workflow, it is better to do preprocessing in ... |
1,814 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Working with time series data
Some imports
Step1: Case study
Step2: I downloaded and preprocessed some of the data (python-airbase)
Step3: As you can see, the missing values are indicated... | Python Code:
%matplotlib inline
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
try:
import seaborn
except:
pass
pd.options.display.max_rows = 8
Explanation: Working with time series data
Some imports:
End of explanation
from IPython.display import HTML
HTML('<iframe src=http://www.eea.eu... |
1,815 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<a name="pagetop"></a>
<div style="width
Step1: <a name="plotting"></a>
Plotting the Data
To plot our data we'll be using MetPy's new declarative plotting functionality. You can write lots ... | Python Code:
from siphon.catalog import TDSCatalog
from datetime import datetime
# Create variables for URL generation
image_date = datetime.utcnow().date()
region = 'Mesoscale-1'
channel = 8
# Create the URL to provide to siphon
data_url = ('https://thredds.ucar.edu/thredds/catalog/satellite/goes/east/products/'
... |
1,816 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
xarray Python library is great for analysing multi-dimensional arrays of data with labelled dimensions, which is a common situation in geosciences.
According to the docs, xarray has two core... | Python Code:
import numpy as np
import xarray as xr
import warnings
warnings.filterwarnings('ignore')
import matplotlib.pyplot as plt
%matplotlib inline
Explanation: xarray Python library is great for analysing multi-dimensional arrays of data with labelled dimensions, which is a common situation in geosciences.
Accord... |
1,817 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Artifact Correction with ICA
ICA finds directions in the feature space
corresponding to projections with high non-Gaussianity. We thus obtain
a decomposition into independent components, and... | Python Code:
import numpy as np
import mne
from mne.datasets import sample
from mne.preprocessing import ICA
from mne.preprocessing import create_eog_epochs, create_ecg_epochs
# getting some data ready
data_path = sample.data_path()
raw_fname = data_path + '/MEG/sample/sample_audvis_filt-0-40_raw.fif'
raw = mne.io.read... |
1,818 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<a id="Top"></a>
___ ___ ___
_____ /\__\ /\ \ ... | Python Code:
# Standard library
import datetime
import time
# Third party libraries
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
# Digitre code
import digitre_preprocessing as prep
import digitre_model
import digitre_classifier
# Reload digitre code in the same session (during development)
impo... |
1,819 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Requisitions and Documents
This example shows the Ovation Service Lab (OSL) APIs for sample accessioning and report download. We'll create a simple Requisition with one sample. Next, we'll u... | Python Code:
import uuid
from pprint import pprint
from datetime import date
from ovation.session import connect
Explanation: Requisitions and Documents
This example shows the Ovation Service Lab (OSL) APIs for sample accessioning and report download. We'll create a simple Requisition with one sample. Next, we'll uploa... |
1,820 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2020 Google LLC.
Licensed under the Apache License, Version 2.0 (the "License")
Step1: Human evaluation of visual metrics
This colab explores correlations between the mucped22 dat... | Python Code:
# Copyright 2022 The Google Research Authors.
#
# 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 la... |
1,821 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step2: P1. Encode and Decode Strings
Design an algorithm to encode a list of strings to a string. The encoded string is then sent over the network and is decoded back to the original list of... | Python Code:
# NOTE: We assume <EOS> is a special token that shows that the string has ended
# and the next string has started.
class Codec:
def encode(self, strs):
Encodes a list of strings to a single string.
:type strs: List[str]
:rtype: str
if strs == []:
... |
1,822 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Esistono molti modi diversi di approcciarsi alla risoluzione di un problema. In base alla propria astuzia, alle proprie conoscenze algoritmiche, matematiche, statistiche, al proprio buonsens... | Python Code:
import random
import string
def random_char():
return random.choice(string.ascii_lowercase + ' ')
def genera_frase():
return [random_char() for n in range(0,len(amleto))]
amleto = list('parmi somigli ad una donnola')
print("target= '"+''.join(amleto)+"'")
frase = genera_frase()
print(str(frase)+" =... |
1,823 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
The Evoked data structure
Step1: Creating Evoked objects from Epochs
Step2: Basic visualization of Evoked objects
We can visualize the average evoked response for left-auditory stimuli usi... | Python Code:
import os
import mne
Explanation: The Evoked data structure: evoked/averaged data
This tutorial covers the basics of creating and working with :term:evoked
data. It introduces the :class:~mne.Evoked data structure in detail,
including how to load, query, subselect, export, and plot data from an
:class:~mne... |
1,824 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
🔪 JAX - The Sharp Bits 🔪
levskaya@ mattjj@
When walking about the countryside of Italy, the people will not hesitate to tell you that JAX has "una anima di pura programmazione funzionale".... | Python Code:
import numpy as np
from jax import grad, jit
from jax import lax
from jax import random
import jax
import jax.numpy as jnp
import matplotlib as mpl
from matplotlib import pyplot as plt
from matplotlib import rcParams
rcParams['image.interpolation'] = 'nearest'
rcParams['image.cmap'] = 'viridis'
rcParams['a... |
1,825 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Example Usage of HDFWriter
If properties of a class needs to be saved in a hdf file, then the class should inherit from HDFWriterMixin as demonstrated below.
hdf_properties (list)
Step1: Y... | Python Code:
from tardis.io.util import HDFWriterMixin
class ExampleClass(HDFWriterMixin):
hdf_properties = ['property1', 'property2']
hdf_name = 'mock_setup'
def __init__(self, property1, property2):
self.property1 = property1
self.property2 = property2
import numpy as np
import pa... |
1,826 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2020 The TensorFlow Authors.
Step1: Tokenize and sequence a bigger corpus of text
<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... |
1,827 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Лабораторная 2-1
Step1: Напишите запрос
Step2: Напишите запрос, возвращающий уникальные названия компаний, которые делают продукцию Gizmo
Step3: Задание #2 | Python Code:
%sql select * from product;
Explanation: Лабораторная 2-1:
Простые табличные запросы
Задание #1
Попробуйте записать запрос, чтобы получить на выходе все продукты, с "Touch" в имени. Укажите их имя и цену и отсортируйте в алфавитном порядке по производителю
End of explanation
%%sql
PRAGMA case_sensitive_lik... |
1,828 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
mpl_toolkits
In addition to the core library of Matplotlib, there are a few additional utilities that are set apart from Matplotlib proper for some reason or another, but are often shipped w... | Python Code:
from mpl_toolkits.mplot3d import Axes3D, axes3d
fig, ax = plt.subplots(1, 1, subplot_kw={'projection': '3d'})
X, Y, Z = axes3d.get_test_data(0.05)
ax.plot_wireframe(X, Y, Z, rstride=10, cstride=10)
plt.show()
Explanation: mpl_toolkits
In addition to the core library of Matplotlib, there are a few additiona... |
1,829 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Decision trees and Random forest
Step1: Data preprocessing
Step2: Regression tree
Step3: Randomly defined train and test set
Step4: Know, we want to define the max_depht parameter that m... | Python Code:
import pandas as pd
import numpy as np
import graphviz
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeRegressor
from sklearn.metrics import mean_squared_error as mse
from sklearn.model_selection import cross_val_score
from sklearn.model_selection import GridSearc... |
1,830 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<a href="http
Step1: 3 topographic grids
For this tutorial we will consider three different topographic surfaces that highlight the difference between each of the flow direction algorithms.... | Python Code:
%matplotlib inline
# import plotting tools
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
from matplotlib import cm
from matplotlib.ticker import LinearLocator, FormatStrFormatter
import matplotlib as mpl
# import numpy
import numpy as np
# import necessary landlab components
from ... |
1,831 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<h1>Hit Processor</h1>
<hr style="border
Step1: <span>
Let's parse
</span>
Step2: <span>
Parse a Hit with Plain Processor
</span>
Step3: <span>
Compute diffs
Step4: <span>
Parse a Hit wi... | Python Code:
import sys
#sys.path.insert(0, '/home/asanso/workspace/att-spyder/att/src/python/')
sys.path.insert(0, 'i:/dev/workspaces/python/att-workspace/att/src/python/')
Explanation: <h1>Hit Processor</h1>
<hr style="border: 1px solid #000;">
<span>
<h2>ATT raw Hit processor.</h2>
</span>
<br>
<span>
This notebook ... |
1,832 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Brief look at Cartopy
Cartopy is a Python package that provides easy creation of maps with matplotlib.
Cartopy vs Basemap
Cartopy is better integrated with matplotlib and in a more active de... | Python Code:
import matplotlib.pyplot as plt
%matplotlib inline
Explanation: Brief look at Cartopy
Cartopy is a Python package that provides easy creation of maps with matplotlib.
Cartopy vs Basemap
Cartopy is better integrated with matplotlib and in a more active development state
Proper handling of datelines in carto... |
1,833 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Visualizing the 2016 General Election Polls
Step1: Hover on the map to visualize the poll data for that state.
Step2: Visualizing the County Results of the 2008 Elections
Step3: Hover on ... | Python Code:
import pandas as pd
import numpy as np
from __future__ import print_function
from ipywidgets import VBox, HBox
import os
codes = pd.read_csv(os.path.abspath('../data_files/state_codes.csv'))
try:
from pollster import Pollster
except ImportError:
print('Pollster not found. Installing Pollster..')
... |
1,834 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Jim's MetaD convergence script, also shows fast file readin using streaming vs slow file readin vs. np.getfromtext
Step1: Graph the final FES and plot the two squares on top of it
Step2: T... | Python Code:
import numpy as np
import matplotlib.pyplot as plt
import glob
import os
from matplotlib.patches import Rectangle
# define all variables for convergence script
# these will pass to the bash magic below used to call plumed sum_hills
dir="MetaD_converge" #where the intermediate fes will be stored
hills="Met... |
1,835 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
ES-DOC CMIP6 Model Properties - Ocnbgchem
MIP Era
Step1: Document Authors
Set document authors
Step2: Document Contributors
Specify document contributors
Step3: Document Publication
Speci... | Python Code:
# DO NOT EDIT !
from pyesdoc.ipython.model_topic import NotebookOutput
# DO NOT EDIT !
DOC = NotebookOutput('cmip6', 'csir-csiro', 'vresm-1-0', 'ocnbgchem')
Explanation: ES-DOC CMIP6 Model Properties - Ocnbgchem
MIP Era: CMIP6
Institute: CSIR-CSIRO
Source ID: VRESM-1-0
Topic: Ocnbgchem
Sub-Topics: Tr... |
1,836 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Preprocessing
Step1: Hide all GPUs from TensorFlow to not automatically occupy any GPU RAM.
Step2: Config
Automatically discover the paths to various data folders and compose the project s... | Python Code:
from pygoose import *
from gensim.models.wrappers.fasttext import FastText
Explanation: Preprocessing: FastText Sequences & Embeddings
Based on the tokenized questions and a pre-built word embedding database, build fixed-length (padded) sequences of word indices for each question, as well as a lookup matri... |
1,837 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Predicting Yelp Star Ratings
In this little exercise, I am going to have a look at the distribution of Yelp ratings (1 to 5 stars) and their correlations to business and user attributes. Eve... | Python Code:
import os, sys
import numpy as np
import scipy as sp
import pandas as pd
import random
import re
import matplotlib
import matplotlib.pyplot as plt
#matplotlib.style.use('ggplot')
matplotlib.style.use('fivethirtyeight')
from sklearn.model_selection import train_test_split
from sklearn import metrics
from sk... |
1,838 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Goals of this Lesson
Gradient Descent for PCA
Nonlinear Dimensionality Reduction
Autoencoder
Step1: Again we need functions for shuffling the data and calculating classification errrors.
St... | Python Code:
from IPython.display import Image
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import time
%matplotlib inline
Explanation: Goals of this Lesson
Gradient Descent for PCA
Nonlinear Dimensionality Reduction
Autoencoder: Model and Learning
Autoencoding Images
Denoising Autoencoder
End... |
1,839 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: <small><i>This notebook was prepared by Donne Martin. Source and license info is on GitHub.</i></small>
Challenge Notebook
Problem
Step2: Unit Test
The following unit test is expecte... | Python Code:
def list_of_chars(list_chars):
Returns a list of characters in reverse order.
Takes a list of characters, if the list is not None, returns the list in
reverse order
Parameters
--------------
Input:
list_chars: list
a list of single character strings
Output... |
1,840 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
automaton.accessible
Create a new automaton from the accessible part of the input, i.e., the subautomaton whose states can be reached from an initial state.
Preconditions
Step1: The followi... | Python Code:
import vcsn
Explanation: automaton.accessible
Create a new automaton from the accessible part of the input, i.e., the subautomaton whose states can be reached from an initial state.
Preconditions:
- None
Postconditions:
- Result.is_accessible()
See also:
- automaton.is_accessible
- automaton.trim
Examples
... |
1,841 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Please find torch implementation of this notebook here
Step11: Data
As data, we use the book "The Time Machine" by H G Wells,
preprocessed using the code in this colab.
Step13: Model
We fi... | Python Code:
import jax.numpy as jnp
import matplotlib.pyplot as plt
import math
from IPython import display
import jax
try:
import flax.linen as nn
except ModuleNotFoundError:
%pip install -qq flax
import flax.linen as nn
from flax import jax_utils
try:
import optax
except ModuleNotFoundError:
%pip... |
1,842 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Kevitsa DC Forward Similation
Step1: Setup
We have stored the data and simulation mesh so that they can just be downloaded and used here
Step2: Model
This model is a synthetic based on geo... | Python Code:
import cPickle as pickle
from SimPEG import EM, Mesh, Utils, Maps
from SimPEG.Survey import Data
%pylab inline
import numpy as np
from pymatsolver import PardisoSolver
from matplotlib.colors import LogNorm
from ipywidgets import interact, IntSlider
Explanation: Kevitsa DC Forward Similation
End of explanat... |
1,843 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
DSGRN Python Interface Tutorial
This notebook shows the basics of manipulating DSGRN with the python interface.
Step2: Network
The starting point of the DSGRN analysis is a network specific... | Python Code:
import DSGRN
Explanation: DSGRN Python Interface Tutorial
This notebook shows the basics of manipulating DSGRN with the python interface.
End of explanation
network = DSGRN.Network(
X1 : (X1+X2)(~X3)
X2 : (X1)
X3 : (X1)(~X2))
DSGRN.DrawGraph(network)
Explanation: Network
The starting point of the DSGRN ana... |
1,844 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Text Classification TFX Pipeline Starter
Objective
Step1: Note
Step2: If the versions above do not match, update your packages in the current Jupyter kernel below. The default %pip package... | Python Code:
import os
import tempfile
import time
from pprint import pprint
import absl
import pandas as pd
import tensorflow as tf
import tensorflow_data_validation as tfdv
import tensorflow_model_analysis as tfma
import tensorflow_transform as tft
import tfx
from tensorflow_metadata.proto.v0 import (
anomalies_p... |
1,845 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
A explorar los datos del LHC
Hoy vamos a combinar dos conceptos que vimos ayer
Step1: Datos LHC
Hemos preparado una version mini de los datos, que funcionara bastante bien.
Los datos estan ... | Python Code:
import pandas as pd
import numpy as np # modulo de computo numerico
import matplotlib.pyplot as plt # modulo de graficas
# esta linea hace que las graficas salgan en el notebook
import seaborn as sns
%matplotlib inline
Explanation: A explorar los datos del LHC
Hoy vamos a combinar dos conceptos que vimos a... |
1,846 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
CS228 Python Tutorial
Adapted by Volodymyr Kuleshov and Isaac Caswell from the CS231n Python tutorial by Justin Johnson
<a href="http
Step1: Python versions
This version of the notebook has... | Python Code:
def quicksort(arr):
if len(arr) <= 1:
return arr
pivot = arr[len(arr) // 2]
left = [x for x in arr if x < pivot]
middle = [x for x in arr if x == pivot]
right = [x for x in arr if x > pivot]
return quicksort(left) + middle + quicksort(right)
quicksort([3,6,8,10,1,2,1])... |
1,847 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
The Utility-Fairness Tradeoff
In this post, I'll be taking a dive into the capabilities of themis_ml as a tool to measure and mitigate discriminatory patterns in training data and the predic... | Python Code:
from themis_ml import datasets
from themis_ml.datasets.german_credit_data_map import \
preprocess_german_credit_data
from themis_ml.metrics import mean_difference, normalized_mean_difference, \
mean_confidence_interval
german_credit = datasets.german_credit()
german_credit[
["credit_risk", "pur... |
1,848 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Sérialisation - correction
Step1: Exercice 1
Step2: Etape 2
Step3: Etape 3 | Python Code:
from jyquickhelper import add_notebook_menu
add_notebook_menu()
Explanation: Sérialisation - correction
End of explanation
import random
values = [ [random.random() for i in range(0,20)] for _ in range(0,100000) ]
col = [ "col%d" % i for i in range(0,20) ]
import pandas
df = pandas.DataFrame( values, colum... |
1,849 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
ES-DOC CMIP6 Model Properties - Toplevel
MIP Era
Step1: Document Authors
Set document authors
Step2: Document Contributors
Specify document contributors
Step3: Document Publication
Specif... | Python Code:
# DO NOT EDIT !
from pyesdoc.ipython.model_topic import NotebookOutput
# DO NOT EDIT !
DOC = NotebookOutput('cmip6', 'mpi-m', 'sandbox-3', 'toplevel')
Explanation: ES-DOC CMIP6 Model Properties - Toplevel
MIP Era: CMIP6
Institute: MPI-M
Source ID: SANDBOX-3
Sub-Topics: Radiative Forcings.
Properties... |
1,850 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
How to start a Pod
In this notebook, we show you how to create a single container Pod.
Start by importing the Kubernetes module
Step1: If you are using a proxy, you can use the client Confi... | Python Code:
from kubernetes import client, config
Explanation: How to start a Pod
In this notebook, we show you how to create a single container Pod.
Start by importing the Kubernetes module
End of explanation
config.load_incluster_config()
Explanation: If you are using a proxy, you can use the client Configuration to... |
1,851 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Final cube analysis
Step1: VISUALIZE POTENTIAL DIFFERENCE PART
Step2: Coordinates
Step3: NACS ANALYSIS
Step4: NACS visualization
Step5: here we try to make interpolated "unified" NAC va... | Python Code:
import quantumpropagator as qp
import matplotlib.pyplot as plt
%matplotlib ipympl
plt.rcParams.update({'font.size': 8})
from mpl_toolkits.mplot3d import axes3d
import matplotlib.pyplot as pltfrom
from ipywidgets import interact,fixed #, interactive, fixed, interact_manual
import ipywidgets as widgets
from... |
1,852 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Using Tensorflow with H2O
This notebook shows how to use the tensorflow backend to tackle a simple image classification problem.
We start by connecting to our h2o cluster
Step1: Image Class... | Python Code:
import sys, os
import h2o
from h2o.estimators.deepwater import H2ODeepWaterEstimator
import os.path
from IPython.display import Image, display, HTML
import pandas as pd
import numpy as np
import random
PATH=os.path.expanduser("~/h2o-3")
h2o.init(port=54321, nthreads=-1)
if not H2ODeepWaterEstimator.availab... |
1,853 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Source alignment and coordinate frames
This tutorial shows how to visually assess the spatial alignment of MEG sensor
locations, digitized scalp landmark and sensor locations, and MRI volume... | Python Code:
import os.path as op
import numpy as np
import nibabel as nib
from scipy import linalg
import mne
from mne.io.constants import FIFF
data_path = mne.datasets.sample.data_path()
subjects_dir = op.join(data_path, 'subjects')
raw_fname = op.join(data_path, 'MEG', 'sample', 'sample_audvis_raw.fif')
trans_fname ... |
1,854 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Create entry points to spark
Step1: load iris data
Step2: Merge features to create a features column
Step3: Index label column with StringIndexer
Import libraries
Step4: Build pipeline
T... | Python Code:
from pyspark import SparkContext
sc = SparkContext(master = 'local')
from pyspark.sql import SparkSession
spark = SparkSession.builder \
.appName("Python Spark SQL basic example") \
.config("spark.some.config.option", "some-value") \
.getOrCreate()
Explanation: Create entry po... |
1,855 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Anna KaRNNa
In this notebook, we'll build a character-wise RNN trained on Anna Karenina, one of my all-time favorite books. It'll be able to generate new text based on the text from the book... | Python Code:
import time
from collections import namedtuple
import numpy as np
import tensorflow as tf
Explanation: Anna KaRNNa
In this notebook, we'll build a character-wise RNN trained on Anna Karenina, one of my all-time favorite books. It'll be able to generate new text based on the text from the book.
This network... |
1,856 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Load a cell
Only need a part of it, so using only the first 29 cycles (splitting on cycle 30)
Step1: OCV rlx curves
Step2: Extract OCV points
Using the select_ocv_points function from cell... | Python Code:
dd = cellreader.get(filename, logging_mode="INFO")
d, _ = helpers.split_experiment(dd, 90)
Explanation: Load a cell
Only need a part of it, so using only the first 29 cycles (splitting on cycle 30)
End of explanation
ocv_cycles = d.get_ocv(
interpolated=True, number_of_points=40, direction="down"
).res... |
1,857 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: Language Translation
In this project, you’re going to take a peek into the realm of neural network machine translation. You’ll be training a sequence to sequence model on a dataset o... | Python Code:
DON'T MODIFY ANYTHING IN THIS CELL
import helper
import problem_unittests as tests
source_path = 'data/small_vocab_en'
target_path = 'data/small_vocab_fr'
source_text = helper.load_data(source_path)
target_text = helper.load_data(target_path)
Explanation: Language Translation
In this project, you’re going ... |
1,858 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Multiclass Support Vector Machine exercise
(Adapted from Stanford University's CS231n Open Courseware)
Complete and hand in this completed worksheet (including its outputs and any supporting... | Python Code:
# Run some setup code for this notebook.
import random
import numpy as np
from cs231n.data_utils import load_CIFAR10
import matplotlib.pyplot as plt
# This is a bit of magic to make matplotlib figures appear inline in the
# notebook rather than in a new window.
%matplotlib inline
plt.rcParams['figure.figsi... |
1,859 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Making batch recommendations using GraphLab Create
In this notebook we will show a complete recommender system implemented using GraphLab's deployment tools. This recommender example is comm... | Python Code:
import graphlab
Explanation: Making batch recommendations using GraphLab Create
In this notebook we will show a complete recommender system implemented using GraphLab's deployment tools. This recommender example is common in many batch scenarios, where a new recommender is trained on a periodic basis, with... |
1,860 | Given the following text problem statement, write Python code to implement the functionality described below in problem statement
Problem:
I have two arrays: | Problem:
import numpy as np
a = np.array(
[[[ 0, 1, 2, 3],
[ 2, 3, 4, 5],
[ 4, 5, 6, 7]],
[[ 6, 7, 8, 9],
[ 8, 9, 10, 11],
[10, 11, 12, 13]],
[[12, 13, 14, 15],
[14, 15, 16, 17],
[16, 17, 18, 19]]]
)
b = np.array(
[[0, 1, 2],
[2, 1, 3],
[1, 0, 3]]
)
arr = np.take... |
1,861 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: Directed, Polar Heat Diffusion
Step2: Definitions
Definitions
Step3: Example 1
Example 1 is a small system set up to run out of heat defined by the short set of relations
A -| B
A -... | Python Code:
import random
import sys
import time
from abc import ABC, abstractmethod
from collections import defaultdict
from dataclasses import dataclass
from itertools import product
from typing import Optional
import matplotlib as mpl
import matplotlib.pyplot as plt
import networkx as nx
import numpy as np
import p... |
1,862 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Quantum State Tomography with Iterative Maximum Likelihood Estimation.
Author
Step4: Define the operator measured, how to obtain it from a density matrix and the iterative operator for MaxL... | Python Code:
import numpy as np
from qutip import Qobj, rand_dm, fidelity, displace, qdiags, qeye, expect
from qutip.states import coherent, coherent_dm, thermal_dm, fock_dm
from qutip.visualization import plot_wigner, hinton
from qutip.wigner import qfunc
import qutip
import matplotlib.pyplot as plt
from matplotlib im... |
1,863 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
ES-DOC CMIP6 Model Properties - Atmoschem
MIP Era
Step1: Document Authors
Set document authors
Step2: Document Contributors
Specify document contributors
Step3: Document Publication
Speci... | Python Code:
# DO NOT EDIT !
from pyesdoc.ipython.model_topic import NotebookOutput
# DO NOT EDIT !
DOC = NotebookOutput('cmip6', 'inm', 'sandbox-1', 'atmoschem')
Explanation: ES-DOC CMIP6 Model Properties - Atmoschem
MIP Era: CMIP6
Institute: INM
Source ID: SANDBOX-1
Topic: Atmoschem
Sub-Topics: Transport, Emiss... |
1,864 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
TimML Notebook 1
A well in uniform flow
Consider a well in the middle aquifer of a three aquifer system. Aquifer properties are given in Table 1. The well is located at $(x,y)=(0,0)$, the di... | Python Code:
%matplotlib inline
from pylab import *
from timml import *
figsize=(8, 8)
ml = ModelMaq(kaq=[10, 20, 5],
z=[0, -20, -40, -80, -90, -140],
c=[4000, 10000])
w = Well(ml, xw=0, yw=0, Qw=10000, rw=0.2, layers=1)
Constant(ml, xr=10000, yr=0, hr=20, layer=0)
Uflow(ml, slope=0.002, an... |
1,865 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Around 25 minutes into this lecture, there is some good discussion of the PageRank algorithm. I have always wanted to code up a basic version of this algorithm, so this is a great excuse. Th... | Python Code:
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
from utils import progress_bar_downloader
import os
pages_link = 'http://www.cs.ubc.ca/~nando/340-2009/lectures/pages.zip'
dlname = 'pages.zip'
#This will unzip into a directory called pages
if not os.path.exists('./%s' % dlname):
pr... |
1,866 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Processing Steps
Determine noise parameters of noise model
This will be based on <a href="http
Step1: First we will take a look at the fluorescence "base line"
Step2: Now compare the fluor... | Python Code:
%matplotlib inline
from load_environment import * # python file with imports and basics to set up this computing environment
Explanation: Processing Steps
Determine noise parameters of noise model
This will be based on <a href="http://www.cs.tut.fi/~foi/papers/Foi-PoissonianGaussianClippedRaw-2007-IEEE_TIP... |
1,867 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Taxi fare prediction using the Chicago Taxi Trips dataset
Table of contents
Overview
Dataset
Objective
Costs
Data analysis
Fit a simple linear regression model
Save the model and upload to a... | Python Code:
import os
PROJECT_ID = ""
# Get your Google Cloud project ID from gcloud
if not os.getenv("IS_TESTING"):
shell_output = !gcloud config list --format 'value(core.project)' 2>/dev/null
PROJECT_ID = shell_output[0]
print("Project ID: ", PROJECT_ID)
Explanation: Taxi fare prediction using the Chica... |
1,868 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Image Gradients
In this notebook we'll introduce the TinyImageNet dataset and a deep CNN that has been pretrained on this dataset. You will use this pretrained model to compute gradients wit... | Python Code:
# As usual, a bit of setup
import time, os, json
import numpy as np
import skimage.io
import matplotlib.pyplot as plt
from cs231n.classifiers.pretrained_cnn import PretrainedCNN
from cs231n.data_utils import load_tiny_imagenet
from cs231n.image_utils import blur_image, deprocess_image
%matplotlib inline
pl... |
1,869 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
2A.ml - Machine Learning et Marketting - correction
Classification binaire, correction.
Step1: Données
Tout d'abord, on récupère la base de données
Step2: Exercice 1
Step3: On traite le... | Python Code:
%matplotlib inline
import matplotlib.pyplot as plt
from jyquickhelper import add_notebook_menu
add_notebook_menu()
Explanation: 2A.ml - Machine Learning et Marketting - correction
Classification binaire, correction.
End of explanation
url = "https://archive.ics.uci.edu/ml/machine-learning-databases/00222/"... |
1,870 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Essentially same as otbn_find_bits.ipynb but streamlined for 100M captures.
Step1: optional, if we need to plot to understand why we're not finding good bit times
Step2: p384 alignment met... | Python Code:
import numpy as np
wave = np.load('waves_p256_100M_2s.npy')
#wave = np.load('waves_p256_100M_2s_12bits.npy')
#wave = np.load('waves_p256_100M_2s_12bits830.npy')
#wave = np.load('waves_p256_100M_2s_12bitsf0c.npy')
import numpy as np
import pandas as pd
from scipy import signal
def butter_highpass(cutoff, fs... |
1,871 | 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 8</font>
Download
Step1: Bokeh
Caso o Bokeh não esteja instalado, executar no prompt ou terminal
Step2: Gráfico de B... | 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 8</font>
Download: http://github.com/dsacademybr
End of explanation
# Imp... |
1,872 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<br/><br/>
skutil
Skutil brings the best of both worlds to H2O and sklearn, delivering an easy transition into the world of distributed computing that H2O offers, while providing the same, f... | Python Code:
from __future__ import print_function, division, absolute_import
import warnings
import skutil
import sklearn
import h2o
import pandas as pd
import numpy as np
# we'll be plotting inline...
%matplotlib inline
print('Skutil version: %s' % skutil.__version__)
print('H2O version: %s' % h2o.__version__)
p... |
1,873 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Run this notebook to produce the cutout catalogs!
Potential TODO
Step1: Create the knownlens catalog
Step2: Convert the annotated catalog and knownlens catalog into cluster catalogs and cu... | Python Code:
import pandas as pd
import swap
base_collection_path = '/nfs/slac/g/ki/ki18/cpd/swap/pickles/15.09.02/'
base_directory = '/nfs/slac/g/ki/ki18/cpd/swap_catalog_diagnostics/'
annotated_catalog_path = base_directory + 'annotated_catalog.csv'
cut_empty = True
stages = [1, 2]
categories = ['ID', 'ZooID', 'locat... |
1,874 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Midterm Review
CSCI 1360E
Step1: Answering this is not simply taking what's in the autograder and copy-pasting it into your solution
Step2: The whole point is that your code should general... | Python Code:
number = 3.14159265359
Explanation: Midterm Review
CSCI 1360E: Foundations for Informatics and Analytics
Material
Anything in Lectures 1 through 10 are fair game!
Anything in assignments 1 through 4 are fair game!
Topics
Data Science
- Definition
- Intrinsic interdisciplinarity
- "Greater Data Science"
... |
1,875 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
EXERCISE
Step1: Exercise
Step2: Some information about the seismic cube
Step3: Exercise
Step4: Exercise
Step5: Exercise
Step6: Exercise | Python Code:
import numpy as np
import matplotlib.pyplot as plt
% matplotlib inline
Explanation: EXERCISE: Seismic – an array of numbers
The numpy array object
End of explanation
import time
start = time.time()
data = np.loadtxt('data/seismic_cube.txt')
end = time.time()
elapsed = end - start
print("Time taken to r... |
1,876 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Autofig Limits
Step1: Here we'll explore the different limit-styles on two plots - the first (blue) where the independent-variable is in the x-dimension, and the second (red) with an extern... | Python Code:
import autofig
import numpy as np
#autofig.inline()
t = np.linspace(0, 2*np.pi, 101)
x = np.sin(t)
y1 = np.cos(t)
y2 = -0.5*y1
y3 = 1.5*y1
Explanation: Autofig Limits
End of explanation
fig1 = autofig.Figure()
fig1.plot(x=t, y=y1, i='x', marker='None', color='b', linestyle='solid', uncover=True)
fig1.plot(... |
1,877 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
ES-DOC CMIP6 Model Properties - Toplevel
MIP Era
Step1: Document Authors
Set document authors
Step2: Document Contributors
Specify document contributors
Step3: Document Publication
Specif... | Python Code:
# DO NOT EDIT !
from pyesdoc.ipython.model_topic import NotebookOutput
# DO NOT EDIT !
DOC = NotebookOutput('cmip6', 'cnrm-cerfacs', 'sandbox-3', 'toplevel')
Explanation: ES-DOC CMIP6 Model Properties - Toplevel
MIP Era: CMIP6
Institute: CNRM-CERFACS
Source ID: SANDBOX-3
Sub-Topics: Radiative Forcing... |
1,878 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Basic plot example
Step1: Here we will set the fields to one of several values so that we can see pre-configured examples. | Python Code:
from matplotlib.pyplot import figure, plot, xlabel, ylabel, title, show
from IPython.display import display
text = widgets.FloatText()
floatText = widgets.FloatText(description='MyField',min=-5,max=5)
floatSlider = widgets.FloatSlider(description='MyField',min=-5,max=5)
#https://ipywidgets.readthedocs.io/e... |
1,879 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
연립방정식과 역행렬
다음과 같이 $x_1, x_2, \cdots, x_n$ 이라는 $n$ 개의 미지수를 가지는 방정식을 연립 방정식(system of equations)이라고 한다.
$$
\begin{matrix}
a_{11} x_1 & + \;& a_{12} x_2 &\; + \cdots + \;& a_{1M} x_M &\; = \;... | Python Code:
A = np.array([[1, 3, -2], [3, 5, 6], [2, 4, 3]])
A
b = np.array([[5], [7], [8]])
b
Ainv = np.linalg.inv(A)
Ainv
x = np.dot(Ainv, b)
x
np.dot(A, x) - b
x, resid, rank, s = np.linalg.lstsq(A, b)
x
Explanation: 연립방정식과 역행렬
다음과 같이 $x_1, x_2, \cdots, x_n$ 이라는 $n$ 개의 미지수를 가지는 방정식을 연립 방정식(system of equations)이라고 한... |
1,880 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Functions
Functions and function arguments
Functions are the building blocks of writing software. If a function is associated with an object and it's data, it is called a method.
Functions ... | Python Code:
def my_function(arg_one, arg_two, optional_1=6, optional_2="seven"):
return " ".join([str(arg_one), str(arg_two), str(optional_1), str(optional_2)])
print(my_function("a", "b"))
print(my_function("a", "b", optional_2="eight"))
#go ahead and try out different components
Explanation: Functions
Functions ... |
1,881 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
SciDB and Machine Learning on Wearable Data
This work is motivated by the following publication out of the IHI 2012 - 2ND ACM SIGHIT International Health Informatics Symposium
Step1: We loa... | Python Code:
from scidbpy import connect
import getpass
import requests
import warnings
warnings.filterwarnings("ignore")
requests.packages.urllib3.disable_warnings(requests.packages.urllib3.exceptions.InsecureRequestWarning)
db = connect(scidb_url="https://localhost:8083",
scidb_auth=('root', getpass.get... |
1,882 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Matplotlib Exercise 1
Imports
Step1: Line plot of sunspot data
Download the .txt data for the "Yearly mean total sunspot number [1700 - now]" from the SILSO website. Upload the file to the ... | Python Code:
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
Explanation: Matplotlib Exercise 1
Imports
End of explanation
import os
assert os.path.isfile('yearssn.dat')
Explanation: Line plot of sunspot data
Download the .txt data for the "Yearly mean total sunspot number [1700 - now]" from the S... |
1,883 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
3D MHD models
This notebook explains how to use cubic results of 3D MHD models on a uniform grid in CRPropa.
Supplied data
The fields need to be supplied in a raw binary file that contains o... | Python Code:
from crpropa import *
## settings for MHD model (must be set according to model)
filename_bfield = "clues_primordial.dat" ## filename of the magnetic field
gridOrigin = Vector3d(0,0,0) ## origin of the 3D data, preferably at boxOrigin
gridSize = 1024 ## size of uniform ... |
1,884 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Adding new backends
Step1: In the sisl.viz framework, the rendering part of the visualization is completely detached from the processing part. Because of that, we have the flexibility to ad... | Python Code:
import sisl
import sisl.viz
# This is a toy band structure to illustrate the concepts treated throughout the notebook
geom = sisl.geom.graphene(orthogonal=True)
H = sisl.Hamiltonian(geom)
H.construct([(0.1, 1.44), (0, -2.7)], )
band_struct = sisl.BandStructure(H, [[0,0,0], [0.5,0,0]], 10, ["Gamma", "X"])
E... |
1,885 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<h1>Table of Contents<span class="tocSkip"></span></h1>
<div class="toc"><ul class="toc-item"><li><span><a href="#Submodular-Optimization-&-Influence-Maximization" data-toc-modified-id="... | Python Code:
# code for loading the format for the notebook
import os
# path : store the current path to convert back to it later
path = os.getcwd()
os.chdir(os.path.join('..', '..', 'notebook_format'))
from formats import load_style
load_style(plot_style=False)
os.chdir(path)
# 1. magic for inline plot
# 2. magic to p... |
1,886 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<small><i>The K-means section of this notebook was put together by Jake Vanderplas. Source and license info is on GitHub.</i></small>
Clustering
Step1: Introducing K-Means
K Means is an alg... | Python Code:
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
from scipy import stats
# use seaborn plotting defaults
import seaborn as sns; sns.set()
Explanation: <small><i>The K-means section of this notebook was put together by Jake Vanderplas. Source and license info is on GitHub.</i></small>
C... |
1,887 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2021 The TensorFlow Authors.
Step1: Migrate from TPU embedding_columns to TPUEmbedding layer
<table class="tfo-notebook-buttons" align="left">
<td>
<a target="_blank" href="... | Python Code:
#@title Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# dist... |
1,888 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Regexs
Up until now, to search in text we have used string methods find, startswith, endswith, etc. But sometimes you need more power.
Regular expressions are their own little language that ... | Python Code:
import re
# To run the examples we are going to use some of the logs from the
# django project, a web framework for python
django_logs = '''commit 722344ee59fb89ea2cd5b906d61b35f76579de4e
Author: Simon Charette <charette.s@gmail.com>
Date: Thu May 19 09:31:49 2016 -0400
Refs #24067 -- Fixed contentt... |
1,889 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: 4chan Sample Thread Exploration
This notebook contains the cleaning and exploration of the chan_example csv which is hosted on the far-right s3 bucket. It contains cleaning out the h... | Python Code:
import boto3
from bs4 import BeautifulSoup
import pandas as pd
import numpy as np
%matplotlib inline
import matplotlib.pyplot as plt
session = boto3.Session(profile_name='default')
s3 = session.resource('s3')
bucket = s3.Bucket("far-right")
session.available_profiles
# print all objects in bucket
for obj i... |
1,890 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Train a gesture recognition model for microcontroller use
This notebook demonstrates how to train a 20kb gesture recognition model for TensorFlow Lite for Microcontrollers. It will produce t... | Python Code:
# Clone the repository from GitHub
!git clone --depth 1 -q https://github.com/tensorflow/tensorflow
# Copy the training scripts into our workspace
!cp -r tensorflow/tensorflow/lite/micro/examples/magic_wand/train train
Explanation: Train a gesture recognition model for microcontroller use
This notebook dem... |
1,891 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Задача 2
Step1: 1. Сформировать СЛАУ для многочлена первой степени, который должен совпадать с функцией в точках 1 и 15.
Step2: 2. Многочлен второй степени в точка 1, 8, 15.
Step3: 3. Мно... | Python Code:
from math import sin, exp
def func(x):
return sin(x / 5.) * exp(x / 10.) + 5. * exp(-x / 2.)
import numpy as np
from scipy import linalg
arrCoordinates = np.arange(1., 15.1, 0.1)
arrFunction = np.array([func(coordinate) for coordinate in arrCoordinates])
Explanation: Задача 2: аппроксимация функции
End... |
1,892 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
所有生成器都是迭代器,因为生成器完全实现了迭代器接口,不过迭代器一般用于从集合取出元素,生成器用于 “凭空” 创造元素。斐波那契数列例子可以很好的说明两者区别:斐波那契数列中的数有无穷个,在一个集合里放不下。
在 Python 3 中,生成器有广泛用途。现在即使是内置的 range() 函数也要返回一个类似生成器的对象,而以前返回完整列表。如果一定让 range() 函数返回列... | Python Code:
import re
import reprlib
RE_WORD = re.compile('\w+')
class Sentence:
def __init__(self, text):
self.text = text
# 返回一个字符串列表,里面的元素是正则表达式的全部非重叠匹配
self.words = RE_WORD.findall(text)
def __getitem__(self, index):
return self.words[index]
# 为了完善序列协议... |
1,893 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
p-Hacking and Multiple Comparisons Bias
By Delaney Mackenzie and Maxwell Margenot.
Part of the Quantopian Lecture Series
Step1: Refresher
Step2: If we add some noise our coefficient will d... | Python Code:
import numpy as np
import pandas as pd
import scipy.stats as stats
import matplotlib.pyplot as plt
Explanation: p-Hacking and Multiple Comparisons Bias
By Delaney Mackenzie and Maxwell Margenot.
Part of the Quantopian Lecture Series:
www.quantopian.com/lectures
github.com/quantopian/research_public
Multipl... |
1,894 | Given the following text description, write Python code to implement the functionality described.
Description:
Find the total marks obtained according to given marking scheme
Function that calculates marks . ; for not attempt score + 0 ; for each correct answer score + 3 ; for each wrong answer score - 1 ; calculate to... | Python Code:
def markingScheme(N , answerKey , studentAnswer ) :
positive = 0
negative = 0
notattempt = 0
for i in range(0 , N ) :
if(studentAnswer[i ] == 0 ) :
notattempt += 1
elif(answerKey[i ] == studentAnswer[i ] ) :
positive += 1
elif(answerKey[i ] != studentAnswer[i ] ) :
negative += ... |
1,895 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Conservative Estimation using a Grid Seach Minimization
This notebook illustrates the different steps for a conservative estimation using a grid search minimization.
Classic Libraries
Step1:... | Python Code:
import openturns as ot
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
%matplotlib inline
%load_ext autoreload
%autoreload 2
random_state = 123
np.random.seed(random_state)
Explanation: Conservative Estimation using a Grid Seach Minimization
This notebook illustrates the different ... |
1,896 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Interactive Widgets
Using interact
Source Link
Step1: Note the semicolon
Step2: Booleans create checkbox
Step3: Using decorators
Step4: From Portilla's notes
This examples clarifies how ... | Python Code:
# Start with some imports!
from __future__ import print_function
from ipywidgets import interact, interactive, fixed
import ipywidgets as widgets
# Very basic function
def f(x):
return x
help(interact)
Explanation: Interactive Widgets
Using interact
Source Link
End of explanation
# Generate a slider to... |
1,897 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: Adding all icons in a single call
Step2: Explicit loop allow for customization in the loop.
Step4: FastMarkerCluster is not as flexible as MarkerCluster but, like the name suggests,... | Python Code:
icon_create_function = \
function(cluster) {
return L.divIcon({
html: '<b>' + cluster.getChildCount() + '</b>',
className: 'marker-cluster marker-cluster-large',
iconSize: new L.Point(20, 20)
});
}
from folium.plugins import MarkerCluster
m = folium.Map(
location=[np.mean(lats), np.... |
1,898 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
1. Regressão Logística com Regularização
Nesta parte do trabalho, será implementada a Regressão Logística Regularizada
para prever se os microchips de uma usina de fabricação passam na garan... | Python Code:
#import os
import pandas as pd
import numpy as np
import matplotlib as plt
from numpy import loadtxt, where, append, zeros, ones, array, linspace, logspace
from pylab import scatter, show, legend, xlabel, ylabel
#%matplotlib inline
# Carregando o arquivo gerado pelo MATLAB
#import scipy.io
#mat = scipy.io... |
1,899 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Une exploration visuelle de l'algorithme du Simplexe en 3D avec Python
Dans ce notebook (utilisant Python 3), je souhaite montrer des animations de l'algorithme du Simplexe, un peu comme dan... | Python Code:
from IPython.display import YouTubeVideo
# https://www.youtube.com/watch?v=W_U8ozVsh8s
YouTubeVideo("W_U8ozVsh8s", width=944, height=531)
Explanation: Une exploration visuelle de l'algorithme du Simplexe en 3D avec Python
Dans ce notebook (utilisant Python 3), je souhaite montrer des animations de l'algori... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.