Unnamed: 0
int64
0
15.9k
cleaned_code
stringlengths
67
124k
cleaned_prompt
stringlengths
168
30.3k
5,200
<ASSISTANT_TASK:> Python Code: # define the font styles title_font = fm.FontProperties(family='serif', style='normal', size=19, weight='normal', stretch='normal') label_font = fm.FontProperties(family='serif', style='normal', size=16, weight='normal', stretch='normal') ticks_font = fm.FontProperties(family='serif', sty...
<SYSTEM_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 our data is formatted in the format we want. Step8: Permutation Test Step9: Create data Step10: Create PermTest instance and formate data...
5,201
<ASSISTANT_TASK:> Python Code: # Authors: Christopher Holdgraf <choldgraf@berkeley.edu> # # License: BSD (3-clause) from scipy.io import loadmat import numpy as np from mayavi import mlab from matplotlib import pyplot as plt from os import path as op import mne from mne.viz import ClickableImage # noqa from mne.viz im...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Load data Step2: Project 3D electrodes to a 2D snapshot Step3: Manually creating 2D electrode positions
5,202
<ASSISTANT_TASK:> Python Code: labVersion = 'cs190_week1_v_1_2' # TODO: Replace <FILL IN> with appropriate code # Manually calculate your answer and represent the vector as a list of integers values. # For example, [2, 4, 8]. x = [3, -6, 0] y = [4, 8, 16] # TEST Scalar multiplication: vectors (1a) # Import test librar...
<SYSTEM_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: (1b) Element-wise multiplication Step3: (1c) Dot product Step4: (1d) Matrix multiplication Step5: Part 2 Step6: (2b) Elemen...
5,203
<ASSISTANT_TASK:> Python Code: # Init matplotlib %matplotlib inline import matplotlib matplotlib.rcParams['figure.figsize'] = (8, 8) # Setup PyAI import sys sys.path.insert(0, '/Users/jdecock/git/pub/jdhp/pyai') # Set the objective function #from pyai.optimize.functions import sphere as func from pyai.optimize.function...
<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: (1+1)-$\sigma$-Self-Adaptation-ES Step3: Some explanations about $\sigma$ and $\tau$ Step4: Other inplementations Step5: Define the objective...
5,204
<ASSISTANT_TASK:> Python Code: import NotebookImport from DX_screen import * gs2 = gene_sets.ix[dx_rna.index].fillna(0) rr = screen_feature(dx_rna.frac, rev_kruskal, gs2.T, align=False) fp = (1.*gene_sets.T * dx_rna.frac).T.dropna().replace(0, np.nan).mean().order() fp.name = 'mean frac' ff_u = 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: Here I'm running GSEA on the fraction upregulated signal across genes. Step2: First I do a greedy filter based on p-values to find non-overlapp...
5,205
<ASSISTANT_TASK:> Python Code: # Authors: Alexandre Gramfort <alexandre.gramfort@telecom-paristech.fr> # # License: BSD (3-clause) import matplotlib.pyplot as plt import mne from mne import io from mne.datasets import sample from mne.minimum_norm import read_inverse_operator, source_band_induced_power print(__doc__) 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: Set parameters Step2: plot mean power
5,206
<ASSISTANT_TASK:> Python Code: # DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'mpi-m', 'mpi-esm-1-2-hr', 'atmos') # Set as follows: DOC.set_author("name", "email") # TODO - please enter value(s) # Set as follows: DOC.set_contributor("name",...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Document Authors Step2: Document Contributors Step3: Document Publication Step4: Document Table of Contents Step5: 1.2. Model Name Step6: 1...
5,207
<ASSISTANT_TASK:> Python Code: import matplotlib.pyplot as plt %matplotlib inline plt.gray() from keras.datasets import mnist (X_train, y_train), (X_test, y_test) = mnist.load_data() fig, axes = plt.subplots(3,5, figsize=(12,8)) for i, ax in enumerate(axes.flatten()): ax.imshow(X_train[i], interpolation='nearest') ...
<SYSTEM_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 performance here is very poor. We really need to train with more samples and for more epochs.
5,208
<ASSISTANT_TASK:> Python Code: # Author: Annalisa Pascarella <a.pascarella@iac.cnr.it> # # License: BSD (3-clause) import os.path as op import matplotlib.pyplot as plt import mne from mne.datasets import sample from mne import setup_volume_source_space from mne import make_forward_solution from mne.minimum_norm import ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Set up our source space. Step2: Export source positions to nift file
5,209
<ASSISTANT_TASK:> Python Code: import pandas as pd import oandapyV20 import oandapyV20.endpoints.orders as orders import configparser config = configparser.ConfigParser() config.read('../config/config_v20.ini') accountID = config['oanda']['account_id'] access_token = config['oanda']['api_key'] client = oandapyV20.API(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: Get a List of Orders for an Account Step2: List all Pending Orders in an Account Step3: Get Details for a Single Order in an Account Step4: R...
5,210
<ASSISTANT_TASK:> Python Code: import time import numpy as np import tensorflow as tf import utils from urllib.request import urlretrieve from os.path import isfile, isdir from tqdm import tqdm import zipfile dataset_folder_path = 'data' dataset_filename = 'text8.zip' dataset_name = 'Text8 Dataset' class DLProgress(tq...
<SYSTEM_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 text8 dataset, a file of cleaned up Wikipedia articles from Matt Mahoney. The next cell will download the data set to the data folder. ...
5,211
<ASSISTANT_TASK:> Python Code: import pandas as pd %pylab inline df = pd.read_csv("weather.csv", header=0, index_col=0) df mean_temp = df["temperature"].mean() mean_temp mean_humidity = df["humidity"].mean() mean_humidity temp_selector = df['temperature'] > mean_temp df[temp_selector][["outlook", "play"]] humidity_...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Represent the following table using a data structure of your choice Step2: Calculate the mean temperature and mean humidity Step3: Print outlo...
5,212
<ASSISTANT_TASK:> Python Code: %matplotlib inline import matplotlib.pyplot as plt import numpy as np import itertools as itt import time import shutil import os import contextlib import pandas as pd import blaze as blz import bquery import cytoolz from cytoolz.curried import pluck as cytoolz_pluck from collections 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: pandas Step2: blaze Step3: bquery without caching Step4: bquery with caching Step5: Running Times Summary Step6: Graphic Summary Step7: Th...
5,213
<ASSISTANT_TASK:> Python Code: import dowhy from dowhy import CausalModel import pandas as pd import numpy as np # Config dict to set the logging level import logging.config DEFAULT_LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'loggers': { '': { 'level': 'WARN', }...
<SYSTEM_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 Dataset Step2: Lalonde Dataset Step3: Step 1 Step4: Lalonde Step5: Step 2 Step6: Lalonde Step7: Step 3 Step8: Lalonde Step9: ...
5,214
<ASSISTANT_TASK:> Python Code: import numpy as np import matplotlib.pyplot as plt from sklearn.datasets import load_iris iris = load_iris() data, labels = iris.data[:,0:2], iris.data[:,2] num_samples = len(labels) # size of our dataset # shuffle the dataset shuffle_order = np.random.permutation(num_samples) data = 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: Like the 1-dimensional problem previously, we can still do linear regression, except now we have two variables and therefore two weights as well...
5,215
<ASSISTANT_TASK:> Python Code: from ipywidgets import widgets, interact from IPython.display import display import seaborn as sbn import matplotlib.pyplot as plt %matplotlib inline import numpy as np from IPython.core.pylabtools import figsize sbn.set_context("talk", font_scale=.8) figsize(10, 8) # The model used for t...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Uncertainty and Modelling Step2: Scatter plots Step3: You might be tempted to plot a histogram of the model outputs. This shows how often a p...
5,216
<ASSISTANT_TASK:> Python Code: # DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'test-institute-2', 'sandbox-2', 'land') # Set as follows: DOC.set_author("name", "email") # TODO - please enter value(s) # Set as follows: DOC.set_contributor("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: Document Authors Step2: Document Contributors Step3: Document Publication Step4: Document Table of Contents Step5: 1.2. Model Name Step6: 1...
5,217
<ASSISTANT_TASK:> Python Code: # DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'mpi-m', 'mpi-esm-1-2-hr', 'seaice') # Set as follows: DOC.set_author("name", "email") # TODO - please enter value(s) # Set as follows: DOC.set_contributor("name"...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Document Authors Step2: Document Contributors Step3: Document Publication Step4: Document Table of Contents Step5: 1.2. Model Name Step6: 2...
5,218
<ASSISTANT_TASK:> Python Code: %matplotlib inline %config InlineBackend.figure_format = 'retina' import numpy as np import pandas as pd import matplotlib.pyplot as plt data_path = 'Bike-Sharing-Dataset/hour.csv' rides = pd.read_csv(data_path) rides.head() rides[:24*10].plot(x='dteday', y='cnt') dummy_fields = ['seas...
<SYSTEM_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 prepare the data Step2: Checking out the data Step3: Dummy variables Step4: Scaling target variables Step5: Splitting the data into...
5,219
<ASSISTANT_TASK:> Python Code: import numpy as np import matplotlib.pyplot as plt import sunpy.instr.aia %matplotlib inline data = np.loadtxt('../aia_sample_data/aia_wresponse_raw.dat') channels = [94,131,171,193,211,304,335] ssw_results = {} for i in range(len(channels)): ssw_results[channels[i]] = {'wavelength':...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Wavelength Response Step2: Run the SunPy calculation. Step3: Plot the results against each other. Step4: Now, do a "residual plot" of the dif...
5,220
<ASSISTANT_TASK:> Python Code: from polyglot.detect import Detector arabic_text = 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: Step2: Example Step4: Mixed Text Step5: If the text contains snippets from different languages, the detector is able to find the most probable langau...
5,221
<ASSISTANT_TASK:> Python Code: import numpy as np from qutip import * H = Qobj([[1],[0]]) V = Qobj([[0],[1]]) P45 = Qobj([[1/np.sqrt(2)],[1/np.sqrt(2)]]) M45 = Qobj([[1/np.sqrt(2)],[-1/np.sqrt(2)]]) R = Qobj([[1/np.sqrt(2)],[-1j/np.sqrt(2)]]) L = Qobj([[1/np.sqrt(2)],[1j/np.sqrt(2)]]) V def HWP(theta): return Qob...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: These are the polarization states Step2: Devices Step3: Example 1) Check that the $|H\rangle$ state is normalized Step4: To show more informa...
5,222
<ASSISTANT_TASK:> Python Code: print("He said, 'what ?'") s = "This is a string." print(s) print(type(s)) print(len(s)) s = 42 print(s) print(type(s)) print(s * 2) print(s + 7) # Neither statement modifies the variable. s += 2**3 # s is being incremented by 2^3 print("Same as s = s + 2**3") print(s) print(s == 42) ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Strings are delimited by ", but can also use '. This is useful because you can now use one set of quotes inside another, and it'll still be one ...
5,223
<ASSISTANT_TASK:> Python Code: #instantiate our environment import os import sys %matplotlib inline import pandas as pd import statsmodels.api as sm # read the data into a pandas dataframe df = pd.read_csv("read_depth.strains.tsv", header=0, delimiter="\t") print("Shape: {}".format(df.shape)) df.head() dfa = df[(df["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: Filter the data Step2: Note that we have reduced our matrix from having 11,054 entries with all the zeros to only having 1,397 entries now! Ste...
5,224
<ASSISTANT_TASK:> Python Code: import pandas as pd import numpy as np import csv from altair import Chart, X, Y, Axis, SortField import matplotlib.pyplot as plt pd.__version__ %matplotlib inline total = pd.read_csv("../data/database2017.csv") total.shape total.tail() totallast30 = total.sort_values(by='created_at',asc...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Leitura dos últimos 30 registros Step2: Faço a leitura dos últimos 30 registros no arquivo para mostrar em gráfico a evolução do consumo da bat...
5,225
<ASSISTANT_TASK:> Python Code: import hail as hl hl.utils.get_movie_lens('data/') users = hl.read_table('data/users.ht') users.filter(users.occupation == 'programmer').count() users.aggregate(hl.agg.filter(users.occupation == 'programmer', hl.agg.count())) users.aggregate(hl.agg.counter(users.occupation == 'programmer...
<SYSTEM_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 also express this query in multiple ways using aggregations Step2: Annotate Step3: Compare this to what we had before Step4: Note Step...
5,226
<ASSISTANT_TASK:> Python Code: # These are all the modules we'll be using later. Make sure you can import them # before proceeding further. from __future__ import print_function import numpy as np import tensorflow as tf from six.moves import cPickle as pickle from six.moves import range pickle_file = 'notMNIST.pickle...
<SYSTEM_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 reload the data we generated in 1_notmnist.ipynb. Step2: Reformat into a shape that's more adapted to the models we're going to train Ste...
5,227
<ASSISTANT_TASK:> Python Code: import numpy as np import matplotlib import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D %matplotlib inline EI = 5000. #kN m^2 H = 3600. #kN m/m F1 = -2600. #kN F2 = -3600. #kN F3 = -4600. #kN phi = np.linspace(np.pi, -np.pi, 501) theta0 = np.arccos(H/F3) 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: 4.1.1 Visualizing the section force orbits Step2: 4.1.2 Numerical solution of the equilibrium equations Step3: The result shows that this nume...
5,228
<ASSISTANT_TASK:> Python Code: client = pymongo.MongoClient("46.101.236.181") db = client.allfake # get collection names collections = sorted([collection for collection in db.collection_names()]) day = {} # number of tweets per day per collection diff = {} # cumullative diffusion on day per colletion for collection in...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Count number of tweets per day for every news, calculate cummulative diffusion Step2: Plot diffusion for every day for all news together Step3:...
5,229
<ASSISTANT_TASK:> Python Code: from euler import Seq, timer def p001(): return ( range(1000) >> Seq.filter(lambda n: (n%3==0) | (n%5==0)) >> Seq.sum) timer(p001) from euler import Seq, timer def p002(): return ( Seq.unfold(lambda (a,b): (b, (b, b+a)), (0,1)) >> Seq.filte...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Even Fibonacci numbers Step2: Largest prime factor Step3: Largest palindrome product Step4: Smallest multiple Step5: Sum square difference S...
5,230
<ASSISTANT_TASK:> Python Code: from jyquickhelper import add_notebook_menu add_notebook_menu() %matplotlib inline from numpy import random n = 1000 X = random.rand(n, 2) X[:5] y = X[:, 0] * 3 - 2 * X[:, 1] ** 2 + random.rand(n) y[:5] from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_tes...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Des données synthétiques Step2: Exercice 1 Step3: Exercice 2 Step4: Exercice 3 Step5: Le coefficient $R^2$ est plus élevé car on utilise ...
5,231
<ASSISTANT_TASK:> Python Code: # First check the Python version import sys if sys.version_info < (3,4): print('You are running an older version of Python!\n\n', 'You should consider updating to Python 3.4.0 or', 'higher as the libraries built for this course', 'have only been tested in...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Session 5 Step2: <style> .rendered_html code { Step3: Let's take a look at the first part of this Step4: We'll just clean up the text a litt...
5,232
<ASSISTANT_TASK:> Python Code: import swat import time import numpy as np import pandas as pd import matplotlib.pyplot as plt import matplotlib.colors as colors import matplotlib.cm as cmx # Also import networkx used for rendering a network import networkx as nx %matplotlib inline s = swat.CAS('http://cas.mycompany.co...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Connect to Cloud Analytic Services in SAS Viya Step2: Load the action set for hypergroup Step3: Load data into CAS Step4: Hypergroup doesn't ...
5,233
<ASSISTANT_TASK:> Python Code: # Criando um dicionario vazio d = {} # Adicionando elementos para chave-valor d['a'] = 'alpha' d['o'] = 'omega' d['g'] = 'gamma' # algumas propriedades uteis d #Exibindo as chaves d.keys() # Iterando sobre as chaves for k in d.keys(): print 'Key:',k,'->',d[k] #Exibindo os valores d.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: Observe que os itens sao apresentados na forma de Tuplas representando o par chave-valor**
5,234
<ASSISTANT_TASK:> Python Code: %matplotlib inline import matplotlib.pyplot as plt import matplotlib import ndreg from ndreg import preprocessor, util, plotter import SimpleITK as sitk matplotlib.rcParams['figure.figsize'] = (10.0, 8.0) def myshow(img, cmap='gray', colorbar=False): plt.imshow(sitk.GetArrayViewFromIm...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Some metadata is required before registration Step2: Load the sample data Step3: Preprocessing Step4: Registration Step5: Visualize register...
5,235
<ASSISTANT_TASK:> Python Code: from sympy import * from geom_util import * from sympy.vector import CoordSys3D N = CoordSys3D('N') alpha1, alpha2, alpha3 = symbols("alpha_1 alpha_2 alpha_3", real = True, positive=True) init_printing() %matplotlib inline %reload_ext autoreload %autoreload 2 %aimport geom_util H1=symbol...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Lame params Step2: Metric tensor Step3: ${\displaystyle \hat{G}=\sum_{i,j} g_{ij}\vec{R}^i\vec{R}^j}$ Step4: Christoffel symbols Step5: Grad...
5,236
<ASSISTANT_TASK:> Python Code: import numpy as np import pandas as pd import itertools from scipy import stats from statsmodels.stats.descriptivestats import sign_test from statsmodels.stats.weightstats import zconfint from statsmodels.stats.weightstats import * %pylab inline seattle_data = pd.read_csv('seattle.txt', ...
<SYSTEM_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: Двухвыборочные критерии для независимых выборок Step3: Ранговый критерий Манна-Уитни Step4: Перестановочный критерий
5,237
<ASSISTANT_TASK:> Python Code: # Load library import pandas as pd # Create data frame df = pd.DataFrame() # Create data df['dates'] = pd.date_range('1/1/2001', periods=5, freq='D') df['stock_price'] = [1.1,2.2,3.3,4.4,5.5] # Lagged values by one row df['previous_days_stock_price'] = df['stock_price'].shift(1) # Show ...
<SYSTEM_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 Date Data Step2: Lag Time Data By One Row
5,238
<ASSISTANT_TASK:> Python Code: from sys import version print(version) from typing import TypeVar, List _a = TypeVar('alpha') def taille(liste : List[_a]) -> int: longueur = 0 for _ in liste: longueur += 1 return longueur taille([]) taille([1, 2, 3]) len([]) len([1, 2, 3]) from typing import TypeVa...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Listes Step2: Exercice 2 Step3: Mais attention le typage est toujours optionnel en Python Step4: Exercice 3 Step5: Notre implémentation e...
5,239
<ASSISTANT_TASK:> Python Code: import os, sys import inspect import numpy as np import datetime as dt import time import pytz import pandas as pd import pdb script_dir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) # add the path to opengrid to sys.path sys.path.append(os.path.join(script_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: Script settings Step2: We create one big dataframe, the columns are the sensors of type electricity Step3: Convert Datetimeindex to local time...
5,240
<ASSISTANT_TASK:> Python Code: import matplotlib import matplotlib.pyplot as plt import numpy as np import pymc as pm from numpy.random import choice %matplotlib inline matplotlib.style.use('ggplot') matplotlib.rc_params_from_file("../styles/matplotlibrc" ).update() def switch_envelope(chosen_envelope): if chosen_...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Helper methods Step2: We also need some helper methods to evaluate the success of our strategy Step3: Implementing the actual strategy Step4: ...
5,241
<ASSISTANT_TASK:> Python Code: x = [7, 3, 5] x.pop? # anything after the hashtag is a comment # load packages import datetime as dt import pandas.io.data as web # data import tools import matplotlib.pyplot as plt # plotting tools # The next one is an IPython command: it says to put plots here in the not...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Example 1 Step2: The variable g (quarterly GDP growth expressed as an annual rate) is now what Python calls a DataFrame, which is a collection ...
5,242
<ASSISTANT_TASK:> Python Code: # These are all the modules we'll be using later. Make sure you can import them # before proceeding further. import matplotlib.pyplot as plt import numpy as np import os import tarfile import urllib from urllib.request import urlretrieve from IPython.display import display, Image from sc...
<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: First, we'll download the dataset to our local machine. The data consists of characters rendered in a variety of fonts on a 28x28 image. The lab...
5,243
<ASSISTANT_TASK:> Python Code: import toytree import toyplot # generate a random tree tre = toytree.rtree.unittree(ntips=10, treeheight=100, seed=123) # draw tree on canvas canvas, axes, mark = tre.draw(ts='c', layout='r', tip_labels=True); # get annotator tool anno = toytree.utils.Annotator(tre, axes, mark) # annotat...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Builtin method to highlight clades Step2: Or, use toyplot directly Step3: More examples
5,244
<ASSISTANT_TASK:> Python Code: import os # The Vertex AI Workbench Notebook product has specific requirements IS_WORKBENCH_NOTEBOOK = os.getenv("DL_ANACONDA_HOME") IS_USER_MANAGED_WORKBENCH_NOTEBOOK = os.path.exists( "/opt/deeplearning/metadata/env_version" ) # Vertex AI Notebook requires dependencies to be install...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Restart the kernel Step2: Set up your Google Cloud project Step3: Region Step4: Timestamp Step5: Authenticate your Google Cloud account Step...
5,245
<ASSISTANT_TASK:> Python Code: from projectq import MainEngine from projectq.backends import AWSBraketBackend from projectq.ops import Measure, H, C, X, All creds = { 'AWS_ACCESS_KEY_ID': 'aws_access_key_id', 'AWS_SECRET_KEY': 'aws_secret_key', } # replace with your Access key and Secret key s3_folder = ['...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Prior to the instantiation of the backend we need to configure the credentials, the S3 storage folder and the device to be used (in the example ...
5,246
<ASSISTANT_TASK:> Python Code: PROJECT_ID = "YOUR PROJECT ID" BUCKET_NAME = "gs://YOUR BUCKET NAME" REGION = "YOUR REGION" SERVICE_ACCOUNT = "YOUR SERVICE ACCOUNT" ! gsutil ls -al $BUCKET_NAME content_name = "pt-img-cls-multi-node-ddp-cust-cont" ! ls trainer ! cat trainer/requirements.txt ! pip install -r trainer/requ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Local Training Step2: Vertex Training using Vertex SDK and Custom Container Step3: Initialize Vertex SDK Step4: Create a Vertex Tensorboard I...
5,247
<ASSISTANT_TASK:> Python Code: import numpy as np import scipy.io as sio import matplotlib.pyplot as plt import control !wget https://alfkjartan.github.io/files/sysid_hw_data.mat data = sio.loadmat("sysid_hw_data.mat") N = len(data["u1"]) plt.figure(figsize=(14,1.7)) plt.step(range(N),data["u1"]) plt.ylabel("u_1") 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: Load the data Step2: Plot the data Step3: Identify first order model Step4: Validation
5,248
<ASSISTANT_TASK:> Python Code: def find_max(words): return sorted(words, key = lambda x: (-len(set(x)), x))[0] <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:
5,249
<ASSISTANT_TASK:> Python Code: cd ~/Desktop/SSUsearch/ mkdir -p ./workdir #check seqfile files to process in data directory (make sure you still remember the data directory) !ls ./data/test/data Seqfile='./data/test/data/1c.fa' Cpu='1' # number of maxixum threads for search and alignment Hmm='./data/SSUsearch_db/Hm...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: README Step2: Other parameters to set Step3: Pass hits to mothur aligner Step4: Get aligned seqs that have > 50% matched to references Step5:...
5,250
<ASSISTANT_TASK:> Python Code: # 定义一个tuple tuple1 = ('bosco','ricky','pinky') tuple1 # 一个项目的 tuple tuple2 = (5,) tuple2 # 一次赋多值 x,y,z = tuple1 print(x,y,z) # 用in判断 'bosco' in tuple1 # 索引 tuple1[0] # string tuple("money") list1 = [16,2,53,24,5,36,67,80] list1 # 索引 indexing list1[5] # 分片 slicing list1[:5] list1[3:] list...
<SYSTEM_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. list<a name="2list"></a> Step2: list2 Step3: list3 Step4: list4 Step5: string Step6: 3. array<a name="3array"></a> Step7: some function...
5,251
<ASSISTANT_TASK:> Python Code: import copy import cPickle import os import subprocess import cdpybio as cpb import matplotlib.pyplot as plt import numpy as np import pandas as pd from scipy.linalg import svd import scipy.stats as stats import seaborn as sns import statsmodels.formula.api as smf import cardipspy as cpy ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: STAR Logs Step2: Picard Metrics Step3: Expression Distribution Step4: We can see overal that there are a fair number of genes that are not ex...
5,252
<ASSISTANT_TASK:> Python Code: import veneer v = veneer.Veneer(port=9876) input_sets = v.input_sets() input_sets input_sets.as_dataframe() things_to_record=[ {'NetworkElement':'Lower Gauge','RecordingVariable':'Downstream Flow Volume'}, {'NetworkElement':'Crop Fields'}, {'NetworkElement':'Recreational Lak...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Finding the input sets in the model Step2: Note Step3: We now want to iterate over the input sets, running the model each time, and retrieving...
5,253
<ASSISTANT_TASK:> Python Code: # Authors: Alexandre Gramfort <alexandre.gramfort@telecom-paristech.fr> # Denis Engemann <denis.engemann@gmail.com> # # License: BSD (3-clause) import matplotlib.pyplot as plt import mne from mne import io from mne.datasets import sample print(__doc__) data_path = sample.data_pat...
<SYSTEM_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: Show event related fields images
5,254
<ASSISTANT_TASK:> Python Code: As I will attempt to describe in the next slides, Python is an amazing way to lead to a more fun learning and teaching experience. It can be a basic calculator, a fancy calculator and Math, Science, Geography.. Tools that will help us in that quest are: When you bring in SymPy to the pi...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: (Main) Tools Step2: Python - Making other subjects more lively
5,255
<ASSISTANT_TASK:> Python Code: import numpy as np import pandas as pd import pandas_datareader as pdr import matplotlib.pyplot as plt import seaborn as sns plt.rc("figure",figsize=(16,8)) plt.rc("font",size=15) plt.rc("lines",linewidth=3) sns.set_style("darkgrid") reader = pdr.fred.FredReader(["HOUST"], start="1980-01...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Load some Data Step2: We fit specify the model without any options and fit it. The summary shows that the data was deseasonalized using the mul...
5,256
<ASSISTANT_TASK:> Python Code: restaurants = pd.read_csv("NYC_Restaurants.csv", dtype=unicode) for index, item in enumerate(restaurants.columns.values): print index, item #use .apply() method to combine the 4 columns to get the unique restaurant name restaurants["RESTAURANT"] = restaurants[["DBA", "BUILDING", "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: Step1: Question 1 Step2: Question 2 Step3: Question 3 Step4: Question 4 Step5: Question 5 Step6: Question 6 Step7: Question 7 Step8: Question 8 ...
5,257
<ASSISTANT_TASK:> Python Code: total = 0 # initialise total for yeargroup in range(6): prompt = "How many pupils are in year S"+str(yeargroup+1)+": " pupils = int(input(prompt)) total = total + pupils # add to total print("Total = ", total) vauxhall = 0 ford = 0 mazda = 0 for car in range(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: If you have done it right, you should see Step2: Run the program above, if you haven't already! It just runs for 10 cars.
5,258
<ASSISTANT_TASK:> Python Code: import sys sys.path.append(r"..") import daymetpy ornl_lat, ornl_long = 35.9313167, -84.3104124 df = daymetpy.daymet_timeseries(lon=ornl_long, lat=ornl_lat, start_year=2012, end_year=2013) df.head() import pandas as pd import seaborn as sns import matplotlib.pyplot as plt %matplotlib in...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Which gives us a nice data frame with weather data for the Oak Ridge National Lab Step2: Which we can visualize using matplotlib and seaborn St...
5,259
<ASSISTANT_TASK:> Python Code: from datetime import datetime, timedelta from IPython.display import display from math import factorial from matplotlib import pyplot as plt import io import numpy as np import pandas as pd Σ = sum %matplotlib inline def timetable(a, b): return b + timedelta(minutes=int(a)) v_ti...
<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: Dados Step5: a) Descrição do sistema de filas, local, data e horários da coleta de dados Step6: b) Número de servidores atendendo = S Step7: ...
5,260
<ASSISTANT_TASK:> Python Code: import random from pomegranate import * random.seed(0) state1 = State( UniformDistribution(0.0, 1.0), name="uniform" ) state2 = State( NormalDistribution(0, 2), name="normal" ) model = HiddenMarkovModel( name="ExampleModel" ) model.add_state( state1 ) model.add_state( state2 ) model.ad...
<SYSTEM_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 create the states of the model, one uniform and one normal. Step2: We will then create the model by creating a HiddenMarkovModel ...
5,261
<ASSISTANT_TASK:> Python Code: !cd data/ && pdftohtml -c -hidden -xml ALA1934_RR-excerpt.pdf ALA1934_RR-excerpt.pdf.xml !ls -1 data/ !head -n 30 data/ALA1934_RR-excerpt.pdf.xml !python3 -m http.server 8080 --bind 127.0.0.1 DATAPATH = 'data/' OUTPUTPATH = 'generated_output/' INPUT_XML = 'ALA1934_RR-excerpt.pdf.xml' 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: We generated an XML which consists of several &lt;page&gt; elements, containing an &lt;image&gt; (the "background" image, i.e. the scanned page)...
5,262
<ASSISTANT_TASK:> Python Code: #Final iteration tried across different cuts. Accuracy >55% keywords = [ 'nice', 'pleased', 'better', 'like', 'easy', 'excellent', 'love','impressed', 'satisfied','pretty', 'best','works great'] for key in keywords: # Note that we add spaces ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Principal Components Analysis Step2: Recursive Feature Elimination Step3: Splitting the data in a train and a test subset Step4: Test the res...
5,263
<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 import sys # to make this notebook's output stable across runs def reset_graph(seed=42): tf.reset_default_graph() tf.set_random_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: A couple utility functions to plot grayscale 28x28 image Step2: PCA with a linear Autoencoder Step3: Normalize the data Step4: Now let's buil...
5,264
<ASSISTANT_TASK:> Python Code: from __future__ import division, print_function %matplotlib inline #format the book import book_format book_format.set_style() import matplotlib.pyplot as plt data = [10.1, 10.2, 9.8, 10.1, 10.2, 10.3, 10.1, 9.9, 10.2, 10.0, 9.9, 11.4] plt.plot(data) plt.xlabel('time') plt.ylabe...
<SYSTEM_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: After a period of near steady state, we have a very large change. Assume the change is past the limit of the aircraft's fli...
5,265
<ASSISTANT_TASK:> Python Code: import pandas as pd import numpy as np from pandas.tools.plotting import scatter_matrix from matplotlib import pyplot as plt from sklearn.model_selection import train_test_split from sklearn.model_selection import KFold from sklearn.model_selection import cross_val_score from sklearn.metr...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: b) Load dataset Step2: The 'Pregnant' column can only take on one of two (in this case) possabilities. Here 1 = pregnant, and 0 = not pregnant ...
5,266
<ASSISTANT_TASK:> Python Code: # Import the library we need, which is Pandas and Matplotlib import pandas as pd import numpy as np import matplotlib.pyplot as plt %matplotlib inline # Set some parameters to get good visuals - style to ggplot and size to 15,10 plt.style.use('ggplot') plt.rcParams['figure.figsize'] = (15...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Question 3 Step2: PRINCIPLE Step3: PRINCIPLE Step4: PRINCIPLE Step5: Question 4 Step6: Now we can fit an ARIMA model on this (Explaining AR...
5,267
<ASSISTANT_TASK:> Python Code: lista_de_numeros = [1, 6, 3, 9, 5, 2] lista_ordenada = sorted(lista_de_numeros) print lista_ordenada print lista_de_numeros lista_de_numeros = [1, 6, 3, 9, 5, 2] print sorted(lista_de_numeros, reverse=True) def crear_curso(): curso = [ {'nombre': 'Rodriguez, Carlos', 'nota':...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Pero, ¿y cómo hacemos para ordenarla de mayor a menor?. <br> Step2: ¿Y si lo que quiero ordenar es una lista de registros?. <br> Step3: Búsque...
5,268
<ASSISTANT_TASK:> Python Code: import os import numpy as np import pandas as pd import tensorflow as tf # read data from file data = pd.read_csv('data/train.csv') print(data.info()) # fill nan values with 0 data = data.fillna(0) # convert ['male', 'female'] values of Sex to [1, 0] data['Sex'] = data['Sex'].apply(lambd...
<SYSTEM_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. 预处理 Step2: 3. 将训练数据切分为训练集(training set)和验证集(validation set) Step3: 二、构建计算图 Step4: 2. 声明参数变量 Step5: 3. 构造前向传播计算图 Step6: 4. 声明代价函数 Step...
5,269
<ASSISTANT_TASK:> Python Code: %matplotlib inline import matplotlib.pyplot as plt import networkx as nx G=nx.DiGraph() G.add_edge('sex','height',weight=0.6) nx.draw_networkx(G, node_color='y',node_size=2000, width=3) plt.axis('off') plt.show() import numpy as np import pandas as pd import csv import json from libpgm.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: Why is this formalism a useful probabalistic problem solving tool? Step2: And now, for some data Step3: A pivot table might give another usefu...
5,270
<ASSISTANT_TASK:> Python Code: editdist_sp = [ (sp1,sp2,editdistance.eval(sp1,sp2)) for sp1,sp2 in itertools.combinations(read_annot["species_fillna"].unique(),2) ] editdist_df = pd.DataFrame.from_records(editdist_sp,columns=["sp1","sp2","edit_distance"]) editdist_df["similarity"] = editdist_df.apply(lambda r: (max(len...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Use new clade groups
5,271
<ASSISTANT_TASK:> Python Code: regimen = clinical['Regimen Type'].ix[pts].dropna() print regimen.value_counts() regimen = regimen[regimen.map(regimen.value_counts()) > 10] regimen = regimen.ix[pts].fillna('Other') regimen = regimen.str.replace(' Based','') regimen = regimen.ix[ti(duration != 'Control')] regimen.value_c...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: LLQ
5,272
<ASSISTANT_TASK:> Python Code: import numpy as np import pandas as pd from IPython.display import Image def mean_squared_error(y_true, y_pred): calculate the mean_squared_error given a vector of true ys and a vector of predicted ys diff = y_true - y_pred return np.dot(diff, diff) / len(diff) 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: Step2: Predictive Modeling Step3: The Central Theses of Machine Learning Step4: How to Fight Overfitting? Step5: <span style="color Step6: L1 Regul...
5,273
<ASSISTANT_TASK:> Python Code: # Versão da Linguagem Python from platform import python_version print('Versão da Linguagem Python Usada Neste Jupyter Notebook:', python_version()) # Imprimindo números pares entre 50 e 101 for i in range(50, 101, 2): print(i) for i in range(3, 6): print (i) for i in range(0, -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: Range
5,274
<ASSISTANT_TASK:> Python Code: import essentia.standard as es from tempfile import TemporaryDirectory # Loading an audio file. audio = es.MonoLoader(filename='../../../test/audio/recorded/dubstep.flac')() # Compute beat positions and BPM. rhythm_extractor = es.RhythmExtractor2013(method="multifeature") bpm, beats, beat...
<SYSTEM_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 now listen to the resulting audio with the beats marked by beeps. We can also visualize beat estimations. Step2: BPM histogram Step3: B...
5,275
<ASSISTANT_TASK:> Python Code: import pandas as pd qs = [(2, 0), (1, 1), (0, 2), (3, 0), (2, 1), (1, 2), (0, 3), (4, 0), (3, 1), (2, 2), (1, 3), (0, 4), ] index = pd.MultiIndex.from_tuples(qs, names=['Boys', 'Girls']) from scipy.stats import binom 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: To compute the proportion of each type of family, I'll use Scipy to compute the binomial distribution. Step2: And put the results into a Pandas...
5,276
<ASSISTANT_TASK:> Python Code: import tensorflow as tf from tensorflow.python.client import timeline import pylab import numpy as np %matplotlib inline %config InlineBackend.figure_format = 'retina' tf.logging.set_verbosity(tf.logging.INFO) tf.reset_default_graph() num_samples = 100000 from datetime import datetime ve...
<SYSTEM_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 Model Test/Validation Data Step2: Look at the Model Graph In Tensorboard Step3: Train Model Step4: Look at the Train and Test Loss Sum...
5,277
<ASSISTANT_TASK:> Python Code: import warnings warnings.filterwarnings('ignore') %matplotlib inline %pylab inline import matplotlib.pylab as plt import numpy as np from distutils.version import StrictVersion import sklearn print(sklearn.__version__) assert StrictVersion(sklearn.__version__ ) >= StrictVersion('0.18.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: Loading and Preparing Data Step3: Big Kudos to Waleed Abdulla for providing the initial idea and many of the functions used to prepare and disp...
5,278
<ASSISTANT_TASK:> Python Code: # Import libraries necessary for this project import numpy as np import pandas as pd from IPython.display import display # Allows the use of display() for DataFrames # Import supplementary visualizations code visuals.py import visuals as vs # Pretty display for notebooks %matplotlib inlin...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: From a sample of the RMS Titanic data, we can see the various features present for each passenger on the ship Step3: The very same sample of th...
5,279
<ASSISTANT_TASK:> Python Code: import logging from conf import LisaLogging LisaLogging.setup() # Execute this cell to enabled executor debugging statements logging.getLogger('Executor').setLevel(logging.DEBUG) from env import TestEnv # Setup a test environment with target configuration env = TestEnv({ # Targe...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Target Configuration Step2: Tests Configuration Step3: Tests execution
5,280
<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 = None # TODO: C...
<SYSTEM_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...
5,281
<ASSISTANT_TASK:> Python Code: %pylab inline from colormap import Colormap c = Colormap() cmap = c.cmap('cool') # let us see what it looks like c.test_colormap(cmap) #Would be nice to plot a bunch of colormap to pick up one interesting c.plot_colormap('diverging') c.plot_colormap(c.misc) c.plot_colormap(c.qualitative) ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Well, I have not found the one I wanted...I wanted from red to white to green Step2: Using cma_builder and test_cmap
5,282
<ASSISTANT_TASK:> Python Code: # First load RESSPyLab and necessary packages import numpy as np import RESSPyLab as rpl # Identify the material material_def = {'material_id': ['Example 1'], 'load_protocols': ['1,5']} # Set the path to the x log file x_log_file_1 = './output/x_log.txt' x_logs_all = [x_log_file_1] # Loa...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Original Voce-Chaboche model Step2: Tables can be easily generated following a standard format for several data sets by appending additional en...
5,283
<ASSISTANT_TASK:> Python Code: import numpy as np from sklearn.preprocessing import scale Dtrans = np.loadtxt("transfusion.data",dtype=np.str_,delimiter=",") X = np.array(Dtrans[1:,0:4],dtype=float) y = np.array(Dtrans[1:,4],dtype=float) X = scale(X) from sklearn import svm import sklearn.linear_model as skl_lm from 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: Exercise 1.1 (10 pts) Use 5-fold cross validation, leave-one-out CV, and a 50% holdout to tune the bandwidth and ridge penalty parameter for the...
5,284
<ASSISTANT_TASK:> Python Code: 7**4 s = "Hi there Sam!" s.split() planet = "Earth" diameter = 12742 print("The diameter of {} is {} kilometers.".format(planet,diameter)) lst = [1,2,[3,4],[5,[100,200,['hello']],23,11],1,7] lst[3][1][2] d = {'k1':[1,2,3,{'tricky':['oh','man','inception',{'target':[1,2,3,'hello']}]}]}...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Split this string Step2: Given the variables Step3: Given this nested list, use indexing to grab the word "hello" Step4: Given this nested di...
5,285
<ASSISTANT_TASK:> Python Code: %matplotlib inline import matplotlib.pyplot as plt import seaborn as sns import numpy as np from scipy.interpolate import interp1d, interp2d f = np.load('trajectory.npz') x = f['x'] y = f['y'] t = f['t'] assert isinstance(x, np.ndarray) and len(x)==40 assert isinstance(y, np.ndarray) 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: 2D trajectory interpolation Step2: Use these arrays to create interpolated functions $x(t)$ and $y(t)$. Then use those functions to create the ...
5,286
<ASSISTANT_TASK:> Python Code: %matplotlib notebook import numpy as np import pandas as pd import statsmodels.api as sm import matplotlib.pyplot as plt # First we'll simulate the synthetic data def simulate_seasonal_term(periodicity, total_cycles, noise_std=1., harmonics=None): duration ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Synthetic data creation Step2: Unobserved components (frequency domain modeling) Step3: Observe that the fitted variances are pretty close to ...
5,287
<ASSISTANT_TASK:> Python Code: import numpy as np import matplotlib.pyplot as plt %matplotlib inline from IPython.display import HTML HTML('../style/course.css') #apply general CSS from scipy.optimize import leastsq plt.rcParams['figure.figsize'] = (18, 6) from IPython.display import HTML HTML('../style/code_toggle.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: Import section specific modules Step5: 2.11 Least-squares Minimization<a id='groundwork Step6: The three functions defined above will be used ...
5,288
<ASSISTANT_TASK:> Python Code: import matplotlib.pyplot as plt import numpy as np import h5py, os, osr, copy %matplotlib inline import warnings warnings.filterwarnings('ignore') def aop_h5refl2array(refl_filename): aop_h5refl2array reads in a NEON AOP reflectance hdf5 file and returns 1. reflectance ar...
<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: The first function we will use is aop_h5refl2array. This function is loaded into the cell below, we encourage you to look through the code to un...
5,289
<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: Unicode strings Step2: The tf.string data type Step3: A tf.string tensor treats byte strings as atomic units. This enables it to store byte st...
5,290
<ASSISTANT_TASK:> Python Code: import inspect import types import sys # I sometimes need to choose PyTorch... #sys.path.insert(0, '/home/tv/pytorch/pytorch/build/lib.linux-x86_64-3.8//') import torch import torch.utils.dlpack # import TVM import sys import os tvm_root = '/home/tv/rocm/tvm/tvm/' tvm_paths = [os.path.joi...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Helpfully, transformers supports tracing their model with the PyTorch JIT. We use their tutorial on it, the following is copied straight from th...
5,291
<ASSISTANT_TASK:> Python Code: # Load data X = np.concatenate((np.ones((pima.shape[0],1)),pima[:,0:8]), axis=1) Y = pima[:,8] Xs = (X - np.mean(X, axis=0))/np.concatenate((np.ones(1),np.std(X[:,1:], axis=0))) n, p = X.shape nsample = 1 nbatch = 768 M = np.identity(p) C = 0 * np.identity(p) eps = 0.1 m = 10 V = 0 * np.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: Correct coefficients Step2: Our code - HMC Step3: Our code - Gradient descent Step5: Cliburn's code
5,292
<ASSISTANT_TASK:> Python Code: trace0 = go.Scatter( x=[1, 2, 3, 4], y=[10, 15, 13, 17] ) trace1 = go.Scatter( x=[1, 2, 3, 4], y=[16, 5, 11, 9] ) data = go.Data([trace0, trace1]) py.iplot(data, filename = 'basic-line') alpha = np.array([5, 5, 5]) rv = st.dirichlet(alpha) coord_step = 0.01 coord_range = ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Try Plotting a Dirichlet Distribution Step4: Make an Interactive 3D Plot with Parameter Selection
5,293
<ASSISTANT_TASK:> Python Code: import array a = array.array('i', range(10)) # 数据类型必须统一 a[1] = 's' a import numpy as np a_list = list(range(10)) b = np.array(a_list) type(b) a = np.zeros(10, dtype=int) print(type(a)) # 查看数组类型 a.dtype a = np.zeros((4,4), dtype=int) print(type(a)) # 查看数组类型 print(a.dtype) a np.ones((4,4)...
<SYSTEM_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: 生成数组 Step3: random Step4: 范围取值 Step5: | Data type | Description | Step6: 数组属性 Step7: 运算 Step8: | Operator | Eq...
5,294
<ASSISTANT_TASK:> Python Code: tweets = [] RUTA = '' for line in open(RUTA).readlines(): tweets.append(line.split('\t')) ultimo_tweet = tweets[-1] print('id =>', ultimo_tweet[0]) print('fecha =>', ultimo_tweet[1]) print('autor =>', ultimo_tweet[2]) print('texto =>', ultimo_tweet[3]) # escribe tu código a continua...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Fíjate en la estructura de la lista Step2: Al lío
5,295
<ASSISTANT_TASK:> Python Code: # Execute this cell to load the notebook's style sheet, then ignore it from IPython.core.display import HTML css_file = '../../style/custom.css' HTML(open(css_file, "r").read()) # Import Libraries (PLEASE RUN THIS CODE FIRST!) # ---------------------------------------------- import nump...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Solving the 1D acoustic wave equation by finite-differences Step2: Source time function Step3: Analytical Solution Step4: Comparison of numer...
5,296
<ASSISTANT_TASK:> Python Code: import os import sys # Google Cloud Notebook if os.path.exists("/opt/deeplearning/metadata/env_version"): USER_FLAG = "--user" else: USER_FLAG = "" ! pip3 install -U google-cloud-aiplatform $USER_FLAG ! pip3 install -U google-cloud-storage $USER_FLAG if not os.getenv("IS_TESTING...
<SYSTEM_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 the latest GA version of google-cloud-storage library as well. Step2: Restart the kernel Step3: Before you begin Step4: Region Step5:...
5,297
<ASSISTANT_TASK:> Python Code: # DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'test-institute-1', 'sandbox-1', 'ocean') # Set as follows: DOC.set_author("name", "email") # TODO - please enter value(s) # Set as follows: DOC.set_contributor("...
<SYSTEM_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...
5,298
<ASSISTANT_TASK:> Python Code: titles.shape[0] titles.sort(columns='year')[0:2] titles[titles['title']=='Hamlet'].shape[0] titles[titles['title']=='North by Northwest'].shape[0] titles[titles['title']=='Hamlet'].sort(columns='year')['year'].values[0] titles[titles['title']=='Treasure Island'].sort(columns='year') ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: What are the earliest two films listed in the titles dataframe? Step2: How many movies have the title "Hamlet"? Step3: How many movies are tit...
5,299
<ASSISTANT_TASK:> Python Code: %pylab inline %matplotlib inline import os SHOGUN_DATA_DIR=os.getenv('SHOGUN_DATA_DIR', '../../../data') from scipy.io import loadmat from shogun import RealFeatures, MulticlassLabels, Math # load the dataset dataset = loadmat(os.path.join(SHOGUN_DATA_DIR, 'multiclass/usps.mat')) Xall = 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: Creating the autoencoder Step2: Pre-training Step3: Fine-tuning Step4: Evaluation Step5: The figure shows the corrupted examples and their r...