Unnamed: 0
int64
0
15.9k
cleaned_code
stringlengths
67
124k
cleaned_prompt
stringlengths
168
30.3k
5,500
<ASSISTANT_TASK:> Python Code: from os.path import join hot_dog_image_dir = 'inputs/seefood/train/hot_dog' hot_dog_paths = [join(hot_dog_image_dir, filename) for filename in ['1000288.jpg', '127117.jpg']] not_hot_dog_image_dir = 'inputs/seefood/train/not_hot_dog' not_hot_dog_paths = [jo...
<SYSTEM_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 Up Preprocessing Step2: 3) Modeling Step3: 4) Visualize Your Results Step4: Now you are ready to move on to transfer learning, which a...
5,501
<ASSISTANT_TASK:> Python Code: from jyquickhelper import add_notebook_menu add_notebook_menu() def big_list1(n): l = [] for i in range(n): l.append(i) return l def big_list2(n): return list(range(n)) def big_list(n): big_list1(n) big_list2(n) %prun -q -T profile_example.txt -D profile_e...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: profiling with cProfile Step2: Memory profile Step3: Thz functions to test must be part of file and cannot be implemented in the notebook. So ...
5,502
<ASSISTANT_TASK:> Python Code: import gzip import requests import zipfile url = "https://dl.dropbox.com/s/lnly9gw8pb1xhir/overfitting.zip" results = requests.get(url) import StringIO z = zipfile.ZipFile(StringIO.StringIO(results.content)) # z.extractall() z.extractall() z.namelist() d = z.open('overfitting.csv') d.read...
<SYSTEM_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 of Salisman's Don't Overfit submission Step2: Develop Tim's model Step3: looks pretty right
5,503
<ASSISTANT_TASK:> Python Code: p_hi = 0.8 # probability of success in the high probability subpopulation p_lo = 0.2 # probability of success in the low probability subpopulation delta_p = 0.05 # effect size # probability of success under treatment P_T_additive = delta_p + 0.5*p_hi+0.5*p_lo # probability of success unde...
<SYSTEM_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 2
5,504
<ASSISTANT_TASK:> Python Code: import os import pandas as pd from sqlalchemy import create_engine with open(os.environ["PGPASS"], "rb") as f: content = f.readline().decode("utf-8").replace("\n", "").split(":") engine = create_engine("postgresql://{user}:{passwd}@{host}/{db}".format(user=content[3], ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: frontpage_examples Step2: Grab some examples Step3: crawls Step4: Remove VPS related info Step5: onion services Step6: Probably unnecessary...
5,505
<ASSISTANT_TASK:> Python Code: # boilerplate code from __future__ import print_function import os from io import BytesIO import numpy as np from functools import partial import PIL.Image from IPython.display import clear_output, Image, display, HTML import tensorflow as tf #!wget https://storage.googleapis.com/downloa...
<SYSTEM_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 id='loading'></a> Step6: To take a glimpse into the kinds of patterns that the network learned to recognize, we will try to generate images ...
5,506
<ASSISTANT_TASK:> Python Code: from __future__ import division import ipyparallel as ipp import qinfer as qi from functools import partial %matplotlib inline import matplotlib.pyplot as plt try: plt.style.use('ggplot') except: pass client = ipp.Client() print(client) dview = client[:] print(dview) serial_m...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Next, we import the IPython parallelization library ipyparallel, as well as QInfer itself and some useful things from the Python standard librar...
5,507
<ASSISTANT_TASK:> Python Code: %matplotlib inline import pyasf import pylab as pl import sympy as sp pl.rcParams.update({'font.size':14}) from IPython.display import display, Math print_latex = lambda x: display(Math(sp.latex(x))) sto = pyasf.unit_cell("sto_bulk_80873.cif") # init the cif file, this one has quite OK De...
<SYSTEM_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 databases we can only calculate the smooth part of the resonant corrections $f_1(E)$ and $f_2(E)$. The fine structure oscillations I obtain...
5,508
<ASSISTANT_TASK:> Python Code: documents = nltk.corpus.PlaintextCorpusReader('../data/EmbryoProjectTexts/files', 'https.+') metadata = zotero.read('../data/EmbryoProjectTexts', index_by='link', follow_links=False) wordcounts_per_document = nltk.ConditionalFreqDist([ (fileid, normalize_token(token)) for fileid...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Our first step is to count up all of the words in each of the documents. This conditional frequency distribution should look familiar by now.
5,509
<ASSISTANT_TASK:> Python Code: # %load ../data/melanoma_data.py from numpy import reshape, sum melanoma_data = reshape([1.57808, 0.00000, 2, 1.27, 35.9945, 1, 1.48219, 0.00000, 2, 0.76, 41.9014, 1, 0.0, 7.33425, 1, 35.00, 70.2164, 2, 2.23288, 0.00000, 1, 1.70, 33.7096, 1, 0.0, 9.38356, 2, 1.00, 47.9726, 1, 3....
<SYSTEM_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 MAP estimate can be obtained in PyMC3 via the find_MAP function. As with sample, we run find_MAP inside a model context, or pass the model e...
5,510
<ASSISTANT_TASK:> Python Code: from lxml import etree tree = etree.parse("data/TEI/sonnet18.xml") print(tree) print(etree.tostring(tree)) print(etree.tostring(tree).decode()) print(etree.tostring(tree, pretty_print=True).decode()) for node in tree.iterfind("//rhyme"): print(node) for node in tree.iterfind("//...
<SYSTEM_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 the record, we should mention that there exist many other libraries in Python to parse XML, such as minidom or BeautifulSoup which is an int...
5,511
<ASSISTANT_TASK:> Python Code: import ctcsound cs = ctcsound.Csound() csd = ''' <CsoundSynthesizer> <CsOptions> -d -o dac -m0 </CsOptions> <CsInstruments> sr = 48000 ksmps = 100 nchnls = 2 0dbfs = 1 instr 1 idur = p3 iamp = p4 icps = cpspch(p5) irise = ...
<SYSTEM_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 start a new thread, passing the opaque pointer of the Csound instance as argument Step2: Now, we can send messages to the performan...
5,512
<ASSISTANT_TASK:> Python Code: import numpy as np import scipy.stats as st from sci_analysis import analyze %matplotlib inline # Create x-sequence and y-sequence from random variables. np.random.seed(987654321) x_sequence = st.norm.rvs(2, size=2000) y_sequence = np.array([x + st.norm.rvs(0, 0.5, size=1) for x in x_sequ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Scatter Plot Step2: Boxplot Borders Step3: Contours Step4: Grouped Scatter Plot Step5: Interpreting the Statistics Step6: fit Step7: point...
5,513
<ASSISTANT_TASK:> Python Code: data = pd.read_csv( '../../data/dailybots.csv' ) #Look at a summary of the data data.describe() data['botfam'].value_counts() grouped_df = data[data.botfam == "Ramnit"].groupby(['industry']) grouped_df.sum() group2 = data[['botfam','orgs']].groupby( ['botfam']) summary = group2.agg([np....
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Exercise 1 Step2: Exercise 2 Step3: Exercise 3 Step4: Exercise 4 Step5: Exercise 5
5,514
<ASSISTANT_TASK:> Python Code: from __future__ import division import graphlab import math import string import numpy products = graphlab.SFrame('amazon_baby.gl/') products products[269] def remove_punctuation(text): import string return text.translate(None, string.punctuation) review_without_punctuation =...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Data preparation Step2: Now, let us see a preview of what the dataset looks like. Step3: Build the word count vector for each review Step4: N...
5,515
<ASSISTANT_TASK:> Python Code: # Basic imports import os import pandas as pd import matplotlib.pyplot as plt import numpy as np import datetime as dt import scipy.optimize as spo import sys from time import time from sklearn.metrics import r2_score, median_absolute_error from multiprocessing import Pool import 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: Let's show the symbols data, to see how good the recommender has to be. Step2: Let's run the trained agent, with the test set Step3: And now a...
5,516
<ASSISTANT_TASK:> Python Code: # your code here # your code here plt.close() # leave this here. it makes sure that if you run this cell again, the plot appears below # parameters # calculate the trajectory # plot-don't forget to label your axes! plt.close() # keep this here # your code here # your code her...
<SYSTEM_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 write a function that returns the total time the projectile will stay in the air (which means return to $y = 0$), in units of seconds, given...
5,517
<ASSISTANT_TASK:> Python Code: from __future__ import print_function, division %matplotlib inline import numpy as np import pandas as pd import random import thinkstats2 import thinkplot import scipy.stats def EvalNormalCdfInverse(p, mu=0, sigma=1): return scipy.stats.norm.ppf(p, loc=mu, scale=sigma) EvalNormalCd...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Analytic methods Step2: Here's the confidence interval for the estimated mean. Step3: normal.py provides a Normal class that encapsulates what...
5,518
<ASSISTANT_TASK:> Python Code: import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns from mpl_toolkits.mplot3d import Axes3D from __future__ import unicode_literals from matplotlib.gridspec import GridSpec # %matplotlib notebook my_...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Loading Dataset Step2: Redshift volume on which I intend to focus my analysis Step3: Selecting the subsample Step4: Characterizing the UV emi...
5,519
<ASSISTANT_TASK:> Python Code: def word_count(document, search_term): Count how many times search_term appears in document. words = document.split() answer = 0 for word in words: if word == search_term: answer += 1 return answer def nearest_square(limit): Find the 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: Step2: Python Advanced Step3: Since the variable answer here is defined within each function seperately, you can reuse the same name of the variable, ...
5,520
<ASSISTANT_TASK:> Python Code: import numpy as np import pandas as pd from sklearn import preprocessing from sklearn.cross_validation import train_test_split from helpers.models import fit_model from helpers.helpers import make_binary, class_info # set random state for camparability random_state = np.random.RandomState...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Preprocesamiento Step2: Obtener los datos como np.array y separar los datos en predictor (X) y objetivo (Y) Step3: Eliminar los datos con etiq...
5,521
<ASSISTANT_TASK:> Python Code: import csv import yaml reader = csv.reader(open("../data/questions.csv")) question_1 = reader.next() question_1 yaml.load(question_1[-1].replace(": u'", ": '")) reader = csv.reader(open("../data/train.csv")) reader.next() train_set = [] for row in reader: train_set.append(row) pr...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Read the first line and see the structure. Step2: Yes, each line is converted into list and it has 6 items as expected. However, how can we use...
5,522
<ASSISTANT_TASK:> Python Code: %matplotlib inline import numpy as np import pandas as pd from scipy.stats import norm import statsmodels.api as sm import matplotlib.pyplot as plt Univariate Local Linear Trend Model class LocalLinearTrend(sm.tsa.statespace.MLEModel): def __init__(self, endog): # Model order...
<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: To take advantage of the existing infrastructure, including Kalman filtering and maximum likelihood estimation, we create a new class which exte...
5,523
<ASSISTANT_TASK:> Python Code: # Install datacommons_pandas !pip install datacommons_pandas --upgrade --quiet # Import Data Commons import datacommons_pandas as dc # Import other required libraries import matplotlib.pyplot as plt import matplotlib.patches as mpatches import pandas as pd import json # In the browser, w...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Example Step2: Using get_places_in to Query Administrative Areas Step3: Let's see what states are in the USA Step4: Great! With the place dci...
5,524
<ASSISTANT_TASK:> Python Code: import cvxpy as cp import numpy as np # Ensure repeatably random problem data. np.random.seed(0) # Generate random data matrix A. m = 10 n = 10 k = 5 A = np.random.rand(m, k).dot(np.random.rand(k, n)) # Initialize Y randomly. Y_init = np.random.rand(m, k) # Ensure same initial random Y, ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Perform alternating minimization Step2: Output results
5,525
<ASSISTANT_TASK:> Python Code: # Setup feedback system from learntools.core import binder binder.bind(globals()) from learntools.computer_vision.ex3 import * import numpy as np import tensorflow as tf import matplotlib.pyplot as plt from matplotlib import gridspec import learntools.computer_vision.visiontools as vision...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Run this cell to get back to where you left off in the previous lesson. We'll use a predefined kernel this time. Step2: 1) Apply Pooling to Con...
5,526
<ASSISTANT_TASK:> Python Code: import sys print sys.executable %load_ext autoreload %autoreload 2 %reload_ext autoreload import sonnet as snt import tensorflow as tf import tflearn import numpy as np import dataset_utils data = dataset_utils.load_data(filename="../synthetic_data/toy.pickle") input_data_, output_mask_,...
<SYSTEM_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 toy data set Step2: Build RNN Model
5,527
<ASSISTANT_TASK:> Python Code: %%script bash # Ignore this boring cell. # It allows one to do C in Jupyter notebook. cat >20170706_head.c <<EOF #include <stdlib.h> #include <stdio.h> #define LINES (3) #define COLUMNS (4) void print_buf(char buf[LINES][COLUMNS]) { for (int row = 0; row < LINES; row++) { for ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: The above is what the output should look like. Step2: Now for some Python.
5,528
<ASSISTANT_TASK:> Python Code: u1 = ["green", "green", "blue", "green"] a1 = set({("green", 3), ("blue", 1)}) assert a1 == set(urn_to_dict(u1).items()) u2 = ["red", "blue", "blue", "green", "yellow", "black", "black", "green", "blue", "yellow", "red", "green", "blue", "black", "yellow", "yellow", "yellow", "green", "bl...
<SYSTEM_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 B Step2: Part C Step3: Part D Step4: Part E
5,529
<ASSISTANT_TASK:> Python Code: %matplotlib inline import math import matplotlib.pyplot as plt import numpy as np import openmc import openmc.mgxs # 1.6 enriched fuel fuel = openmc.Material(name='1.6% Fuel') fuel.set_density('g/cm3', 10.31341) fuel.add_nuclide('U235', 3.7503e-4) fuel.add_nuclide('U238', 2.2625e-2) fuel...
<SYSTEM_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 need to define materials that will be used in the problem Step2: With our three materials, we can now create a Materials object that c...
5,530
<ASSISTANT_TASK:> Python Code: a=5 a==6 i=6 i>5 i=2 i>5 i=2 i!=6 i=6 i!=6 "ACDC"=="Michael Jackson" "ACDC"!="Michael Jackson" '+'>'!' 'B'>'A' 'BA'>'AB' age=19 #age=18 #expression that can be true or false if age>18: #within an indent, we have the expression that is run if the condition is true pr...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: The result is false, as 5 does not equal 6. Step2: If we set i=2 the condition is false as 2 is less than 5 Step3: Let's display some values f...
5,531
<ASSISTANT_TASK:> Python Code: import csv import numpy as np import scipy as sp import pandas as pd import sklearn as sk import matplotlib.pyplot as plt from IPython.display import Image print('csv: {}'.format(csv.__version__)) print('numpy: {}'.format(np.__version__)) print('scipy: {}'.format(sp.__version__)) print('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: The easiest way to learn how regression works is by thinking about an example. Consider an imaginary dataset of buildings built in Denver contai...
5,532
<ASSISTANT_TASK:> Python Code: imcontroller = ImageController(demo.image_info) demo.image_info.items() imcontroller.generate_image_obj() imcontroller.channels imcontroller print('Numerical Labels that index image: ') print(imcontroller.image_obj.labels) print('Channels: ') print(imcontroller.channels) print('Image ty...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Normally the image controller would be passed images directly, but for now, we have to load them from disk by calling generate_im_obj Step2: Fr...
5,533
<ASSISTANT_TASK:> Python Code: import urllib, time, hashlib hosts = ['http://www.scikit-learn.org', 'http://www.numpy.org', 'http://www.scipy.org', 'http://pandas.pydata.org'] start = time.time() for host in hosts: f = urllib.request.urlopen(host) print(f.read().upper()[:20], host) print("Elapsed time: {}".form...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Multi-threaded Step2: Asynchronous Step3: Some thoughts about callbacks Step4: What should our MedBot do? Step5: Sending the alarm Step6: H...
5,534
<ASSISTANT_TASK:> Python Code: from sklearn.datasets import load_iris from sklearn.pipeline import make_pipeline from sklearn import preprocessing from sklearn import model_selection from sklearn import svm # load iris data iris = load_iris() X = iris.data y = iris.target # Create a pipeline that scales the data then ...
<SYSTEM_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 classifier pipeline Step2: Cross validation Step3: Model evaluation
5,535
<ASSISTANT_TASK:> Python Code: from causalinfo import * from numpy import log2 from numpy.testing import assert_allclose # You only need this if you want to draw pretty pictures of the Networksa from nxpd import draw, nxpdParams nxpdParams['show'] = 'ipynb' w, x, y, z = make_variables("W X Y Z", 2) wdist = UniformDist(...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Ay & Polani, Example 3 Step2: Ay & Polani, Example 5.1 Step3: Ay & Polani, Example 5.2
5,536
<ASSISTANT_TASK:> Python Code: names = {} for node in graph: for edge in node: if edge.guid == "169a81aefca74e92b45e3fa03c7021df": value = node[edge].value if value in names: raise ValueError('name: "{}" defined twice'.format(value)) names[value] = node ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Pikov Classes Step2: Gamekitty Step3: Create frames for each "clip" Step4: Create the root node Step5: More clips and transitions
5,537
<ASSISTANT_TASK:> Python Code: # Update the PIP version. !python -m pip install --upgrade pip !pip install kfp==1.1.1 !pip install kubeflow-katib==0.10.1 from IPython.display import display_html display_html("<script>Jupyter.notebook.kernel.restart()</script>",raw=True) import kfp import kfp.dsl as dsl from kfp impor...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Restart the Notebook kernel to use the SDK packages Step2: Import required packages Step3: Define an Experiment Step4: Define a Trial templat...
5,538
<ASSISTANT_TASK:> Python Code: # Author: Alexandre Gramfort <alexandre.gramfort@telecom-paristech.fr> # # License: BSD (3-clause) import numpy as np import matplotlib.pyplot as plt import mne from mne.datasets import sample from mne.minimum_norm import apply_inverse_epochs, read_inverse_operator from mne.minimum_norm 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: View activation time-series to illustrate the benefit of aligning/flipping Step2: Viewing single trial dSPM and average dSPM for unflipped pool...
5,539
<ASSISTANT_TASK:> Python Code: import os import pandas as pd import numpy as np import xgboost as xgb from xgboost.sklearn import XGBClassifier from sklearn import cross_validation, metrics from sklearn.grid_search import GridSearchCV from sklearn.model_selection import train_test_split import matplotlib.pylab as 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: Step1: Load Data Step2: Define a function for modeling and cross-validation Step3: Step 1- Find the number of estimators for a high learning rate Ste...
5,540
<ASSISTANT_TASK:> Python Code: %matplotlib inline import matplotlib.pyplot as plt import numpy as np def well2d(x, y, nx, ny, L=1.0): Compute the 2d quantum well wave function. psi=(2/L)*np.sin((nx*np.pi*x)/L)*np.sin((ny*np.pi*y)/L) return psi psi = well2d(np.linspace(0,1,10), np.linspace(0,1,10), 1, 1) as...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step2: Contour plots of 2d wavefunctions Step3: The contour, contourf, pcolor and pcolormesh functions of Matplotlib can be used for effective visuali...
5,541
<ASSISTANT_TASK:> Python Code: import pypot.dynamixel ports = pypot.dynamixel.get_available_ports() if not ports: raise IOError('no port found!') print 'ports found', ports my_port = "/dev/ttyACM1" #Change this value to match your setup using_XL320 = False #Change this value to True if you use XL-320 motors ...
<SYSTEM_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 the available ports, select the port where the new motor is pluggued. Step2: Select the new ID and the new baudrate you wish for your moto...
5,542
<ASSISTANT_TASK:> Python Code: import math import torch import tqdm import gpytorch from matplotlib import pyplot as plt %matplotlib inline %load_ext autoreload %autoreload 2 # Training data is 100 points in [0,1] inclusive regularly spaced train_x_mean = torch.linspace(0, 1, 20) # We'll assume the variance shrinks th...
<SYSTEM_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 training data Step2: Setting up the model Step3: Training the model with uncertain features
5,543
<ASSISTANT_TASK:> Python Code: from datetime import date from organizer.models import Tag, Startup, NewsLink from blog.models import Post edut = Tag(name='Education', slug='education') edut edut.save() edut.delete() edut # still in memory! type(Tag.objects) # a model manager Tag.objects.create(name='Video Games', 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: Interacting With the Database Step2: Creation and Destruction with Managers Step3: Methods of Data Retrieval Step4: The get method Step5: Th...
5,544
<ASSISTANT_TASK:> Python Code: pudl_settings = pudl.workspace.setup.get_defaults() settings_file_name= 'etl_full.yml' etl_settings = EtlSettings.from_yaml( pathlib.Path(pudl_settings['settings_dir'], settings_file_name)) validated_etl_settings = etl_settings.datasets datasets = validated_etl_settin...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: You can skip the settings step above and set these years/tables yourself here without using the settings files... just know they are not validat...
5,545
<ASSISTANT_TASK:> Python Code: import pandas as pd import numpy as np import matplotlib.pyplot as plt import matplotlib.dates as mdates %matplotlib notebook # use the 'seaborn-colorblind' style plt.style.use('seaborn-colorblind') # SOURCE: 2018: https://www.officeholidays.com/countries/usa/michigan/2018 # scrap tool: ...
<SYSTEM_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 Dataset Step2: Processing Data Step3: Plotting
5,546
<ASSISTANT_TASK:> Python Code: import math x = math.sin(1.2) x from math import pi theta_d = 30.0 theta_r = pi / 180.0 * theta_d print(theta_r) from math import pi def degrees_to_radians(theta_d): Convert an angle from degrees to radians. Parameters ---------- theta_d : float 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: Go to the editor in spyder and enter those commands in a file Step2: Also, in the top right of the spyder window, select the "Variable explorer...
5,547
<ASSISTANT_TASK:> Python Code: import os PROJECT = "cloud-training-demos" # REPLACE WITH YOUR PROJECT ID BUCKET = "cloud-training-demos-ml" # REPLACE WITH YOUR BUCKET NAME REGION = "us-central1" # REPLACE WITH YOUR BUCKET REGION e.g. us-central1 # Do not change these os.environ["PROJECT"] = PROJECT os.environ["BUCKET"]...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step2: Create raw dataset Step3: Create dataset for WALS Step4: Creating rows and columns datasets Step5: To summarize, we created the following dat...
5,548
<ASSISTANT_TASK:> Python Code: from qrays import Qvector, Vector a = Qvector((1,0,0,0)) a.length() b = Qvector((0,1,0,0)) (a-b).length() from tetvols import make_tet import unittest class TestQuadrays(unittest.TestCase): def test_martian(self): p = Qvector((2,1,0,1)) q = Qvector((2,1,1,0)) ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: The Quadray coordinate system stands on its own without merging with 20th Century Neoplatonist esoterica. Some of the shoptalk which follows is ...
5,549
<ASSISTANT_TASK:> Python Code: import numpy as np def V_vdW(p, kT, N, a=0, b=0): Solve the van der Waals equation for V. coeffs = [p, - (kT * N + p * N *b), a * N**2, - a * N**3 * b] V = sorted(np.roots(coeffs)) return np.real(V).tolist() print(V_vdW(1.0, 1.0, 1000)) import signac project = signac.get...
<SYSTEM_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.4 Modifying the Data Space Step2: You will notice that this equation is a cubic polynomial and therefore has 3 possible solutions instead of ...
5,550
<ASSISTANT_TASK:> Python Code: # DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'messy-consortium', 'emac-2-53-aerchem', 'toplevel') # Set as follows: DOC.set_author("name", "email") # TODO - please enter value(s) # Set as follows: DOC.set_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: Document Authors Step2: Document Contributors Step3: Document Publication Step4: Document Table of Contents Step5: 1.2. Model Name Step6: 2...
5,551
<ASSISTANT_TASK:> Python Code: %matplotlib inline import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D import platform from utils import * from mesh import * from deformation import * import numpy as np import os from sklearn import preprocessing, decomposition, neighbors, cluster from scipy import 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: 2. Introduction Step2: 3.2 Classification approach - Supervised Step3: 3.2.2 Compute Laplacian, eigenvectors and eigenvalues. Step4: Calculat...
5,552
<ASSISTANT_TASK:> Python Code: import numba import numexpr as ne import numpy as np import matplotlib.pyplot as roberplot import matplotlib.image as mpimg %load_ext line_profiler %load_ext memory_profiler def rgb2gray(rgb): return np.dot(rgb[...,:3], [0.299, 0.587, 0.114]) def image_plot(img): roberplot.figure(...
<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: Local Binary Pattern Representation Step5: Just an example of usage
5,553
<ASSISTANT_TASK:> Python Code: import time import numpy as np import visa rm = visa.ResourceManager() # Creamos al Resource Manager rm.list_resources() # Esto les permitirá ver qué es lo que pyvisa reconoce conectado a la PC resource_name = 'USB0::0x0699::0x0346::C033250::INSTR' # Este es un nombre ejemplo con el cual ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Es importante en los pasos que acabamos de dar que reconozcamos cuando Pyvisa reconoce nuestro instrumental y cuando no. Si nos conectamos por U...
5,554
<ASSISTANT_TASK:> Python Code: %matplotlib inline import pytz import matplotlib.pyplot as plt import pandas as pd import ulmo from ulmo.util import convert_datetime print(ulmo.cuahsi.wof.__doc__) print([obj for obj in dir(ulmo.cuahsi.wof) if not obj.startswith('__')]) # WaterML/WOF WSDL endpoints wsdlurl = 'http://54....
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: CUAHSI WaterOneFlow Step2: Get site information Step3: Get Values Step4: 'odm2timeseries Step5: site_values['values'] is a list of individua...
5,555
<ASSISTANT_TASK:> Python Code: import os import mne sample_data_folder = mne.datasets.sample.data_path() sample_data_raw_file = os.path.join(sample_data_folder, 'MEG', 'sample', 'sample_audvis_raw.fif') raw = mne.io.read_raw_fif(sample_data_raw_file) raw.crop(tmax=60).load_data() ra...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: We've seen in a previous tutorial &lt;tut-raw-class&gt; how to plot data Step2: It may not be obvious when viewing this tutorial online, but by...
5,556
<ASSISTANT_TASK:> Python Code: def DH_simbolico(a, d, α, θ): from sympy import Matrix, sin, cos # YOUR CODE HERE raise NotImplementedError() from sympy import Matrix, sin, cos, pi from nose.tools import assert_equal assert_equal(DH_simbolico(0,0,0,pi/2), Matrix([[0,-1,0,0],[1,0,0,0], [0,0,1,0],[0,0,0,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: Cree una función que tome como argumentos los parametros de los grados de libertad de un manipulador tipo PUMA y devuelva las matrices de transf...
5,557
<ASSISTANT_TASK:> Python Code: # DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'csiro-bom', 'sandbox-3', 'landice') # 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,558
<ASSISTANT_TASK:> Python Code: from IPython.display import Image Image(filename='images/mdgxs.png', width=350) %matplotlib inline import numpy as np import matplotlib.pyplot as plt import openmc import openmc.mgxs as mgxs # Instantiate some Nuclides h1 = openmc.Nuclide('H1') o16 = openmc.Nuclide('O16') u235 = openmc....
<SYSTEM_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 variety of tools employing different methodologies have been developed over the years to compute multi-group cross sections for certain applic...
5,559
<ASSISTANT_TASK:> Python Code: # DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'nuist', 'sandbox-2', 'landice') # Set as follows: DOC.set_author("name", "email") # TODO - please enter value(s) # Set as follows: DOC.set_contributor("name", "e...
<SYSTEM_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,560
<ASSISTANT_TASK:> Python Code: import graphlab sales = graphlab.SFrame('kc_house_data_small.gl/') import numpy as np # note this allows us to refer to numpy as np instead def get_numpy_data(data_sframe, features, output): data_sframe['constant'] = 1 # this is how you add a constant column to an SFrame # add 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: Load in house sales data Step2: Import useful functions from previous notebooks Step3: We will also need the normalize_features() function fro...
5,561
<ASSISTANT_TASK:> Python Code: from pyspark.sql import SQLContext from pyspark.sql.types import * sqlContext = SQLContext(sc) schema = StructType([ \ StructField("state", StringType(), True), \ StructField("account_length", DoubleType(), True), \ StructField("area_code", StringType(), True), \ StructFie...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Basic DataFrame operations Step2: Exercise Step3: Feature Visualization Step4: DataTypes Step5: Seaborn Step6: We can examine feature diffe...
5,562
<ASSISTANT_TASK:> Python Code: T = 120 Tr = 2.2*120 print [Tr/10, Tr/4] h = 40.0 pc = -1.0/120 pd = np.exp(pc*h) print pd s,z = sy.symbols('s, z') h = sy.symbols('h', positive=True) F = (16*s+1)/(100*s+1) H = sy.simplify(F.subs(s, (z-1)/(z*h))) print H p1,p2,p3,p4 = sy.symbols('p1, p2, p3, p4') sy.expand((z-0.7+sy.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: (b) Step2: Problem 2 Step3: Problem 3 Step4: Set up the state-space model. Make sure it is correct. Step5: (c) Finding the feedback gain Ste...
5,563
<ASSISTANT_TASK:> Python Code: from serial import Serial from Servo import Servo from IPython.html.widgets import interact sp = Serial("/dev/ttyUSB0", 19200) a = Servo(sp, dir = 'a') w1 = interact(a.set_pos, pos = (-90, 90)) import time #-- Sequence of angles seq = [40, 0, 20, -40, -80, 0] #-- Repeat the sequence...
<SYSTEM_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 the Servo class. It is needed for creating the Servo objects Step2: Import the IPython 3 interact function. It is needed for creating th...
5,564
<ASSISTANT_TASK:> Python Code: %pylab notebook fe_25 = 25 # [Hz] fe_60 = 60 # [Hz] P = array([2.0, 4.0, 6.0, 8.0, 10.0, 12.0, 14.0]) n = 120*fe_25 / P print(''' |-----------------+--------------| | Number of Poles | n_m | |-----------------+--------------|''') # We use a simple for-loop to print a row per re...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Description Step2: (a) Step3: Alternatively (and much simpler) you can use the "max()" function Step4: (b)
5,565
<ASSISTANT_TASK:> Python Code: workDir = '/home/nick/notebook/SIPSim/dev/bac_genome3/validation/' R_dir = '/home/nick/notebook/SIPSim/lib/R/' figDir = '/home/nick/notebook/SIPSim/figures/' nprocs = 3 import os import numpy as np import dill import pandas as pd %load_ext rpy2.ipython %%R library(ggplot2) library(plyr) ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Init Step2: Determining the probability of detecting the taxa across the entire gradient Step3: skewed normal distribution Step4: small unifo...
5,566
<ASSISTANT_TASK:> Python Code: %%capture !pip install git+https://github.com/biothings/biothings_explorer#egg=biothings_explorer # import modules from biothings_explorer from biothings_explorer.hint import Hint from biothings_explorer.user_query_dispatcher import FindConnection import nest_asyncio nest_asyncio.apply()...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Next, import the relevant modules Step2: Step 1 Step3: Step 2 Step4: Here, we formulate a FindConnection query with "hyperphenylalaninemia" a...
5,567
<ASSISTANT_TASK:> Python Code: import numpy as np from scipy.io import loadmat, savemat from numpy import random from os import path mat = loadmat('../../../data/multiclass/usps.mat') Xall = mat['data'] Yall = np.array(mat['label'].squeeze(), dtype=np.double) # map from 1..10 to 0..9, since shogun # requires ...
<SYSTEM_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 plot the first five examples of the train data (first row) and test data (second row). Step2: Then we import shogun components and conve...
5,568
<ASSISTANT_TASK:> Python Code: %pylab inline %matplotlib inline import os SHOGUN_DATA_DIR=os.getenv('SHOGUN_DATA_DIR', '../../../data') # import all Shogun classes from shogun import * from matplotlib.patches import Ellipse # a tool for visualisation def get_gaussian_ellipse_artist(mean, cov, nstd=1.96, color="red", li...
<SYSTEM_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 Mixture Models and Expectation Maximisation in Shogun Step2: Set up the model in Shogun Step3: Sampling from mixture models Step4: E...
5,569
<ASSISTANT_TASK:> Python Code: def addFunction(inputNumber): result = inputNumber + 2 return result print addFunction(2) var = 2 print addFunction(var) def addFunction(inputNumber): if inputNumber < 0: return 'Number must be positive!' result = inputNumber + 2 return result print addFunct...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: On its own, this code will only define what the function does, but will not actually run any code. To execute the code inside the function you h...
5,570
<ASSISTANT_TASK:> Python Code: %pylab inline import scipy as sp zz = np.loadtxt('wiggleZ_DR1_z.dat',dtype='float'); # Load WiggleZ redshifts np.min() # Check bounds np.max() nbins = 50; # Is this a good choice? n, bins, patches = hist() # With hist, one needs to (spuriously) request the patch objects as well x = bi...
<SYSTEM_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 from file Step2: Check bounds Step3: Construct histogram from data Step4: Interpolate histogram output -> p(z); n.b. that you can a...
5,571
<ASSISTANT_TASK:> Python Code: ### Get Gradient Jacobians (Change in h(x) i.e. ground level/ Change in x/y) grad_lat = (np.gradient(map_terrain, axis = 0))/75 grad_lon = (np.gradient(map_terrain, axis = 1))/75 grid_points = np.array(list(product(map_lat_range, map_lon_range))) map_grad_stack_lat = grad_lat.reshape(-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: Terrain Altimeter Sensor Step2: Set Up Navigation Filter Step3: Plot Results
5,572
<ASSISTANT_TASK:> Python Code: # Print platform info of Python exec env. import sys sys.version import warnings warnings.simplefilter('ignore', FutureWarning) from pandas import * show_versions() data = read_excel('WHO POP TB some.xls') data.head() data.tail() data.info() data.describe() tbColumn = data['TB deaths'] ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: The data Step2: The range of the problem Step3: The total number of deaths in 2013 is Step4: The largest and smallest number of deaths in a s...
5,573
<ASSISTANT_TASK:> Python Code: !pip install arviz %matplotlib inline import matplotlib.pyplot as plt import numpy as np import pymc3 as pm import pandas as pd import theano import seaborn as sns sns.set_style("whitegrid") np.random.seed(123) url = "https://github.com/twiecki/WhileMyMCMCGentlySamples/blob/master/content...
<SYSTEM_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 intuitive specification Step2: I have seen plenty of traces with terrible convergences but this one might look fine to the unassuming eye. ...
5,574
<ASSISTANT_TASK:> Python Code: count,feature_names=text.count_letters('data/languages/E3.txt') print((count,feature_names)) count,feature_names=text.count_letters('data/languages/E3.txt') print((count,feature_names)) p=text.letter_freq('English',feature_names) print(p) print((sum(count*log10(p)))) C=text.LanguageFileCl...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Text Classification from Folders Step2: Footnote Step3: Bigrams/Trigrams Step4: specify the ngram_range - the smallest ngram to use, and the ...
5,575
<ASSISTANT_TASK:> Python Code: %matplotlib inline from matplotlib import pyplot as plt import numpy as np xv=[1,2,3,4]; yv=[5,1,4,0] plt.plot(xv,yv); plt.plot(xv,yv,'ro'); myplot=plt.plot(xv,yv,'k--'); plt.setp(myplot,linewidth=3.0,marker='+',markersize=30); myplot=plt.plot(xv,yv,'k--'); plt.setp(myplot,'linewidth',...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Above commands enable pylab environment => direct access to numpy, scipy and matplotlib. The option 'inline' results in plot outputs to be direc...
5,576
<ASSISTANT_TASK:> Python Code: sexual_mean, sexual_standard_deviation = 1.1, 0.15 asexual_mean, asexual_standard_deviation = 1.2, 0.3 pod_sexual = norm.cdf(0, loc=sexual_mean, scale=sexual_standard_deviation) pod_asexual = norm.cdf(0, loc=asexual_mean, scale=asexual_standard_deviation) print("The probability that the ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: One way to figure out the expected extinction time is to figure out the expected number of generations until the mean population growth rate dip...
5,577
<ASSISTANT_TASK:> Python Code: import numpy as np # importamos bibliotecas para plotear import matplotlib import matplotlib.pyplot as plt # para desplegar los plots en el notebook %matplotlib inline # para cómputo simbólico from sympy import * init_printing() x, y = symbols('x y') f = (1-x-y)*x f g = (4-7*x-3*y)*y g 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: Equilibrios Step2: Jacobiana Step3: Evaluada en un punto de equilibrio
5,578
<ASSISTANT_TASK:> Python Code: from IPython.display import HTML HTML('''<script> code_show=true; function code_toggle() { if (code_show){ $('div.input').hide(); } else { $('div.input').show(); } code_show = !code_show } $( document ).ready(code_toggle); </script> <form action="javascript:code_toggle()"><input 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: The base catalog Step2: Target_Name is the name of the (central) object at each observation, from that we see we have 681 unique sources out of...
5,579
<ASSISTANT_TASK:> Python Code: data_in_shape = (6, 6, 3) L = AveragePooling2D(pool_size=(2, 2), strides=None, padding='valid', data_format='channels_last') layer_0 = Input(shape=data_in_shape) layer_1 = L(layer_0) model = Model(inputs=layer_0, outputs=layer_1) # set weights to random (use seed for reproducibility) np.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: [pooling.AveragePooling2D.1] input 6x6x3, pool_size=(2, 2), strides=(1, 1), padding='valid', data_format='channels_last' Step2: [pooling.Averag...
5,580
<ASSISTANT_TASK:> Python Code: !pip install lxml !pip install BeautifulSoup4 import urllib.request from lxml import html from bs4 import BeautifulSoup # Scrape all HTML from webpage. def scrapewebpage(url): # Open URL and get HTML. web = urllib.request.urlopen(url) # Make sure there wasn't any errors opening the UR...
<SYSTEM_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. Define functions for scraping Step2: 3. Scrape Internet Movie Database Step3: 4. Scrape Washington Post Step4: 5. Scrape Wikipedia Step5: ...
5,581
<ASSISTANT_TASK:> Python Code: from neon.backends import gen_backend be = gen_backend(backend='gpu', batch_size=1) print be import pickle as pkl sentence_length = 128 vocab_size = 20000 # we have some special codes pad_char = 0 # padding character start = 1 # marker for start of review oov = 2 # when the word is ou...
<SYSTEM_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 also define a few parameters, and the load the vocabulary. The vocab is a 1 Step2: Load Model Step3: Inference Step5: Now we write our new...
5,582
<ASSISTANT_TASK:> Python Code: %matplotlib inline import numpy as np import matplotlib.pyplot as plt import GPy import pods from IPython.display import display data = pods.datasets.olympic_sprints() X = data['X'] y = data['Y'] print data['info'], data['details'] print data['citation'] print data['output_info'] prin...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Running Example Step2: When using data sets it's good practice to cite the originators of the data, you can get information about the source of...
5,583
<ASSISTANT_TASK:> Python Code: import pandas as pd import numpy as np import tensorflow as tf import tflearn from tflearn.data_utils import to_categorical reviews = pd.read_csv('reviews.txt', header=None) labels = pd.read_csv('labels.txt', header=None) from collections import Counter total_counts = Counter() for idx,...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Preparing the data Step2: Counting word frequency Step3: Let's keep the first 10000 most frequent words. As Andrew noted, most of the words in...
5,584
<ASSISTANT_TASK:> Python Code: import copy import numpy as np from astropy.io import fits import matplotlib.pyplot as plt % matplotlib inline #%matplotlib auto # Observation obs = fits.getdata("/home/jneal/.handy_spectra/HD211847-1-mixavg-tellcorr_1.fits") plt.plot(obs["wavelength"], obs["flux"]) plt.hlines(1, 2111, 2...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: The obeservatios were originally automatically continuum normalized in the iraf extraction pipeline. Step2: The two PHOENIX ACES spectra here ...
5,585
<ASSISTANT_TASK:> Python Code: import pandas as pd pd.options.mode.chained_assignment = None # default='warn', hides SettingWithCopyWarning file = 'data/evaluations.csv' conversion_dict = {'research_type': lambda x: int(x == 'E')} evaluation_data = pd.read_csv(file, sep=',', header=0, index_col=0, converters=conversio...
<SYSTEM_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 dataset has 400 samples with 27 columns. Some of these columns are not necessary for further analysis Step2: The above two rows exemplify a...
5,586
<ASSISTANT_TASK:> Python Code: display('Number of rows: {}'.format(len(df))) display('Unique SSIDs: {}'.format(len(df['SSID'].unique()))) display('Unique MACs: {}'.format(len(df['MAC'].unique()))) display('Number of Auth Mode types: {}'.format(len(df['AuthMode'].unique()))) def auth_filter(x): if 'WPA2' in x: ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: So there are a significant number of open networks, but the overall majority use WPA2. That's good for the University but not so great for attac...
5,587
<ASSISTANT_TASK:> Python Code: import mltoolbox.image.classification as model from google.datalab.ml import * import os bucket = 'gs://' + datalab_project_id() + '-coast' preprocessed_dir = bucket + '/preprocessed' staging_dir = bucket + '/staging' model_dir = bucket + '/model' train_set = BigQueryDataSet('SELECT image...
<SYSTEM_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 Step2: Check your job status. You can run Step3: Evaluation Step4: Model Deployment Step5: Online Prediction Step6: Batch Predicti...
5,588
<ASSISTANT_TASK:> Python Code: #@title Licensed under the Apache License v2.0 with LLVM Exceptions. # See https://llvm.org/LICENSE.txt for license information. # SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception #@title General setup import os import tempfile ARTIFACTS_DIR = os.path.join(tempfile.gettempdir(), "...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Dynamic Shapes Step2: Create a program using TensorFlow and import it into IREE Step3: Test the imported program Step4: Download compilation ...
5,589
<ASSISTANT_TASK:> Python Code: # Imports import matplotlib.pyplot as plt %matplotlib inline import numpy as np from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute from qiskit.tools.visualization import matplotlib_circuit_drawer as circuit_drawer from qiskit.tools.visualization import plot_his...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Recall that to make the Bell state $|\psi\rangle= (|00\rangle+|11\rangle)/\sqrt{2}$ from the initial state $|00\rangle$, the quantum circuit fir...
5,590
<ASSISTANT_TASK:> Python Code: import time import numpy as np from pypot.creatures import PoppyTorso poppy = PoppyTorso() for m in poppy.motors: m.goto_position(0, 2) # Left arm is compliant, right arm is active for m in poppy.l_arm: m.compliant = False for m in poppy.r_arm: m.compliant = False # The tor...
<SYSTEM_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, create your Pypot robot Step2: Initialize your robot positions to 0 Step3: The left arm must be compliant (so you can move it), and th...
5,591
<ASSISTANT_TASK:> Python Code: import pandas as pd df = pd.DataFrame({'product': [1179160, 1066490, 1148126, 1069104, 1069105, 1160330, 1069098, 1077784, 1193369, 1179741], 'score': [0.424654, 0.424509, 0.422207, 0.420455, 0.414603, 0.168784, 0.168749, 0.168738, 0.168703, 0.168684]}) products = [1066...
<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,592
<ASSISTANT_TASK:> Python Code: %matplotlib inline import numpy import matplotlib.pyplot as plt t = numpy.linspace(0.0, 1.6e3, 100) c_0 = 1.0 decay_constant = numpy.log(2.0) / 1600.0 fig = plt.figure() axes = fig.add_subplot(1, 1, 1) axes.plot(t, 1.0 * numpy.exp(-decay_constant * t)) axes.set_title("Radioactive Decay w...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Numerical Methods for Initial Value Problems Step2: Examples Step3: Examples Step4: A similar method can be derived if we consider instead us...
5,593
<ASSISTANT_TASK:> Python Code: baseDir = '/home/nick/notebook/SIPSim/dev/priming_exp/' workDir = os.path.join(baseDir, 'exp_info') otuTableFile = '/var/seq_data/priming_exp/data/otu_table.txt' otuTableSumFile = '/var/seq_data/priming_exp/data/otu_table_summary.txt' metaDataFile = '/var/seq_data/priming_exp/data/allsamp...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Init Step2: Loading OTU table (filter to just bulk samples) Step3: Which gradient(s) to simulate? Step4: Notes Step5: Total richness of star...
5,594
<ASSISTANT_TASK:> Python Code: from openhunt.mordorutils import * spark = get_spark() mordor_file = "https://raw.githubusercontent.com/OTRF/mordor/master/datasets/small/windows/lateral_movement/host/empire_psexec_dcerpc_tcp_svcctl.zip" registerMordorSQLTable(spark, mordor_file, "mordorTable") df = spark.sql( ''' SELE...
<SYSTEM_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 & Process Mordor Dataset Step2: Analytic I
5,595
<ASSISTANT_TASK:> Python Code: !pip install cython https://github.com/SciTools/cartopy/archive/v0.18.0b1.zip import cartopy.io.img_tiles as cimgt request = cimgt.OSM() import cartopy.crs as ccrs carto_proj = ccrs.GOOGLE_MERCATOR %matplotlib notebook import matplotlib.pyplot as plt fig = plt.figure() ax = fig.add_sub...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Selecting a Tileset Step2: Projection Step3: Rendering Tiles Step4: To render a specific region, call set_extent with the geodetic (lat/lon) ...
5,596
<ASSISTANT_TASK:> Python Code: %matplotlib inline from astropy.table import Table import numpy as np import matplotlib.pyplot as plt data = Table.read('GTR-ADM-QSO-ir-testhighz_findbw_lup_2016_starclean.fits') # X is in the format need for all of the sklearn tools, it just has the colors # X = np.vstack([ data['ug'], 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: Second, load the test data Step2: I had some problems with GTR-ADM-QSO-ir_good_test_2016n.fits because it thought that there were blank entries...
5,597
<ASSISTANT_TASK:> Python Code: reset_start_time(O.map, title='map') # alias is "select" # warming up: d = subs(O.from_((1, 2 , 3)).map(lambda x: x * 2)) rst(O.pluck, title='pluck') d = subs(O.from_([{'x': 1, 'y': 2}, {'x': 3, 'y': 4}]).pluck('y')) class Coord: def __init__(self, x, y): self.x = x 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: ...by emitting all of the items emitted by corresponding Observables Step2: flat_map_latest(select_switch) Step3: concat_map Step4: many_sele...
5,598
<ASSISTANT_TASK:> Python Code: from __future__ import division import gym import numpy as np import random import tensorflow as tf import matplotlib.pyplot as plt %matplotlib inline import tensorflow.contrib.slim as slim env = gym.make('CartPole-v0') class experience_buffer(): def __init__(self, buffer_size = 100...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Load the environment Step2: The Deep Q-Network Step3: Implementing the network itself Step4: Training the network Step5: Some statistics on ...
5,599
<ASSISTANT_TASK:> Python Code: # location is relative or absolute path to the file sne = ans.snanaSims.SnanaSims.fromSNANAfileroot('snana_fits', location=ans.example_data, n=1) sn = ans.snanaSims.SnanaSims.reformat_SNANASN(sne.snList[0]) ans.snanaSims.SnanaSims.matchSNANAbandnamesinregistry() sn[:5] sn.meta model ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Pick out the very first SN and reformat it to look the way sncosmo expects SN to look Step2: Make sure SNCosmo can understand band names Step3...