Unnamed: 0
int64
0
15.9k
cleaned_code
stringlengths
67
124k
cleaned_prompt
stringlengths
168
30.3k
3,300
<ASSISTANT_TASK:> Python Code: import hydrofunctions as hf print("Hydrofunctions version: ", hf.__version__) import numpy as np print("Numpy version: ", np.__version__) import pandas as pd print("Pandas version: ", pd.__version__) import requests print("Requests version: ", requests.__version__) import matplotlib as 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: Create sample NWIS responses to requests. Step2: Check values of test fixtures Step3: Check individual values within the mult_flags fixture St...
3,301
<ASSISTANT_TASK:> Python Code: from __future__ import print_function # Import libraries import numpy as np import pandas as pd import matplotlib.pyplot as plt import psycopg2 import os # below is used to print out pretty pandas dataframes from IPython.display import display, HTML %matplotlib inline def execute_query_sa...
<SYSTEM_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 - Generate materialized views Step3: Now we generate the aline_cohort table using the aline_cohort.sql file. Step4: The following codeblock ...
3,302
<ASSISTANT_TASK:> Python Code: # Import Numpy, TensorFlow, TFLearn, and MNIST data import numpy as np import tensorflow as tf import tflearn import tflearn.datasets.mnist as mnist # Retrieve the training and test data trainX, trainY, testX, testY = mnist.load_data(one_hot=True) # Visualizing the data import matplotli...
<SYSTEM_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 training and test data Step2: Visualize the training data Step3: Building the network Step4: Training the network Step5: Testing
3,303
<ASSISTANT_TASK:> Python Code: import numpy as np %matplotlib inline import matplotlib.pyplot as plt import seaborn as sns def np_fact(n): Compute n! = n*(n-1)*...*1 using Numpy. # YOUR CODE HERE a = np.arange(1, n+1, 1) #Makes array from 1 to n+1 if n==0: return 1 #If n is 1 or...
<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: Factorial Step4: Write a function that computes the factorial of small numbers using a Python loop. Step5: Use the %timeit magic to time both ...
3,304
<ASSISTANT_TASK:> Python Code: DEM_filepath = "" sample_points_filepath = "" import matplotlib.pylab as plt %matplotlib inline import rasterio import fiona plt.plot([1,2,3,4]) plt.ylabel('some numbers') plt.show() with rasterio.drivers(): with rasterio.open(DEM_filepath) as source_dem: array_dem = source_...
<SYSTEM_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 statements Step2: Examples
3,305
<ASSISTANT_TASK:> Python Code: %run db2.ipynb %sql -sampledata %%sql -q DROP TABLE HC.PATIENTS; CREATE TABLE HC.PATIENTS ( SIN VARCHAR(11), USERID VARCHAR(8), NAME VARCHAR(8), ADDRESS VARCHAR(12), PHARMACY VARCHAR(12), ACCT_BALANCE DEC(9,2), PCP_ID VARCHAR(8) ); INSERT INTO HC.PATIENTS...
<SYSTEM_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 populate the database with the EMPLOYEE and DEPARTMENT tables so that we can run the various examples. Step2: Health Care Scenario Step3: S...
3,306
<ASSISTANT_TASK:> Python Code:: model.score(x_test, y_test) <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:
3,307
<ASSISTANT_TASK:> Python Code: import sympy from sympy import Symbol, sqrt x = Symbol('x', real=True) a = Symbol('a', real=True) y = Symbol('y', real=True) b = Symbol('b', real=True) r = sqrt(x ** 2 + y ** 2) sympy.init_printing() z = sympy.integrate(1/r, x, conds='none') print z import numpy as np import math 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: Nystrom method Step2: A sidenote about fitting by sum of exponentials Step3: Off-diagonal blocks correspond to "far" interaction Step4: Plott...
3,308
<ASSISTANT_TASK:> Python Code: from scipy.misc import imsave, toimage from os import listdir from os.path import basename, splitext import glob import numpy as np npy_path = '../compressed-models/alexnet/npy/' jpg_path = '../compressed-models/alexnet/jpegs/' gif_path = '../compressed-models/alexnet/gifs/' png_path = '....
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Load all npys and convert them to JPEG Step2: Load all npys and convert them to GIF Step3: Load all npys and convert them to PNG Step4: 2. Re...
3,309
<ASSISTANT_TASK:> Python Code: from rmtk.vulnerability.common import utils import double_MSA_on_SDOF import numpy from rmtk.vulnerability.derivation_fragility.NLTHA_on_SDOF.read_pinching_parameters import read_parameters import MSA_utils %matplotlib inline capacity_curves_file = '/Users/chiaracasotto/GitHub/rmtk_data/...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Load capacity curves Step2: Load ground motion records Step3: Load damage state thresholds Step4: Calculate fragility function Step5: Fit lo...
3,310
<ASSISTANT_TASK:> Python Code: # your function # test your function text = 'This is an example text. The text mentions a former president of the United States, Barack Obama.' basename = 'test_text.tsv' output_dir = 'test_dir' text_to_conll_simple(text, nlp, output_dir...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Tip 0 Step2: Tip 1 Step3: Tip 2 Step4: Tip 3 Step5: 3. Building python modules to process files in a directory
3,311
<ASSISTANT_TASK:> Python Code: import pandas as pd import numpy as np symbol = 'Security 1' symbol2 = 'Security 2' price_data = pd.DataFrame(np.cumsum(np.random.randn(150, 2).dot([[0.5, 0.4], [0.4, 1.0]]), axis=0) + 100, columns=[symbol, symbol2], index=pd.date_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: Introduction <a class="anchor" id="introduction"></a> Step2: Brush Selectors <a class="anchor" id="brushselectors"></a> Step3: Linking the bru...
3,312
<ASSISTANT_TASK:> Python Code: %matplotlib inline import matplotlib.pyplot as plt import numpy as np from IPython.display import Image from qutip import * Image(filename='images/optomechanical_setup.png', width=500, embed=True) # System Parameters (in units of wm) #----------------------------------- Nc = 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: Optomechanical Hamiltonian Step2: Assuming that $a^{+}$, $a$ and $b^{+}$,$b$ are the raising and lowering operators for the cavity and mechanic...
3,313
<ASSISTANT_TASK:> Python Code: # Tensorflow import tensorflow as tf from tensorflow.contrib.layers import fully_connected # Common imports import numpy as np import numpy.random as rnd import os import sys # to make this notebook's output stable across runs rnd.seed(42) # To plot pretty figures %matplotlib inline 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: Autoencoder Step2: Stacked Autoencoders on MNIST Step3: Train all layers at once Step4: Now let's train it! Note that we don't feed target va...
3,314
<ASSISTANT_TASK:> Python Code: from __future__ import absolute_import, division, print_function import glob import imageio import os import PIL import time import numpy as np import matplotlib.pyplot as plt import tensorflow as tf from tensorflow.keras import layers from IPython import display np.random.seed(1) tf.ran...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Next, we'll define some of the environment variables we'll use in this notebook. Note that we are setting the EMBED_DIM to be 64. This is the di...
3,315
<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: 自定义联合算法,第 1 部分:Federated Core 简介 Step2: 联合数据 Step3: 更普遍的是,TFF 中的联合类型是通过指定其成员组成(留驻在各个设备上的数据项)的类型 T 和托管此类型联合值的设备组 G(加上我们会在稍后提及的第三个可选位)来定义的。我们将托管...
3,316
<ASSISTANT_TASK:> Python Code: symbols = '$#%^&' [ord(s) for s in symbols] tuple(ord(s) for s in symbols) (ord(s) for s in symbols) for x in (ord(s) for s in symbols): print(x) import array array.array('I', (ord(s) for s in symbols)) colors = ['black', 'white'] sizes = ['S', 'M', 'L'] for tshirt in ((c, s) for c 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: Tuples as Records Step2: Tuple Unpacking Step3: Named tuples Step5: Slicing Step6: Assigning to Slices Step7: Using + and * with Sequences ...
3,317
<ASSISTANT_TASK:> Python Code: import os import pandas as pd import seaborn as sns import numpy as np from scipy import stats, integrate import matplotlib.pyplot as plt import sklearn from sklearn.model_selection import train_test_split from sklearn import linear_model os.getcwd() a = pd.read_csv('per_scholas_data.csv'...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Merged dataframe only containes 9 records...may not be very useful. Go back to the first data frame. Step2: There seems to be a good correlati...
3,318
<ASSISTANT_TASK:> Python Code: %reset -f %matplotlib notebook %load_ext autoreload %autoreload 1 %aimport functions import numpy as np import copy import acoustics from functions import * import matplotlib.pyplot as plt import matplotlib as mpl import seaborn as sns mpl.rcParams['lines.linewidth']=0.5 # uncomment next ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Intervalle Step2: Integration Step3: Beispeiel Step4: Auswahl einer Vorbeifahrt und zusammenstellung der Daten Step5: Plotten der Mikrophon ...
3,319
<ASSISTANT_TASK:> Python Code: # Import SPI Rack, D5a module and D4 module from spirack import SPI_rack, D4_module, D5a_module from time import sleep import numpy as np %matplotlib notebook import matplotlib.pyplot as plt COM_speed = 1e6 # Baud rate, doesn't matter much timeout = 1 # In seconds spi_rack = SPI_rack('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: Initialisation Step2: Create a new D5a module object at the correct (set) module address using the SPI object. Here we reset the voltages to ze...
3,320
<ASSISTANT_TASK:> Python Code: ''' This variables MUST not be changed. They represent the movements of the masterball. ''' R_0 = "Right 0" R_1 = "Right 1" R_2 = "Right 2" R_3 = "Right 3" V_0 = "Vertical 0" V_1 = "Vertical 1" V_2 = "Vertical 2" V_3 = "Vertical 3" V_4 = "Vertical 4" V_5 = "Vertical 5" V_6 = "Vertical 6" ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: R_i moves the ith row to the right. For instance, R_2 applied to the solved state will produce Step2: 2. Implement iterative deepening search S...
3,321
<ASSISTANT_TASK:> Python Code: %matplotlib inline Example: - Minimize Rosenbrock's Function with Nelder-Mead. - Plot of parameter convergence to function minimum. Demonstrates: - standard models - minimal solver interface - parameter trajectories using retall # Nelder-Mead solver from mystic.solver...
<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: mystic Step4: Diagnostic tools Step6: NOTE IPython does not handle shell prompt interactive programs well, so the above should be run from a c...
3,322
<ASSISTANT_TASK:> Python Code: import pandas as pd import numpy as np from fbprophet import Prophet import matplotlib.pyplot as plt from sklearn.metrics import mean_squared_error, r2_score, mean_absolute_error %matplotlib inline plt.rcParams['figure.figsize']=(20,10) plt.style.use('ggplot') sales_df = pd.read_csv('....
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Read in the data Step2: Prepare for Prophet Step3: Let's rename the columns as required by fbprophet. Additioinally, fbprophet doesn't like th...
3,323
<ASSISTANT_TASK:> Python Code: import pandas as pd print("Pandas version: {}".format(pd.__version__)) # опции отображения pd.options.display.max_rows = 6 pd.options.display.max_columns = 6 pd.options.display.width = 100 import gzip # датасет на 47 мегабайт, мы возьмем только 10 review_lines = gzip.open('data/reviews/r...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Чтение и запись данных Step2: Теперь мы получили list с текстовыми строками, нам нужно преобразовать их в dict и передать в DataFrame. <br/> St...
3,324
<ASSISTANT_TASK:> Python Code: %matplotlib inline import os mtxFile = os.path.join( os.environ["SERPENT_TOOLS_DATA"], "depmtx_ref.m") import serpentTools reader = serpentTools.read(mtxFile) reader reader.n0 reader.zai reader.sparse reader.depmtx reader.plotDensity() reader.plotDensity( what='n0', # 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: Depletion Matrix Step2: We have access to all the data present in the file directly on the reader. Step3: This input file did not include fiss...
3,325
<ASSISTANT_TASK:> Python Code: # Ignore %load_ext sql %sql sqlite:// %config SqlMagic.feedback = False %%sql -- Create a table of criminals CREATE TABLE criminals (pid, name, age, sex, city, minor); INSERT INTO criminals VALUES (412, 'James Smith', 15, 'M', 'Santa Rosa', 1); INSERT INTO criminals VALUES (901, 'Gordon ...
<SYSTEM_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: View Table Step3: Update One Row Step4: Update Multiple Rows Using A Conditional Step5: View Table Again
3,326
<ASSISTANT_TASK:> Python Code: import urllib.request import wfdb import psycopg2 from psycopg2.extensions import AsIs target_url = "https://physionet.org/physiobank/database/mimic3wdb/matched/RECORDS-waveforms" data = urllib.request.urlopen(target_url) # it's a file like object and works just like a file lines = data....
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: 2) Leemos el archivo con las WaveForm que vamos a utilizar Step2: 3) Limpiamos los caracteres extraños y Dividimos la cadena donde pXXNNNN-YYYY...
3,327
<ASSISTANT_TASK:> Python Code: !pip install --pre deepchem import deepchem deepchem.__version__ import deepchem as dc import numpy as np tasks, datasets, transformers = dc.molnet.load_muv(split='stratified') train_dataset, valid_dataset, test_dataset = datasets n_tasks = len(tasks) n_features = train_dataset.get_data...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: The MUV dataset is a challenging benchmark in molecular design that consists of 17 different "targets" where there are only a few "active" compo...
3,328
<ASSISTANT_TASK:> Python Code: from __future__ import division import matplotlib.pyplot as plt import bayesian_changepoint_detection.generate_data as gd import seaborn %matplotlib inline %load_ext autoreload %autoreload 2 partition, data = gd.generate_xuan_motivating_example(200,500) import numpy as np changes = np.cu...
<SYSTEM_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 plot this data Step2: Let's try to detect the changes with independent features Step3: Unfortunately, not very good... Now let's try the...
3,329
<ASSISTANT_TASK:> Python Code: import pandas as pd import numpy as np import fredpy as fp import matplotlib.pyplot as plt plt.style.use('classic') %matplotlib inline # Export path: Set to empty string '' if you want to export data to current directory export_path = '../Csv/' # Load FRED API key fp.api_key = fp.load_api...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Download and manage data Step2: Compute capital stock for US using the perpetual inventory method Step3: Compute total factor productivity Ste...
3,330
<ASSISTANT_TASK:> Python Code: # Import Numpy, TensorFlow, TFLearn, and MNIST data import numpy as np import tensorflow as tf import tflearn import tflearn.datasets.mnist as mnist # Retrieve the training and test data trainX, trainY, testX, testY = mnist.load_data(one_hot=True) # Visualizing the data import matplotli...
<SYSTEM_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 training and test data Step2: Visualize the training data Step3: Building the network Step4: Training the network Step5: Testing
3,331
<ASSISTANT_TASK:> Python Code: import pymongo from pymongo import MongoClient client = MongoClient('mongodb://localhost:27017/') db = client.airbnb listings = db.Rawdata reviews = db.reviews import pandas as pd listings_df = pd.DataFrame(list(listings.find())) reviews_df = pd.DataFrame(list(reviews.find())) listing...
<SYSTEM_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 Python to MongoDB Step2: Retrieve from Database Step3: Retrieve Tables from Database Step4: Store data in a pandas dataframe for furt...
3,332
<ASSISTANT_TASK:> Python Code: from __future__ import print_function from IPython.html import widgets print(widgets.Button.on_click.__doc__) from IPython.display import display button = widgets.Button(description="Click Me!") display(button) def on_button_clicked(b): print("Button clicked.") button.on_click(on_bu...
<SYSTEM_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 Button is not used to represent a data type. Instead the button widget is used to handle mouse clicks. The on_click method of the Button c...
3,333
<ASSISTANT_TASK:> Python Code: import os import pandas as pd import numpy as np import scipy as sp import seaborn as sns import matplotlib.pyplot as plt import json from IPython.display import Image from IPython.core.display import HTML import tensorflow as tf retval=os.chdir("..") clean_data=pd.read_pickle('./clean_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: Training and Testing Split Step2: Setting Up Tensor Flow Step3: Testing Estimators
3,334
<ASSISTANT_TASK:> Python Code:: import matplotlib.pyplot as plt plt.figure(figsize=(10,6)) plt.bar(x=range(0,len(X_train.columns)), height=pca.explained_variance_ratio_, tick_label=X_train.columns) plt.title('Explained Variance Ratio') plt.ylabel('Explained Variance Ratio') plt.xlabel('Component') plt....
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description:
3,335
<ASSISTANT_TASK:> Python Code: import sys sys.path.extend(['../']) import numpy as np import matplotlib.pyplot as plt plt.style.use('seaborn-whitegrid') %matplotlib inline import onsager.crystal as crystal import onsager.OnsagerCalc as onsager from scipy.constants import physical_constants kB = physical_constants['Bolt...
<SYSTEM_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 BCC lattice (lattice constant in nm). Step2: Elastic constants converted from GPa ($10^9$ J/m$^3$) to eV/(atomic volume). Step3: Add ca...
3,336
<ASSISTANT_TASK:> Python Code: import os from gensim import utils from gensim.models import translation_matrix from gensim.models import KeyedVectors train_file = "OPUS_en_it_europarl_train_5K.txt" with utils.smart_open(train_file, "r") as f: word_pair = [tuple(utils.to_unicode(line).strip().split()) for line in 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: For this tutorial, we'll train our model using the English -> Italian word pairs from the OPUS collection. This corpus contains 5000 word pairs....
3,337
<ASSISTANT_TASK:> Python Code: import pandas as pd import matplotlib.pyplot as plt %matplotlib inline df = pd.read_csv("07-hw-animals.csv") df df.columns df.head() df['animal'].head(3) df.sort_values('length', ascending=False).head(3) df['animal'].value_counts() dogs = df[df['animal'] == "dog"] dogs animal_larg...
<SYSTEM_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. Set all graphics from matplotlib to display inline Step2: 3. Read the csv in (it should be UTF-8 already so you don't have to worry about en...
3,338
<ASSISTANT_TASK:> Python Code: print(__doc__) import sys import numpy as np np.random.seed(777) import os # The followings are hacks to allow sphinx-gallery to run the example. sys.path.insert(0, os.getcwd()) main_dir = os.path.basename(sys.modules['__main__'].__file__) IS_RUN_WITH_SPHINX_GALLERY = main_dir != os.getcw...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Simple example Step2: Now let's assume this did not finish at once but took some long time Step3: Continue the search
3,339
<ASSISTANT_TASK:> Python Code: from pyspark.sql import SparkSession spark = SparkSession.builder \ .appName('2.1. Google Cloud Storage (CSV) & Spark DataFrames') \ .getOrCreate() spark.conf.set("spark.sql.repl.eagerEval.enabled",True) from google.cloud import storage gcs_client = storage.Client() bucket = gcs_cli...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Enable repl.eagerEval Step2: List files in a GCS bucket Step3: Alternatively use the hdfs cmd to list files in a directory which supports GCS ...
3,340
<ASSISTANT_TASK:> Python Code: from __future__ import print_function import statsmodels.api as sm import numpy as np from statsmodels.iolib.table import (SimpleTable, default_txt_fmt) data = sm.datasets.longley.load() data.exog = sm.add_constant(data.exog) print(data.exog[:5]) ols_resid = sm.OLS(data.endog, data.exog...
<SYSTEM_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 Longley dataset is a time series dataset Step2: Let's assume that the data is heteroskedastic and that we know Step3: Assume that the erro...
3,341
<ASSISTANT_TASK:> Python Code: # Authors: Hari Bharadwaj <hari@nmr.mgh.harvard.edu> # # License: BSD (3-clause) import numpy as np import mne from mne import io from mne.time_frequency import tfr_multitaper from mne.datasets import somato print(__doc__) data_path = somato.data_path() raw_fname = data_path + '/MEG/soma...
<SYSTEM_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 real somatosensory sample data. Step2: Calculate power
3,342
<ASSISTANT_TASK:> Python Code: from IPython.display import YouTubeVideo YouTubeVideo('V08g_lkKj6Q') with open("primes_file.txt", "r") as primes: output = [] for line in primes.readlines()[3:]: # skip first 4 lines if line.strip() == 'end.': break for column in line.split(): ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: output will be global since the above cell is run top level, not inside the scope of a function. Checking the last few entries below, to confir...
3,343
<ASSISTANT_TASK:> Python Code: %matplotlib inline from matplotlib import cm # Import badlands grid generation toolbox import pybadlands_companion.hydroGrid as hydr # display plots in SVG format %config InlineBackend.figure_format = 'svg' #help(hydr.hydroGrid.__init__) hydro1 = hydr.hydroGrid(folder='output/h5', ncpus...
<SYSTEM_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. Load catchments parameters Step2: 2. Extract particular catchment dataset Step3: We can visualise the stream network using the viewNetwork ...
3,344
<ASSISTANT_TASK:> Python Code: import os import sys os.environ["SPARK_HOME"] = "/Users/projects/.pyenv/versions/3.7.10/envs/tatapower/lib/python3.7/site-packages/pyspark" # os.environ["HADOOP_HOME"] = "" # os.environ["PYSPARK_PYTHON"] = "/opt/cloudera/parcels/Anaconda/bin/python" # os.environ["JAVA_HOME"] = "/usr/java/...
<SYSTEM_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 and creating SparkSession Step2: Setting filesystem and files Step3: Convert CSV's dataframes to Apache Parquet files Step4: Load t...
3,345
<ASSISTANT_TASK:> Python Code: import sys sys.path.append('/Users/pradap/Documents/Research/Python-Package/anhaid/py_entitymatching/') import py_entitymatching as em import pandas as pd import os # Display the versions print('python version: ' + sys.version ) print('pandas version: ' + pd.__version__ ) print('magellan ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Matching two tables typically consists of the following three steps Step2: Block tables to get candidate set Step3: Debug blocker output Step4...
3,346
<ASSISTANT_TASK:> Python Code: !pip install hanlp_restful -U from hanlp_restful import HanLPClient HanLP = HanLPClient('https://www.hanlp.com/api', auth=None, language='zh') # auth不填则匿名,zh中文,mul多语种 HanLP.text_style_transfer(['国家对中石油抱有很大的期望.', '要用创新去推动高质量的发展。'], target_style='gov_doc') <END_...
<SYSTEM_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: 申请秘钥
3,347
<ASSISTANT_TASK:> Python Code: # mode practice ## Practice here def fibo(n): # Recursive Fibonacci sequence! if n == 0: return 0 elif n == 1: return 1 return fibo(n-1) + fibo(n-2) # below this cell # Move this cell down <END_TASK>
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Help with commands Step2: Line numbers
3,348
<ASSISTANT_TASK:> Python Code: # Import TensorFlow >= 1.10 and enable eager execution import tensorflow as tf tf.enable_eager_execution() import os import time import numpy as np import matplotlib.pyplot as plt import PIL from IPython.display import clear_output path_to_zip = tf.keras.utils.get_file('facades.tar.gz', ...
<SYSTEM_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 dataset Step2: Use tf.data to create batches, map(do preprocessing) and shuffle the dataset Step3: Write the generator and discrimina...
3,349
<ASSISTANT_TASK:> Python Code: import pandas as pd sdss = pd.read_csv('../datasets/Skyserver_SQL2_27_2018 6_51_39 PM.csv', skiprows=1) sdss.head(2) sdss['class'].value_counts() sdss.info() sdss.describe() sdss.columns.values sdss.drop(['objid', 'run', 'rerun', 'camcol', 'field', 'specobjid'], axis=1, inplace=True) ...
<SYSTEM_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 class identifies an object to be either a galaxy, star or quasar. Step2: The dataset has 10000 examples, 17 features and 1 target. Step3: ...
3,350
<ASSISTANT_TASK:> Python Code: import prody as pd # Note: if you're a Pandas user, it has the same conventional abbreviation "pd", so be careful ubi = pd.parsePDB("1ubi") print(ubi) print(ubi.numAtoms()) print(pd.calcGyradius(ubi)) # This function calculates the radius of gyration of the atoms pd.saveAtoms(ubi) 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: Most ProDy functions follow a specific naming convention Step2: How cool is that?! Step3: File Handling Step4: You can also save to and load ...
3,351
<ASSISTANT_TASK:> Python Code: import numpy as np import pandas as pd import sklearn.metrics.pairwise data = pd.read_csv('data/lastfm-matrix-germany.csv').set_index('user') data.head() data.shape ##### Implement this part of the code ##### raise NotImplementedError("Code not implemented, follow the instructions.") # ...
<SYSTEM_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. The data Step2: The resulting DataFrame contains a row for each user and each column represents an artist. The values indicate whether the u...
3,352
<ASSISTANT_TASK:> Python Code: import matplotlib.pyplot as plt import numpy as np from scipy.spatial import ConvexHull, Delaunay, delaunay_plot_2d, Voronoi, voronoi_plot_2d from scipy.spatial.distance import euclidean from metpy.gridding import polygons, triangles from metpy.gridding.interpolation import nn_point plt.r...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: For a test case, we generate 10 random points and observations, where the Step2: Using the circumcenter and circumcircle radius information fro...
3,353
<ASSISTANT_TASK:> Python Code: import sys #only needed to determine Python version number # Handle table-like data and matrices import numpy as np import pandas as pd # Visualisation import matplotlib as mpl import matplotlib.pyplot as plt import matplotlib.pylab as pylab import seaborn as sns # Enable inline plotting ...
<SYSTEM_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 Importamos las librerias que vamos a necesitar Step2: • Agrupa los países en grupos Step3: • Mapeamos las razas Step4: • Mapea el tipo de...
3,354
<ASSISTANT_TASK:> Python Code: import matplotlib.pyplot as plt # For graphics %matplotlib inline import numpy as np # linear algebra and math import pandas as pd # data frames from openfisca_core.model_api import * from openfisca_senegal import SenegalTaxBenefitSystem # The Senegalese tax-benefits system from openf...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Building the artificial data Step2: We assume that 2/3 of the household heads are married and that only married houshold do have children. The ...
3,355
<ASSISTANT_TASK:> Python Code: %pylab inline # Número de figuritas total en el álbum n_total=640.0 # Figuritas en un sobre n_total_sobre=5 from scipy.misc import comb # Probabilidad de que en un sobre aparezcan i figuritas repetidas def prob_repetidas(n_total,n_tengo,n_total_sobre,i): prob_i_repetidas=comb(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: El álbum tiene 640 figuritas, y el sobre siempre trae 5 Step2: Lo que tengo que hacer es calcular la probabilidad de que salga una repetida de ...
3,356
<ASSISTANT_TASK:> Python Code: from jyquickhelper import add_notebook_menu add_notebook_menu() s = date 0 : 14/9/2000 date 1 : 20/04/1971 date 2 : 14/09/1913 date 3 : 2/3/1978 date 4 : 1/7/1986 date 5 : 7/3/47 date 6 : 15/10/1914 date 7 : 08/03/1941 date 8 : 8/1/1980 date 9 : 30/6/1976 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: Step2: Lorsqu'on remplit un formulaire, on voit souvent le format "MM/JJ/AAAA" qui précise sous quelle forme on s'attend à ce qu’une date soit écrite. ...
3,357
<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: Preprocessing data with TensorFlow Transform Step2: Imports and globals Step3: Next download the data files Step4: Name our columns Step5: H...
3,358
<ASSISTANT_TASK:> Python Code: %load_ext autoreload %autoreload 2 from IPython.display import HTML %%html <!-- make tables display a little nicer in markdown cells --> <style>table {float:left;}</style> import os, sys import pandas as pd PARTIAL_PATH = os.path.join('tests', 'incomplete.tsv') # ensure numbers with pot...
<SYSTEM_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 Partial Contact Data Step2: Make Standardized Columns to Match Contacts With Step3: The dataframe info shows that a whole bunch of c...
3,359
<ASSISTANT_TASK:> Python Code: import pandas as pd table_alg =pd.ExcelFile("results_cec2015.pdf.xlsx") print(table_alg.sheet_names) df=table_alg.parse(table_alg.sheet_names[1]) print(df) def get_best_pos(function, accuracy_level=0): This function get the final position from the function and the accurary_leve...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Then, we read the Sheet right (the 2 in the example) Step3: I need a function that get the right position of the Data Frame, considering the fu...
3,360
<ASSISTANT_TASK:> Python Code: # Install tweepy # !pip install tweepy # Import the libraries we need import tweepy import json import time import networkx import os import matplotlib.pyplot as plt from collections import Counter # Authenticate! auth = tweepy.OAuthHandler("Consumer Key", "Consumer Secret") auth.set_acce...
<SYSTEM_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>2. Pulling ego tweets</h2> Step2: <h2>3. Pulling retweeters</h2> Step3: <h2>4. Visualizing the network of retweeters</h2> Step4: <h2>5. P...
3,361
<ASSISTANT_TASK:> Python Code: # A bit of setup import numpy as np import matplotlib.pyplot as plt from cs231n.classifiers.neural_net import TwoLayerNet from __future__ import print_function %matplotlib inline plt.rcParams['figure.figsize'] = (10.0, 8.0) # set default size of plots plt.rcParams['image.interpolation'] =...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Implementing a Neural Network Step2: We will use the class TwoLayerNet in the file cs231n/classifiers/neural_net.py to represent instances of o...
3,362
<ASSISTANT_TASK:> Python Code: with open("erty.txt", "w") as f: f.write("try.try.try") import pymmails server = pymmails.create_smtp_server("gmail", "xavier.somebody@gmail.com", "pwd") pymmails.send_email(server, "xavier.somebody@gmail.com", "xavier.somebodyelse@else.com", "results", "body", attach...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: In fonction create_smtp_server, the string gmail is replaced by smtp.gmail.com
3,363
<ASSISTANT_TASK:> Python Code: !pip install keras==2.0.8 from keras.datasets import mnist from keras.layers import * from keras.layers import Dense, Input, Flatten from keras.models import Model from keras.layers.merge import concatenate from keras.utils import np_utils img_rows, img_cols = 28, 28 if K.image_data_forma...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Step 2 Step2: Keras supports different Merge strategies Step3: Here we insert the auxiliary loss, allowing the LSTM and Embedding layer to be ...
3,364
<ASSISTANT_TASK:> Python Code: from binary_tools.binary.kicks import* from binary_tools.binary.tests.test_kicks import* from binary_tools.binary.orbits import* from binary_tools.binary.tests.run_tests import* phi = rand_phi() theta = rand_theta() velocity = rand_velocity(100) post_explosion_params_circular(133, 5.5...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: kicks Step2: $\theta$ follows the distribution Step3: the velocity follows the maxwellian distribution Step4: The following function created ...
3,365
<ASSISTANT_TASK:> Python Code: import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets("MNIST_data/", one_hot=True, reshape=False) DO NOT MODIFY THIS CELL def fully_connected(prev_layer, num_units): Create a fully connectd layer with the given layer...
<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: Batch Normalization using tf.layers.batch_normalization<a id="example_1"></a> Step6: We'll use the following function to create convolutional l...
3,366
<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 import matplotlib.image as mpimg from IPython.display import Image from astropy.io import fits import aplpy #Disable astropy/aplpy loggin...
<SYSTEM_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: 6.4 Residuals and Image Quality<a id='deconv Step6: Figure Step7: Left Step8: Method 1 will always re...
3,367
<ASSISTANT_TASK:> Python Code: import numpy as np %matplotlib inline from matplotlib import pyplot as plt from mpl_toolkits.mplot3d import Axes3D from mpl_toolkits.mplot3d import proj3d np.set_printoptions(suppress=True,precision=3) from matplotlib.patches import FancyArrowPatch X_men=np.array([[1.97,110,5],[1.80,70,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: Let us define a very simple dataset, with 6 people, identified by their heigth, weigth, and the length of their middle finger (?). Each column i...
3,368
<ASSISTANT_TASK:> Python Code: import numpy as np def convolution(img, kernel, padding=1, stride=1): img: input image with one channel kernel: convolution kernel h, w = img.shape kernel_size = kernel.shape[0] # height and width of image with padding ph, pw = h + 2 * padding,...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Week 5 Step2: 下面在图像上简单一下测试我们的conv函数,这里使用3*3的高斯核对下面的图像进行滤波. Step4: 上面我们实现了实现了对单通道输入单通道输出的卷积.在CNN中,一般使用到的都是多通道输入多通道输出的卷积,要实现多通道的卷积, 我们只需要对循环调用上面...
3,369
<ASSISTANT_TASK:> Python Code: %%bigquery -- LIMIT 0 is a free query; this allows us to check that the table exists. SELECT * FROM babyweight.babyweight_data_train LIMIT 0 %%bigquery -- LIMIT 0 is a free query; this allows us to check that the table exists. SELECT * FROM babyweight.babyweight_data_eval LIMIT 0 %%bigqu...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Lab Task #1 Step2: Get training information and evaluate Step3: Now let's evaluate our trained model on our eval dataset. Step4: Let's use ou...
3,370
<ASSISTANT_TASK:> Python Code: import pandas as pd import xgboost as xgb import numpy as np import seaborn as sns from hyperopt import hp from hyperopt import hp, fmin, tpe, STATUS_OK, Trials %matplotlib inline train = pd.read_csv('bike.csv') train['datetime'] = pd.to_datetime( train['datetime'] ) train['day'] = train[...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Modeling Step2: Tuning hyperparmeters using Bayesian optimization algorithms
3,371
<ASSISTANT_TASK:> Python Code: hosts = [] n_hosts = 1000 for i in range(n_hosts): if i < n_hosts / 2: hosts.append(Host(color='blue')) else: hosts.append(Host(color='red')) # Pick 5 red hosts and 5 blue hosts at random, and infect it with a virus of the same color. blue_hosts = [h for h in host...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Initialization Step2: Parameters Step3: Run Simulation! Step4: Result Step5: Result Step6: Result
3,372
<ASSISTANT_TASK:> Python Code: import gzip import pandas # Download genotyping platform SNPs adf_files = [ 'A-GEOD-8882/A-GEOD-8882.adf.txt', 'A-GEOD-6434/A-GEOD-6434.adf.txt', 'A-AFFY-107/A-AFFY-107.adf.txt', 'A-AFFY-72/A-AFFY-72.adf.txt', ] base_url = 'http://www.ebi.ac.uk/arrayexpress/files' for adf...
<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: Create BAM Files for SNPs for genotyping chips Step3: Manual step Step4: Download Entrez Gene locations Step5: Compute SNPs per gene using be...
3,373
<ASSISTANT_TASK:> Python Code: import nltk nltk.help.upenn_tagset() nltk.help.upenn_tagset('WP$') nltk.help.upenn_tagset('PDT') nltk.help.upenn_tagset('DT') nltk.help.upenn_tagset('POS') nltk.help.upenn_tagset('RBR') nltk.help.upenn_tagset('RBS') nltk.help.upenn_tagset('MD') from pprint import pprint sent = 'Beautiful...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Or this summary table (also c.f. https Step2: Various algorithms can be used to perform POS tagging. In general, the accuracy is pretty high (s...
3,374
<ASSISTANT_TASK:> Python Code: # Importing libraries %pylab inline %matplotlib inline import pandas as pd import matplotlib.pyplot as plt from matplotlib.colors import LogNorm from sklearn import preprocessing import numpy as np # Convert variable data into categorical, continuous, discrete, # and dummy variable 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: Seperation of columns into categorical, continous and discrete Step2: Importing life insurance data set Step3: Pre-processing raw dataset for ...
3,375
<ASSISTANT_TASK:> Python Code: from liquidSVM import * %matplotlib inline import numpy as np import matplotlib.pyplot as plt # Load test and training data reg = LiquidData('reg-1d') model = lsSVM(reg.train,display=1) result, err = model.test(reg.test) err[0,0] plt.plot(reg.test.data, reg.test.target, '.') x = np.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: Some stuff we need for this notebook Step2: LS-Regression Step3: Now reg.train contains the training data and reg.test the testing data. Step4...
3,376
<ASSISTANT_TASK:> Python Code: %matplotlib inline import pickle as pkl import matplotlib.pyplot as plt import numpy as np from scipy.io import loadmat import tensorflow as tf !mkdir data from urllib.request import urlretrieve from os.path import isfile, isdir from tqdm import tqdm data_dir = 'data/' if not isdir(data_...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Getting the data Step2: These SVHN files are .mat files typically used with Matlab. However, we can load them in with scipy.io.loadmat which we...
3,377
<ASSISTANT_TASK:> Python Code: # import word2vec model from gensim from gensim.models.word2vec import Word2Vec # load pre-trained model model = Word2Vec.load_word2vec_format('eswikinews.bin', binary=True) def presidents_comp(country): ### Su código debe ir aquí return [] for country in ['colombia', 'venezuela'...
<SYSTEM_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. Comparando composicionalidad y analogía. Step2: El siguiente paso es usar analogías para encontrar el presidente de un país dado. Step3: ¿C...
3,378
<ASSISTANT_TASK:> Python Code: from IPython.display import Image Image("../docs/images/gds.png") import pp c = pp.Component() w = pp.c.waveguide(width=0.6) wr = w.ref() c.add(wr) pp.qp(c) c = pp.Component() wr = c << pp.c.waveguide(width=0.6) pp.qp(c) c = pp.Component() wr1 = c << pp.c.waveguide(width=0.6) wr2 = 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: Adding a component reference Step2: We have two ways to add a reference to our device Step3: or we can do it in a single line (my preference) ...
3,379
<ASSISTANT_TASK:> Python Code: %pylab inline %matplotlib inline from scipy.io import loadmat from modshogun import RealFeatures, MulticlassLabels, Math # load the dataset dataset = loadmat('../../../data/multiclass/usps.mat') Xall = dataset['data'] # the usps dataset has the digits labeled from 1 to 10 # we'll subtrac...
<SYSTEM_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 network Step2: We can also visualize what the network would look like. To do that we'll draw a smaller network using networkx. The...
3,380
<ASSISTANT_TASK:> Python Code: labVersion = 'cs190_week3_v_1_3' # load testing library from test_helper import Test import os.path baseDir = os.path.join('data') inputPath = os.path.join('cs190', 'millionsong.txt') fileName = os.path.join(baseDir, inputPath) numPartitions = 2 rawData = sc.textFile(fileName, numPartiti...
<SYSTEM_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 Step3: (1b) Using LabeledPoint Step5: Visualization 1 Step6: (1c) Find the range Step7: (1d) Shift labels Step8: Visualization 2 ...
3,381
<ASSISTANT_TASK:> Python Code: # Import the Iris Dataset and Build a GLM import h2o h2o.init() from h2o.estimators.glm import H2OGeneralizedLinearEstimator # import the iris dataset: # this dataset is used to classify the type of iris plant # the original dataset can be found at https://archive.ics.uci.edu/ml/datasets/...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Specify Feature of Interest Step2: Generate a PDP per class manualy Step3: Use target parameter and plot H2O multinomial PDP
3,382
<ASSISTANT_TASK:> Python Code: import numpy as np import sklearn from sklearn.model_selection import train_test_split import pandas as pd import matplotlib.pyplot as plt from sklearn.model_selection import cross_val_score %matplotlib inline data_fs = pd.read_csv(r'data/data_fs.csv', low_memory=False) data_fs.head(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: Look at the first 10 rows of this dataset. Step2: The dataset has many NaN's and also a lot of categorical features. So at first, you should pr...
3,383
<ASSISTANT_TASK:> Python Code: x = np.mat(np.arange(-1.,1.,0.01)).T N = len(x) degree = 10 #A = np.hstack((np.power(x,0), np.power(x,1), np.power(x,2))) B = np.hstack((np.power(x,i) for i in range(degree+1))) B = B[:,np.random.permutation(degree+1)] #B = np.hstack((np.power(x,i) for i in range(degree+1))) #B = np.rando...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Householder Reflection Step2: We have explicitely constructed $H$ (or $P$) but this is not needed. It is sufficient to store the Householder ve...
3,384
<ASSISTANT_TASK:> Python Code: import psycopg2 with psycopg2.connect(database='radon_fingerprints', host='localhost', port=5437) as conn: with conn.cursor() as cursor: cursor.execute("CREATE EXTENSION IF NOT EXISTS plpythonu;") cursor.execute( ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step3: Create Compute-Intensive Python Function Step4: Quick Test on the Setup Function Step5: Compare Performance of the Numba Compiled Version with...
3,385
<ASSISTANT_TASK:> Python Code: # Author: Remi Flamary <remi.flamary@unice.fr> # # License: MIT License import numpy as np import matplotlib.pylab as pl import ot # necessary for 3d plot even if not used from mpl_toolkits.mplot3d import Axes3D # noqa from matplotlib.collections import PolyCollection # noqa #import ot....
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Gaussian Data Step2: Dirac Data Step3: Final figure
3,386
<ASSISTANT_TASK:> Python Code: file_listcal = "alma_sourcecat_searchresults_20180419.csv" q = databaseQuery() listcal = q.read_calibratorlist(file_listcal, fluxrange=[0.1, 999999]) len(listcal) print("Name: ", listcal[0][0]) print("J2000 RA, dec: ", listcal[0][1], listcal[0][2]) print("Alias: ", listcal[0][3]) print("...
<SYSTEM_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, retrieve all the calibrator with a flux > 0.1 Jy Step2: Select all calibrators that heve been observed at least in 3 Bands [ >60s in B...
3,387
<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: 전략의 종류 Step3: MirroredStrategy 인스턴스가 생겼습니다. 텐서플로가 인식한 모든 GPU를 사용하고, 장치 간 통신에는 NCCL을 사용할 것입니다. Step4: 장치 간 통신 방법을 바꾸고 싶다면...
3,388
<ASSISTANT_TASK:> Python Code: import pandas as pd import numpy as np # Set some Pandas options pd.set_option('display.notebook_repr_html', False) pd.set_option('display.max_columns', 20) pd.set_option('display.max_rows', 25) from datetime import datetime now = datetime.now() now now.day now.weekday() from datetime 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: Date/Time data handling Step2: In addition to datetime there are simpler objects for date and time information only, respectively. Step3: Havi...
3,389
<ASSISTANT_TASK:> Python Code: d = None with open('..\..\group_analysis.json') as f: d = json.load(f) df_num_groups = pd.DataFrame(data={'Min. Num. of Groups': d['min_num_groups'], 'Avg. Num. of Groups': d['avg_num_groups'], 'Max. Num. of Groups': d['max_num_groups']}) df_num_groups plt.figure() ax = df_num_groups...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Number of groups for frame Step2: Number of elements on each group for frame
3,390
<ASSISTANT_TASK:> Python Code: %matplotlib inline %config InlineBackend.figure_format = 'retina' import datetime as dt import matplotlib.pyplot as plt import pandas as pd import pytz import requests from urllib.error import HTTPError # output color from prettyprinting import * tz = pytz.timezone('Europe/Madrid') url_pe...
<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: Perfiles de consumo del PVPC para clientes sin registro horario Step4: Descarga de CSV's mensuales con los perfiles finales de consumo Step5: ...
3,391
<ASSISTANT_TASK:> Python Code: import pandas as pd import pandas_datareader.data as web import matplotlib.pyplot as plt # Defines the chart color scheme using Tableu's Tableau10 plt.style.use('https://gist.githubusercontent.com/mbonix/8478091db6a2e6836341c2bb3f55b9fc/raw/7155235ed03e235c38b66c160d402192ad4d94d9/tablea...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Then, let's choose a bunch of stocks to analyze. They are Step2: Now, let's download stock data from Yahoo!Finance, using pandas-datareader mod...
3,392
<ASSISTANT_TASK:> Python Code: num_units = 400 #state size input_len = 60 target_len = 30 batch_size = 50 with_EOS = False total_train_size = 57994 from time import sleep data_path = '../../../../Dropbox/data' ph_data_path = data_path + '/price_history' npz_full = ph_data_path + '/price_history_mobattrs_date_dp_60to30...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Include relevant deals Step2: So for the same date window if we find data from the relevant deal we are good to go Step3: This is taking longe...
3,393
<ASSISTANT_TASK:> Python Code: from __future__ import print_function, division import torch import torch.nn as nn import torch.optim as optim from torch.optim import lr_scheduler import numpy as np import torchvision from torchvision import datasets, models, transforms import matplotlib.pyplot as plt import time 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: Load Data Step3: Visualize a few images Step4: Training the model Step5: Visualizing the model predictions Step6: Finetuning the convnet Ste...
3,394
<ASSISTANT_TASK:> Python Code: import exercise_utils as eu import math from collections import defaultdict # esse é o nosso dataset users_interests = eu.get_users_interests() # se não tivermos o dataset, usar eu.get_users_interests_poor() unique_interests = sorted(list({ interest for u...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: O código abaixo cria um vetor global de todos os possíveis interesses. Step3: Montando a Matrix Step4: Função de Similaridade Step5: Usando a...
3,395
<ASSISTANT_TASK:> Python Code: # DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'noaa-gfdl', 'sandbox-2', 'ocean') # 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...
3,396
<ASSISTANT_TASK:> Python Code: from nltk.featstruct import FeatStruct f1 = FeatStruct( '[Vorname=Max, Nachname=Mustermann,' + 'Privat=[Strasse=Hauptstrasse, Ort=[Muenchen]]]' ) f2 = FeatStruct( '[Arbeit=[Strasse="Oettingenstrasse", Ort=(1)["Muenchen"]],' + 'Privat=[Ort->(1)]]') f3 = FeatStruct( '[...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Gegeben seien folgende Merkmalstrukturen Step2: Unifizieren Sie Step3: f2 mit f4 Step5: Aufgabe 2 &nbsp;&nbsp;&nbsp; Typhierarchie im NLTK St...
3,397
<ASSISTANT_TASK:> Python Code: import os import numpy as np import matplotlib.pyplot as plt from astropy.table import Table from astropy.io import fits import seaborn as sns import multiprocessing nproc = multiprocessing.cpu_count() // 2 from desispec.io.util import write_bintable from desiutil.log import get_logger 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: Establish the I/O path, output filename, and random seed. Step2: All or none of the output files can be overwritten using these keywords. Step3...
3,398
<ASSISTANT_TASK:> Python Code: import numpy as np import matplotlib.pyplot as plt # Import TF 2. %tensorflow_version 2.x import tensorflow as tf # Fix seed so that the results are reproducable. tf.random.set_seed(0) np.random.seed(0) try: import t3f except ImportError: # Install T3F if it's not already installe...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Generating problem instance Step2: Initialize the variable and compute the loss Step3: SGD optimization Step4: Speeding it up Step5: Compili...
3,399
<ASSISTANT_TASK:> Python Code: import os SHOGUN_DATA_DIR=os.getenv('SHOGUN_DATA_DIR', '../../../data') from scipy.io import loadmat import shogun as sg import numpy as np import matplotlib.pyplot as plt import matplotlib %matplotlib inline # load the dataset dataset = loadmat(os.path.join(SHOGUN_DATA_DIR, 'multiclass/u...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Creating the network Step2: We can also visualize what the network would look like. To do that we'll draw a smaller network using networkx. The...