Unnamed: 0
int64
0
15.9k
cleaned_code
stringlengths
67
124k
cleaned_prompt
stringlengths
168
30.3k
4,000
<ASSISTANT_TASK:> Python Code: import pandas as pd data = pd.read_csv('test_user_data.csv') print(data.head(10)) apply_ex = data.groupby('user_id').apply(len) print(apply_ex.head()) transform_ex = data.groupby('user_id').transform(len) print(transform_ex.head()) data['event_count'] = data.groupby('user_id')['user_id...
<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 data contains one event per row and has 5 variables Step2: The output here is a pandas Series with each user_id as the index and the count ...
4,001
<ASSISTANT_TASK:> Python Code: import cartopy.crs as ccrs import matplotlib.pyplot as plt import xarray as xr %matplotlib inline ds = xr.tutorial.load_dataset("air_temperature") air = ds.air.isel(time=[0, 724]) - 273.15 # This is the map projection we want to plot *onto* map_proj = ccrs.LambertConformal(central_longi...
<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 example dataset Step2: Multiple plots and map projections Step3: Centered colormaps Step4: Control the plot's colorbar Step5: Multiple ...
4,002
<ASSISTANT_TASK:> Python Code: import random gameStake = 50 cards = range(10) class Player: # in the __init__() function, use the two input variables to initialize the ID and starting pot of each player def __init__(self, inputID, startingPot): # [CREATE YOUR INITIALIZATIONS HERE] ...
<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 will establish some general variables for our game, including the 'stake' of the game (how much money each play is worth), as well as a...
4,003
<ASSISTANT_TASK:> Python Code: import rebound sim = rebound.Simulation() sim.add(m=1., x=1., vz = 2.) sim.add(m=1., a=1.) sim.status() sim.add(m=1.e-3, a=100.) sim.add(primary=sim.particles[1], a=0.01) orbits = sim.calculate_orbits() for orbit in orbits: print(orbit) print(sim.particles[3].calculate_orbit(prim...
<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: Any components not passed automatically default to 0. REBOUND can also accept orbital elements. Step2: We always have to pass a semimajor ax...
4,004
<ASSISTANT_TASK:> Python Code: import pandas as pd import numpy as np import exatomic u = exatomic.Universe() u #myxyz = exatomic.XYZ('../data/examples/porphyrin.xyz') myxyz = exatomic.XYZ('porphyrin.xyz') myxyz.head() myxyz.atom.head() # Atomic units are used throughout the exatomic package myuni = myxyz.to_univ...
<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: Here are some test demo containers to play around with Step2: exatomic universes in principle contain a QM/MD calculation or set of calculation...
4,005
<ASSISTANT_TASK:> Python Code: from urllib.request import urlretrieve from os.path import isfile, isdir from tqdm import tqdm vgg_dir = 'tensorflow_vgg/' # Make sure vgg exists if not isdir(vgg_dir): raise Exception("VGG directory doesn't exist!") class DLProgress(tqdm): last_block = 0 def hook(self, block_...
<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: Flower power Step2: ConvNet Codes Step3: Below I'm running images through the VGG network in batches. Step4: Building the Classifier Step5: ...
4,006
<ASSISTANT_TASK:> Python Code: # Authors: Luke Bloy <luke.bloy@gmail.com> # Eric Larson <larson.eric.d@gmail.com> # # License: BSD (3-clause) import os.path as op import numpy as np import mne from mne.cov import compute_covariance from mne.datasets import somato from mne.time_frequency import csd_morlet 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: Reading the raw data and creating epochs Step2: Compute covariances Step3: Compute some source estimates Step4: Plot source estimates Step5: ...
4,007
<ASSISTANT_TASK:> Python Code: from math import exp # Could avoid this by using our constants.py module! h = 6.626e-34 # MKS k = 1.38e-23 c = 3.00e8 def intensity(wave, temp, mydefault=0): wavelength = wave / 1e10 B = 2 * h * c**2 / (wavelength**5 * (exp(h * c / (wavelength * k * temp)) - 1)) return B myw...
<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: Q. Is the following call sequence acceptable? Step2: No! The following are all OK! Step3: Keyword arguments Step4: The first two arguments in...
4,008
<ASSISTANT_TASK:> Python Code: import pandas as pd import numpy as np df1 = pd.DataFrame({'A':['A0','A1','A2','A3'], 'B':['B0','B1','B2','B3'], 'C':['C0','C1','C2','C3'], 'D':['D0','D1','D2','D3']}, index=[0,1,2,3]) df1 df2 = 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: 使用join='inner' 查看结果 ,和outer一样! Step2: 修改df3的index,看看结果 Step3: 修改df5,使得某几行和df2一样,再看看结果 Step4: 如同numpy.concatenate()方法, pandas.concat方法接收一个列表或者...
4,009
<ASSISTANT_TASK:> Python Code: # Run some setup code for this notebook. from __future__ import division import sys import os sys.path.append('..') import graphlab import numpy as np products = graphlab.SFrame('datasets/') # feature processing # --------------------------------------------------------------- import j...
<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 and process review dataset Step2: Just like we did previously, we will work with a hand-curated list of important words extracted from the...
4,010
<ASSISTANT_TASK:> Python Code: %load_ext brythonmagic from brythonmagic import load_brython_dev load_brython_dev() from brythonmagic import load_js_lib load_js_lib("https://cdnjs.cloudflare.com/ajax/libs/highcharts/5.0.7/highcharts.js") html = <div id="hc_ex1" style="width: 700px; height: 300px;"></div> %%brython -...
<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: And the brython js lib Step2: [It is highly recommended that, at least, you read the brythonmagic docs to understand what it does. It is also r...
4,011
<ASSISTANT_TASK:> Python Code: %load_ext watermark %watermark -a 'Sebastian Raschka' -u -d -v -p numpy,pandas,matplotlib,scikit-learn from sklearn.grid_search import GridSearchCV from sklearn.pipeline import Pipeline from sklearn.preprocessing import StandardScaler from sklearn.svm import SVC from sklearn.datasets impo...
<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 Note about GridSearchCV's best_score_ attribute Step2: By executing the code above, we created a simple data set of random integers that shal...
4,012
<ASSISTANT_TASK:> Python Code: import os from io import BytesIO import tarfile import tempfile from six.moves import urllib from matplotlib import gridspec from matplotlib import pyplot as plt import numpy as np from PIL import Image import tensorflow as tf class DeepLabModel(object): Class to load deeplab model and...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step7: Import helper methods Step8: Select a pretrained model Step10: Run on sample images
4,013
<ASSISTANT_TASK:> Python Code: import numpy as np import pandas as pd from sympy import * init_printing() from myhdl import * from myhdlpeek import * import random #python file of convince tools. Should be located with this notebook from sympy_myhdl_tools import * def DFFSyncCenter(D_in, Q_out, Qn_out, clk): @alwa...
<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: Flip-Flops vs Latches Step2: Sythinsis Step3: !? clock in not hooked up on the wiring in this code need to figure out why Step4: Sythinsis St...
4,014
<ASSISTANT_TASK:> Python Code: import pandas imdb = pandas.read_csv('data/imdb_labelled.txt', sep="\t", names=["sentences", "polarity"]) yelp = pandas.read_csv('data/yelp_labelled.txt', sep="\t", names=["sentences", "polarity"]) amazon = pandas.read_csv('data/amazon_cells_labelled.txt', sep="\t", names=["sentences", "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: 1. Tokenization Step2: 1. Dicionário Step3: 1. Vetorização Step4: 1. Word normalization
4,015
<ASSISTANT_TASK:> Python Code: # Import matplotlib import matplotlib # Import pandas import pandas as pd # Tell matplotlib to plot in this window instead of a separate window. %matplotlib inline # Load data into dataframe (we will get to this later) df = pd.read_csv('data/simple.csv') # Plot data as line plot using sim...
<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: As you get more experienced you may want to use matplotlib directly
4,016
<ASSISTANT_TASK:> Python Code: %load_ext autoreload %autoreload 2 from LogGabor import LogGabor parameterfile = 'https://raw.githubusercontent.com/bicv/LogGabor/master/default_param.py' lg = LogGabor(parameterfile) lg.set_size((32, 32)) import os import numpy as np np.set_printoptions(formatter={'float': '{: 0.3f}'.fo...
<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 install the dependencies related to running this notebook, see Installing notebook dependencies. Step2: Perspectives Step3: Back to top Ste...
4,017
<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 classes from thinkbayes2 from thinkbayes2 import Pmf, Cdf, Suite, J...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step4: The Weibull distribution Step5: SciPy also provides functions to evaluate the Weibull distribution, which I'll use to check my implementation. ...
4,018
<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 library from modsim import * # set the ra...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step5: More than one State object Step7: And here's run_simulation, which is a solution to the exercise at the end of the previous notebook. Step8: N...
4,019
<ASSISTANT_TASK:> Python Code: import pyisc; import numpy as np from scipy.stats import poisson %matplotlib inline from pylab import hist, plot, figure po_normal = poisson(10) po_anomaly = poisson(25) freq_normal = po_normal.rvs(10000) freq_anomaly = po_anomaly.rvs(15) data = np.column_stack([ list(freq_norma...
<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 Creation Step2: Create an 2D array with two columns that combines random frequency and time period equal to 1. Step3: If we plot the hist...
4,020
<ASSISTANT_TASK:> Python Code: import numpy as np import matplotlib.pyplot as plt from sklearn import svm, datasets from sklearn.metrics import roc_curve, auc from sklearn.model_selection import train_test_split bc = datasets.load_breast_cancer() X = bc.data y = bc.target random_state = np.random.RandomState(0) # shuf...
<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: Import some data to play with Step2: Split the data and prepare data for ROC Curve Step3: Plot ROC Curve using Matplotlib Step4: Create ROCAU...
4,021
<ASSISTANT_TASK:> Python Code: def aquire_audio_data(): D, T = 4, 10000 y = np.random.normal(size=(D, T)) return y y = aquire_audio_data() Y = stft(y, **stft_options).transpose(2, 0, 1) with tf.Session() as session: Y_tf = tf.placeholder( tf.complex128, shape=(None, None, None)) Z_tf = wpe(Y...
<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: Example with real audio recordings Step2: Audio data Step3: STFT Step4: iterative WPE Step5: Power spectrum
4,022
<ASSISTANT_TASK:> Python Code: from __future__ import absolute_import from __future__ import division from __future__ import print_function import inspect import time import numpy as np import tensorflow as tf from tensorflow.python.framework import ops from tensorflow.python.framework import dtypes #import reader impo...
<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: MSCOCO Captions Step2: How can you look at feature maps from the first convolutional layer? Look here if you need a hint. Step3: How can you l...
4,023
<ASSISTANT_TASK:> Python Code: import csv import requests response = requests.get("http://api.open-notify.org/iss-now.json") response.status_code # Set up the parameters we want to pass to the API. # This is the latitude and longitude of New York City. parameters = {"lat": 40.71, "lon": -74} # Make a get request with...
<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: Status Codes Step2: Query Parameters
4,024
<ASSISTANT_TASK:> Python Code: %matplotlib inline %config InlineBackend.figure_format = 'retina' import pickle as pkl import numpy as np import tensorflow as tf import matplotlib.pyplot as plt from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets('MNIST_data') def model_inputs(re...
<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: Model Inputs Step2: Generator network Step3: Discriminator Step4: Hyperparameters Step5: Build network Step6: Discriminator and Generator L...
4,025
<ASSISTANT_TASK:> Python Code: DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE from urllib.request import urlretrieve from os.path import isfile, isdir from tqdm import tqdm import problem_unittests as tests import tarfile cifar10_dataset_folder_path = 'cifar-10-batches-py' class DLProgress(tqdm): last_b...
<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: Image Classification Step2: Explore the Data Step5: Implement Preprocess Functions Step8: One-hot encode Step10: Randomize Data Step12: Che...
4,026
<ASSISTANT_TASK:> Python Code: import pandas as pd import numpy as np import scipy.optimize import scipy.special import matplotlib.pyplot as plt import seaborn as sns import pathlib import sys import PaSDqc %matplotlib inline sample_mda = PaSDqc.PSDTools.SamplePSD.load_from_file("../data/intro_PSDs/example_MDA.spec", ...
<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 using PaSDqc API Step2: Load normalization file included in PaSDqc package Step3: Fit the amplicon distribution curves using the erf...
4,027
<ASSISTANT_TASK:> Python Code: def loadContributions(file, withsexe=False): contributions = pd.read_json(path_or_buf=file, orient="columns") rows = []; rindex = []; for i in range(0, contributions.shape[0]): row = {}; row['id'] = contributions['id'][i] rindex.append(contributions...
<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: Build clustering model Step2: Build the optimal model and apply it Step3: Cluster Profiles
4,028
<ASSISTANT_TASK:> Python Code: import pg8000 conn = pg8000.connect(user='postgres', password='password', database="homework2_radhika") conn.rollback() conn.rollback() cursor = conn.cursor() statement = "SELECT movie_title, release_date from uitem WHERE horror=1 AND scifi=1 ORDER BY release_date DESC;" cursor.execute...
<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: If you get an error stating that database "homework2" does not exist, make sure that you followed the instructions above exactly. If necessary, ...
4,029
<ASSISTANT_TASK:> Python Code: import sys sys.path.append('../code/functions') sys.path.append('/home/simpleElastix/build/SimpleITK-build/Wrapping/Python') import pickle import cv2 import time import SimpleITK as sitk import numpy as np import matplotlib.pyplot as plt import nibabel as nib from cluster import Cluster 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: Visualization Function Step2: Registration Functions
4,030
<ASSISTANT_TASK:> Python Code: import wicked as w from IPython.display import display, Math, Latex def latex(expr): Function to render any object that has a member latex() function display(Math(expr.latex())) w.reset_space() w.add_space("o", "fermion", "occupied", ['i','j','k','l','m','n']) w.add_space("...
<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: Generating and implementing many-body equations Step2: Generating equations for fully contracted terms Step3: First we convert the expression ...
4,031
<ASSISTANT_TASK:> Python Code: # We'll also import a few standard python libraries from matplotlib import pyplot import numpy as np import time # These are the droids you are looking for. from caffe2.python import core, workspace from caffe2.proto import caffe2_pb2 # Let's show all plots inline. %matplotlib inline pri...
<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 might see a warning saying that caffe2 does not have GPU support. That means you are running a CPU-only build. Don't be alarmed - anything C...
4,032
<ASSISTANT_TASK:> Python Code: # In iPython or the iPython notebook, it's easiest to use the pylab magic, which # imports matplotlib, numpy, and scipy. # The inline flag means that images will be shown here in the notebooks, rather # than in pop-up windows. %pylab notebook # If you are using 'regular' Python, however, ...
<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 figures Step2: In this case, x is now a NumPy array with 300 values ranging from 0 to 2$\pi$ (included). y is the sine (array of 300 v...
4,033
<ASSISTANT_TASK:> Python Code: %matplotlib inline import pandas as pd import numpy as np import matplotlib.pyplot as plt def load_pts(csv_name): data = np.asarray(pd.read_csv(csv_name, header=None)) X = data[:,0:2] y = data[:,2] plt.scatter(X[np.argwhere(y==0).flatten(),0], X[np.argwhere(y==0).flatten(...
<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: 1.阅读并绘制数据 Step2: 该函数将帮助我们绘制模型。 Step3: 2. 将我们的数据分为训练和测试集 Step4: 3. 拟合一个决策树模型 Step5: Now let's plot the model, and find the testing f1_score, ...
4,034
<ASSISTANT_TASK:> Python Code: %matplotlib inline import os import numpy as np import pandas as pd from matplotlib import pyplot as plt from PyFin.api import * from alphamind.api import * from alphamind.strategy.strategy import Strategy, RunningSetting from alphamind.portfolio.meanvariancebuilder import target_vol_buil...
<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: 1. Single Day Analysis Step2: Portfolio Construction Step8: 2. Porfolio Construction
4,035
<ASSISTANT_TASK:> Python Code: DON'T MODIFY ANYTHING IN THIS CELL import helper data_dir = './data/simpsons/moes_tavern_lines.txt' text = helper.load_data(data_dir) # Ignore notice, since we don't use it for analysing the data text = text[81:] view_sentence_range = (0, 10) DON'T MODIFY ANYTHING IN THIS CELL 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: TV Script Generation Step3: Explore the Data Step6: Implement Preprocessing Functions Step9: Tokenize Punctuation Step11: Preprocess all the...
4,036
<ASSISTANT_TASK:> Python Code: import sys print(sys.version) from typing import List, Tuple Position = int Interval = Tuple[Position, Position] import re def bad_events(pattern: str, string: str) -> List[Interval]: # m.span(1) = (m.start(1), m.end(1)) return [m.span(1) for m in re.finditer(f"(?=({pattern}))", ...
<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: Introduction Step2: The solution I came up with Step3: Let's compute the union of two consecutive intervals, if they are not disjoint Step4: ...
4,037
<ASSISTANT_TASK:> Python Code: %matplotlib inline import numpy as np from matplotlib import pyplot as plt from mdtraj.utils import timing from msmbuilder.example_datasets import load_doublewell from msmbuilder.cluster import NDGrid from msmbuilder.msm import BayesianMarkovStateModel, MarkovStateModel trjs = load_doubl...
<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 some double-well data Step2: We'll discretize the space using 10 states Step3: Now lets try using 50 states
4,038
<ASSISTANT_TASK:> Python Code: from datetime import datetime import matplotlib.pyplot as plt import metpy.calc as mpcalc from metpy.io import get_upper_air_data from metpy.io.upperair import UseSampleData from metpy.plots import SkewT with UseSampleData(): # Only needed to use our local sample data # Download and ...
<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 a new figure. The dimensions here give a good aspect ratio
4,039
<ASSISTANT_TASK:> Python Code: from xml.etree import ElementTree as ET document_tree = ET.parse( './data/mondial_database_less.xml' ) # print names of all countries for child in document_tree.getroot(): print (child.find('name').text) # print names of all countries and their cities for element in document_tree.ite...
<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: XML example Step2: XML exercise Step3: 10 countries with the lowest infant mortality rates Step4: 10 cities with the largest population Step5...
4,040
<ASSISTANT_TASK:> Python Code: # Make plots inline %matplotlib inline # Make inline plots vector graphics instead of raster graphics from IPython.display import set_matplotlib_formats set_matplotlib_formats('pdf', 'svg') # import modules for plotting and data analysis import matplotlib.pyplot as plt import numpy as 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: Step1: Now, we'll tackle the "function in time" part of this model by learning how to make and use arrays to represent time. Step2: We can assign time...
4,041
<ASSISTANT_TASK:> Python Code: %matplotlib inline from ecell4.prelude import * sp1 = Species("A") print(sp1.serial()) sp1.set_attribute("radius", 0.005) sp1.set_attribute("D", 1) sp1.set_attribute("location", "cytoplasm") print(sp1.has_attribute("radius")) print(sp1.get_attribute("radius")) print(sp1.get_attribute("r...
<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.1. Species Step2: There are some naming conventions for the name of Species. Step3: The arguments in set_attribute is the name of attribute ...
4,042
<ASSISTANT_TASK:> Python Code: %matplotlib inline import os import sys sys.path.append(os.path.join('..', '..')) from data_models.parameters import arl_path results_dir = arl_path('test_results') from matplotlib import pylab pylab.rcParams['figure.figsize'] = (8.0, 8.0) pylab.rcParams['image.cmap'] = 'rainbow' import n...
<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: Construct LOW core configuration Step2: We create the visibility. This just makes the uvw, time, antenna1, antenna2, weight columns in a table ...
4,043
<ASSISTANT_TASK:> Python Code: # A bit of setup import numpy as np import matplotlib.pyplot as plt from cs231n.classifiers.neural_net import TwoLayerNet %matplotlib inline plt.rcParams['figure.figsize'] = (10.0, 8.0) # set default size of plots plt.rcParams['image.interpolation'] = 'nearest' plt.rcParams['image.cmap'] ...
<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: Implementing a Neural Network Step2: We will use the class TwoLayerNet in the file cs231n/classifiers/neural_net.py to represent instances of o...
4,044
<ASSISTANT_TASK:> Python Code: # DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'cmcc', 'sandbox-3', 'aerosol') # Set as follows: DOC.set_author("name", "email") # TODO - please enter value(s) # Set as follows: DOC.set_contributor("name", "em...
<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,045
<ASSISTANT_TASK:> Python Code:: import pandas as pd X = pd.get_dummies(X, columns=['neighbourhood_group','room_type'], drop_first=True) <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:
4,046
<ASSISTANT_TASK:> Python Code: %%file multihello.py '''hello from another process ''' from multiprocessing import Process def f(name): print 'hello', name if __name__ == '__main__': p = Process(target=f, args=('world',)) p.start() p.join() # EOF !python2.7 multihello.py if __name__ == '__main__': ...
<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: On Windows Step2: Data parallelism versus task parallelism Step3: Manager and proxies Step4: See Step5: Issues Step6: Queue and Pipe Step7:...
4,047
<ASSISTANT_TASK:> Python Code: # Function for rotating the image files. def Image_Rotate(img, angle): Rotates a given image the requested angle. Returns the rotated image. rows,cols = img.shape M = cv2.getRotationMatrix2D((cols/2,rows/2), angle, 1) return(cv2.warpAffine(img,M,(cols,rows))) # 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: Step2: Image_Augmentation Step4: VGG_Prep Step5: VGG_16 Bottleneck Step6: Running the model on the Train, Test, and Validation Data Step7: Train To...
4,048
<ASSISTANT_TASK:> Python Code: # Import required modules import pandas as pd # Create a values as dictionary of lists raw_data = {'0': ['first_name', 'Molly', 'Tina', 'Jake', 'Amy'], '1': ['last_name', 'Jacobson', 'Ali', 'Milner', 'Cooze'], '2': ['age', 52, 36, 24, 73], '3': ['preTestScore',...
<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 example data Step2: Replace the header value with the first row's values
4,049
<ASSISTANT_TASK:> Python Code: # General imports %matplotlib inline import logging import numpy as np import pylab as plt from scipy import stats from scipy import integrate from scipy.integrate import simps,trapz,quad,nquad from scipy.interpolate import interp1d from scipy.misc import factorial # Constants MMIN,MMAX ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step3: Constants and Defaults Step6: Subhalo Mass Function Step10: Substructure Likelihood Function Step12: Mass Probability Step14: Likelihood Fun...
4,050
<ASSISTANT_TASK:> Python Code: from SimPEG import Mesh, EM, Utils, Maps from matplotlib.colors import LogNorm %pylab inline import numpy as np from scipy.constants import mu_0 from ipywidgets import interact, IntSlider import cPickle as pickle url = "https://storage.googleapis.com/simpeg/kevitsa_synthetic/" files = ['d...
<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: Model Step2: Question Step3: Next, we put the model on the mesh Step4: Forward Simulation Step5: Compute Predicted Data Step6: Question Ste...
4,051
<ASSISTANT_TASK:> Python Code: G = nx.Graph() #create a graph G.add_nodes_from([0,1,2,3]) #add some nodes G.add_edges_from([(0,1),(1,2),(2,3),(3,0)]) #add some edges pos = {0:[1,1],1:[1,2],2:[2,3],3:[3,2]} #dictionary of positions nx.draw_networkx(G,pos) ...
<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: Graph layouts Step2: Draw only specific nodes Step3: Colors Step4: Plotting with node/edge attributes
4,052
<ASSISTANT_TASK:> Python Code: ## import system module import json import rethinkdb as r import time import datetime as dt import asyncio from shapely.geometry import Point, Polygon import random import pandas as pd import os import matplotlib.pyplot as plt ## import custom module from streettraffic.server import Traff...
<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: Generate Random Routes Step2: Now we simply copy the text above and go to https Step4: Use the web UI Step5: Be Bold and try 100 routes
4,053
<ASSISTANT_TASK:> Python Code: try: import cirq except ImportError: print("installing cirq...") !pip install --quiet cirq import cirq print("installed cirq.") # Standard imports import numpy as np from cirq.contrib.svg import SVGCircuit exponents = np.linspace(0, 7/4, 8) exponents import itertools...
<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: Cross Entropy Benchmarking Theory Step2: The action of random circuits with noise Step3: Random circuit Step4: Estimating fidelity Step5: Ex...
4,054
<ASSISTANT_TASK:> Python Code: print("Hello, world!") x = 5 type(x) y = 5.5 type(y) x = 5 * 5 type(x) y = 5 / 5 type(y) x = 5 / 5 type(x) y = int(x) type(y) z = str(y) type(z) some_list = [1, 2, 'something', 6.2, ["another", "list!"], 7371] print(some_list[3]) type(some_list) some_tuple = (1, 2, 'something', 6.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: Yep, that's all that's needed! Step2: It's important to note Step3: What's the type for x? Step4: What's the type for y? Step5: There are fu...
4,055
<ASSISTANT_TASK:> Python Code: print(__doc__) # Authors: Gael Varoquaux # Jaques Grobler # Kevin Hughes # License: BSD 3 clause from sklearn.decomposition import PCA from mpl_toolkits.mplot3d import Axes3D import numpy as np import matplotlib.pyplot as plt from scipy import stats e = np.exp(1) np.ran...
<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 data Step2: Plot the figures
4,056
<ASSISTANT_TASK:> Python Code: from IPython.display import YouTubeVideo YouTubeVideo('sDG5tPtsbSA', width=800, height=450) from os.path import join image_dir = '../input/dog-breed-identification/train/' img_paths = [join(image_dir, filename) for filename in ['0c8fe33bd89646b678f6b2891df8a1c...
<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: Sample Code Step2: Function to Read and Prep Images for Modeling Step3: Create Model with Pre-Trained Weights File. Make Predictions Step4: V...
4,057
<ASSISTANT_TASK:> Python Code: import numpy as np import matplotlib.pyplot as plt import structcol as sc from structcol import refractive_index as ri from structcol import montecarlo as mc from structcol import detector as det import pymie as pm from pymie import size_parameter, index_ratio import seaborn as sns impor...
<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: Run Monte Carlo model and calculate reflectance and polarization for trajectories Step2: initialize and run trajectories Step3: calculate refl...
4,058
<ASSISTANT_TASK:> Python Code: #Original data source #http:§§//www.content.digital.nhs.uk/catalogue/PUB23139 #Get the datafile !wget -P data http://www.content.digital.nhs.uk/catalogue/PUB23139/gp-reg-patients-LSOA-alt-tall.csv #Import best ever data handling package import pandas as pd #Load downloaded CSV file df=pd....
<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: Previously, I have created a simple sqlite3 database containing administrative open data from NHS Digital (database generator script). Step2: L...
4,059
<ASSISTANT_TASK:> Python Code: %matplotlib inline import numpy as np from sklearn import datasets from sklearn.cross_validation import train_test_split from sklearn.preprocessing import StandardScaler # Initialize the random generator seed to compare results np.random.seed(0) # Load Iris data set iris = datasets.load_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: Part 1 Step2: Next code, let you plot the evolution of above computed train and test accuracies. Step3: This figure points out the necessity o...
4,060
<ASSISTANT_TASK:> Python Code: import ipyparallel as ipp c = ipp.Client(profile='mpi') %%px --group-outputs=engine from mpi4py import MPI print(f"Hi, I'm rank %d." % MPI.COMM_WORLD.rank) %%px from devito import configuration configuration['mpi'] = True %%px # Keep generated code as simple as possible configuration['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: In this tutorial, to run commands in parallel over the engines, we will use the %px line magic. Step2: Overview of MPI in Devito Step3: An Ope...
4,061
<ASSISTANT_TASK:> Python Code: import time import random #import sys #a = int(sys.argv[1]) #b = int(sys.argv[2]) def wait(x): time.sleep(x) def time_cron(a,b): time_interval = random.uniform(a,b) # while(1): # measure process time t0 = time.clock() wait(time_interval) print time.clock() - t0...
<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) Scrieti doua functii de verificare daca un numar este prim, si verificati care dintre ele este mai eficienta din punct de vedere al timpului....
4,062
<ASSISTANT_TASK:> Python Code: from pymldb import Connection mldb = Connection("http://localhost") mldb.get("/v1/types") #keyword arguments to get() are appended to the GET query string mldb.get("/v1/types", x="y") #dictionaries arguments to put() and post() are sent as JSON via PUT or POST mldb.put("/v1/datasets/samp...
<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: Accessing the REST API Step2: Here we create a dataset and insert two rows of two columns into it Step3: SQL Queries
4,063
<ASSISTANT_TASK:> Python Code: %%bash echo "Pip Version Info: " && python2 --version && python2 -m pip --version && echo echo "Google Cloud SDK Info: " && gcloud --version && echo echo "Ksonnet Version Info: " && ks version && echo echo "Kubectl Version Info: " && kubectl version ! python2 -m pip install -U pip # Code...
<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 Pip Packages Step2: Configure Variables Step3: Setup Authorization Step4: Additionally, to interact with the underlying cluster, we c...
4,064
<ASSISTANT_TASK:> Python Code: # To support both python 2 and python 3 from __future__ import division, print_function, unicode_literals # Common imports import numpy as np import os # to make this notebook's output stable across runs np.random.seed(42) # To plot pretty figures %matplotlib inline import matplotlib as m...
<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: Linear regression using the Normal Equation Step2: The figure in the book actually corresponds to the following code, with a legend and axis la...
4,065
<ASSISTANT_TASK:> Python Code: import numpy as np from emo_utils import * import emoji import matplotlib.pyplot as plt %matplotlib inline X_train, Y_train = read_csv('data/train_emoji.csv') X_test, Y_test = read_csv('data/tesss.csv') maxLen = len(max(X_train, key=len).split()) index = 1 print(X_train[index], label_to...
<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: 1 - Baseline model Step2: Run the following cell to print sentences from X_train and corresponding labels from Y_train. Change index to see dif...
4,066
<ASSISTANT_TASK:> Python Code:: import matplotlib.pyplot as plt plt.scatter(x, y) plt.show() <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:
4,067
<ASSISTANT_TASK:> Python Code: import matplotlib.pyplot as plt import matplotlib.image as mpimg import numpy as np import cv2 import pandas import os def getPathFor(file_path): current_directory = %pwd path = os.path.join(current_directory, file_path) print("About to open file: {}\n".format(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: Next class is responsible for filtering out lanes detection area Step2: Here is the result of getColorMask function, that turns all white and y...
4,068
<ASSISTANT_TASK:> Python Code: %matplotlib inline from random import random import math import numpy as np import copy from scipy import stats import matplotlib.pyplot as plt import pickle as pkl from scipy.spatial import distance import seaborn as sns sns.set_style('darkgrid') def loadMovieLens(path='./data/movielens...
<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: Loading the data Step2: Content example Step3: Splitting data between train/test Step4: split used for convenience on the average by movie ba...
4,069
<ASSISTANT_TASK:> Python Code: import os os.environ['TF_CPP_MIN_LOG_LEVEL']='2' import numpy as np np.set_printoptions(threshold=np.nan) import tensorflow as tf import time import pandas as pd import matplotlib.pyplot as plt import progressbar data_path = 'https://raw.githubusercontent.com/michaelneuder/image_quality_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: everything looks good with c,s, cxs. now to check the down sampled images as well as luminance.
4,070
<ASSISTANT_TASK:> Python Code: mylist = [1, 4, -5, 10, -7, 2, 3, -1] [n for n in mylist if n > 0] [n for n in mylist if n < 0] pos = (n for n in mylist if n > 0) pos for x in pos: print(x) values = ['1', '2', '-3', '-', '4', 'N/A', '5'] def is_int(val): try: x = int(val) return True except...
<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: 有时候,过滤规则比较复杂,不能简单的在列表推导或者生成器表达式中表达出来。 比如,假设过滤的时候需要处理...
4,071
<ASSISTANT_TASK:> Python Code: # https://github.com/dfm/corner.py import corner import hydropy as hp mpl.rcParams['font.size'] = 16 mpl.rcParams['axes.labelsize'] = 18 mpl.rcParams['xtick.labelsize'] = 16 mpl.rcParams['ytick.labelsize'] = 16 import pylab as p p.rc('mathtext', default='it') from biointense.model impor...
<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: Respirometer model in pyIDEAS Step2: We define the model equations and set up the model Step3: Reading in the observations Step4: Decubber th...
4,072
<ASSISTANT_TASK:> Python Code: from pynq.overlays.base import BaseOverlay base = BaseOverlay("base.bit") from pynq.lib import Pmod_PWM pwm = Pmod_PWM(base.PMODA,0) import time # Generate a 10 us clocks with 50% duty cycle period=10 duty=50 pwm.generate(period,duty) # Sleep for 4 seconds and stop the timer time.sleep(...
<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. Connect Scope Step2: 3. Generate a clock of $50\%$ duty cycle and $10\,\mu$s period Step3: 4. Generate a clock of $25\%$ duty cycle and $20...
4,073
<ASSISTANT_TASK:> Python Code: import os import sys import numpy as np import pandas as pd from matplotlib import pyplot as plt from pathlib import Path import tensorflow as tf %matplotlib notebook #%matplotlib inline models_data_folder = Path.home() / "Documents/models/" # create and add up two constants a = tf.const...
<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: Core (Low Level APIs) Step2: Eager Execution Step3: Dataset API Step4: Save and Restore Variables Step5: Save and Restore a Model Step6: Se...
4,074
<ASSISTANT_TASK:> Python Code: # importing import numpy as np import matplotlib.pyplot as plt import matplotlib # showing figures inline %matplotlib inline # plotting options font = {'size' : 20} plt.rc('font', **font) plt.rc('text', usetex=True) matplotlib.rc('figure', figsize=(18, 6) ) # Function for Generating 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: Step2: Function for Random Walks Step3: Showing a Bunch of Realizations for a Random Walk Step4: Determining ACF of the Random Walk
4,075
<ASSISTANT_TASK:> Python Code: import o2sclpy import matplotlib.pyplot as plot import sys import math import numpy from sklearn.gaussian_process import GaussianProcessRegressor from sklearn.gaussian_process.kernels import RBF, ConstantKernel plots=True if 'pytest' in sys.modules: plots=False link=o2sclpy.linker() ...
<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: Link the o2scl library Step2: Create a sample function to interpolate Step3: Create sample data from our function Step4: Compute the mean and...
4,076
<ASSISTANT_TASK:> Python Code: from __future__ import division from IPython.display import display import pandas as pd import matplotlib %matplotlib inline import matplotlib.pyplot as plt import humanize from sqlitedict import SqliteDict db = SqliteDict('./pet_friendly.sqlite') pd.set_option('float_format', '{:.2f}'....
<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: I'll skip the data gathering step. I used a CSV file with the list of countries and regions to parse Airbnb.com website and saved the data as a ...
4,077
<ASSISTANT_TASK:> Python Code: import caffe import matplotlib.pyplot as plt import matplotlib.ticker as plticker import matplotlib as mpl import numpy as np import os import struct %matplotlib inline # Function adapted from https://gist.github.com/akesling/5358964. def load_mnist_test_data(path = "."): fname_img =...
<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: Since the digits of the MNIST were stored in a special format, we need to load them Step2: Now we can visualize one by one as follows (<span st...
4,078
<ASSISTANT_TASK:> Python Code: from predictor import evaluation as ev from predictor.dummy_mean_predictor import DummyPredictor predictor = DummyPredictor() y_train_true_df, y_train_pred_df, y_val_true_df, y_val_pred_df = ev.run_single_val(x, y, ahead_days, predictor) print(y_train_true_df.shape) print(y_train_pred_df....
<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: Done. Let's test the reshape_by_symbol function Step2: So, the reshape_by_symbol function seems to work with run_single_val. It could be added ...
4,079
<ASSISTANT_TASK:> Python Code: %matplotlib inline import numpy as np import matplotlib.pyplot as plt import seaborn as sns; sns.set() rng = np.random.RandomState(1) X = np.dot(rng.rand(2, 2), rng.randn(2, 200)).T plt.scatter(X[:, 0], X[:, 1]) plt.axis('equal'); from sklearn.decomposition import PCA pca = PCA(n_compon...
<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: Intuition of PCA Step2: By eye, what can we say about this dataset? Step3: PCA learns what the components are an how variance is explained by ...
4,080
<ASSISTANT_TASK:> Python Code: %matplotlib inline import numpy import matplotlib from matplotlib.patches import Circle, Wedge, Polygon from matplotlib.collections import PatchCollection import matplotlib.pyplot as plt import matplotlib.patches as mpatches import matplotlib.lines as mlines import matplotlib.path as mpat...
<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: Ship test Step2: Island Test
4,081
<ASSISTANT_TASK:> Python Code: !pip install git+https://github.com/biothings/biothings_explorer#egg=biothings_explorer from biothings_explorer.hint import Hint from biothings_explorer.user_query_dispatcher import FindConnection import nest_asyncio nest_asyncio.apply() ht = Hint() anisindione = ht.query("Anisindione")...
<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, import the relevant modules Step2: Step 1 Step3: Step 2 Step4: The df object contains the full output from BioThings Explorer. Each row...
4,082
<ASSISTANT_TASK:> Python Code: %matplotlib inline import pandas as pd import matplotlib.pyplot as plt import os import sys import numpy as np import math track_params = pd.read_csv('../TRAIN/track_parms.csv') track_params.tail() # Create binary labels track_params['phi_bool'] = track_params.phi.apply(lambda x: "+" if...
<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: Get angle values and cast to boolean Step2: Create our simple classification targets Step3: Look at the distributions to see if we have any im...
4,083
<ASSISTANT_TASK:> Python Code: import yaml from bokeh.layouts import column from bokeh.models import ColumnDataSource, Slider from bokeh.plotting import figure from bokeh.themes import Theme from bokeh.io import show, output_notebook from bokeh.sampledata.sea_surface_temperature import sea_surface_temperature output_no...
<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: There are various application handlers that can be used to build up Bokeh documents. For example, there is a ScriptHandler that uses the code fr...
4,084
<ASSISTANT_TASK:> Python Code: query_dict = {'expansions__vectors__rep': 0, 'expansions__k':3, 'labelled':'amazon_grouped-tagged', 'expansions__use_similarity': 0, 'expansions__neighbour_strategy':'linear', 'expansions__vectors__dimensionality': 100, ...
<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: Overall, precision and recall are balanced and roughly equal. Better models are better in both P and R. Step2: Find the smallest cluster and pr...
4,085
<ASSISTANT_TASK:> Python Code: import numpy as np import matplotlib.pyplot as plt %matplotlib inline import pyqg # create the model object m = pyqg.BTModel(L=2.*np.pi, nx=256, beta=0., H=1., rek=0., rd=None, tmax=40, dt=0.001, taveint=1, ntd=4) # in this example we u...
<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: McWilliams performed freely-evolving 2D turbulence ($R_d = \infty$, $\beta =0$) experiments on a $2\pi\times 2\pi$ periodic box. Step2: Initial...
4,086
<ASSISTANT_TASK:> Python Code: %pylab inline !cd toy_datasets; wget -O magic04.data -nc https://archive.ics.uci.edu/ml/machine-learning-databases/magic/magic04.data import numpy, pandas from rep.utils import train_test_split from sklearn.metrics import roc_auc_score columns = ['fLength', 'fWidth', 'fSize', 'fConc', '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: Loading data Step2: Variables used in training Step3: Metric definition Step4: Compute threshold vs metric quality Step5: The best quality S...
4,087
<ASSISTANT_TASK:> Python Code: import time from collections import namedtuple import numpy as np import tensorflow as tf with open('anna.txt', 'r') as f: text=f.read() vocab = set(text) vocab_to_int = {c: i for i, c in enumerate(vocab)} int_to_vocab = dict(enumerate(vocab)) encoded = np.array([vocab_to_int[c] for ...
<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'll load the text file and convert it into integers for our network to use. Here I'm creating a couple dictionaries to convert the chara...
4,088
<ASSISTANT_TASK:> Python Code: from IPython.core.display import HTML css_file = 'pynoddy.css' HTML(open(css_file, "r").read()) %matplotlib inline #import the ususal libraries + the pynoddy UncertaintyAnalysis class import sys, os # determine path of repository to set paths corretly below repo_path = os.path.realpath('...
<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 Gippsland Basin Model Step2: While we could hard-code parameter variations here, it is much easier to store our statistical information in ...
4,089
<ASSISTANT_TASK:> Python Code: !pip install -q amplpy ampltools MODULES=['ampl', 'coin'] from ampltools import cloud_platform_name, ampl_notebook from amplpy import AMPL, register_magics if cloud_platform_name() is None: ampl = AMPL() # Use local installation of AMPL else: ampl = ampl_notebook(modules=MODULES)...
<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 Colab & Kaggle interagration Step2: Use %%ampl_eval to evaluate AMPL commands Step3: Use %%writeifile to create files Step4: Use %%amp...
4,090
<ASSISTANT_TASK:> Python Code: import os import sys sys.path.append(os.environ["SPARK_HOME"] + "/python/lib/py4j-0.10.4-src.zip") sys.path.append(os.environ["SPARK_HOME"] + "/python/lib/pyspark.zip") from pyspark import SparkConf, SparkContext sconf = SparkConf() sconf.setAppName("ES-Spark Integration") sconf.setMaster...
<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: Goal Step3: Configure ES parameters Step4: ES returns key-value RDD where key is ID of the document, and value is content of _source field ...
4,091
<ASSISTANT_TASK:> Python Code: import mne mne.set_log_level('WARNING') mne.set_log_level('INFO') mne.set_config('MNE_LOGGING_LEVEL', 'WARNING', set_env=True) mne.get_config_path() from mne.datasets import sample # noqa data_path = sample.data_path() raw_fname = data_path + '/MEG/sample/sample_audvis_filt-0-40_raw...
<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: If you'd like to turn information status messages off Step2: But it's generally a good idea to leave them on Step3: You can set the default le...
4,092
<ASSISTANT_TASK:> Python Code: import numpy as np import numpy.polynomial.polynomial as npp from scipy.stats import norm from scipy.special import comb import matplotlib.pyplot as plt def Plw(n,l,w,delta): return np.sum([comb(w,l-r)*comb(n-w,r)*(delta**(w-l+2*r))*((1-delta)**(n-w+l-2*r)) for r in range(l+1)]) # w...
<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: Implement the helper function which computes the probability $P_\ell^w$ that a received word $\boldsymbol{y}$ is exactly at Hamming distance $\e...
4,093
<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 wr...
<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: ライブラリをインポートします。neural_structured_learning を nsl と略します。 Step3: ハイパーパラメータ Step4: MNIST データセット Step5: モデルを数値的に安定させるには、nor...
4,094
<ASSISTANT_TASK:> Python Code: # DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'messy-consortium', 'sandbox-1', 'atmoschem') # Set as follows: DOC.set_author("name", "email") # TODO - please enter value(s) # Set as follows: DOC.set_contribut...
<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,095
<ASSISTANT_TASK:> Python Code: %matplotlib inline import matplotlib.pyplot as plt import numpy as np from IPython.html.widgets import interact, interactive, fixed from IPython.display import display def random_line(m, b, sigma, size=10): Create a line y = m*x + b + N(0,sigma**2) between x=[-1.0,1.0] Param...
<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: Line with Gaussian noise Step5: Write a function named plot_random_line that takes the same arguments as random_line and creates a random line ...
4,096
<ASSISTANT_TASK:> Python Code: import pandas as pd url = "https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data" df = pd.read_csv(url,names=['sepal_length', 'sepal_width', 'petal_length', 'petal_width', ...
<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: read_html Step2: Plotting Step3: It would be nice to encode by color and plot all combinations of values, but this isn't easy with matplotlib....
4,097
<ASSISTANT_TASK:> Python Code: with open('tmp/pymotw.txt', 'wt') as f: f.write('contents go here') class Context: def __init__(self): print('__init__()') def __enter__(self): print('__enter__()') return self def __exit__(self, exc_type, exc_val, exc_tb): print('__exit__(...
<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 context manager is enabled by the with statement, and the API involves two methods. The __enter__() method is run when execution flow enters t...
4,098
<ASSISTANT_TASK:> Python Code: r = requests.get("https://www.topuniversities.com/sites/default/files/qs-rankings-data/357051.txt") json_dict = r.json() json_dict = json_dict['data'] json_dict = json_dict[:199] for e in json_dict: #Delete useless informations del e['nid'] del e['logo'] del e['core_id'] ...
<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: Per university ratio Step2: As we can see except for the first few universites which clearly have a higher ratio than the others, the ratio ten...
4,099
<ASSISTANT_TASK:> Python Code: print('Original bounds: ', t[0], t[-1]) t_obs = t[D['T_flag'] != -1] D = D[t_obs[0]:t_obs[-1]] # Truncate dataframe so it is sandwiched between observed values t = D.index T = D['T'] print('New bounds: ', t[0], t[-1]) t_obs = D.index[D['T_flag'] != -1] t_interp = D.index[D['T_flag'] == -...
<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: Red dots are interpolated values. Step2: We want to obtain a stationary "feature" from the data, firt differences are an easy place to start. S...