Unnamed: 0
int64
0
15.9k
cleaned_code
stringlengths
67
124k
cleaned_prompt
stringlengths
168
30.3k
4,900
<ASSISTANT_TASK:> Python Code: %matplotlib inline from seabird.cnv import fCNV !wget https://raw.githubusercontent.com/castelao/seabird/master/sampledata/CTD/dPIRX003.cnv profile = fCNV('dPIRX003.cnv') print ("The profile coordinates is latitude: %.4f, and longitude: %.4f" % \ (profile.attributes['LATITUDE'], pro...
<SYSTEM_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 first download an example file with some CTD data Step2: The profile dPIRX003.cnv.OK was loaded with the default rule cnv.yaml Step3: Or...
4,901
<ASSISTANT_TASK:> Python Code: from pyspark import SparkContext sc = SparkContext(master = 'local') from pyspark.sql import SparkSession spark = SparkSession.builder \ .appName("Python Spark SQL basic example") \ .config("spark.some.config.option", "some-value") \ .getOrCreate() ad = spar...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Linear regression without cross-valiation Step2: Transform data structure Step3: Build linear regression model Step4: Fit the model Step5: P...
4,902
<ASSISTANT_TASK:> Python Code: import pandas as pd import numpy as np d = {'l': ['left', 'right', 'left', 'right', 'left', 'right'], 'r': ['right', 'left', 'right', 'left', 'right', 'left'], 'v': [-1, 1, -1, 1, -1, np.nan]} df = pd.DataFrame(d) def g(df): return df.groupby('r')['v'].apply(pd.Series.sum,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:
4,903
<ASSISTANT_TASK:> Python Code: !pip install git+https://github.com/google/starthinker CLOUD_PROJECT = 'PASTE PROJECT ID HERE' print("Cloud Project Set To: %s" % CLOUD_PROJECT) CLIENT_CREDENTIALS = 'PASTE CLIENT CREDENTIALS HERE' print("Client Credentials Set To: %s" % CLIENT_CREDENTIALS) FIELDS = { 'auth_read': '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: 2. Get Cloud Project ID Step2: 3. Get Client Credentials Step3: 4. Enter Column Mapping Parameters Step4: 5. Execute Column Mapping
4,904
<ASSISTANT_TASK:> Python Code: import time from collections import namedtuple import numpy as np import tensorflow as tf with open('anna.txt', 'r') as f: text=f.read() vocab = set(text) vocab_to_int = {c: i for i, c in enumerate(vocab)} int_to_vocab = dict(enumerate(vocab)) chars = np.array([vocab_to_int[c] for 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: First we'll load the text file and convert it into integers for our network to use. Step3: Now I need to split up the data into batches, and in...
4,905
<ASSISTANT_TASK:> Python Code: %matplotlib inline import os import numpy as np import matplotlib.pyplot as plt import astropy.io.fits as pyfits import drizzlepac import grizli from grizli.pipeline import photoz from grizli import utils, prep, multifit, fitting utils.set_warnings() print('\n Grizli version: ', grizli.__...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Pull out the photometry of the nearest source matched in the photometric catalog. Step2: Scaling the spectrum to the photometry Step3: An offs...
4,906
<ASSISTANT_TASK:> Python Code: %matplotlib inline import matplotlib.pyplot as plt import numpy as np import nltk from nltk import word_tokenize text = word_tokenize("And now for something completely different") nltk.pos_tag(text) text = word_tokenize("They refuse to permit us to obtain the refuse permit") nltk.pos_tag(...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: CC Step2: text.similar(w) finds words that appear in similar contexts to w Step3: words similar to 'bought' -- mostly verbs Step4: words simi...
4,907
<ASSISTANT_TASK:> Python Code: import pickle import xml.etree.ElementTree as ET import urllib.request xml_path = 'https://feeds.capitalbikeshare.com/stations/stations.xml' tree = ET.parse(urllib.request.urlopen(xml_path)) root = tree.getroot() station_location = dict() for child in root: tmp_lst = [float(child[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: Import Capital Bikeshare station information .xml file Step2: create dictionary of bikeshare station (key) and its location (value) Step3: sav...
4,908
<ASSISTANT_TASK:> Python Code: import numpy as np from matplotlib import pyplot as plt %matplotlib inline import os import sys import warnings warnings.filterwarnings('ignore') import time from scipy.stats import ks_2samp from astropy.io import fits,ascii from astropy.table import Table from astropy.coordinates 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: SF Main sequence with full sample Step2: Statistics Step3: Number with HI detections Step4: Table 1 Step5: Figure 1 Step6: With BT cut Step...
4,909
<ASSISTANT_TASK:> Python Code: import numpy as np import pandas as pd import seaborn as sns import matplotlib.pyplot as plt import xgboost as xgb from sklearn.metrics import roc_curve, auc from sklearn.metrics import precision_recall_curve df = pd.read_csv("iris.csv") def rotMat3D(a,r): Return the matrix that rota...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step3: Rotations Step5: PCA Step8: FastFourier Transformation Step9: Save python object with pickle Step10: Progress Bar Step11: Check separations...
4,910
<ASSISTANT_TASK:> Python Code: import math prime =[] def simpleSieve(limit ) : mark =[True for i in range(limit + 1 ) ] p = 2 while(p * p <= limit ) : if(mark[p ] == True ) : for i in range(p * p , limit + 1 , p ) : mark[i ] = False   p += 1  for p in range(2 , limit ) : if mark[p ] : 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:
4,911
<ASSISTANT_TASK:> Python Code: %matplotlib inline import matplotlib.pyplot as plt import numpy as np from palettable.colorbrewer.qualitative import Set1_9 Set1_9.name Set1_9.type Set1_9.number Set1_9.colors Set1_9.hex_colors Set1_9.mpl_colors Set1_9.mpl_colormap # requires ipythonblocks Set1_9.show_as_blocks() Set1_9....
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Palettable API Step2: Setting the matplotlib Color Cycle Step3: Using a Continuous Palette
4,912
<ASSISTANT_TASK:> Python Code: testsample = sample.Sample() testsample.readout_tone_length = 200e-9 # length of the readout tone testsample.clock = 1e9 # sample rate of your physical awg/pulse generator testsample.tpi = 100e-9 # duration of a pi-pulse testsample.tpi2 = 50e-9 # duration of a pi/2-pulse testsample.iq_fre...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Building sequences Step2: Building sequences from pulses Step3: As you can see, wait times can be added with the add_wait command. In this cas...
4,913
<ASSISTANT_TASK:> Python Code: #!wget -N https://rapidsai-cloud-ml-sample-data.s3-us-west-2.amazonaws.com/airline_small.parquet def load_data(fpath): Simple helper function for loading data to be used by CPU/GPU models. :param fpath: Path to the data to be ingested :return: DataFrame wrapping the 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: Step2: Define data loader, using cuDF Step4: Define our training routine. Step5: Implement our MLFlow training loop, and save our best model to the t...
4,914
<ASSISTANT_TASK:> Python Code: %matplotlib inline %config InlineBackend.figure_format = 'retina' import numpy as np import pandas as pd import matplotlib.pyplot as plt data_path = 'Bike-Sharing-Dataset/hour.csv' rides = pd.read_csv(data_path) rides.head() rides[:24*10].plot(x='dteday', y='cnt') dummy_fields = ['seas...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Load and prepare the data Step2: Checking out the data Step3: Dummy variables Step4: Scaling target variables Step5: Splitting the data into...
4,915
<ASSISTANT_TASK:> Python Code: from openhunt.mordorutils import * spark = get_spark() sd_file = "https://raw.githubusercontent.com/OTRF/Security-Datasets/master/datasets/atomic/windows/credential_access/host/empire_mimikatz_sam_access.zip" registerMordorSQLTable(spark, sd_file, "sdTable") df = spark.sql( ''' SELECT `...
<SYSTEM_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 Security Dataset Step2: Analytic I
4,916
<ASSISTANT_TASK:> Python Code: !pip install git+https://github.com/biothings/biothings_explorer.git from biothings_explorer.smartapi_kg import MetaKG kg = MetaKG() kg.constructMetaKG(source="remote") kg.filter({"input_type": "Gene", "output_type": "ChemicalSubstance"}) kg.filter({"input_type": "Gene", "output_type":...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Construct Meta-KG from SmartAPI Step2: Filter Step3: Find Meta-KG operations that converys Gene->Metabolize->ChemicalSubstance Step4: Filter ...
4,917
<ASSISTANT_TASK:> Python Code: import pandas as pd import os import numpy as np import pymc3 as pm import seaborn as sns import matplotlib.pyplot as plt %matplotlib inline true_rating = { 'All Stars': 2.0, 'Average': 0.0, 'Just Having Fun': -1.2, } true_index = { 0: 'All Stars', 1: 'Average', 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: We have two teams, one of which is much better than the other. Let's make a simulated season between these teams. Step2: Prior on each team is ...
4,918
<ASSISTANT_TASK:> Python Code: import pandas as pd import numpy as np import matplotlib import matplotlib.pyplot as plt matplotlib.style.use('ggplot') # Look Pretty def drawLine(model, X_test, y_test, title): fig = plt.figure() ax = fig.add_subplot(111) ax.scatter(X_test, y_test, c='g', marker='o') ax....
<SYSTEM_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 Convenience Function Step2: The Assignment Step3: Create your linear regression model here and store it in a variable called model. Don't ac...
4,919
<ASSISTANT_TASK:> Python Code: import pandas as pd test_data = pd.read_csv("../data/temp.standardized.csv") test_data.head() import crowdtruth from crowdtruth.configuration import DefaultConfig class TestConfig(DefaultConfig): inputColumns = ["gold", "event1", "event2", "text"] outputColumns = ["response"] ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Declaring a pre-processing configuration Step2: Our test class inherits the default configuration DefaultConfig, while also declaring some addi...
4,920
<ASSISTANT_TASK:> Python Code: %matplotlib inline # Arrays import numpy as np # Plotting import matplotlib.pyplot as plt from itertools import product # Operating system interfaces import os, sys # Parallel computing from multiprocessing import Pool # pairinteraction :-) from pairinteraction import pireal as pi # Creat...
<SYSTEM_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 plate lies in the $xy$-plane with the surface at $z = 0$. The atoms lie in the $xz$-plane with $z>0$. Step2: Next we define the state that ...
4,921
<ASSISTANT_TASK:> Python Code: # Import and instantiate energy_landscape object. from catmap.api.ase_data import EnergyLandscape energy_landscape = EnergyLandscape() # Import all gas phase species from db. search_filter_gas = [] energy_landscape.get_molecules('molecules.db', selection=search_filter_gas) # Import all ad...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: The site_specific option accepts True, False or a string. In the latter case, the site key is recognized only if the value matches the string, w...
4,922
<ASSISTANT_TASK:> Python Code: #load GPIO library import RPi.GPIO as GPIO #Set BCM (Broadcom) mode for the pin numbering GPIO.setmode(GPIO.BCM) # If we assign the name 'PIN' to the pin number we intend to use, we can reuse it later # yet still change easily in one place PIN = 18 # set pin as output GPIO.setup(PIN, GPI...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: BCM is the numbering that is engraved on the Raspberry Pi case we use and that you can also find back on the printed Pinout schema (BCM stands f...
4,923
<ASSISTANT_TASK:> Python Code: # USAGE: Equal-Weight Portfolio. # 1) if 'exclude_non_overlapping=True' below, the portfolio will only contains # days which are available across all of the algo return timeseries. # # if 'exclude_non_overlapping=False' then the portfolio returned will span from the # earliest ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Volatility-weighted Portfolio (using just np.std as weighting metric) Step2: Volatility-weighted Portfolio (with constraint of no asset weight ...
4,924
<ASSISTANT_TASK:> Python Code: ##Some code to run at the beginning of the file, to be able to show images in the notebook ##Don't worry about this cell #Print the plots in this screen %matplotlib inline #Be able to plot images saved in the hard drive from IPython.display import Image #Make the notebook wider from IPy...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: 3. Dimensionality reduction Step2: Correlation between variables Step3: Revenue, employees and assets are highly correlated. Step4: 3.1 Combi...
4,925
<ASSISTANT_TASK:> Python Code: # As usual, a bit of setup import time, os, json import numpy as np import matplotlib.pyplot as plt from cs231n.gradient_check import eval_numerical_gradient, eval_numerical_gradient_array from cs231n.rnn_layers import * from cs231n.captioning_solver import * from cs231n.classifiers.rnn 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: Next Character Prediction with RNN's Step2: In the above code, we reformatedd X_train, X_val and X_test to timed parts so that they are suitabl...
4,926
<ASSISTANT_TASK:> Python Code: %matplotlib inline import pandas as pd import matplotlib.pyplot as plt #Bibliotecas necessárias from numpy.random import shuffle, randint, choice lista = [] for i in range (1,1001): numero = randint (1,7) lista.append(numero) plt.hist(lista,6,normed = True) plt.axis([1,6,0,0.25])...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: <font color='blue'>Exercício 1</font> Step2: B Step3: B
4,927
<ASSISTANT_TASK:> Python Code: import sympy #symbolic algebra library import sympy.physics.mechanics as mech import control #control analysis library sympy.init_printing(use_latex='mathjax') from IPython.display import display %matplotlib inline %load_ext autoreload %autoreload 2 import px4_logutil import pylab 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: Define BKE Function Step2: Define Symbolic Variables Step3: Dynamics Analysis Step4: Define Points of Interest Step5: Creation of the Bodies...
4,928
<ASSISTANT_TASK:> Python Code: # Some magic to make plots appear within the notebook %matplotlib inline import numpy as np # In case we need to use numpy import pymt.models model = pymt.models.Child() help(model) rm -rf _model # Clean up for the next step config_file, initdir = model.setup('_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: Run CHILD in PyMT Step2: You can now see the help information for Child. This time, have a look under the Parameters section (you may have to s...
4,929
<ASSISTANT_TASK:> Python Code: import math "{:03}".format(1) "{:.<9}".format(3) "{:.<9}".format(11) "{:.>9}".format(3) "{:.>9}".format(11) "{:.=9}".format(3) "{:.=9}".format(11) "{:.^9}".format(3) "{:.^9}".format(11) "{:+}".format(3) "{:+}".format(-3) "{:-}".format(3) "{:-}".format(-3) "{: }".format(3) "{: }".format(...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Short documentation Step2: Sign Step3: Width Step4: Precision Step5: Width + Precision Step6: Type Step7: Float Step8: Comparison between...
4,930
<ASSISTANT_TASK:> Python Code: %load_ext autoreload %autoreload 2 import pymarc import random from bookwormMARC.bookwormMARC import BRecord from bookwormMARC.bookwormMARC import parse_record from bookwormMARC.hathi_methods import All_Hathi from bookwormMARC.bookwormMARC import LCCallNumber import bz2 import bookwormMAR...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: This converts a json object into a MARC class so the existing methods will work Step2: This class has the base names of the files and my direct...
4,931
<ASSISTANT_TASK:> Python Code: import graphlab sales = graphlab.SFrame('kc_house_data.gl/') train_data,test_data = sales.random_split(.8,seed=0) example_features = ['sqft_living', 'bedrooms', 'bathrooms'] example_model = graphlab.linear_regression.create(train_data, target = 'price', features = example_features, ...
<SYSTEM_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: Split data into training and testing. Step3: Learning a multiple regression model Step4: Now that we have fit...
4,932
<ASSISTANT_TASK:> Python Code: !pip install -I "phoebe>=2.0,<2.1" %matplotlib inline import phoebe from phoebe import u # units import numpy as np import matplotlib.pyplot as plt logger = phoebe.logger() b = phoebe.default_star(starA='sun') print b['sun'] b.set_value('teff', 1.0*u.solTeff) b.set_value('rpole', 1.0*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: As always, let's do imports and initialize a logger and a new bundle. See Building a System for more details. Step2: Setting Parameters Step3:...
4,933
<ASSISTANT_TASK:> Python Code: import IPython IPython.__version__ from IPython.display import YouTubeVideo YouTubeVideo("05fA_DXgW-Y") import numpy numpy.__version__ from IPython.display import YouTubeVideo YouTubeVideo("1zmV8lZsHF4") import matplotlib matplotlib.__version__ from IPython.display import YouTubeVide...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Documentation Step2: <a href="http Step3: <i>"NumPy is an extension to the Python programming language, adding <b>support for large, multi-dim...
4,934
<ASSISTANT_TASK:> Python Code: from __future__ import division, print_function from sklearn.datasets import make_circles from sklearn.preprocessing import StandardScaler from sklearn.model_selection import train_test_split, GridSearchCV from sklearn.metrics import accuracy_score from sklearn.metrics import roc_curve, 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: An Introduction to Machine Learning with Scikit-learn Step2: Generating data Step3: To avoid overfitting, we split the data into a training se...
4,935
<ASSISTANT_TASK:> Python Code: import numpy as np %matplotlib inline import matplotlib.pyplot as plt # Required packages sqlachemy, pandas (both are part of anaconda distribution, or can be installed with a python installer) # One step requires the LSST stack, can be skipped for a particular OPSIM database in question...
<SYSTEM_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 OpSim output for modern versions Step2: Read in the OpSim DataBase into a pandas dataFrame Step3: The opsim database is a large file (...
4,936
<ASSISTANT_TASK:> Python Code: tree1 = tree.DecisionTreeClassifier( criterion ='entropy',random_state = 0) fittedtree=tree1.fit( X_train, y_train) #print metrics.confusion_matrix(y_train, fittedtree.predict(X_train)) #print metrics.accuracy_score(y_train, fittedtree.predict(X_train)) cross_validation.cross_val_score(...
<SYSTEM_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 the Data Step2: Formatting & Identifying the Data Step3: Exploring the Data Step4: Because the TxDot Estimates are so highly correlat...
4,937
<ASSISTANT_TASK:> Python Code: PROJECT_ID = "<your-project-id>" #@param {type:"string"} ! gcloud config set project $PROJECT_ID import sys # If you are running this notebook in Colab, run this cell and follow the # instructions to authenticate your GCP account. This provides access to your # Cloud Storage bucket and 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: Authenticate your GCP account Step2: Create a Cloud Storage bucket Step3: Only if your bucket doesn't already exist Step4: Finally, validate ...
4,938
<ASSISTANT_TASK:> Python Code: %matplotlib inline import matplotlib import numpy as np import pandas as pd import scipy.io import matplotlib.pyplot as plt from IPython.display import Image, display import h2o from h2o.estimators.deeplearning import H2OAutoEncoderEstimator h2o.init() !wget -c http://www.cl.cam.ac.uk/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: http Step3: We now need some code to read pgm files. Step4: Let's import it to H2O Step5: Reconstructing the hidden space Step6: Then we imp...
4,939
<ASSISTANT_TASK:> Python Code: import openanalysis.tree_growth as TreeGrowth from openanalysis.base_data_structures import PriorityQueue def dijkstra(G, source=None): # This signature is must if source is None: source = G.nodes()[0] # selecting root as source V = G.nodes() dist, prev = {}...
<SYSTEM_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 Notes Step2: Now, Let's implement the algorithm Step3: Note how implementation looks similiar to the algorithm, except the if b...
4,940
<ASSISTANT_TASK:> Python Code: ## matrix and vector tools import pandas as pd from pandas import DataFrame as df from pandas import Series import numpy as np ## sklearn from sklearn.datasets import make_friedman1 from sklearn.feature_selection import RFE from sklearn.svm import SVR from sklearn.svm import SVC from skle...
<SYSTEM_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 Import and pre-processing Step2: Data Pre-processing Step3: Analysis I Step4: Some PSSM shows deviation from expected normal distributio...
4,941
<ASSISTANT_TASK:> Python Code: # Author: Marijn van Vliet <w.m.vanvliet@gmail.com> # # License: BSD-3-Clause import numpy as np import mne from mne.datasets import sample from mne.minimum_norm import read_inverse_operator, apply_inverse print(__doc__) data_path = sample.data_path() subjects_dir = data_path / 'subjects'...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Plot the source estimate Step2: Plot the activation in the direction of maximal power for this data Step3: The normal is very similar Step4: ...
4,942
<ASSISTANT_TASK:> Python Code: from IPython.display import Image Image("Figures/EbbTideCurrent.jpg") Image("Figures/SlackTide.jpg") Image("Figures/FloodTideCurrent.jpg") import numpy as np import xarray as xr import matplotlib.pyplot as plt from ipywidgets import interact, interactive, fixed from tydal.module3_utils...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Slack Tide Step2: Flood Tide Step3: Tidal Currents Exploration Step4: In the following interactive plot you can calculate the velocity of the...
4,943
<ASSISTANT_TASK:> Python Code: import urllib.request import json job = urllib.request.urlopen("http://ql.linea.gov.br/dashboard/api/job/?process=1").read() api = json.loads(job) mergedqa = api['results'][0]['output'] print('mergedQA loaded!') import sys sys.path.append('/app/qlf/backend/framework/qlf') from bokeh.io 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: 1.2 Loading Bokeh and adding QLF ploting code to the python path Step2: 2. Wedge Plot Step4: 2.2 Creating tooltip format Step5: 2.3 Showing a...
4,944
<ASSISTANT_TASK:> Python Code: # Hit shift + enter or use the run button to run this cell and see the results print 'hello world' # The last line of every code cell will be displayed by default, # even if you don't print it. Run this cell to see how this works. 2 + 2 # The result of this line will not be displayed 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: Nicely formatted results Step2: Creating cells Step3: Once you've run all three cells, try modifying the first one to set class_name to your n...
4,945
<ASSISTANT_TASK:> Python Code: from read_video import * import numpy as np import matplotlib.pyplot as plt import cv2 video_to_read = "/Users/cody/test.mov" max_buf_size_mb = 500; %time frame_buffer = ReadVideo(video_to_read, max_buf_size_mb) frame_buffer.nbytes print("Matrix shape: {}".format(frame_buffer.shape)) ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Time Critical Path Step2: Plot First and Last Frames Step3: Reshape the Data for Clustering Step4: Begin Heavy Lifting Step5: Analysis Step6...
4,946
<ASSISTANT_TASK:> Python Code: q = select fd.id, fd.name, fd.state, COALESCE(fd.population, 0) as population, sum(rm.structure_count) as structure_count, fd.population / sum(rm.structure_count)::float as people_per_structure from firestation_firedepartment fd inner join firestation_firedepartmentriskmod...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: People per structure used for sanity check on parcel counts by department Step3: Get owned census-tracts for department and count parcels Step5...
4,947
<ASSISTANT_TASK:> Python Code: %matplotlib inline import sys import os import platform import numpy as np import matplotlib.pyplot as plt import flopy #Set name of MODFLOW exe # assumes executable is in users path statement version = 'mf2005' exe_name = 'mf2005' if platform.system() == 'Windows': exe_name = 'mf200...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Each Util2d instance now has a .format attribute, which is an ArrayFormat instance Step2: The ArrayFormat class exposes each of the attributes ...
4,948
<ASSISTANT_TASK:> Python Code:: import tensorflow as tf from tensorflow.keras.losses import CategoricalCrossentropy y_true = [[0, 1, 0], [1, 0, 0]] y_pred = [[0.15, 0.75, 0.1], [0.75, 0.15, 0.1]] cross_entropy_loss = CategoricalCrossentropy() print(cross_entropy_loss(y_true, y_pred).numpy()) import tensorflow as tf fro...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description:
4,949
<ASSISTANT_TASK:> Python Code: # Copyright 2018 The TensorFlow Hub Authors. All Rights Reserved. # # 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 # # http://www.apache.org/licenses/LICENSE...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Predict Shakespeare with Cloud TPUs and Keras Step2: Data, model, and training Step4: Build the tf.data.Dataset Step6: Build the model Step7:...
4,950
<ASSISTANT_TASK:> Python Code: import cv2 img = cv2.imread('test.png',0) resized_image = cv2.resize(img, (28, 28), interpolation = cv2.INTER_AREA) test_images[test_images>0]=1 train_images[train_images>0]=1 <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: convert grey scale image to binary
4,951
<ASSISTANT_TASK:> Python Code: # import pandas as pd import pandas as pd # Create two lists i = [1,2,3,4,5] j = [1,2,3,4,5] # List every single x in i with every single y (i.e. Cartesian product) [(x, y) for x in i for y in j] # An alternative way to do the cartesian product # import itertools import itertools # 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: Create Data Step2: Calculate Cartesian Product (Method 1) Step3: Calculate Cartesian Product (Method 2)
4,952
<ASSISTANT_TASK:> Python Code: %matplotlib inline import matplotlib.pyplot as plt from scipy import stats import numpy as np class Random_Variable: def __init__(self, name, values, probability_distribution): self.name = name self.values = values self.probability_distribution = pro...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: We can simulate the generation process of conditianal probabilities by appropriately sampling from three random variables. Step2: Notice that w...
4,953
<ASSISTANT_TASK:> Python Code: %matplotlib inline import pandas as pd import matplotlib.pyplot as plt df = pd.read_csv("netflix_titles.csv") df df.type.value_counts().plot(kind="bar") # para apresentar os dois gráficos juntos, precisamos primeiro criar uma figura fig = plt.figure(1, figsize=(20,10)) # podemos també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: Passo 1 Step2: Nosso dataset contém 6234 elementos, com 12 atributos cada, além de possuir missing data. Step3: Adições ao passar do tempo Ste...
4,954
<ASSISTANT_TASK:> Python Code: name=input('请输入你的名字') print(name) date=float(input('请输入你的生日')) if 1.19<date<2.19: print('你是水瓶座') elif 2.18<date<3.21: print('你是双鱼座') elif 3.20<date<4.20: print('你是白羊座') elif 4.19<date<5.21: print('你是金牛座') elif 5.20<date<6.22: print('你是双子座') elif 6.21<date<7.23: pri...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: 写程序,可由键盘读入两个整数m与n(n不等于0),询问用户意图,如果要求和则计算从m到n的和输出,如果要乘积则计算从m到n的积并输出,如果要求余数则计算m除以n的余数的值并输出,否则则计算m整除n的值并输出。 Step2: 写程序,能够根据北京雾霾PM2.5数值给出对应的防护建议。如当...
4,955
<ASSISTANT_TASK:> Python Code: !sudo chown -R jupyter:jupyter /home/jupyter/imported/formparsing.ipynb from IPython.display import Markdown as md ### change to reflect your notebook _nb_repo = 'training-data-analyst' _nb_loc = "blogs/form_parser/formparsing.ipynb" _nb_title = "Form Parsing Using Google Cloud Document A...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Form Parsing using Google Cloud Document AI Step2: Document Step3: Note Step4: Enable Document AI Step5: Create a service account authorizat...
4,956
<ASSISTANT_TASK:> Python Code: %matplotlib widget # To ignore warnings (http://stackoverflow.com/questions/9031783/hide-all-warnings-in-ipython) import warnings warnings.filterwarnings('ignore') import IPython import math import numpy as np import matplotlib import matplotlib.pyplot as plt from mpl_toolkits.mplot3d imp...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Interactive Matplotlib plots in Jupyter Step2: Example Step3: Plotly Step4: https Step5: Make a first widget Step6: Link the widget to a fu...
4,957
<ASSISTANT_TASK:> Python Code: #First, the libraries. And, make sure matplotlib shows up in jupyter notebook! hurrah import pandas as pd from sklearn import datasets from pandas.tools.plotting import scatter_matrix import matplotlib.pyplot as plt %matplotlib inline iris = datasets.load_iris() x = iris.data[:,2:] # 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: 2. Redo the model with a 75% - 25% training/test split and compare the results. Are they better or worse than before? Discuss why this may be. S...
4,958
<ASSISTANT_TASK:> Python Code: from IPython.display import Image Image('images/02_network_flowchart.png') Image('images/02_convolution.png') %matplotlib inline import matplotlib.pyplot as plt import tensorflow as tf import numpy as np from sklearn.metrics import confusion_matrix import time from datetime import timed...
<SYSTEM_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 input image is processed in the first convolutional layer using the filter-weights. This results in 16 new images, one for each filter in th...
4,959
<ASSISTANT_TASK:> Python Code: import numpy as np %matplotlib inline import matplotlib.pyplot as plt import seaborn as sns import networkx as nx K_5=nx.complete_graph(5) nx.draw(K_5) def complete_deg(n): Return the integer valued degree matrix D for the complete graph K_n. a=np.zeros((n,n)) np.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: Complete graph Laplacian Step3: The Laplacian Matrix is a matrix that is extremely important in graph theory and numerical analysis. It is defi...
4,960
<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: TensorFlow を使用した Azure Blob Storage Step2: Azurite のインストールとセットアップ(オプション) Step3: TensorFlow を使用した Azure Storage のファイルの読み取りと書き込み
4,961
<ASSISTANT_TASK:> Python Code: import mne root = mne.datasets.sample.data_path() / 'MEG' / 'sample' raw_file = root / 'sample_audvis_raw.fif' raw = mne.io.read_raw_fif(raw_file, verbose=False) events = mne.find_events(raw, stim_channel='STI 014') # we'll skip the "face" and "buttonpress" conditions to save memory even...
<SYSTEM_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 Evoked objects from Epochs Step2: You may have noticed that MNE informed us that "baseline correction" has been Step3: Basic visualiz...
4,962
<ASSISTANT_TASK:> Python Code: from sympy import symbols, nonlinsolve pc, pa, p1, p2, c1, c2 = symbols('pc pa p1 p2 c1 c2') expr1 = ( (pc*(p1-pa) ) / (p1*(pc-pa)) - c1) expr2 = ( (pc*(p2-pa) ) / (p2*(pc-pa)) - c2) expr1 = expr1.subs(p1, 0.904) expr1 = expr1.subs(c1, 0.628) print(expr1) expr2 = expr2.subs(p2, 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: Next we need to define six different variables Step2: Now we can create two SymPy expressions that represent our two equations. We can subtract...
4,963
<ASSISTANT_TASK:> Python Code: # DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'cmcc', 'cmcc-esm2-sr5', 'ocnbgchem') # 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...
4,964
<ASSISTANT_TASK:> Python Code: # Numpy import numpy as np # Scipy from scipy import stats from scipy import linspace # Plotly from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot import plotly.graph_objs as go init_notebook_mode(connected=True) # Offline plotting # Probabilities P_G = 0.8 # 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: Define Common Parameters Step2: Question 1. Step3: Run the simulation using the Binomial process which is equivalent to performing a very larg...
4,965
<ASSISTANT_TASK:> Python Code: import math def vol(rad): return 4/3*math.pi*(rad**(3)) vol(2) def ran_check(num,low,high): return low <= num <= high ran_check(3,4,5) ran_check(3,1,100) def ran_bool(num,low,high): return low <= num <= high ran_bool(3,1,10) def up_low(s): nUpper = 0 nLower ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Write a function that checks whether a number is in a given range (Inclusive of high and low) Step2: If you only wanted to return a boolean Ste...
4,966
<ASSISTANT_TASK:> Python Code: import pandas as pd iris = pd.read_csv('data/iris.csv') # Display the first few rows of the dataframe iris.head() iris.count() iris.dtypes %matplotlib inline import seaborn as sns import matplotlib.pyplot as plt sns.FacetGrid(iris, hue="Species", size=6) \ .map(plt.scatter, "SepalLe...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: We can see the number of records in each column to ensure all of our datapoints are complete Step2: And we can see the data type for each colum...
4,967
<ASSISTANT_TASK:> Python Code: from python.f06 import * %matplotlib inline # try varying p0 # then set kact_s < 0.1, and try varying p0 interact(plot_switch, k=fixed(4), n=fixed(3)) interact(plot_switch_eqns, k=fixed(4), n=fixed(3)) # try kdecay = 0.13 interact(plot_switch_ss, k=fixed(4)) # n = 2 interact(plot_hh) ...
<SYSTEM_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 steady-states are solutions to Step2: So we see that the qualitative behaviour of the system depends on whether the maximum slope of the Hi...
4,968
<ASSISTANT_TASK:> Python Code: import turtle # necesitamos un módulo llamado turtle para esta parte ventana = turtle.Screen() # crea una ventana para dibujar henry = turtle.Turtle() # crea una tortuga (cursor) que se llama henry henry.forward(150) # le decimos a henry qu...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Trata de dibujar un cuadrado de 150 pasos de lado. Step2: ¿Para qué escribimos turtle.Turtle() para obtener un nuevo objeto Turtle (tortuga)? S...
4,969
<ASSISTANT_TASK:> Python Code: # setting up our imports from gensim.models import ldaseqmodel from gensim.corpora import Dictionary, bleicorpus import numpy from gensim.matutils import hellinger # loading our corpus and dictionary try: dictionary = Dictionary.load('datasets/news_dictionary') except FileNotFoundErr...
<SYSTEM_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 will be loading the corpus and dictionary from disk. Here our corpus in the Blei corpus format, but it can be any iterable corpus. Step2: Fo...
4,970
<ASSISTANT_TASK:> Python Code: A = (np.arange(9) - 4).reshape((3, 3)) A np.linalg.norm(A) np.trace(np.eye(3)) A = np.array([[1, 2], [3, 4]]) A np.linalg.det(A) A = np.array([[1.0, 3.0], [1.0, 4.0]]) A B = sp.linalg.logm(A) B sp.linalg.expm(B) <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: 대각 성분 Step2: 행렬식 Step3: 전치 행렬과 대칭 행렬
4,971
<ASSISTANT_TASK:> Python Code: from beakerx import * f = EasyForm("Form and Run") f.addTextField("first") f['first'] = "First" f.addTextField("last") f['last'] = "Last" f.addButton("Go!", tag="run") f "Good morning " + f["first"] + " " + f["last"] f['last'][::-1] + '...' + f['first'] f['first'] = 'Beaker' f['last'] =...
<SYSTEM_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 access the values from the form by treating it as an array indexed on the field names Step2: The array works both ways, so you set defa...
4,972
<ASSISTANT_TASK:> Python Code: from iuvs import io %autocall 1 import os files = !ls ~/data/iuvs/level1b/*.gz for file in files: print(os.path.basename(file)) l1b = io.L1BReader(files[-1]) l1b.DarkIntegration l1b.detector_dark.shape def compare_darks(dark1, dark2): fig, ax = subplots(nrows=2, figsize=(10,8))...
<SYSTEM_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 file with very lighty dark Step2: The DarkIntegration data shows that there are 2 observations of darks, approx 22 minutes apart Step3:...
4,973
<ASSISTANT_TASK:> Python Code: !pip install -U tfx # getting the code directly from the repo x = !pwd if 'feature_selection' not in str(x): !git clone -b main https://github.com/tensorflow/tfx-addons.git %cd tfx-addons/tfx_addons/feature_selection import os import pprint import tempfile import urllib import absl ...
<SYSTEM_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 packages Step2: Palmer Penguins example pipeline Step3: Run TFX Components Step4: As seen above, .selected_features contains the featu...
4,974
<ASSISTANT_TASK:> Python Code: import numpy import nibabel import os from haxby_data import HaxbyData from nilearn.input_data import NiftiMasker %matplotlib inline import matplotlib.pyplot as plt import sklearn.manifold import scipy.cluster.hierarchy datadir='/home/vagrant/nilearn_data/haxby2001/subj2' print('Using dat...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Let's ask the following question Step2: Let's test whether similarity is higher for faces across runs within-condition versus similarity betwee...
4,975
<ASSISTANT_TASK:> Python Code: # Converting real to integer print 'int(3.14) =', int(3.14) # Converting integer to real print 'float(5) =', float(5) # Calculation between integer and real results in real print '5.0 / 2 + 3 = ', 5.0 / 2 + 3 # Integers in other base print "int('20', 8) =", int('20', 8) # base 8 print "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: The real numbers can also be represented in scientific notation, for example Step2: The operator % is used for string interpolation. The interp...
4,976
<ASSISTANT_TASK:> Python Code: import matplotlib.pyplot as plt import numpy as np %matplotlib inline x = np.arange(0, 100) def square(x): return (x % 50) < 25 plt.plot(x, square(x)) import magma as m m.set_mantle_target("ice40") import mantle from loam.boards.icestick import IceStick icestick = IceStick() icestick...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: To implement our square wave in magma, we start by importing the IceStick module from loam. We instance the IceStick and turn on the Clock and J...
4,977
<ASSISTANT_TASK:> Python Code: # As usual, a bit of setup import time, os, json import numpy as np import matplotlib.pyplot as plt from cs231n.gradient_check import eval_numerical_gradient, eval_numerical_gradient_array from cs231n.rnn_layers import * from cs231n.captioning_solver import CaptioningSolver from cs231n.cl...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Image Captioning with RNNs Step2: Microsoft COCO Step3: Look at the data Step4: Recurrent Neural Networks Step5: Vanilla RNN Step6: Vanilla...
4,978
<ASSISTANT_TASK:> Python Code: p = ppp.ShiftingPerformance() o2 = ppp.PROPELLANTS['OXYGEN (GAS)'] ch4 = ppp.PROPELLANTS['METHANE'] p.add_propellants([(ch4, 1.0), (o2, 1.0)]) p.set_state(P=10, Pe=0.01) print p for k,v in p.composition.items(): print "{} : ".format(k) pprint.pprint(v[0:8], indent=4) OF = np.lin...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Equilibrium with condensed species Step2: Smoky white space shuttle SRB exhaust Step3: And one final condensed species case
4,979
<ASSISTANT_TASK:> Python Code: url1 = "http://data.insideairbnb.com/united-states/" url2 = "ny/new-york-city/2016-02-02/data/listings.csv.gz" full_df = pd.read_csv(url1+url2, compression="gzip") full_df.head() df = full_df[["id", "price", "number_of_reviews", "review_scores_rating"]] df.head() df.replace({'price': {'...
<SYSTEM_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 don't want all data, so let's focus on a few variables. Step2: Need to convert prices to floats Step3: We might think that better apartment...
4,980
<ASSISTANT_TASK:> Python Code: from __future__ import (absolute_import, division, print_function, unicode_literals) from builtins import * # Note: This step can take a while to run. from io import BytesIO, TextIOWrapper from zipfile import ZipFile import urllib.request import csv from shapely.g...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step2: Prepare emissions Step3: Now, let's inspect our emissions to ensure they look resonable. Step4: Fig. 1 Step5: Summarizing results Step6: We'...
4,981
<ASSISTANT_TASK:> Python Code: from IPython.display import IFrame IFrame('http://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data', width=300, height=200) # import load_iris function from datasets module from sklearn.datasets import load_iris # save "bunch" object containing iris dataset and its attrib...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: 150 observations Step2: scikit-learn 4-step modeling pattern Step 1 Step3: Step 2 Step4: Name of the object does not matter Step5: Step 3 St...
4,982
<ASSISTANT_TASK:> Python Code: import pyspark.sql.types as typ labels = [ ('INFANT_ALIVE_AT_REPORT', typ.StringType()), ('BIRTH_YEAR', typ.IntegerType()), ('BIRTH_MONTH', typ.IntegerType()), ('BIRTH_PLACE', typ.StringType()), ('MOTHER_AGE_YEARS', typ.IntegerType()), ('MOTHER_RACE_6CODE', typ.Str...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Next, we load the data. Step2: Specify our recode dictionary. Step3: Our goal is to predict whether the 'INFANT_ALIVE_AT_REPORT' is either 1 o...
4,983
<ASSISTANT_TASK:> Python Code: #importar los paquetes que se van a usar import pandas as pd import pandas_datareader.data as web import numpy as np import datetime from datetime import datetime import scipy.stats as stats import matplotlib.pyplot as plt import seaborn as sns %matplotlib inline #algunas opciones para Py...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Una vez cargados los paquetes, es necesario definir los tickers de las acciones que se usarán, la fuente de descarga (Yahoo en este caso, pero t...
4,984
<ASSISTANT_TASK:> Python Code: %matplotlib inline from __future__ import print_function from __future__ import division import numpy as np from the_collector import BagReader from mpl_toolkits.mplot3d import Axes3D from matplotlib import pyplot as plt from math import sin, cos, atan2, pi, sqrt, asin from math import 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: Step6: NXP IMU Step7: Run Raw Compass Performance Step8: Now using this bias, we should get better performance.
4,985
<ASSISTANT_TASK:> Python Code: from IPython.core.display import Image Image(filename='./imgs/recsys_arch.png') import pandas as pd unames = ['user_id', 'username'] users = pd.read_table('./data/users_set.dat', sep='|', header=None, names=unames) rnames = ['user_id', 'course_id', 'rating'] rating...
<SYSTEM_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 CourseTalk dataset Step2: Using pd.merge we get it all into one big DataFrame. Step3: Collaborative filtering Step4: Now let's filter do...
4,986
<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: Hamiltonian Time Evolution and Expectation Value Computation Step2: Application of one- and two-body fermionic gates Step3: Exact evolution im...
4,987
<ASSISTANT_TASK:> Python Code: import numpy as np A = np.mat('1 2 3; 4 5 6; 7 8 9') print "Creation from string:\n", A # 转置 print "Transpose A :\n", A.T # 逆矩阵 print "Inverse A :\n", A.I # 通过NumPy数组创建矩阵 print "Creation from array: \n", np.mat(np.arange(9).reshape(3,3)) A = np.eye(2) print "A:\n", A B = 2 * A print "B:...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: 1. 矩阵 Step2: 1.2 从已有矩阵创建新矩阵 Step3: 2. 线性代数 Step4: 2.2 行列式 Step5: 2.3 求解线性方程组 Step6: 2.4 特征值和特征向量 Step7: 2.5 奇异值分解 Step8: *号表示共轭转置 Step9: ...
4,988
<ASSISTANT_TASK:> Python Code: import pandas as pd # import a ticker formatting class from matplotlib from matplotlib.ticker import FuncFormatter %matplotlib inline # create a data frame df = pd.read_csv('data/mlb.csv') # use head to check it out df.head() # group by team, aggregate on sum grouped_by_team = df[['TEA...
<SYSTEM_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 Jupyter know that you're gonna be charting inline Step2: Read in MLB data Step3: Prep data for charting Step4: Make a horizonal bar chart...
4,989
<ASSISTANT_TASK:> Python Code: import warnings warnings.filterwarnings('ignore') import matplotlib.pyplot as plt import numpy as np %matplotlib inline x = np.linspace(0,1,100) def pltsin(freq, ampl): y = ampl*np.sin(2*np.pi*x*freq) plt.plot(x, y) plt.ylim(-10,10) # fix limits of the vertical axis pltsin...
<SYSTEM_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 the beginning there was a sine wave Step2: Next, define a 1d array to pass into sin() function. Step3: Define a trivial function to plot a ...
4,990
<ASSISTANT_TASK:> Python Code: %matplotlib inline %autosave 0 import sys, os sys.path.insert(0, os.path.expanduser('~/work/git/github/taku-y/bmlingam')) sys.path.insert(0, os.path.expanduser('~/work/git/github/pymc-devs/pymc3')) import theano theano.config.floatX = 'float64' from copy import deepcopy import hashlib imp...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Experimental condition Step2: Program Step3: Append results to dataframe Step4: Save and load data frame Step6: Perform experiment over cond...
4,991
<ASSISTANT_TASK:> Python Code: %matplotlib inline import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns sns.set() from scipy.optimize import fmin data = pd.DataFrame({'x':np.array([2.2, 4.3, 5.1, 5.8, 6.4, 8.0]), 'y':np.array([0.4, 10.1, 14.0, 10.9, 15.4, 18.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: We can build a model to characterize the relationship between $X$ and $Y$, recognizing that additional factors other than $X$ (the ones we have ...
4,992
<ASSISTANT_TASK:> Python Code: # These libraries are needed for the pygrib library in Colab. # Note that is needed if you install pygrib using pip. # If you use conda, the libraries will be installed automatically. ! apt-get install libeccodes-dev libproj-dev # Install the python packages ! pip install pyproj ! pip 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: Install pysteps Step2: Getting the example data Step3: Next, we need to create a default configuration file that points to the downloaded data...
4,993
<ASSISTANT_TASK:> Python Code: import graphlab import numpy as np sales = graphlab.SFrame('kc_house_data.gl/') from math import log, sqrt sales['sqft_living_sqrt'] = sales['sqft_living'].apply(sqrt) sales['sqft_lot_sqrt'] = sales['sqft_lot'].apply(sqrt) sales['bedrooms_square'] = sales['bedrooms']*sales['bedrooms'] #...
<SYSTEM_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: Create new features Step3: Squaring bedrooms will increase the separation between not many bedrooms (e.g. 1) a...
4,994
<ASSISTANT_TASK:> Python Code: a = 5 print(a) print(type(a)) print(hex(id(a))) a = 'five' print(a) print(type(a)) print(hex(id(a))) def echo(a): return a print(echo(5)) print(echo('five')) def sum(a, b): return a + b l = [1, 2, 3] print(len(l)) s = "Just a sentence" print(len(s)) d = {'a': 1, 'b': 2} 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: This little example shows a lot about the Python typing system. The variable a is not statically declared, after all it can contain only one typ...
4,995
<ASSISTANT_TASK:> Python Code: import matplotlib matplotlib.use("Agg") import fredpy as fp import pandas as pd import matplotlib.pyplot as plt plt.style.use('classic') import matplotlib.animation as animation import os import time # Approximately when the program started start_time = time.time() # start and end dates 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: Download Data and Merge into DataFrame Step2: Construct Figure Step3: Create Animation and Save Step4: Print Time to Run
4,996
<ASSISTANT_TASK:> Python Code: PATH='data/aclImdb/' names = ['neg','pos'] %ls {PATH} %ls {PATH}train %ls {PATH}train/pos | head trn,trn_y = texts_from_folders(f'{PATH}train',names) val,val_y = texts_from_folders(f'{PATH}test',names) trn[0] trn_y[0] veczr = CountVectorizer(tokenizer=tokenize) trn_term_doc = veczr.fit...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Here is the text of the first review Step2: CountVectorizer converts a collection of text documents to a matrix of token counts (part of sklear...
4,997
<ASSISTANT_TASK:> Python Code: from os import path # Third-party from astropy.io import ascii from astropy.table import Table import astropy.coordinates as coord import astropy.units as u from astropy.constants import G, c import matplotlib.pyplot as plt from matplotlib.colors import Normalize import numpy as np plt.st...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: APW RV's Step2: RAVE Step3: Get only ones where both stars have RV measurements
4,998
<ASSISTANT_TASK:> Python Code: import pandas as pd from simpledbf import Dbf5 import geopandas as gpd import requests import zipfile import io import os %matplotlib inline PROVINCIAS_URL = "http://www.ign.gob.ar/descargas/geodatos/SHAPES/ign_provincia.zip" DEPARTAMENTOS_URL = "http://www.ign.gob.ar/descargas/geodatos/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: Provincias Step2: Departamentos Step3: Municipios Step4: Los polígonos de algunos municipios están separados. Se juntan para solucionar la du...
4,999
<ASSISTANT_TASK:> Python Code: from cfg import read_grammar_rules from cfg import WCFG from rule import Rule from symbol import is_terminal, is_nonterminal, make_symbol # for convenience we will use `defaultdict` from the package collections # which allows us to define a default constructor for values from collections...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step5: CKY parser Step10: Agenda Step11: Let's see how it works Step12: we can push items into the agenda Step13: and the agenda will make sure the...