Unnamed: 0
int64
0
15.9k
cleaned_code
stringlengths
67
124k
cleaned_prompt
stringlengths
168
30.3k
11,100
<ASSISTANT_TASK:> Python Code: %%bash signac --help % pwd % rm -rf projects/tutorial/cli % mkdir -p projects/tutorial/cli % cp idg projects/tutorial/cli % cd projects/tutorial/cli %%bash signac init TutorialCLIProject %%bash signac project signac project --workspace %%bash signac job '{"kT": 1.0, "p": 1.0, "N": 10...
<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 interact with a project on the command line, the current working directory needs to be within or below the project root directory. Step2: Ne...
11,101
<ASSISTANT_TASK:> Python Code: #cargar librerias import pandas as pd import numpy as np df = pd.read_csv('co_properties.csv.gz', compression='gzip', header=0, sep=',', quotechar='"') df.head() df.l3.value_counts() df=df[df['l3']=='Bogotá D.C'] df.l3.value_counts() df.groupby('currency').agg({'id':'count'}) df=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: Cargo los datos que vienen de <a href='https Step2: Propiedades en Bogotá Step3: Propiedades que el precio esta en COP Step4: Propiedades en...
11,102
<ASSISTANT_TASK:> Python Code: PATH_NEWS_ARTICLES = "" from nltk.corpus import stopwords from nltk.tokenize import TweetTokenizer from nltk.stem.snowball import SnowballStemmer import re import pickle import pandas as pd import gensim from gensim import corpora, models df=pd.read_csv(PATH_NEWS_ARTICLES) df.head(5) sto...
<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. TEXT PROCESSING Step2: 2. TOPIC MODELING Step4: Generate Topics for a new Article Step5: Describing parameters
11,103
<ASSISTANT_TASK:> Python Code: # Authors: Alexandre Barachant <alexandre.barachant@gmail.com> # # License: BSD (3-clause) import numpy as np import matplotlib.pyplot as plt from sklearn.model_selection import StratifiedKFold from sklearn.pipeline import make_pipeline from sklearn.linear_model import LogisticRegression ...
<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 and read data
11,104
<ASSISTANT_TASK:> Python Code: %%capture --no-stderr KFP_PACKAGE = 'https://storage.googleapis.com/ml-pipeline/release/0.1.14/kfp.tar.gz' !pip3 install $KFP_PACKAGE --upgrade import kfp.components as comp dataproc_submit_hadoop_job_op = comp.load_component_from_url( 'https://raw.githubusercontent.com/kubeflow/pipe...
<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 the component using KFP SDK Step2: Sample Step3: Insepct Input Data Step4: Clean up the existing output files (optional) Step5: Example...
11,105
<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: Image classification with TensorFlow Lite Model Maker Step2: Import the required packages. Step3: Simple End-to-End Example Step4: You could ...
11,106
<ASSISTANT_TASK:> Python Code: from larray import * # load 'demography_eurostat' dataset demography_eurostat = load_example_data('demography_eurostat') # extract the 'population' array from the dataset population = demography_eurostat.population population # Array summary: metadata + dimensions + description of axes ...
<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: Inspecting Array objects Step2: Get axes Step3: Get axis names Step4: Get number of dimensions Step5: Get length of each dimension Step6: G...
11,107
<ASSISTANT_TASK:> Python Code: import reprlib class Sentence: def __init__(self, text): self.text = text self.words = text.split() def __getitem__(self, index): return self.words[index] def __len__(self): #completes sequence protocol, but not needed for iterab...
<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 iterate over an object x, Python automatically calls iter(x) (i.e. x.__iter__). Step2: What's actually going on here? Step3: We can comple...
11,108
<ASSISTANT_TASK:> Python Code: from __future__ import print_function from IPython.display import Image import base64 Image(data=base64.decodestring("iVBORw0KGgoAAAANSUhEUgAAAMYAAABFCAYAAAARv5krAAAYl0lEQVR4Ae3dV4wc1bYG4D3YYJucc8455yCSSIYrBAi4EjriAZHECyAk3rAID1gCIXGRgIvASIQr8UTmgDA5imByPpicTcYGY+yrbx+tOUWpu2e6u7qnZ7qXVFP...
<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: We're going to be building a model that recognizes these digits as 5, 0, and 4. Step3: Working with the images Step4: The first 10 pixels are ...
11,109
<ASSISTANT_TASK:> Python Code: import numpy as np import matplotlib.pyplot as plt import pints import pints.toy model = pints.toy.Hes1Model() print('Outputs: ' + str(model.n_outputs())) print('Parameters: ' + str(model.n_parameters())) times = model.suggested_times() smooth_times = np.linspace(times[0], times[-1], 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: We can get some suggested parameters and plot some data! In experiments, typically it is not easy to have high sampling rate (time points), so o...
11,110
<ASSISTANT_TASK:> Python Code: def cria_matriz(num_linhas, num_colunas): matriz = [] #lista vazia for i in range(num_linhas): linha = [] for j in range(num_colunas): linha.append(0) matriz.append(linha) for i in range(num_colunas): for j in range(num_linhas): ...
<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: Exercício 1 Step2: Exercício 2 Step3: Praticar tarefa de programação Step4: Exercício 2
11,111
<ASSISTANT_TASK:> Python Code: import os, glob import fitsio import numpy as np import matplotlib.pyplot as plt from astropy.table import vstack, Table, hstack import seaborn as sns sns.set(context='talk', style='ticks', font_scale=1.0) %matplotlib inline lslgaver = b'L6' lslgafile = '/global/cfs/cdirs/desi/users/ioann...
<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: Geometry comparison of LSLGA galaxies Step2: Compare the various sizes
11,112
<ASSISTANT_TASK:> Python Code: # load and plot dataset from pandas import read_csv from pandas import datetime from matplotlib import pyplot # load dataset def parser(x): return datetime.strptime(x, '%Y-%m-%d') series = read_csv('../data/yellowstone-visitors.csv', header=0, parse_dates=[0], index_col=0, squeeze=Tru...
<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 park's recreational visits are highly seasonable with the peak season in July. The park tracks monthly averages from the last four years on...
11,113
<ASSISTANT_TASK:> Python Code: from pytadbit.mapping.analyze import eig_correlate_matrices, correlate_matrices from pytadbit import load_hic_data_from_reads from cPickle import load from matplotlib import pyplot as plt reso = 1000000 base_path = 'results/{0}/03_filtering/valid_reads12_{0}.tsv' bias_ice_path = 'results/...
<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: Write a little function to load HiCData obeject Step2: Load data Step3: DRY normalized Step4: Plot correlations Step5: DRY Step6: Repeat at...
11,114
<ASSISTANT_TASK:> Python Code: (val_classes, train_classes, val_labels, train_labels, val_filenames, train_filenames, test_filenames) = get_classes('data/fish/') print(val_classes) print(train_classes) print(val_labels) print(train_labels) print(val_filenames) print(train_filenames) print(test_filenames) # removing ...
<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: Precompute convolutional output Step2: Fully convolutional net (FCN) Step3: Bounding boxes and Multi-Output
11,115
<ASSISTANT_TASK:> Python Code: %matplotlib inline import matplotlib.pylab as plt from tsfresh.examples.har_dataset import download_har_dataset, load_har_dataset, load_har_classes import seaborn as sns from tsfresh import extract_features, extract_relevant_features, select_features from tsfresh.utilities.dataframe_funct...
<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 visualize data Step2: Extract Features Step3: Train and evaluate classifier Step4: Compare against naive classification accuracy
11,116
<ASSISTANT_TASK:> Python Code: %matplotlib inline import numpy as np import time as tm 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 fre...
<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...
11,117
<ASSISTANT_TASK:> Python Code: %%file data.scons Flow('trace',None,'spike n1=2001 d1=0.001 k1=1001 | ricker1 frequency=30') Flow('gather','trace','spray axis=2 n=49 d=25 o=0 label=Offset unit=m | nmostretch inv=y half=n v0=2000') Result('gather','window f1=888 n1=392 | grey title=Gather') from m8r import view view('gat...
<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: Display the same with Python (matplotlib) Step2: Apply moveout with incorrect velocity Step3: Slope estimation Step4: Non-physical flattening...
11,118
<ASSISTANT_TASK:> Python Code: import numpy as np import pandas as pd import matplotlib.pyplot as plt df = pd.read_csv('ohw_anonymised.csv', index_col='datetime', parse_dates=True) df_ohw20 = df[df.ohw20_repo] df weekly_commits = df.author.groupby(df.index.week).count() df_hw = df[df.index.week==33] hw_commits = df_h...
<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 read in the anaonymised data to a pands dataframe and make a second dataframe of only commits to OHW20 repos Step2: Commits in time Step3: ...
11,119
<ASSISTANT_TASK:> Python Code: import pandas as pd df = pd.read_csv('Class10_wine_data.csv') df.head() # Plot the first two feature columns import matplotlib.pyplot as plt import seaborn as sns sns.set_style('white') #plt.figure(figsize=(8,6)) plt.scatter(df['Alcohol'], df['Malic acid']) plt.xlabel('Alcohol (%/L)') pl...
<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: There are a number of different features here. We'll focus on the first two Step2: Standarization scaling Step3: We've accomplished what we se...
11,120
<ASSISTANT_TASK:> Python Code: import sys import numpy as np import scipy.stats as stats import matplotlib.pyplot as plt import statsmodels.sandbox.stats.multicomp as mc import multiprocessing as mp %matplotlib inline import os os.environ['OMP_NUM_THREADS'] = str(1) import warnings warnings.filterwarnings('ignore') 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: 0.0 Basic parameters Step4: Set up basic functions Step6: Set up functions for RSA analysis (instead of SVM decoding) Step7: Run statistics w...
11,121
<ASSISTANT_TASK:> Python Code: items = ['banana', 'apple', 'carrot'] stock = [2, 3, 4] def get_stock(item_name, items, stock): item_index = items.index(item_name) how_many = stock[item_index] return how_many print(get_stock('apple', items, stock)) items = [('banana', 2), ('apple', 3), ('carrot', 4)] 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: <p style="text-align Step2: <p style="text-align Step3: <p style="text-align Step4: <p style="text-align Step5: <p style="text-align Step6: ...
11,122
<ASSISTANT_TASK:> Python Code: name = input('请输入你的姓名') print('你好',name) print('请输入出生的月份与日期') month = int(input('月份:')) date = int(input('日期:')) if month == 4: if date < 20: print(name, '你是白羊座') else: print(name,'你是非常有性格的金牛座') if month == 5: if date < 21: print(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: 练习 2:写程序,可由键盘读入两个整数m与n(n不等于0),询问用户意图,如果要求和则计算从m到n的和输出,如果要乘积则计算从m到n的积并输出,如果要求余数则计算m除以n的余数的值并输出,否则则计算m整除n的值并输出。 Step2: 练习 3:写程序,能够根据北京雾霾PM2.5数值给出...
11,123
<ASSISTANT_TASK:> Python Code: import SimpleITK as sitk from downloaddata import fetch_data, fetch_data_all print(sitk.Version()) from __future__ import print_function import importlib from distutils.version import LooseVersion required_packages = {'IPython' : '4.0.0', 'numpy' : '1.9.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: The following cell checks that all expected packages and correct versions are installed. SimpleITK may possibly work with other versions of thes...
11,124
<ASSISTANT_TASK:> Python Code: import pandas as pd import numpy as np lenses_data = pd.read_csv('https://archive.ics.uci.edu/ml/machine-learning-databases/lenses/lenses.data', sep='\s+', header=None ) lenses_data.columns= ['index', 'age', 'spec_type', 'astigmatic', 'tear_prod_rate', 'lens_type...
<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: Attribute Information Step2: Calculating Mututal Information Score Directly Step3: Mutual Information is defined by Step4: Next step is to ca...
11,125
<ASSISTANT_TASK:> Python Code: from scipy.special import legendre q = 20 n_steps = 100000 t = np.linspace(0, 1, n_steps) P = np.asarray([legendre(i)(2*t - 1) for i in range(q)]).T total = np.zeros((q,q)) for Pt in P: Ct = np.outer(Pt, Pt) total += Ct / n_steps plt.figure(figsize=(12,6)) plt.subplot(1, 2, 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: That seems to indicate this identity Step2: Hmm... now that is a very interesting structure. I'm even more convinced that there's a nice comp...
11,126
<ASSISTANT_TASK:> Python Code: %matplotlib inline import numpy as np import matplotlib.pyplot as plt from numpy.linalg import eigvalsh from collections import namedtuple import TB TB.band(TB.Si) TB.band(TB.GaAs) TB.band(TB.Ge) def SiGe_band(x=0.2): Si_data = TB.bandpts(TB.Si) Ge_data = TB.bandpts(TB.Ge) da...
<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: Interpolated SiGe band structure Step2: Plotting misc parts of Brillouin zones
11,127
<ASSISTANT_TASK:> Python Code: import numpy as np import flopy reload(flopy) from flopy.modflow import * from flopy.mt3d import * nlay, nrow, ncol = 3, 10, 10 ml = Modflow("test") dis = ModflowDis(ml,nlay=nlay, nrow=nrow, ncol=ncol) mt = Mt3dms(modflowmodel=ml) btn = Mt3dBtn(mt, sconc=1.0,ncomp=2) mt = Mt3dms(modflow...
<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 btn, sconc is passed as a normal util_3d-compatible argument, no need for the list anymore Step2: or we pass in the sconc2 kwarg explicitly...
11,128
<ASSISTANT_TASK:> Python Code: # Authors: Jona Sassenhagen <jona.sassenhagen@gmail.com> # # License: BSD-3-Clause import mne from mne.event import define_target_events from mne.channels import make_1020_channel_selections print(__doc__) data_path = mne.datasets.testing.data_path() fname = data_path / 'EEGLAB' / 'test_...
<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 EEGLAB example data (a small EEG dataset) Step2: Create Epochs Step3: Plot using Step4: Plot using median
11,129
<ASSISTANT_TASK:> Python Code: # General syntax to import specific functions in a library: ##from (library) import (specific library function) from pandas import DataFrame, read_csv # General syntax to import a library but no functions: ##import (library) as (give the library a nickname/alias) import matplotlib.pyplo...
<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 Data Step2: To merge these two lists together we will use the zip function. Step3: We are basically done creating the data set. We now ...
11,130
<ASSISTANT_TASK:> Python Code: import LangByWord as lbw import BuildTrainingDataFiles as btdf # Set the input directory for preprocessing here: base_input_dir = '/Users/frank/data/LanguageDetectionModel/txt' # Set the output directory for the preprocessing here: base_output_dir = '/Users/frank/data/LanguageDetectionMo...
<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: Preprocess the database Step2: Begin preprocessing the language data Step3: Train the language detection model and save as an object. Step4: ...
11,131
<ASSISTANT_TASK:> Python Code: # If we're running on Colab, install empiricaldist # https://pypi.org/project/empiricaldist/ import sys IN_COLAB = 'google.colab' in sys.modules if IN_COLAB: !pip install empiricaldist # Get utils.py from os.path import basename, exists def download(url): filename = basename(url) ...
<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: Whenever people compare Bayesian inference with conventional approaches, one of the questions that comes up most often is something like, "What ...
11,132
<ASSISTANT_TASK:> Python Code: import graph_tool.all as gt import pandas as pd import numpy as np from IPython.display import display %matplotlib inline print("graph-tool version: {}".format(gt.__version__.split(' ')[0])) with pd.option_context('display.max_colwidth', -1): display(pd.DataFrame.from_records(gt.coll...
<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: Show datasets in collection Step2: Another graph example Step3: Social graph drawing 101 Step4: Create a graph using Python iterations Step5:...
11,133
<ASSISTANT_TASK:> Python Code: import magpy as mp single_particle = mp.Model( radius = [12e-9], anisotropy = [4e4], anisotropy_axis = [[0., 0., 1.]], magnetisation_direction = [[1., 0., 0.]], location = [[0., 0., 0.]], damping = 0.1, temperature = 300., magnetisation = 400e3 ) results ...
<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 create our model, we need to specify the geometry and material properties of the system. The units and purpose of each property is defined be...
11,134
<ASSISTANT_TASK:> Python Code: num = float(input()) if num >= 5.50: print("Excellent!") grade = float(input()) if grade >= 5.50: print("Excellent!") else: print("Not excellent.") num = int(input()) if num % 2 == 0: print("even") else: print("odd") num = int(input()) if num == 0: print("zero")...
<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: <h2>02.Excellent or Not</h2> Step2: <h1>03.Even or Odd</h1> Step3: <h2>04.Greater Number</h2> Step4: <h2>06.Bonus Score</h2> Step5: <h2>07.S...
11,135
<ASSISTANT_TASK:> Python Code: import libsbml import pandas as pd import re !curl -o BMID000000140222.xml http://www.ebi.ac.uk/biomodels-main/download?mid=BMID000000140222 document = libsbml.readSBML('BMID000000140222.xml') model = document.getModel() bigg = re.compile(r'BIGG:.*</p>') brenda = re.compile(r'BRENDA:.*...
<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: Retrieving the whole-genome metabolic model from path2models Step2: reading path2models SBML Step3: construct regex patterns Step4: create pa...
11,136
<ASSISTANT_TASK:> Python Code: dimensions = 10 input_scale = 1 n_neurons_per_dim = 50 intercept_low = -0.5 intercept_high = 1.0 tau_input = 0.01 tau_recurrent = 0.1 tau_reset = 0.2 max_rate_high = 200 max_rate_low = 150 sensory_delay = 0.05 reset_scale = 0.3 model = nengo.Network() with model: vocab = spa.Vocabular...
<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 is the plot of the average firing rate across all the neurons Step2: But that's across all the neurons. In the empirical data we're compa...
11,137
<ASSISTANT_TASK:> Python Code: %matplotlib inline from matplotlib import pylab as plt !cd ../devops/geoserver && vagrant status from IPython.core.display import display, HTML from geonotebook.config import Config geoserver = Config().vis_server display(HTML(geoserver.c.get("/about/status").text)) !curl -o /tmp/L57.G...
<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: Make sure you have the geoserver VM running Step2: Display geoserver status Step3: Get the data from S3 Step4: Adding an RGB layer to the map...
11,138
<ASSISTANT_TASK:> Python Code: import pandas as pd import numpy as np import matplotlib.pyplot as plt %pylab inline #use a nicer plotting style plt.style.use(u'seaborn-notebook') print(plt.style.available) data = pd.read_csv('./data/assembly.dat',delimiter='\t',skiprows=11,names=['s','usec','ax','ay','az','gx','gy','g...
<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: Motion Data Step2: for more details on plotting options see also Step3: try it with the gyroscope data ... what's the difference? Step4: Feat...
11,139
<ASSISTANT_TASK:> Python Code: import seisobs sfile_directory = 'TEST_' cat = seisobs.seis2cat(sfile_directory) cat spec1 = seisobs.specs.specs['1'] print ('colspecs\n') print (spec1.colspec) print ('\n') print ('colnames\n') print (spec1.colname) print('\n') print ('colformat\n') print (spec1.colformat) example_lin...
<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 should have taken about 20 seconds to read in 50 files. A bit slow so hopefully you don't have to read thousands of s-files very often. Ste...
11,140
<ASSISTANT_TASK:> Python Code: from sklearn.datasets import load_iris from sklearn.neighbors import KNeighborsClassifier iris = load_iris() X, y = iris.data, iris.target classifier = KNeighborsClassifier() y import numpy as np rng = np.random.RandomState(0) permutation = rng.permutation(len(X)) X, y = X[permutation],...
<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 labels in iris are sorted, which means that if we split the data as illustrated above, the first fold will only have the label 0 in it, whil...
11,141
<ASSISTANT_TASK:> Python Code: import pandas as pd import seaborn as sns %matplotlib inline posts_df = pd.DataFrame.from_csv("reddit_posts_the_donald_201604.csv") posts_df[0:5] posts_df['created'] = pd.to_datetime(posts_df.created_utc, unit='s') posts_df['created_date'] = posts_df.created.dt.date posts_df['downs'] = po...
<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: Visualizations Step2: Daily average of number of upvotes per post
11,142
<ASSISTANT_TASK:> Python Code: import pymongo db = pymongo.MongoClient().tweets_db coll = db.emotweets coll coll.count() query = {'coordinates': {'$ne': None}} coll.find(query).count() query = {'hashtags': {'$in': ['happy']}} coll.find(query).count() coll.find_one() %matplotlib inline import pymongo # in case we...
<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 establish a link with the database. We know that the database created by tweetharvester is called tweets_db and within it is a collectio...
11,143
<ASSISTANT_TASK:> Python Code: #Import modules import sys, os import pandas as pd from openpyxl import load_workbook #Set the location of the data directory dataDir = '../../Data' #Get the water balance input csv file inDataFN = dataDir + os.sep + 'StateData' + os.sep + 'la_2010.csv' #Get the template inXlsxFN = dataD...
<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/Set the filenames required Step2: Below we set the field to column mappings. The number on the right of the '=' refers to the column in the...
11,144
<ASSISTANT_TASK:> Python Code: import vector2d u = vector2d.Vector(1,2) u INVENTORY_TEXT = apple, 0.60 banana, 0.20 grapefruit, 0.75 grapes, 1.99 kiwi, 0.50 lemon, 0.20 lime, 0.25 mango, 1.50 papaya, 2.95 pineapple, 3.50 blueberries, 1.99 blackberries, 2.50 peach, 0.50 plum, 0.33 clementine, 0.25 cantaloupe, 3.25 pea...
<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: This module has a special section, starting with Step4: Item Step5: Here are some tests your code should pass Step6: How do they behave in a ...
11,145
<ASSISTANT_TASK:> Python Code: import dicom # for reading dicom files import os # for doing directory operations import pandas as pd # for some simple data analysis (right now, just to load in the labels data and quickly reference it) # Change this to wherever you are storing your data: # IF YOU ARE FOLLOWING ON KAGGL...
<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: At this point, we've got the list of patients by their IDs, and their associated labels stored in a dataframe. Now, we can begin to iterate thro...
11,146
<ASSISTANT_TASK:> Python Code: import os workDir = '/home/nick/notebook/SIPSim/dev/bac_genome1210/SSU_genes_per_ng_DNA/' rnammerDir = os.path.join(workDir + 'rnammer') genomeDir = '/home/nick/notebook/SIPSim/dev/bac_genome1210/genomes/' import glob import pyfasta import numpy as np import pandas as pd from collections...
<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: Init Step2: Size distribution of bacterial genomes Step3: Distribution of 16S gene copies per genome Step4: Fitting distribution Step5: Dist...
11,147
<ASSISTANT_TASK:> Python Code: path = Config().data/'rossmann' train_df = pd.read_pickle(path/'train_clean') train_df.head().T n = len(train_df); n idx = np.random.permutation(range(n))[:2000] idx.sort() small_df = train_df.iloc[idx] small_cont_vars = ['CompetitionDistance', 'Mean_Humidity'] small_cat_vars = ['Store'...
<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: Experimenting with a sample Step2: Preparing full data set Step3: Model Step4: (10th place in the competition was 0.108) Step5: (10th place ...
11,148
<ASSISTANT_TASK:> Python Code: a = spot.translate('(a U b) & GFc & GFd', 'BA', 'complete'); a a.show("v") a.show(".ast") f = spot.formula('a U b'); f spot.translate(f) f.translate() f.translate('mon') f = spot.formula('Ga | Gb | Gc'); f f.translate('ba', 'small').show('.v') f.translate('ba', 'det').show('v.') spo...
<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 call the spot.setup() in the first cells has installed a default style for the graphviz output. If you want to change this style temporaril...
11,149
<ASSISTANT_TASK:> Python Code: import numpy as np from qiskit_aqua.operator import Operator num_qubits = 2 temp = np.random.random((2 ** num_qubits, 2 ** num_qubits)) qubitOp = Operator(matrix=temp + temp.T) temp = np.random.random((2 ** num_qubits, 2 ** num_qubits)) evoOp = Operator(matrix=temp + temp.T) from qiskit_...
<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 EOH, we would like to evolve some initial state (e.g. the uniform superposition state) with evoOp and do a measurement using qubitOp. Below,...
11,150
<ASSISTANT_TASK:> Python Code: def pretty_print_review_and_label(i): print(labels[i] + "\t:\t" + reviews[i][:80] + "...") g = open('reviews.txt','r') # What we know! reviews = list(map(lambda x:x[:-1],g.readlines())) g.close() g = open('labels.txt','r') # What we WANT to know! labels = list(map(lambda x:x[:-1].uppe...
<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 Step2: Lesson Step3: Project 1 Step4: We'll create three Counter objects, one for words from postive reviews, one for words from negativ...
11,151
<ASSISTANT_TASK:> Python Code: # Import libraries import numpy as np import pandas as pd from time import time from sklearn.metrics import f1_score # Read student data student_data = pd.read_csv("student-data.csv") print "Student data read successfully!" # TODO: Calculate number of students n_students = len(student_da...
<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: Implementation Step2: Preparing the Data Step3: Preprocess Feature Columns Step4: Implementation Step5: Training and Evaluating Models Step6...
11,152
<ASSISTANT_TASK:> Python Code: %matplotlib inline import matplotlib.pyplot as plt import SimpleITK as sitk # Download data to work on %run update_path_to_download_script from downloaddata import fetch_data as fdata img1 = sitk.ReadImage(fdata("cthead1.png")) sitk.Show(img1, title="cthead1") img2 = sitk.ReadImage(fdata...
<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: SimpleITK has a built in Show method which saves the image to disk and launches a user configurable program ( defaults to ImageJ ), to display t...
11,153
<ASSISTANT_TASK:> Python Code: with open('paris.txt') as f: lines = f.read().splitlines() N, M, T, C, S = map(int, lines[0].split()) paris_coords = [] for i in range(1, N + 1): paris_coords.append(list(map(float, lines[i].split()))) # Read coords paris = {node: {} for node in range(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: How many nodes? Step2: Which means the node 0 leads to the node 1079 with cost 113 and so on. Step3: Geolocation using geopy Step5: We need a...
11,154
<ASSISTANT_TASK:> Python Code: import pandas as pd import glob import os import numpy as np import matplotlib.pyplot as plt import sklearn import sklearn.ensemble from sklearn.ensemble import RandomForestClassifier from sklearn.model_selection import cross_val_score, train_test_split, cross_val_predict, learning_curve ...
<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: Importing the quite heavy DataFrame with the voting fields and the results. We drop a useless column and create a Name field, which will contain...
11,155
<ASSISTANT_TASK:> Python Code: import numpy as np np.linspace(0,10,11) def myFib(a,b): return a+b fibLength = 10 #the length we want for our Fibonacci sequence fibSeq = np.zeros(fibLength) #make a numpy array of 10 zeros # Let's define the first 2 elements of the Fibonacci sequence fibSeq[0] = 0 fibSeq[1] = 1 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: You can do a lot with the numpy module. Below is an example to jog your memory Step2: Do you remember the Fibonacci sequence from yesterday's L...
11,156
<ASSISTANT_TASK:> Python Code: parm_runtime_env_GCP = True # parm_runtime_env_GCP = False # Copyright 2016 Google Inc. # Licensed under the Apache License, Version 2.0 (the "License"); # import subprocess # retcode = subprocess.call(['pip', 'install', '-U', 'google-api-python-client']) # retcode = subprocess.call(['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: Using Google Cloud Platform's Machine Learning APIs Step2: 导入需要用到的一些功能程序库: Step3: GCP Machine Learning API Key Step4: 多媒体二进制base64码转换 (Define...
11,157
<ASSISTANT_TASK:> Python Code: from datetime import datetime TIMESTAMP = datetime.now().strftime("%Y%m%d%H%M%S") import os PROJECT_ID = "" # TODO: your PROJECT_ID here. os.environ["PROJECT_ID"] = PROJECT_ID BUCKET_NAME = PROJECT_ID # TODO: replace your BUCKET_NAME, if needed REGION = "us-central1" os.environ["BUCKET_...
<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 the following cell to create your Cloud Storage bucket if it does not already exist. Step2: Import libraries Step3: Download and preproces...
11,158
<ASSISTANT_TASK:> Python Code: def z_score(x, m, s): return (x - m) / s print(z_score(95, 100, 15), z_score(130, 100, 15), z_score(7, 100, 15)) # We should see -0.3333333333333333 2.0 -6.2 or 1/3 deviation below average, 2 above and 6.2 below. import scipy.stats as st def p(x, m, s): z = z_score(x, m, s) ...
<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 created a function that takes the observation, mean and standard deviation and returns the z-score. Notice it's just a little bit of arithmet...
11,159
<ASSISTANT_TASK:> Python Code: import pandas import numpy import os import ijson path = os.chdir('/Users/superuser/Documents/projects/SDRegionalDataLib/age friendly community/acs2015_1yr_B01001/') ageData = pandas.read_csv('acs2015_1yr_B01001.csv'); ageData.head() colNames = list(ageData.columns.values) #show the firs...
<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: <font color = 'blue'> get a list of the column names </font> Step2: <font color='blue'> function Step3: codingDF is intended to be used as a l...
11,160
<ASSISTANT_TASK:> Python Code: class Dataset(torch.utils.data.Dataset): Class for getting individual Pixel Data element frame items of a DICOM VL Whole Slide Microscocpy Image data set stored on a remote server. def __init__(self, url: str, study_id: str, series_id: str, instance_id: str): ...
<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: Implement a custom pytoch Dataset to load image frames from a remote DICOM VL Whole Slide Microscopy Image instance Step6: Implement a simple b...
11,161
<ASSISTANT_TASK:> Python Code: import numpy as np import matplotlib.pyplot as plt # Initialize random number generator np.random.seed(123) # True parameter values alpha, sigma = 1, 1 beta = [1, 2.5] # Size of dataset size = 100 # Predictor variable X1 = np.random.randn(size) X2 = np.random.randn(size) * 0.2 # Simulate ...
<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 is what the simulated data look like. We use the pylab module from the plotting library matplotlib. Step2: Model Specification Step3: Now...
11,162
<ASSISTANT_TASK:> Python Code: from biofloat import ArgoData from os.path import join, expanduser ad = ArgoData(cache_file = join(expanduser('~'), 'biofloat_fixed_cache_age365_variablesDOXY_ADJUSTED-PSAL_ADJUSTED-TEMP_ADJUSTED.hdf')) ocdf = ad.get_cache_file_oxy_count_df() print ocdf.groupby('wmo').sum().sum() pr...
<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: That's over 10 million measurements from over 42,000 profiles from 301 floats. The load_biofloat_cache.py script examined 559 floats for valid o...
11,163
<ASSISTANT_TASK:> Python Code: from IPython.display import Image Image(filename='lda_plate.png') vocabulary = [] for cdn1 in sim.codons: for cdn2 in sim.codons: if cdn1 == cdn2: continue vocabulary.append(cdn1+"-"+cdn2) print 'vocabulary: ', len(vocabulary) transitions = np.zeros((N,M-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: Recall that the Dirichlet Process (DP) (Ferguson, 1973) is essentially a distribution over distributions, where each draw from a DP is itself a ...
11,164
<ASSISTANT_TASK:> Python Code: from biothings_explorer.user_query_dispatcher import FindConnection from biothings_explorer.hint import Hint ht = Hint() # find all potential representations of CML cml_hint = ht.query("MONDO:0011996") # select the correct representation of CML cml = cml_hint['Disease'][0] cml # find all ...
<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 can see above, by default, BTE will query all APIs integrated. Step2: The Registry class stores all APIs used in BTE. Step3: check the ...
11,165
<ASSISTANT_TASK:> Python Code: greeting = 'Hello' guest = "John" my_string = 'Hello "John"' named_greeting = 'Hello, {name}'.format(name=guest) named_greeting2 = '{}, {}'.format(greeting, guest) print named_greeting print named_greeting2 fruit_list = ['apple', 'orange', 'peach', 'mango', 'bananas', 'pineapple'] name_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: data containers Step2: Indexing starts with zero. Step3: tuples Step4: sets Step5: dictionaries Step7: Functions Step8: function is just a...
11,166
<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: ビジュアルアテンションを用いた画像キャプショニング Step2: MS-COCO データセットのダウンロードと準備 Step3: オプション Step4: InceptionV3 を使った画像の前処理 Step5: InceptionV3 を初期化し Imagenet で学習済み...
11,167
<ASSISTANT_TASK:> Python Code: %matplotlib inline %config InlineBackend.figure_format = 'retina' import matplotlib.pyplot as plt import torch from torch import nn from torch import optim import torch.nn.functional as F from torchvision import datasets, transforms, models data_dir = 'Cat_Dog_data' # TODO: Define transf...
<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: Most of the pretrained models require the input to be 224x224 images. Also, we'll need to match the normalization used when the models were trai...
11,168
<ASSISTANT_TASK:> Python Code: help(abs) import numpy as np help(np) !echo this is output from the echo command from the Linux shell !python --version !python -c 'print("foo"); print("bar")' !python -c 'print("foo"); print("bar")' | wc -l !python -c 'import numpy as np; help(np)' | wc -l !python -c 'import numpy 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: We have to import the numpy module in order to get help on any of its functions which we attempt below. But if we ask for help on all of np (num...
11,169
<ASSISTANT_TASK:> Python Code: import openpyxl # Import OS module to navigate directories import os # Change the directory to the excel file location, using relative and absolute paths as previously discussed. os.chdir('files') os.listdir() workbook = openpyxl.load_workbook('example.xlsx') type(workbook) sheet = wor...
<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 must first nagivate to the directory containing the spreadsheets, which for this notebook is the subdirectory 'files'. Step2: We must now op...
11,170
<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 * m = UNITS...
<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: Bungee jumping Step3: Now here's a version of make_system that takes a Params object as a parameter. Step4: Let's make a System Step6: spring...
11,171
<ASSISTANT_TASK:> Python Code: # matplotlib und numpy importieren %pylab nbagg # Arbeiten mit Daten import pandas as pd # Zum Fitten import lmfit # Fehlerrechnung import uncertainties as uct from uncertainties.umath import * def residual(userfcn): Gibt für eine Modellfunktion die entsprechende Residuenfunkt...
<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: Die Fitroutine minimiert das $\chi^2$, welches aus den Quadraten der Residuen (=Abweichung der Modellvorhersage von den Messwerten) berechnet wi...
11,172
<ASSISTANT_TASK:> Python Code: naturalness = 'naturalness' naturalness_value_field = 'value' n_types = 7 sample_points = 'sample_points_field' radius = 500 use_viewshed = False def getViewshedSuffix(): if use_viewshed: viewshed_suffix = '_viewshed' else: viewshed_suffix = '' return viewshed...
<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 viewshed suffix (for filenames) Step2: Import statements Step3: GRASS import statements Step4: Function declarations Step5: extract poin...
11,173
<ASSISTANT_TASK:> Python Code: import pandas as pd # DataFrame cariñosamente df df = pd.read_csv('cs_DGII_Nomina_2016.csv',sep=';', encoding="ISO-8859-1") # encoding??? df.head() df.tail(10) df.shape df.info() df.isnull().any() df.columns df.Mes.head() df.columns = [x.strip().lower() for x in df.columns.values...
<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: Cargamos el archivo a un DataFrame en memoria Step2: Demos un vistazo a los primeros 5 registros Step3: y a los ultimos 10 Step4: Que tamaño ...
11,174
<ASSISTANT_TASK:> Python Code: with open('./apps/server_app.py', 'r') as f: print(f.read()) # Exercise: Modify the app to display the pickup locations and add a tilesource, then run the app with bokeh serve # Tip: Refer to the previous notebook import holoviews as hv import geoviews as gv import dask.dataframe 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: Of the three parts of this app, part 2 should be very familiar by now -- load some taxi dropoff locations, declare a Points object, datashade th...
11,175
<ASSISTANT_TASK:> Python Code: from nltk.tag import StanfordNERTagger from nltk.tokenize import word_tokenize # Adapt those lines to your installation jar_location = '/Users/sech/stanford-ner-2018-10-16/stanford-ner.jar' model_location_3classes = '/Users/sech/stanford-ner-2018-10-16/classifiers/english.all.3class.dists...
<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 take a paragraph from the Wikipedia page of Ada Lovelace as an example. We need to put the text in triple quotes since the text itself con...
11,176
<ASSISTANT_TASK:> Python Code: # These are the libraries will be used for this lab. import numpy as np import matplotlib.pyplot as plt import torch import pandas as pd # Convert 2D List to 2D Tensor twoD_list = [[11, 12, 13], [21, 22, 23], [31, 32, 33]] twoD_tensor = torch.tensor(twoD_list) print("The New 2D 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: Step1: <!--Empty Space for separating topics--> Step2: Bravo! The method <code>torch.tensor()</code> works perfectly.Now, let us try other functions w...
11,177
<ASSISTANT_TASK:> Python Code: # reload modules # Reload all modules (except those excluded by %aimport) every time before executing the Python code typed. %load_ext autoreload %autoreload 2 # import libraries import logging import os import sys import gc import pandas as pd import numpy as np import random import 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: 1.1. Initialise General Settings Step2: Common variables Step3: <br/><br/> Step4: <br/><br/> Step5: 2.3. Load Features Names Step6: 2.4. L...
11,178
<ASSISTANT_TASK:> Python Code: __author__ = "kyubyong. kbpark.linguist@gmail.com" import numpy as np np.__version__ x = np.arange(4).reshape((2, 2)) print("x=\n", x) x = np.arange(4).reshape((2, 2)) print("x=\n", x) x = np.arange(10).reshape((2, 5)) print("x=\n", x) x = np.arange(1, 11).reshape((2, 5)) print("x=\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: Order statistics Step2: Q2. Return the maximum value of x along the second axis. Reduce the second axis to the dimension with size one. Step3: ...
11,179
<ASSISTANT_TASK:> Python Code: sset0 = storage.samplesets[0] numeric_labels = { s.ensemble : s.replica for s in sset0} string_labels = { s.ensemble : str(s.replica) for s in sset0 } numeric_to_string = { numeric_labels[e] : string_labels[e] for e in numeric_labels.keys()} %%time trace_1 = paths.trace_ensembles_for_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: Step1: Trace of ensemble visited by a replica Step2: Replica flow Step3: Trips Step4: Transition matrix Step5: If you would like to set a different...
11,180
<ASSISTANT_TASK:> Python Code: from __future__ import unicode_literals # If Python 2 import spacy.en from spacy.tokens import Token from spacy.parts_of_speech import ADV nlp = spacy.en.English() # Find log probability of Nth most frequent word probs = [lex.prob for lex in nlp.vocab] probs.sort() words = [w for w in nlp...
<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: spaCy tokenizes words, then treats each token as a Token object. Each token has an integer and string representation. Each token also has things...
11,181
<ASSISTANT_TASK:> Python Code: !pip install --user statsmodels %matplotlib inline import pandas as pd import matplotlib.pyplot as plt import numpy as np import datetime %config InlineBackend.figure_format = 'retina' df = pd.read_csv('gs://cloud-training/ai4f/AAPL10Y.csv') df['date'] = pd.to_datetime(df['date']) df.sor...
<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 data from Google Clod Storage Step2: Prepare data for ARIMA Step3: Let's create a column for weekly returns. Take the log to of the ret...
11,182
<ASSISTANT_TASK:> Python Code: from __future__ import division import graphlab products = graphlab.SFrame('amazon_baby_subset.gl/') import json with open('important_words.json', 'r') as f: important_words = json.load(f) important_words = [str(s) for s in important_words] # Remote punctuation def remove_punctuati...
<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...
11,183
<ASSISTANT_TASK:> Python Code: a = 10 b = 22 print("a =", a, ", b =", b) print("~~~~~~~~~~~~~~~~~") print("a + b:\t", a + b) print("a - b:\t", a - b) print("a * b:\t", a * b) print("a / b:\t", a / b) print("a//b:\t", a//b) print("a % b:\t", a % b) print("-a:\t", -a) print("a < b:\t", a < b) print("a > b:\t", a > b) 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: Numeric Vs String Step2: As shown above only "*" multiplication is possible between string & real numeric value Step3: Complex Vs Numeric Step...
11,184
<ASSISTANT_TASK:> Python Code: import diplib as dip a = dip.Image((10,20), 1) a.Fill(3) b = a[0:4, 4:-1] b.Fill(55) a[:3, :10] = 100 a[5:7, 10:15] = 200 a.Show('normal') m = a >= 100 m.Show() a[m].Show('normal') a[m] = 176 a.Show('normal') import numpy as np b = np.random.rand(a.Size(1), a.Size(0)) dip.Show(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: The image object Step2: Indexing into an Image object works as it does for other array types in Step3: Images can be displayed using the Show ...
11,185
<ASSISTANT_TASK:> Python Code: !gsutil cp gs://ml-design-patterns/audio_train/00353774.wav cello.wav !gsutil cp gs://ml-design-patterns/audio_train/001ca53d.wav sax.wav import matplotlib.pyplot as plt from scipy import signal from scipy.io import wavfile import numpy as np fig, ax = plt.subplots(2, 2, figsize=(15, 10))...
<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: Vision ML on video Step3: Text
11,186
<ASSISTANT_TASK:> Python Code: from IPython.display import display from datetime import datetime from matplotlib import pyplot as plt from scipy import misc import h5py import json import numpy as np import os import pandas as pd import sys # local sys.path.insert(0, os.path.dirname(os.getcwd())) from pywim.utils.dsp....
<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.2.1 Start up Step2: 1.2.2 Creating the file Step3: 1.2.3 Reading the file
11,187
<ASSISTANT_TASK:> Python Code: # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, sof...
<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: Support Vector Machines Step2: You can see in the data description above that the range of values for each of the columns is quite a bit differ...
11,188
<ASSISTANT_TASK:> Python Code: def stupid_generator(end): i = 0 while i < end: yield i i+=1 stupid_generator(3) def stupid_list(end): i = 0 result = [] while i < end: result.append(i) i+=1 return result stupid_list(3) it = stupid_generator(3) it.next() list(stup...
<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: Le but de la fonction stupid_generator est de lister les entiers inférieurs à end. Cependant, elle ne retourne pas directement la liste mais un ...
11,189
<ASSISTANT_TASK:> Python Code: from __future__ import print_function %matplotlib inline import openpathsampling as paths import numpy as np import matplotlib.pyplot as plt from tqdm.auto import tqdm import os import openpathsampling.visualize as ops_vis from IPython.display import SVG %%time flexible = paths.Storage("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: Note that the accepted trials with recrossing does not account for how long the trial remained active. It also doesn't tell us whether the trial...
11,190
<ASSISTANT_TASK:> Python Code: def change_base(x: int, base: int): ret = "" while x > 0: ret = str(x % base) + ret x //= base return ret <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:
11,191
<ASSISTANT_TASK:> Python Code: from iuvs import io %autocall 1 files = !ls ~/data/iuvs/level1b/*.gz files l1b = io.L1BReader(files[1]) l1b.darks_interpolated.shape dark0 = l1b.detector_dark[0] dark1 = l1b.detector_dark[1] dark2 = l1b.detector_dark[2] io.image_stats(dark0) io.image_stats(dark1) io.image_stats(dark2) ...
<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 darks_interpolated data-cube consists of the interpolated darks that have been subtracted from the raw image cube for this observation. They...
11,192
<ASSISTANT_TASK:> Python Code: # Authors: Alexandre Gramfort <alexandre.gramfort@inria.fr> # # License: BSD-3-Clause import matplotlib.pyplot as plt import mne from mne import io from mne.stats import permutation_cluster_test from mne.datasets import sample print(__doc__) data_path = sample.data_path() raw_fname = dat...
<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 the channel of interest Step3: Compute statistic Step4: Plot
11,193
<ASSISTANT_TASK:> Python Code: filename = "../data/example_file.txt" fp = open(filename, "w") for string in ["Hello", "Hey", "moi"]: fp.write(string + "\n") fp.close() fp = open(filename, "r") for line in fp: print(line.strip()) # the \n is contained in the line, calling strip removes whitespace at the end 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: Context handlers Step2: File i/o packages in stdlib Step3: The implementation technical details like the "rt" vs "r" mode vary a bit, check do...
11,194
<ASSISTANT_TASK:> Python Code: %load_ext rpy2.ipython %%R physeqDir = '/var/seq_data/fullCyc/MiSeq_16SrRNA/515f-806r/lib1-7/phyloseq/' physeq_bulk_core = 'bulk-core' physeq_SIP_core = 'SIP-core_unk' %%R library(dplyr) library(tidyr) library(ggplot2) library(phyloseq) %%R F = file.path(physeqDir, physeq_SIP_core) phys...
<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: Init Step2: Mapping bulk and SIP data Step3: Pre-fraction dataset
11,195
<ASSISTANT_TASK:> Python Code: import gym import tensorflow as tf import numpy as np # Create the Cart-Pole game environment env = gym.make('CartPole-v0') env.reset() rewards = [] actions = [np.random.choice(2) for _ in range(100)] for _ in range(1000): env.render() state, reward, done, info = env.step(env.ac...
<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 Step2: We interact with the simulation through env. To show the simulation running, you can use env.render() to render one frame. Passing ...
11,196
<ASSISTANT_TASK:> Python Code: class Sarsa_Agent: def __init__(self, environment, n0, mlambda): self.n0 = float(n0) self.env = environment self.mlambda = mlambda # N(s) is the number of times that state s has been visited # N(s,a) is the number of times that action 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: Plot the mean- squared error against λ. Step2: For λ = 0 and λ = 1 only, plot the learning curve of mean-squared error against episode number. ...
11,197
<ASSISTANT_TASK:> Python Code: from numpy import random, array #Create fake income/age clusters for N people in k clusters def createClusteredData(N, k): random.seed(10) pointsPerCluster = float(N)/k X = [] for i in range (k): incomeCentroid = random.uniform(20000.0, 200000.0) ageCentroi...
<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 use k-means to rediscover these clusters in unsupervised learning
11,198
<ASSISTANT_TASK:> Python Code: import numpy as np import pandas as pd import seaborn as sns import matplotlib.pyplot as plt import xgboost as xgb from sklearn.metrics import roc_curve, auc from sklearn.metrics import precision_recall_curve df = pd.read_csv("iris.csv") def rotMat3D(a,r): Return the matrix that rota...
<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: Rotations Step5: PCA Step8: FastFourier Transformation Step9: Save python object with pickle Step10: Progress Bar Step11: Check separations...
11,199
<ASSISTANT_TASK:> Python Code: %matplotlib inline import numpy as np from datetime import date from matplotlib import pyplot as plt # Load marineHeatWaves definition module import marineHeatWaves as mhw sst = np.loadtxt('data/sst_WA.csv', delimiter=',') # Generate time vector using datetime format (January 1 of year 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: 2. Load daily SST data Step2: 3. Detect Marine Heatwave Step3: 3.2 Check properties of MHWs Step4: Maximum intensities (in $^∘$C) of the fir...