Unnamed: 0 int64 0 15.9k | cleaned_code stringlengths 67 124k ⌀ | cleaned_prompt stringlengths 168 30.3k ⌀ |
|---|---|---|
4,500 | <ASSISTANT_TASK:>
Python Code:
from scipy.special import k0 # bessel function K0
import numpy as np
def dWpp(r, z, a, b, D):
Returns additional drawdown caused by partial penetration
Solution by Hantush. See Kruseman and De Ridder (1994), p159.
The real extra drawdown is Q/(2 pi kD) * dW
Parmeters:... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Partial penetration
Step2: Let's apply this solution and see if it works.
Step3: As was said, it is difficult to see wether this result is co... |
4,501 | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
import numpy as np
from scipy.special import expit
import matplotlib.pyplot as plt
# define our hypothesis (vectorized!)
def f(x):
return expit(np.matrix([0, 1, -.5,.5])*x);
x_min = -5; x_max = 5
y_min = -5; y_max = 5
x1 = np.linspace(x_min, x_max, 200)
y1 = np.lins... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Create the domain for the plot
Step2: Make the plots
|
4,502 | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
try:
import seaborn
except ImportError:
pass
pd.options.display.max_rows = 10
df = pd.DataFrame({'key':['A','B','C','A','B','C','A','B','C'],
'data': [0, 5, 10, 5, 10, 15,... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Some 'theory'
Step2: Using the filtering and reductions operations we have seen in the previous notebooks, we could do something like
Step3: A... |
4,503 | <ASSISTANT_TASK:>
Python Code:
from IPython.display import YouTubeVideo
YouTubeVideo('KE952yueVLA', width=720, height=400, loop=1, autoplay=0)
from IPython.display import YouTubeVideo
YouTubeVideo('lfNVv0A8QvI', width=720, height=400, loop=1, autoplay=0)
from IPython.display import YouTubeVideo
YouTubeVideo('hxdPdKbq... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Some sort of mapping between neural activity and a state in the world
Step2: Rectified Linear Neuron
Step3: Leaky integrate-and-fire neuron
St... |
4,504 | <ASSISTANT_TASK:>
Python Code:
import graphviz as gv
class TwoThreeTree:
sNodeCount = 0
def __init__(self):
TwoThreeTree.sNodeCount += 1
self.mID = TwoThreeTree.sNodeCount
def getID(self):
return self.mID
def isNil(self):
return False
def ... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: This notebook presents 2-3 trees. We define these trees inductively as follows
Step2: The function make_string is a helper function used to sh... |
4,505 | <ASSISTANT_TASK:>
Python Code:
# Configure Jupyter so figures appear in the notebook
%matplotlib inline
# Configure Jupyter to display the assigned value after an assignment
%config InteractiveShell.ast_node_interactivity='last_expr_or_assign'
# import functions from the modsim.py module
from modsim import *
init = St... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: SIR implementation
Step2: To convert from number of people to fractions, we divide through by the total.
Step4: make_system creates a System o... |
4,506 | <ASSISTANT_TASK:>
Python Code:
import numpy as np
a = np.array([[0,1,0,0], [0,0,1,0], [0,1,1,0], [1,0,0,1]])
def LI_vecs(M):
dim = M.shape[0]
LI=[M[0]]
for i in range(dim):
tmp=[]
for r in LI:
tmp.append(r)
tmp.append(M[i]) #set tmp=LI+[M[i]]
if np.... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
|
4,507 | <ASSISTANT_TASK:>
Python Code:
import ConfigParser
CP = ConfigParser.ConfigParser()
CP.read("../.config")
head = CP.get('IPyLogbook-Config','head')
url = CP.get('IPyLogbook-Config','url')
port = CP.get('IPyLogbook-Config','ssh-port')
headLink="[Logbook HEAD]("+url+":"+port+"/tree)"
extensionsLink="[Logbook Extensions](... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Create Logbook Entry
Step2: List Logbook Entries
Step3: Backup Logbook
|
4,508 | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
import csv
import json
import os
import ujson
import urllib2
import glob
import pickle
import re
import time
from wordcloud import WordCloud
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
import scipy as sp
from riotwatcher import RiotWatcher
co... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: To use the Riot api, one more important thing to do is to get your own API key. API key can be obtained from here. Note that normal developr API... |
4,509 | <ASSISTANT_TASK:>
Python Code:
import sys
sys.path.append("../")
import pyfesom as pf
import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap
from matplotlib.colors import LinearSegmentedColormap
import numpy as np
# %matplotlib notebook
%matplotlib inline
from matplotlib import cm
from netCDF4 import ... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: First, as usuall load the mesh
Step2: Load data for one year
Step3: Select one month
Step4: Decide start and end points of the transect and p... |
4,510 | <ASSISTANT_TASK:>
Python Code:
# install Pint if necessary
try:
import pint
except ImportError:
!pip install pint
# download modsim.py if necessary
from os.path import exists
filename = 'modsim.py'
if not exists(filename):
from urllib.request import urlretrieve
url = 'https://raw.githubusercontent.com/A... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: In this chapter we model systems that involve rotating objects.
Step2: Rmin and Rmax are the initial and final values for the radius, r.
Step3... |
4,511 | <ASSISTANT_TASK:>
Python Code:
import numpy as np
import matplotlib.pyplot as plt
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
import mne
from mne.datasets import sample
from mne.decoding import (SlidingEstimator, General... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Transformation classes
Step2: PSDEstimator
Step3: Source power comodulation (SPoC)
Step4: Decoding over time
Step5: You can retrieve the spa... |
4,512 | <ASSISTANT_TASK:>
Python Code:
import string
upcase = [x for x in string.ascii_uppercase]
lcase = [x for x in string.ascii_lowercase]
print(upcase[:5], lcase[:5])
pd.DataFrame([upcase, lcase])
pd.DataFrame([upcase, lcase]).T
letters = pd.DataFrame({'lowercase':lcase, 'uppercase':upcase})
letters.head()
pd.DataFrame... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: You can create DataFrames by passing in np arrays, lists of series, or dictionaries.
Step2: We’ll be covering a lot of different aspects here b... |
4,513 | <ASSISTANT_TASK:>
Python Code:
import collections
import subprocess
import itertools
import os
import time
import madoka
import numpy as np
import redis
ALPHANUM = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
NUM_ALPHANUM_COMBINATION = 238328
zipf_array = np.random.zipf(1.5, NUM_ALPHANUM_COMBINATION... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Counting error rate
|
4,514 | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
from medpy.io import load
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.cm as cm
i, h = load("flair.nii.gz")
i[np.random.randint(0, i.shape[0], int(0.05 * i.size)), np.random.randint(0, i.shape[1], int(0.05 * i.size))] = i.min()
i[np.random.randin... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Using our previous approach of simply thresholding to obtain the brain mask will fail now.
Step2: What we instead obtain is a rough estimation ... |
4,515 | <ASSISTANT_TASK:>
Python Code:
import numpy as np
import pandas as pd
import mne
pd.DataFrame(np.random.normal(size=(16, 100))).to_csv("fnirs.csv")
data = pd.read_csv('fnirs.csv')
ch_names = ['S1_D1 hbo', 'S1_D1 hbr', 'S2_D1 hbo', 'S2_D1 hbr',
'S3_D1 hbo', 'S3_D1 hbr', 'S4_D1 hbo', 'S4_D1 hbr',
... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: First, we generate an example CSV file which will then be loaded in to MNE.
Step2: <div class="alert alert-danger"><h4>Warning</h4><p>The chann... |
4,516 | <ASSISTANT_TASK:>
Python Code:
# Import the Earth Engine Python Package into Python environment.
import ee
import ee.mapclient
# Initialize the Earth Engine object, using the authentication credentials.
ee.Initialize()
image = ee.Image('srtm90_v4')
from IPython.display import Image
Image(url=image.getThumbUrl({'min':0... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Visualize Geographic Data
Step3: Try it with mapclient
Step4: Testing Out Jill's Method for Displaying Maps
|
4,517 | <ASSISTANT_TASK:>
Python Code:
from __future__ import print_function # For py 2.7 compat
from IPython.html import widgets # Widget definitions
from IPython.display import display # Used to display widgets in the notebook
from IPython.utils.traitlets import Unicode # Used to declare attributes of our widget
class DateW... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Abstract
Step2: Our widget inherits from widgets.DOMWidget since it is intended that it will be displayed in the notebook directly.
Step3: Now... |
4,518 | <ASSISTANT_TASK:>
Python Code:
A = [9,3,9,3,9,7,9]
print len(A)
print sorted(A)
single_num = sorted(A)[0]
count = 0
if len(A) == 0:
print A
for num in sorted(A):
print "num: ", num
if num % single_num:
print "single num: ", single_num
print "count: ", count
... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: designing algorithm
Step2: version 2-
Step3: V3
Step4: V4
Step5: V 5 - Some where long the lines forgot about the fine line "All but one occ... |
4,519 | <ASSISTANT_TASK:>
Python Code:
%%bash
gcloud config list
!bq ls
!bq ls --project_id qwiklabs-resources
!bq ls --project_id qwiklabs-resources tpcds_2t_baseline
%%bigquery
SELECT
dataset_id,
table_id,
-- Convert bytes to GB.
ROUND(size_bytes/pow(10,9),2) as size_gb,
-- Convert UNIX EPOCH to a timestamp.
... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Google Cloud resources are organized hierarchically. Starting from the bottom of the hierarchy, projects are the first level, and they contain o... |
4,520 | <ASSISTANT_TASK:>
Python Code:
### General imports
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import colors as mcolors
import GPy
import time
np.random.seed(12345)
### Emukit imports
from emukit.test_functions.forrester import multi_fidelity_forrester_function
from emukit.core... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Set up our toy problem (1D optimisation of the forrester function with two fidelity levels) and collect 6 initial points at low fidelity and 3 a... |
4,521 | <ASSISTANT_TASK:>
Python Code:
# Basic imports
import os
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import datetime as dt
import scipy.optimize as spo
import sys
from time import time
from sklearn.metrics import r2_score, median_absolute_error
from multiprocessing import Pool
%matplotlib inl... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Let's show the symbols data, to see how good the recommender has to be.
Step2: Let's run the trained agent, with the test set
Step3: And now a... |
4,522 | <ASSISTANT_TASK:>
Python Code:
import io3d
import matplotlib.pyplot as plt
import io3d
import matplotlib.pyplot as plt
datap = io3d.read("http://home.zcu.cz/~mjirik/lisa/sample_data/nrn4.pklz")
plt.imshow(datap.data3d[5,:,:], cmap='gray')
io3d.datasets.download("3Dircadb1.1")
datap = io3d.read_dataset("3Dircadb1", "... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Alternative 2
Step2: Download the data
Step3: Read intensity data
Step4: Alternative 1
Step5: Show one slice
Step6: Show multiple slices
St... |
4,523 | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
import numpy as np
from numpy.random import random
# from matplotlib import pyplot as plt, animation
from matplotlib import pyplot as plt, rcParams, animation, rc
rc('animation', html='html5')
rcParams['figure.figsize'] = 3, 3 # sets plot window size
%precision 4
np.set... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Let's start out with a line
Step2: Coming up with an update function that'll make our guesses of a & b closer to what a & b actually are, each ... |
4,524 | <ASSISTANT_TASK:>
Python Code:
import os
import larch # !conda install larch -c conda-forge # for estimation
import pandas as pd
os.chdir('test')
modelname = "atwork_subtour_frequency"
from activitysim.estimation.larch import component_model
model, data = component_model(modelname, return_data=True)
data.coefficien... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: We'll work in our test directory, where ActivitySim has saved the estimation data bundles.
Step2: Load data and prep model for estimation
Step3... |
4,525 | <ASSISTANT_TASK:>
Python Code:
from pymldb import Connection
mldb = Connection("http://localhost")
mldb.query(
SELECT
jseval('
return val * 2;
','val', 5) AS output
)
mldb.query(
SELECT
jseval('
var output = {};
output["mult"] = val * 2;
... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step2: Basic usage examples
Step4: The variable val takes the input value 5 and the code is then evaluated.
Step5: In the above example, the string v... |
4,526 | <ASSISTANT_TASK:>
Python Code:
import requests
base_url = 'http://192.168.59.103:8500/v1/kv/'
response = requests.put(base_url + 'key1', data="value1")
print(response.text)
from consul import Consul
c = Consul('192.168.59.103')
index, data = c.kv.get('key1')
print(data['Value'].decode('utf8'))
<END_TASK> | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Getting a key/value with python-consul
|
4,527 | <ASSISTANT_TASK:>
Python Code:
# help(font_manager)
path = '../fonts/segoeuib.ttf'
prop = font_manager.FontProperties(fname=path)
print prop.get_name()
print prop.get_family()
font0 = FontProperties()
font1 = font0.copy()
font1.set_family(prop.get_name())
# Data to plot
labels = ['Python', 'R','MATLAB', 'C', 'C++']
si... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Controlling font properties
|
4,528 | <ASSISTANT_TASK:>
Python Code:
# Set up
import numpy as np
from __future__ import division # division
import pandas as pd
import seaborn as sns # for visualiation
from scipy.stats import ttest_ind # t-tests
import statsmodels.formula.api as smf # linear modeling
import statsmodels.api as sm
import matplotlib.pyplot as ... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Data Exploration (15 minutes)
Step2: List pertinent observations from the above analysis
Step3: What is your interpretation of the coefficient... |
4,529 | <ASSISTANT_TASK:>
Python Code:
%%R
otu.tbl.file1 = '/home/nick/notebook/SIPSim/dev/bac_genome1210/atomIncorp_taxaIncorp/0/10/1/OTU_n2_abs1e9_sub-norm_filt.physeq'
otu.tbl.file2 = '/home/nick/notebook/SIPSim/dev/bac_genome1210/atomIncorp_taxaIncorp/100/10/1/OTU_n2_abs1e9_sub-norm_filt.physeq'
physeq1 = readRDS(otu.tbl.f... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Calculating centroid of binned fraction samples
|
4,530 | <ASSISTANT_TASK:>
Python Code:
!head ../data/model.txt
import pandas as pd
import numpy as np
%matplotlib inline
import matplotlib.pyplot as plt
import matplotlib as mpl
from IPython.display import display
model = pd.read_csv(
"../data/model.txt", delim_whitespace=True, skiprows = 3,
parse_dates = {'Timestamp':... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Ejercicios
Step2: Misma matriz scatter para los 1000 registros con mayor velocidad
Step3: Histórico de la velocidad media
Step4: Media móvil ... |
4,531 | <ASSISTANT_TASK:>
Python Code:
'''
Solution
'''
import pandas as pd
# Dataset from - https://archive.ics.uci.edu/ml/datasets/SMS+Spam+Collection
df = pd.read_table('smsspamcollection/SMSSpamCollection',
sep='\t',
header=None,
names=['label', 'sms_message'])
# O... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Step 1.2
Step2: Step 2.1
Step3: Step 2
Step4: Step 3
Step5: Step 4
Step6: Congratulations! You have implemented the Bag of Words process fr... |
4,532 | <ASSISTANT_TASK:>
Python Code:
def plot_predict_actual_values(date, y_pred, y_test, ylabel):
plot the predicted values and actual values (for the test data)
fig, axs = plt.subplots(figsize=(16,6))
axs.plot(date, y_pred, color='red', label='predicted values')
axs.plot(date, y_test, color='blue'... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Network Traffic Forecasting (using time series data)
Step2: Download raw dataset and load into dataframe
Step3: Below are some example records... |
4,533 | <ASSISTANT_TASK:>
Python Code:
from __future__ import division, print_function
import matplotlib.pyplot as plt
%matplotlib inline
import scipy.stats
import numpy as np
def E(W, s):
N = len(s)
return -0.5 * np.sum(W[i, j] * s[i] * s[j] for i, j in np.ndindex(N, N))
N = 6
beta_0 = 0.007
tau = 1.06
epsilon = 1e-2... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Exercise 1
Step2: Simulation with M=1
Step3: Simulation with M=500
Step4: All possible states
Step5: Exercise 2
|
4,534 | <ASSISTANT_TASK:>
Python Code:
import sys
if 'google.colab' in sys.modules:
!pip install --upgrade pip
# Install the TensorFlow Extended library
!pip install -U tfx
import os
import pprint
import tempfile
import urllib
import absl
import tensorflow as tf
import tensorflow_model_analysis as tfma
tf.get_logger().prop... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Install TFX
Step2: Restart the kernel
Step3: Let's check the library versions.
Step4: Set up pipeline paths
Step5: Download example data
Ste... |
4,535 | <ASSISTANT_TASK:>
Python Code:
import graphviz
import pandas
from sklearn import tree
from sklearn.model_selection import train_test_split
clf = tree.DecisionTreeClassifier()
input = pandas.read_csv("/home/glenn/git/clojure-news-feed/client/ml/etl/throughput.csv")
data = input[input.columns[6:9]]
target = input['cloud'... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Next, we evaluate scikit-learn accuracy where we predict feed implementation based on latency.
Step2: As you can see, scikit-learn has a 99% ac... |
4,536 | <ASSISTANT_TASK:>
Python Code:
cd /tmp
# Delete the repo if it happens to already exist:
!rm -rf git-intro
# Create the repo
!git clone https://github.com/DS-100/git-intro git-intro
!ls -lh | grep git-intro
cd git-intro
# What files are in the repo?
!ls -lh
# What about hidden files?
!ls -alh
# What's the current sta... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Looking at files in a repo
Step2: The special .git directory is where git stores all its magic. If you delete it (or this whole directory), th... |
4,537 | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
from bigbang.archive import Archive
import bigbang.parse as parse
import bigbang.graph as graph
import bigbang.mailman as mailman
import bigbang.process as process
import bigbang.twopeople as twoppl
import matplotlib.pyplot as plt
import networkx as nx
import numpy as ... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Next we'll import dependencies.
Step2: Let's begin with just one mailing list to simplify.
Step3: Let's look at the matrix of who replies to w... |
4,538 | <ASSISTANT_TASK:>
Python Code:
import numpy as np
import graphlab
from scipy.sparse import csr_matrix
from sklearn.metrics.pairwise import pairwise_distances
import time
from copy import copy
import matplotlib.pyplot as plt
%matplotlib inline
'''Check GraphLab Create version'''
from distutils.version import StrictVersi... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Load in the Wikipedia dataset
Step2: For this assignment, let us assign a unique ID to each document.
Step3: Extract TF-IDF matrix
Step5: For... |
4,539 | <ASSISTANT_TASK:>
Python Code:
#Set model parameters
#square neighborhood radius
R = 3
#number of states / colors
K = 8
#excitation threshhold
T = 6
#initial conditions on 300x300 lattice
initial = random_state_v2((300,300), K, 2.0/9)
#initialize CA object with chosen parameters and initial condition
spirals = greenber... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Animate the spacetime field produced by the above code
Step2: You can also animate on the fly using the .animate() method. We run the same code... |
4,540 | <ASSISTANT_TASK:>
Python Code:
import importlib
autograd_available = True
# if automatic differentiation is available, use it
try:
import autograd
except ImportError:
autograd_available = False
pass
if autograd_available:
import autograd.numpy as np
from autograd import grad
else:
import num... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Specify the function to minimize as a simple python function.<br>
Step2: Plot the function as a 2d surface plot. Different colors indicate diff... |
4,541 | <ASSISTANT_TASK:>
Python Code:
!pip install git+https://github.com/google/starthinker
CLOUD_PROJECT = 'PASTE PROJECT ID HERE'
print("Cloud Project Set To: %s" % CLOUD_PROJECT)
CLIENT_CREDENTIALS = 'PASTE CREDENTIALS HERE'
print("Client Credentials Set To: %s" % CLIENT_CREDENTIALS)
FIELDS = {
'auth_dv': 'user', # ... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: 2. Get Cloud Project ID
Step2: 3. Get Client Credentials
Step3: 4. Enter Bulk Editor For DV360 Parameters
Step4: 5. Execute Bulk Editor For D... |
4,542 | <ASSISTANT_TASK:>
Python Code:
mod = pysces.model('lin4_fb')
sc = psctb.Symca(mod)
sc.do_symca()
sc.cc_results
sc.cc_results.ccJR1_R4
sc.cc_results.ccJR1_R4.expression
sc.cc_results.ccJR1_R4.numerator
sc.cc_results.ccJR1_R4.denominator
sc.cc_results.ccJR1_R4.value
sc.cc_results.ccJR1_R4.CP001
sc.cc_results.ccJR... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Additionally Symca has the following arguments
Step2: do_symca has the following arguments
Step3: Inspecting an individual control coefficient... |
4,543 | <ASSISTANT_TASK:>
Python Code:
#@title Licensed under the Apache License, Version 2.0 (the "License"); { display-mode: "form" }
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable l... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Monte Carlo Pricing in Tensorflow Quant Finance (TFF) using Euler Scheme
Step2: Diffusion process $X(t) = (X_1(t), .. X_n(t))$ is a solution to... |
4,544 | <ASSISTANT_TASK:>
Python Code:
# Import TensorFlow and enable eager execution
# This code requires TensorFlow version >=1.9
import tensorflow as tf
tf.enable_eager_execution()
# We'll generate plots of attention in order to see which parts of an image
# our model focuses on during captioning
import matplotlib.pyplot as... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Download and prepare the MS-COCO dataset
Step2: Optionally, limit the size of the training set for faster training
Step3: Preprocess the image... |
4,545 | <ASSISTANT_TASK:>
Python Code:
import re
pattern = 'this'
text = 'Does this text match the pattern'
match = re.search(pattern, text)
s = match.start()
e = match.end()
print('Found "{}" \n in "{}" from {} to {} ("{}")'.format(match.re.pattern,match.string, s, e, text[s:e]))
import re
regexes = [
re.compile(p)
f... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: 2 Compiling Expressions
Step2: 3 Multiple Matches
Step4: 4 Repetition
Step5: When processing a repetition instruction, re will usually consum... |
4,546 | <ASSISTANT_TASK:>
Python Code:
from devito import *
from sympy import init_printing, symbols, solve
init_printing(use_latex=True)
grid = Grid(shape=(5, 6), extent=(1., 1.))
grid
?Function
f = Function(name='g', grid=grid)
f
f.data
g = TimeFunction(name='g', grid=grid)
g
from examples.cfd import init_smooth, plot_f... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: From equation to stencil code in a few lines of Python
Step2: Functions and data
Step3: Ok, let's create a function $f(x, y)$ and look at the ... |
4,547 | <ASSISTANT_TASK:>
Python Code:
cube_params = {
'freq' : 604000,
'alpha' : 0,
'delta' : 0,
'spe_bw' : 4000,
'spe_res' : 1,
's_f' : 4,
's_a' : 0}
# freq_init = cube_params['freq'] - cube_params['spe_bw']/2.0
# freq_end = cube_params['freq'] + cube_params['spe_bw']/2.0
# molist_presen... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: To select the isolist, the wavelength range of the cube is obtained, and a searching from theoretical catalog Splatalogue is performed. All the ... |
4,548 | <ASSISTANT_TASK:>
Python Code:
# Get http://geneontology.org/ontology/go-basic.obo
from goatools.base import download_go_basic_obo
obo_fname = download_go_basic_obo()
# Get ftp://ftp.ncbi.nlm.nih.gov/gene/DATA/gene2go.gz
from goatools.base import download_ncbi_associations
gene2go = download_ncbi_associations()
from ... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: 1b. Download Associations, if necessary
Step2: 2. Load Ontologies, Associations and Background gene set
Step3: 2b. Load Associations
Step4: 2... |
4,549 | <ASSISTANT_TASK:>
Python Code:
import growler
growler.__meta__.version_info
app = growler.App("NotebookServer")
@app.use
def print_client_info(req, res):
ip = req.ip
reqpath = req.path
print("[{ip}] {path}".format(ip=ip, path=reqpath))
print(" >", req.headers['USER-AGENT'])
print(flush=True)
i =... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Create growler application with name NotebookServer
Step2: Add a general purpose method which prints ip address and the USER-AGENT header
Step3... |
4,550 | <ASSISTANT_TASK:>
Python Code:
# Load libraries
import pandas as pd
import numpy as np
# Create feature matrix with two highly correlated features
X = np.array([[1, 1, 1],
[2, 2, 0],
[3, 3, 1],
[4, 4, 0],
[5, 5, 1],
[6, 6, 0],
[7, 7, 1... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Load Data
Step2: Identify Highly Correlated Features
Step3: Drop Marked Features
|
4,551 | <ASSISTANT_TASK:>
Python Code:
%%HTML
<style>
.rendered_html {
font-size: 0.7em;
}
.CodeMirror-scroll {
font-size: 1.2em;
}
.rendered_html table, .rendered_html th, .rendered_html tr, .rendered_html td, .rendered_html h2, .rendered_html h4 {
font-size: 100%;
}
</style>
import pandas as pd
import pandas as ... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Systems check
Step2: Note
Step3: Note
Step4: Note
Step5: We have an index, and three columns
Step6: Definitely a string. We'll note thi... |
4,552 | <ASSISTANT_TASK:>
Python Code:
# DO NOT EDIT !
from pyesdoc.ipython.model_topic import NotebookOutput
# DO NOT EDIT !
DOC = NotebookOutput('cmip6', 'snu', 'sandbox-2', 'atmos')
# Set as follows: DOC.set_author("name", "email")
# TODO - please enter value(s)
# Set as follows: DOC.set_contributor("name", "email... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Document Authors
Step2: Document Contributors
Step3: Document Publication
Step4: Document Table of Contents
Step5: 1.2. Model Name
Step6: 1... |
4,553 | <ASSISTANT_TASK:>
Python Code:
remote_data = True
remote_server_auto = True
case_name = 'cylinder'
data_dir='/gpfs/thirdparty/zenotech/home/dstandingford/VALIDATION/CYLINDER'
data_host='dstandingford@vis03'
paraview_cmd='mpiexec /gpfs/cfms/apps/zCFD/bin/pvserver'
if not remote_server_auto:
paraview_cmd=None
if not ... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: zCFD Validation and Regression¶
Step2: Initialise Environment
Step3: Data Connection
Step4: Get control dictionary¶
Step5: Get status file
S... |
4,554 | <ASSISTANT_TASK:>
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 writin... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Parameter server training with ParameterServerStrategy
Step3: Cluster setup
Step4: The in-process cluster setup is frequently used in unit tes... |
4,555 | <ASSISTANT_TASK:>
Python Code:
from __future__ import print_function
import tensorflow as tf
import numpy as np
from datetime import date
date.today()
author = "kyubyong. https://github.com/Kyubyong/tensorflow-exercises"
tf.__version__
np.__version__
sess = tf.InteractiveSession()
_x = np.array([1, 2, 3, 4])
x = tf.co... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: NOTE on notation
Step2: Q2. Extract the diagonal of X.
Step3: Q3. Permutate the dimensions of x such that the new tensor has shape (3, 4, 2).
... |
4,556 | <ASSISTANT_TASK:>
Python Code:
%%capture
!python -m pip install iree-compiler iree-runtime iree-tools-tf -f https://github.com/google/iree/releases
# Import IREE's TensorFlow Compiler and Runtime.
import iree.compiler.tf
import iree.runtime
from matplotlib import pyplot as plt
import numpy as np
import tensorflow as t... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: 2. Import TensorFlow and Other Dependencies
Step2: 3. Load the MNIST Dataset
Step3: 4. Create a Simple DNN
Step4: 5. Compile the Model with I... |
4,557 | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
from bigbang.archive import Archive
import bigbang.parse as parse
import bigbang.analysis.graph as graph
import bigbang.ingress.mailman as mailman
import bigbang.analysis.process as process
import networkx as nx
import matplotlib.pyplot as plt
import pandas as pd
from ... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Next we'll import dependencies.
Step2: Now we will use BigBang to process mailing list archives we've already downloaded.
Step3: Here we will ... |
4,558 | <ASSISTANT_TASK:>
Python Code:
# Import necessary packages
import tensorflow as tf
import tqdm
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
# Import MNIST data so we have something for our experiments
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step6: Neural network classes for testing
Step9: There are quite a few comments in the code, so those should answer most of your questions. However, l... |
4,559 | <ASSISTANT_TASK:>
Python Code:
# Load Biospytial modules and etc.
%matplotlib inline
import sys
sys.path.append('/apps')
import django
django.setup()
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
## Use the ggplot style
plt.style.use('ggplot')
from external_plugins.spystats import tools
%run ..... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Algorithm for processing Chunks
Step2: Take an average of the empirical variograms also with the envelope.
Step3: Let's bring the whole empiri... |
4,560 | <ASSISTANT_TASK:>
Python Code:
# Authors: Eric Larson <larson.eric.d@gmail.com>
# Adam Li <adam2392@gmail.com>
# Alex Rockhill <aprockhill@mailbox.org>
#
# License: BSD-3-Clause
import os.path as op
import numpy as np
import matplotlib.pyplot as plt
import mne
from mne.datasets import fetch_fsaverage
... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Let's load some sEEG data with channel locations and make epochs.
Step2: Let use the Talairach transform computed in the Freesurfer recon-all
S... |
4,561 | <ASSISTANT_TASK:>
Python Code:
import os
import numpy as np
import GPy
import pods
%matplotlib inline
import matplotlib as plt
plt.rcParams['figure.figsize'] = (10.0, 4.0)
# This downloads cel files if they are not present.
# These cel files would be needed if you want to do
# the full Bioconductor analysis below.
p... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Use Bioconductor for Processing
Step2: This portion of the code will do the PUMA analysis of the gene
Step3: Read Gene Expression Data into Pa... |
4,562 | <ASSISTANT_TASK:>
Python Code:
import pandas as pd
from sqlalchemy import create_engine
def connection(user,passwd,dbname, echo_i=False):
str1 = ('postgresql+pg8000://' + user +':' + passw + '@switch-db2.erg.berkeley.edu:5432/'
+ dbname + '?ssl=true&sslfactory=org.postgresql.ssl.NonValidatingFactory')... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: After importing the required packages, first create the engine to connect to the DB. The approach I generally use is to create a string based on... |
4,563 | <ASSISTANT_TASK:>
Python Code:
plt.imshow(X_train[0].reshape(28,28)) # This is what the image looks like
from scipy.ndimage import interpolation
def moments(image):
c0,c1 = np.mgrid[:image.shape[0],:image.shape[1]] # A trick in numPy to create a mesh grid
totalImage = np.sum(image) #sum of pixels
m0 = np.su... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Results
|
4,564 | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
# Discretization
c1=20 # Number of grid points per dominant wavelength
c2=0.5 # CFL-Number
nx=2000 # Number of grid points
T=10 # Total propagation time
# Source Signal
f0= 10 # Center frequency Ricker-wave... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Input Parameter
Step2: Preparation
Step3: Create space and time vector
Step4: Source signal - Ricker-wavelet
Step5: Time stepping
Step6: Sa... |
4,565 | <ASSISTANT_TASK:>
Python Code:
# This cell loads the data and cleans it for you, and log10 transforms the drug resistance values.
# Remember to run this cell if you want to have the data loaded into memory.
DATA_HANDLE = 'drug_data/hiv-protease-data.csv' # specify the relative path to the protease drug resistance data... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Problem Set on Machine Learning
Step2: Question
Step3: Question
|
4,566 | <ASSISTANT_TASK:>
Python Code:
import SimpleITK as sitk
import numpy as np
%matplotlib inline
import gui
from matplotlib import pyplot as plt
from ipywidgets import interact, fixed
# Utility method that either downloads data from the Girder repository or
# if already downloaded returns the file name for reading from di... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Creating and Manipulating Transforms
Step2: Transform are defined by two sets of parameters, the Parameters and FixedParameters. FixedParamete... |
4,567 | <ASSISTANT_TASK:>
Python Code:
import steps.interface
from steps.model import *
from steps.geom import *
from steps.sim import *
from steps.saving import *
from steps.rng import *
import numpy as np
import math
# Potassium conductance = 0.036 S/cm2
# Potassium single-channel conductance
K_G = 20.0e-12 # Siemens
# Pota... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Next we define some parameters for the simulation, which are intended to remain constant throughout the script. We start with the potassium chan... |
4,568 | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
import pandas as pd
import numpy as np
import scipy.stats as st
from scipy.stats import norm
import matplotlib.pyplot as plt
import seaborn as sns
sns.set(color_codes=True)
from IPython.core.display import HTML
css = open('style-table.css').read() + open('style-notebook... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: So, we see that we have 130 data points to work with. First, we want to take a look at the overall distribution.
Step2: We see that our sample ... |
4,569 | <ASSISTANT_TASK:>
Python Code:
crime_rate_data = graphlab.SFrame.read_csv('Philadelphia_Crime_Rate_noNA.csv')
crime_rate_data
graphlab.canvas.set_target('ipynb')
crime_rate_data.show(view='Scatter Plot', x = "CrimeRate", y = "HousePrice")
crime_model = graphlab.linear_regression.create(crime_rate_data,
... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Fit the regression model using crime rate as the feature
Step2: Look at the fit of the (initial) model
Step3: We can see that there is an outl... |
4,570 | <ASSISTANT_TASK:>
Python Code:
import pandas as pd
%matplotlib inline
import numpy as np
from sklearn.linear_model import LogisticRegression
df = pd.read_csv("../data/hanford.csv")
df.describe()
df['Mortality'].hist(bins=5)
df['Mortality'].mean()
df['Mort_high'] = df['Mortality'].apply(lambda x:1 if x>=147.1 else 0)... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: 2. Read in the hanford.csv file in the data/ folder
Step2: <img src="../../images/hanford_variables.png"></img>
Step3: 4. Find a reasonable th... |
4,571 | <ASSISTANT_TASK:>
Python Code:
from gvanim import Animation
from gvanim.jupyter import interactive
ga = Animation()
heap = [ None, 5, 6, 7, 8, 9, 10, 11, 12 ]
ga.label_node( 1, heap[ 1 ] )
for i in range( 2, len( heap ) ):
ga.label_node( i, heap[ i ] )
ga.add_edge( i // 2, i )
def down_heap( i, n ):
t = ... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Define an heap
Step2: Now draw it (nodes will be named as the array indices and labelled as the array values)
Step3: Define the usual iterativ... |
4,572 | <ASSISTANT_TASK:>
Python Code:
with open('../pipeline/data/Day90ApartmentData.json') as g:
my_dict2 = json.load(g)
dframe = DataFrame(my_dict2)
dframe = dframe.T
dframe = dframe[['content', 'laundry', 'price', 'dog', 'bed',
'bath', 'feet', 'long', 'parking', 'lat', 'smoking', 'getphotos',
'cat', 'hasmap', 'wheel... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step2: Clean up the data a bit
Step3: It looks like Portland!!!
Step4: We'll use K Means Clustering because that's the clustering method I recently l... |
4,573 | <ASSISTANT_TASK:>
Python Code:
X = np.array([[-1, -1], [-2, -1], [-3, -2], [1, 1], [2, 1], [3, 2]])
plt.scatter(X[:,0], X[:,1], s=100)
plt.xlim(-4,4)
plt.ylim(-3,3)
plt.title("original data")
plt.show()
from sklearn.decomposition import PCA
pca = PCA(n_components=2)
pca.fit(X)
Z = pca.transform(X)
Z
w, V = np.linalg.ei... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: 위로 세워지지 않고 옆으로 뻗은 이유는 확률 변수의 좌표 변환 이야기를 다시 하는 것이다.~~
Step2: IRIS 데이터의 예
Step3: 이미지 PCA
Step4: 다차원 공간에서 그림 1개는 점 1개이다. 예를 들어 0 한 개는 어느 한 공간(다른... |
4,574 | <ASSISTANT_TASK:>
Python Code:
import sys
import warnings
warnings.filterwarnings("ignore")
import numpy as np
import PIL
from matplotlib import pyplot as plt
from tqdm import tqdm
%matplotlib inline
# the following line is not required if BatchFlow is installed as a python package.
sys.path.append('../..')
from batchf... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: You don't need to implement a MNIST dataset. It is already done for you.
Step2: We can use deep learning frameworks such as TensorFlow or PyTor... |
4,575 | <ASSISTANT_TASK:>
Python Code:
def int_montecarlo1(f, a, b, N):
# Evaluación numérica de integrales por Montecarlo tipo 1
# f=f(x) es la función a integrar (debe ser declarada previamente) que devuelve para cada x su valor imagen,
# a y b son los límites inferior y superior del intervalo donde se integrará ... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Considere las funciones $f_1(x)=\sqrt{1+x^{4}}$, $f_2(x)=\ln(\ln x)$, $f_3(x)=\frac {1}{\ln x}$, $f_4(x)=e^{e^{x}}$, $f_5(x)=e^{-{\frac {x^{2}}{... |
4,576 | <ASSISTANT_TASK:>
Python Code:
# Authors: Denis Engemann <denis.engemann@gmail.com>
#
# License: BSD (3-clause)
import mne
from mne import io
from mne.event import define_target_events
from mne.datasets import sample
import matplotlib.pyplot as plt
print(__doc__)
data_path = sample.data_path()
raw_fname = data_path + ... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Set parameters
Step2: Find stimulus event followed by quick button presses
Step3: View evoked response
|
4,577 | <ASSISTANT_TASK:>
Python Code:
from pred import Predictor
from pred import sequence_vector
from pred import chemical_vector
par = ["pass", "ADASYN", "SMOTEENN", "random_under_sample", "ncl", "near_miss"]
for i in par:
print("y", i)
y = Predictor()
y.load_data(file="Data/Training/k_acetylation.csv")
y.p... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Controlling for Random Negatve vs Sans Random in Imbalanced Techniques using K acytelation.
Step2: Chemical Vector
|
4,578 | <ASSISTANT_TASK:>
Python Code:
from pygmyhdl import *
initialize()
# The following function will define a chunk of logic, hence the @chunk decorator precedes it.
# The blinker logic takes three inputs:
# clk_i: This is a clock signal input.
# led_o: This is an output signal that drives an LED on and off.
# le... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: After importing, set up the module to get it ready for what comes next
Step2: Next, the logic that blinks the LED is defined
Step3: The blinke... |
4,579 | <ASSISTANT_TASK:>
Python Code:
# Import the Kotta module
from kotta import Kotta, KottaJob
from kotta.kotta_functions import *
# Create a Kotta Connection using Login with Amazon credentials
# The token from Kotta is stored in the auth.file
konn = Kotta(open('../auth.file').read())
''' A typical python function
my... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: A simple python function
Step2: Running my_sum on Kotta
Step3: Running my_sum on Kotta non-blocking
Step4: Handling errors
|
4,580 | <ASSISTANT_TASK:>
Python Code:
from lightning import Lightning
from numpy import random, zeros
lgn = Lightning(ipython=True, host='http://public.lightning-viz.org')
x = random.randn(100)
y = random.randn(100)
lgn.scatter(x, y, brush=True, zoom=False)
x = random.rand(100) * 10
y = random.rand(100) * 10
viz = lgn.scat... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Connect to server
Step2: <hr> Adding brushing
Step3: <hr> Getting selections
Step4: Let's say I use the brush in the visualization above to s... |
4,581 | <ASSISTANT_TASK:>
Python Code:
x = int(input("Please enter an integer: "))
x
if x < 0:
x = 0
print('Negative changed to zero')
elif x == 0:
print('Zero')
elif x == 1:
print('Single')
else:
print('More')
# Measure some strings:
words = ['cat', 'window', 'defenestrate']
for w in words:
print(w, l... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: for Statements
Step2: The range() Function
Step3: In many ways the object returned by range() behaves as if it is a list, but in fact it isn’t... |
4,582 | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
from time import time, sleep
import numpy as np
import matplotlib.pyplot as plt
from IPython import display
--------------------------------------
-- Tech note
--------------------------------------
Inspired by torch I would use
np.multiply, np... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step2: Важно
Step4: Optimizer is implemented for you.
Step5: Toy example
Step6: Define a logistic regression for debugging.
Step7: Start with batch... |
4,583 | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
%load_ext autoreload
%autoreload 2
import os, sys, time, gzip
import pickle as pkl
import numpy as np
import pandas as pd
from scipy.sparse import lil_matrix, issparse, hstack, vstack
import matplotlib.pyplot as plt
import seaborn as sns
from models import MTC
from skle... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Given a new song, recommend to the longest playlist
Step2: Given a new song, recommend to the shortest playlist
Step3: Popularity (in test set... |
4,584 | <ASSISTANT_TASK:>
Python Code:
import sys
sys.path.append('/Users/pradap/Documents/Research/Python-Package/anhaid/py_entitymatching/')
import py_entitymatching as em
import pandas as pd
import os
# Display the versions
print('python version: ' + sys.version )
print('pandas version: ' + pd.__version__ )
print('magellan ... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Matching two tables typically consists of the following three steps
Step2: Block Tables To Get Candidate Set
Step3: Match tuple pairs in candi... |
4,585 | <ASSISTANT_TASK:>
Python Code:
from shenfun import *
from shenfun.la import SolverGeneric1ND
import sympy as sp
r = 1
theta, phi = psi = sp.symbols('x,y', real=True, positive=True)
rv = (r*sp.sin(theta)*sp.cos(phi), r*sp.sin(theta)*sp.sin(phi), r*sp.cos(theta))
N, M = 64, 64
L0 = FunctionSpace(N, 'C', domain=(0, np.p... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Define spherical coordinates $(r, \theta, \phi)$
Step2: We define bases with the domains $\theta \in [0, \pi]$ and $\phi \in [0, 2\pi]$. Also d... |
4,586 | <ASSISTANT_TASK:>
Python Code:
from IPython.display import FileLink, display
display(FileLink('data/NASA_TM_81232.pdf'))
remote_data = True
remote_server_auto = True
case_name = 'caratung-ar-6p0-pitch-8p0'
data_dir='/gpfs/thirdparty/zenotech/home/dstandingford/VALIDATION/CARATUNG'
data_host='dstandingford@vis03'
par... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Define Data Location
Step2: Validation and regression
Step3: Initialise Environment
Step4: Data Connection
Step5: Get control dictionary
Ste... |
4,587 | <ASSISTANT_TASK:>
Python Code:
keep_prob = 0.5
do_dropout = True
import torch
import copy
w1 = torch.randn(4, 4) # 某层的weights
w = copy.deepcopy(w1)
w
def dropout_strict(w, keep_prob):
implement inverted dropout ensuring that the share of kept neurons is strictly keep_prob.
Args:
w (torch.tensor) ... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step2: 用pytorch来实现,尽量做到每层保留的节点为keep_prob * 节点数
Step4: 用numpy来实现,比较简单,当节点数量大时,随机的结果基本能够保证实际保留情况符合保留概率
|
4,588 | <ASSISTANT_TASK:>
Python Code:
import numpy as np
sea_level = 0.5
def wave_height():
hs = np.random.random()
return hs
def wave_period(hs):
tps = np.random.random()
return tps
def water_elevation(hs, tps):
swel = np.random.random()
return swel
def storm_duration(hs, swel):
st_dur = np.random... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step 1 <br>
Step1: Step 2 <br>
Step 3<br>
Step2: Step 4<br>
Step3: Step 5<br>
Step4: Step 6<br>
Step 7<br>
|
4,589 | <ASSISTANT_TASK:>
Python Code:
%load_ext sql
%sql mysql://studentuser:studentpw@mysqlserver/dognitiondb
%sql USE dognitiondb
%config SqlMagic.displaylimit=25
%%sql
SELECT COUNT(breed)
FROM dogs
%%sql
DESCRIBE complete_tests
%%sql
SELECT COUNT(DISTINCT Dog_Guid)
FROM complete_tests
WHERE created_at >= '2014-03-01'
%%... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: The Jupyter interface conveniently tells us how many rows are in our query output, so we can compare the results of the COUNT function to the re... |
4,590 | <ASSISTANT_TASK:>
Python Code:
import graphviz
import nltk
from nltk import Nonterminal
from nltk.parse.generate import generate
from nltk.tree import Tree
def does_tcl_work():
Checks if Tcl is installed and works (e.g. it won't on a headless server).
tree = nltk.tree.Tree('test', [])
try:
tree._rep... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step2: 10. Syntax — Lab exercises
Step4: Disclaimer
Step7: Unfortunately, generate() only generates the sentences in order. Also, it can run into pro... |
4,591 | <ASSISTANT_TASK:>
Python Code:
import numpy as np
from scipy import linalg
#the function to calculate the coefficent
def approx(x, y, n, w):
x = np.matrix(x).transpose()
y = np.matrix(y).transpose()
f, b = x.shape
c, d = y.shape
if c != f or b != d:
print('The Input vector have wrong dimens... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Final Code
Step2: How and Why it work
Step3: we start with f that is a sawthoot wave
Step4: we choose the number of armonichs that we want in... |
4,592 | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
from scipy import integrate
def trapz(f, a, b, N):
Integrate the function f(x) over the range [a,b] with N points.
k = np.arange(1,N)
h = (b-a)/N
I = h*0.5*f(a) + h*0.5*f(b) + h*f(a+k*h).sum()
retur... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step2: Trapezoidal rule
Step3: Now use scipy.integrate.quad to integrate the f and g functions and see how the result compares with your trapz functio... |
4,593 | <ASSISTANT_TASK:>
Python Code:
# DO NOT EDIT !
from pyesdoc.ipython.model_topic import NotebookOutput
# DO NOT EDIT !
DOC = NotebookOutput('cmip6', 'ec-earth-consortium', 'ec-earth3-cc', 'ocean')
# Set as follows: DOC.set_author("name", "email")
# TODO - please enter value(s)
# Set as follows: DOC.set_contrib... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Document Authors
Step2: Document Contributors
Step3: Document Publication
Step4: Document Table of Contents
Step5: 1.2. Model Name
Step6: 1... |
4,594 | <ASSISTANT_TASK:>
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)
view_sentence_range = (0, 10)
DON'T MODIFY AN... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Language Translation
Step3: Explore the Data
Step6: Implement Preprocessing Function
Step8: Preprocess all the data and save it
Step10: Chec... |
4,595 | <ASSISTANT_TASK:>
Python Code:
# DO NOT EDIT !
from pyesdoc.ipython.model_topic import NotebookOutput
# DO NOT EDIT !
DOC = NotebookOutput('cmip6', 'mohc', 'hadgem3-gc31-ll', 'atmos')
# Set as follows: DOC.set_author("name", "email")
# TODO - please enter value(s)
# Set as follows: DOC.set_contributor("name",... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Document Authors
Step2: Document Contributors
Step3: Document Publication
Step4: Document Table of Contents
Step5: 1.2. Model Name
Step6: 1... |
4,596 | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
import matplotlib.pyplot as plt
plt.plot([1,2,3], [4,7, -1], 'bo')
fig1 = plt.figure()
# This line will be pasted in by course attendee.
plt.plot([1,2,3], [4,7,-1], '*r')
fig1.savefig("my_first_plot.jpeg", dpi=300)
import pandas as pd
imp... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Now we need to import the matplotlib plotting library. We use the import and as keyword to do this. The keyword as allows us to replace the leng... |
4,597 | <ASSISTANT_TASK:>
Python Code:
import os
import pandas as pd
try:
os.makedirs(os.path.join("data", "tutorial"))
print("Pasta criada.")
except OSError:
print("Pasta já existe!")
nome do arquivo
file_name = os.path.join("data", "tutorial", "orders.csv")
criação do DataFrame
df = pd.DataFrame(
column... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Operações com Arquivos
Step5: Dataset orders.csv
Step9: Dataset stores.csv
Step13: Dataset product.csv
Step14: Leitura de Arquivos
Step17: ... |
4,598 | <ASSISTANT_TASK:>
Python Code:
# Authors: Alexandre Gramfort <alexandre.gramfort@telecom-paristech.fr>
# Eric Larson <larson.eric.d@gmail.com>
# License: BSD (3-clause)
import os.path as op
import numpy as np
from numpy.random import randn
from scipy import stats as stats
import mne
from mne import (io, spatia... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Set parameters
Step2: Read epochs for all channels, removing a bad one
Step3: Transform to source space
Step4: Transform to common cortical s... |
4,599 | <ASSISTANT_TASK:>
Python Code:
def to_binary(x):
the_sum = 0
# enumerate returns pairs of values from `x`
# as well as the index of each value
for index, value in enumerate(x):
the_sum += value * 2**index
return the_sum
my_list = [1, 1]
to_binary(my_list)
my_list = [1, 0, 0, 0, 1, 1, 0,... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: One note - there are actually 2 possible solutions to this problem, depending on which value of [1, 0, 0, 0, 1, 1, 0, 1] is treated as the least... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.