Unnamed: 0
int64
0
15.9k
cleaned_code
stringlengths
67
124k
cleaned_prompt
stringlengths
168
30.3k
13,200
<ASSISTANT_TASK:> Python Code: try: import OpenMRS as om except: # At this point, you probably haven't installed OpenMRS. You can install it by: # sudo pip install git+https://github.com/BerryAI/Acai # Now we are going to import OpenMRS from the source. # Note: This assumes you are currently in 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: Load example data Step2: Start and train a recomemndation engine Step3: Now the recommendation engine knows about users and their ratings. We ...
13,201
<ASSISTANT_TASK:> Python Code: warnings, url = gf.get_warnings_as_json([3022, 3023, 3024], "2017-12-01", "2018-05-31", lang_key=1, simple=False, recursive_count=5) print(url) warnings_flattened = (flatten(w) for w in warnings) df = pd.DataFrame(warnings_flattened) df.head(5) df.columns df_a = df # define individual col...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: See full list at http Step2: List relevant parameters for the regression analysis Step3: Clean and save dataframe Step4: Plotting Step5: Dec...
13,202
<ASSISTANT_TASK:> Python Code: import pandas as pd df = pd.DataFrame({'user':[1,1,2,2,3], 'time':[20,10,11,18, 15], 'amount':[10.99, 4.99, 2.99, 1.99, 10.99]}) ### Output your answer into variable 'result' def g(df): return df.groupby('user')[['time', 'amount']].apply(lambda x: x.values.tolist()[::-1]).to_frame(nam...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description:
13,203
<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. Here I'm creating a couple dictionaries to convert the chara...
13,204
<ASSISTANT_TASK:> Python Code: # Standard imports %matplotlib inline import numpy as np import matplotlib.pyplot as plt plt.style.use('seaborn-whitegrid') # x-axis range x = np.linspace(0, 10, 100) # Create first of two panels plt.subplot(2,1,1) # (row, col, panel no.) plt.plot(x, np.sin(x)) # Create second of two pa...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Matplotlib's Two Interfaces Step2: In order to change the figure and axes you could use the plt.gcf() (get current figure) and plt.gca() (get c...
13,205
<ASSISTANT_TASK:> Python Code: %matplotlib inline from matplotlib import pyplot as plt import numpy as np from PIL import Image img = Image.open("img/colonies.jpg") plt.imshow(img) arr = np.array(img) print("x,y,RGB ->",arr.shape) arr = np.array(img) plt.imshow(arr) plt.show() arr[:,:,1] = 255 plt.imshow(arr) 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: The Python Image Library (PIL) Step2: You can load images as Image instances Step3: Image instances can be interconverted with numpy arrays St...
13,206
<ASSISTANT_TASK:> Python Code: oxp = Symbol("Omega_x'") b = Symbol("b") n = Symbol("n") theta = Symbol("theta") w = Symbol("w") s = Symbol("s") a = Symbol("a") subsampledOmega = (binomial(s, b) * binomial(n - s, a - b)) / binomial(n, a) subsampledFpF = Sum(subsampledOmega, (b, theta, s)) subsampledOmegaSlow = (binomial...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: where n refers to the size of the population of cells, a is the number of active cells at any instance in time, s is the number of actual synaps...
13,207
<ASSISTANT_TASK:> Python Code: %matplotlib inline import numpy as np from landlab import RasterModelGrid grid = RasterModelGrid((200, 400), xy_spacing=(10e3, 20e3)) grid.dy, grid.dx from landlab.components.flexure import Flexure Flexure.input_var_names Flexure.var_units("lithosphere__overlying_pressure_increment")...
<SYSTEM_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 the grid Step2: Create a rectilinear grid with a spacing of 10 km between rows and 20 km between columns. The numbers of rows and columm...
13,208
<ASSISTANT_TASK:> Python Code: import pandas as pd df = pd.read_csv('data/airline_delay_causes_2015.csv') df.head() df.columns = df.columns.str.strip() df['month'] = df['month'].map(lambda x: '0' + str(x) if len(str(x)) < 2 else x) df.month.unique() agg_month_sum = df.groupby('month',as_index=False).sum() not_ontime_...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Since month in dimple only except 2 digit format, change this Step2: We want to have total number of operations and total minutes delay. So we'...
13,209
<ASSISTANT_TASK:> Python Code: # Import modules import numpy as np import scipy import sympy as sym from scipy import sparse from matplotlib import pyplot as plt from mpl_toolkits.mplot3d import axes3d from IPython.display import Math from IPython.display import display sym.init_printing(use_latex=True) def heatfd(xl,...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: 8.1 Parabolic Equations Step2: Backward Difference Method Step3: Example Step4: Example Step5: Crank-Nicolson Method Step6: Example Step7: ...
13,210
<ASSISTANT_TASK:> Python Code: import pandas as pd import numpy as np import matplotlib.pyplot as plt %matplotlib inline data = pd.read_csv("train.csv") data.head() print data.iloc[1][0] plt.imshow(data.iloc[1][1:].reshape(28,28),cmap='Greys') plt.show() print data.iloc[28][0] plt.imshow(data.iloc[28][1:].reshape(28,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: So that's what the dataset looks like, each pixel is a column, each row is an image in the dataset. Actually I have a corresponding 'test' datas...
13,211
<ASSISTANT_TASK:> Python Code: import vpython as vp #Code def charge_color(charge): if charge>0: charge_color = vp.color.red elif charge <0: charge_color = vp.color.blue else: charge_color = vp.color.white return charge_color # def getfield(position): r = position field =...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Se configura la escena y el sistema coordenado Step2: Se configura la fuente del campo eléctrico Step3: Se representa la fuente del Campo Eléc...
13,212
<ASSISTANT_TASK:> Python Code: import numpy as np # a vector: the argument to the array function is a Python list v = np.array([1,2,3,4]) v # a matrix: the argument to the array function is a nested Python list M = np.array([[1, 2], [3, 4]]) M type(v), type(M) v.shape M.shape M.size np.shape(M) np.size(M) M.dtype...
<SYSTEM_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 numpy package the terminology used for vectors, matrices and higher-dimensional data sets is array. Step2: The v and M objects are both...
13,213
<ASSISTANT_TASK:> Python Code: cred=db.login.find_one({}) #Tweepy Login credensials are stored in mongodb databse auth = tweepy.OAuthHandler(cred["consumerKey"], cred["consumerSecret"]) auth.set_access_token(cred["oauthTocken"], cred["oauthTokenSecret"]) api = tweepy.API(auth) api cities=["Delhi","Kolkata","Bangalore"...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: <h2>Where On Earth ID (WOEID)</h2> Step2: Performing Latest Trend Query & Strore them Step3: Clean OUr Data drop unneccesary content Step4: I...
13,214
<ASSISTANT_TASK:> Python Code: from collections import defaultdict from itertools import chain import numpy as np import sympy as sp import matplotlib.pyplot as plt from ipywidgets import interact from chempy import Substance, Reaction, ReactionSystem from chempy.kinetics.rates import Arrhenius, MassAction from chempy....
<SYSTEM_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 use a generic model representing a decay-chain with two decays Step2: "Arrhenius" behaviour means that the rate of reaction depends exp...
13,215
<ASSISTANT_TASK:> Python Code: def ptrans(f,t): import numpy as np g = np.empty_like(f) if f.ndim == 1: W = f.shape[0] col = np.arange(W) g = f[(col-t)%W] elif f.ndim == 2: H,W = f.shape rr,cc = t row,col = np.indices(f.shape) g = f[(row-rr)%H, (col-cc)%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: Examples Step2: Example 1 Step3: Example 2 Step4: Equation
13,216
<ASSISTANT_TASK:> Python Code: %matplotlib inline from micromeritics import util from micromeritics import isotherm_examples as ex import matplotlib.pyplot as plt carb = ex.carbon_black() # example isotherm of Carbon Black with N2 at 77K sial = ex.silica_alumina() # example isotherm of Silica Alumina with N2 at 77K 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: It is also useful to show the isotherm with the Pressure axis scaled as logarithmic. Step2: While it is more common to show isotherm data using...
13,217
<ASSISTANT_TASK:> Python Code:: import matplotlib.pyplot as plt plt.plot(k,l) <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:
13,218
<ASSISTANT_TASK:> Python Code: # Limit processing of protocol parts for development PROCESS_PARTS_LIMIT = 500 # Enable caching of protocol parts data (not efficient, should only be used for local development with sensible PROCESS_PARTS_LIMIT) PROCESS_PARTS_CACHE = True # Filter the meetings to be processed, these kwarg...
<SYSTEM_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 source data Step2: Inspect the datapackages which will be loaded Step3: Run the flow Step4: Aggregate and print stats
13,219
<ASSISTANT_TASK:> Python Code: # Authors: Alexandre Gramfort <alexandre.gramfort@inria.fr> # Denis A. Engemann <denis.engemann@gmail.com> # # License: BSD-3-Clause import mne from mne import io from mne.datasets import sample from mne.cov import compute_covariance print(__doc__) data_path = sample.data_path()...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Set parameters Step2: Compute covariance using automated regularization Step3: Show the evoked data Step4: We can then show whitening for our...
13,220
<ASSISTANT_TASK:> Python Code: # These are all the modules we'll be using later. Make sure you can import them # before proceeding further. from __future__ import print_function import matplotlib.pyplot as plt import numpy as np import os import sys import tarfile from IPython.display import display, Image from scipy 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: Step3: First, we'll download the dataset to our local machine. The data consists of characters rendered in a variety of fonts on a 28x28 image. The lab...
13,221
<ASSISTANT_TASK:> Python Code: import geopandas as gpd import matplotlib.pyplot as plt import seaborn as sns from cartoframes.auth import set_default_credentials from cartoframes.data.observatory import * from cartoframes.data.services import Isolines from cartoframes.viz import * sns.set_style('whitegrid') %matplotlib...
<SYSTEM_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 CARTO default credentials Step3: Note about credentials Step4: <a id='section2'></a> Step5: Visualize isochrones Step6: <a id='section3'...
13,222
<ASSISTANT_TASK:> Python Code: %matplotlib inline from matplotlib import pyplot as plt import datetime as dt from QuantLib import * plt.style.use('fivethirtyeight') bid_rates = [0.044696, 0.0441, 0.0441, 0.0439, 0.0439, 0.04405, 0.0441, 0.043954, 0.044863] mid_rates = [0.045128, 0.044413, 0.044288, 0.044, 0.044125, 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: 市场数据 Step2: 构造收益率曲线 Step3: 获取收益率曲线数据
13,223
<ASSISTANT_TASK:> Python Code: 2+2 from gensim.models import Word2Vec import gensim model = gensim.models.KeyedVectors.load_word2vec_format( './private_data/GoogleNews-vectors-negative300.bin', binary=True) # What does a word vector look like? model.word_vec("cheeseburger") cheeseburger = model.word_vec("cheesebu...
<SYSTEM_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 notebook understand that I was asking for the execution of a command. OK, with that concept of what you are looking at out of the way, let's...
13,224
<ASSISTANT_TASK:> Python Code: problem = lambda m, i: 0 < m < i no_problem = lambda m, i: not problem(m, i) and not problem(3 - m, 3 - i) def next_states(state): m, i, b = state if b == 1: return { (m-mb, i-ib, 0) for mb in range(m+1) for ib in range(i+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: $\texttt{no_problem}(m, i)$ is true if there is no problem on either side. Step2: A state is represented as a triple. The triple $(m, i, b)$ s...
13,225
<ASSISTANT_TASK:> Python Code: df = pd.read_csv('Iris.csv') df.head() x_data = df.iloc[:, :-1].values.astype(np.float32) y_datalabel = df.iloc[:, -1] y_data = LabelEncoder().fit_transform(df.iloc[:, -1]) onehot = np.zeros((y_data.shape[0], np.unique(y_data).shape[0])) for i in range(y_data.shape[0]): onehot[i, y_da...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: ```text Step2: text
13,226
<ASSISTANT_TASK:> Python Code: from pliers.extractors import FaceRecognitionFaceLocationsExtractor # A picture of Barack Obama image = join(get_test_data_path(), 'image', 'obama.jpg') # Initialize Extractor ext = FaceRecognitionFaceLocationsExtractor() # Apply Extractor to image result = ext.transform(image) result.to_...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Face detection with multiple inputs Step2: Note how the merged pandas DataFrame contains 5 rows, even though there were only 3 input images. Th...
13,227
<ASSISTANT_TASK:> Python Code: import os import tensorflow as tf import numpy as np from google.cloud import bigquery 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-centra...
<SYSTEM_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 use this helper funciton to write lists containing article ids, categories, and authors for each article in our database to local file. ...
13,228
<ASSISTANT_TASK:> Python Code: %load_ext autoreload %autoreload 2 import sys sys.path.append("../../") from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import glob import tabulate import pprint import click import numpy as np import pandas as pd from...
<SYSTEM_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 check data Step2: ## Analysis Step3: What are optimal levels of hebbian and weight pruning
13,229
<ASSISTANT_TASK:> Python Code: from robots.robots import Robot from numpy import pi params = [[ "l1", 0, 0, "q1"]] robot1 = Robot("Pendulo simple", "R", [0.4], [0], params, "cinematico") robot1.inicializar_puertos() %matplotlib widget robot1.visualizador() <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: Se definen los parametros DH del manipulador a visualizar, se le da un nombre, se define el tipo de articulaciones que tiene el manipulador, las...
13,230
<ASSISTANT_TASK:> Python Code: #Initialization of iPython, some helper functions. %matplotlib inline import numpy as np import matplotlib.pyplot as plt import pandas as pd plt.style.use('ggplot') from sympy import * from IPython.display import display, Math, Latex init_printing(use_latex="mathjax") _Omega=u'\u03A9' def...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Basic assumptions Step2: Rated tip power (40 W) is defined for typical supply voltage (12 V). For lower supply voltage maximum power is lower t...
13,231
<ASSISTANT_TASK:> Python Code: # Author: Mathurin Massias <mathurin.massias@gmail.com> # Yousra Bekhti <yousra.bekhti@gmail.com> # Daniel Strohmeier <daniel.strohmeier@tu-ilmenau.de> # Alexandre Gramfort <alexandre.gramfort@inria.fr> # # License: BSD (3-clause) import os.path as op import mne fr...
<SYSTEM_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 somatosensory MEG data Step2: Run iterative reweighted multidict TF-MxNE solver Step3: Generate stc from dipoles Step4: Show the evoked ...
13,232
<ASSISTANT_TASK:> Python Code: import numpy as np import igraph import timeit import itertools def enumerate_matrix(gmat, i): def enumerate_adj_list(adj_list, i): def enumerate_edge_list(edge_list, i): def do_sim(n): retlist = [] nrep = 10 nsubrep = 10 # this is (sort of) a Python way of 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: Now, define a function that returns the index numbers of the neighbors of a vertex i, when the Step2: Define a function that enumerates the ne...
13,233
<ASSISTANT_TASK:> Python Code: # Import libraries import numpy as np import pandas as pd from time import time from sklearn.metrics import f1_score # Read student data student_data = pd.read_csv("student-data.csv") print "Student data read successfully!" # TODO: Calculate number of students n_students = len(student_da...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Implementation Step2: Preparing the Data Step3: Preprocess Feature Columns Step4: Implementation Step5: Training and Evaluating Models Step6...
13,234
<ASSISTANT_TASK:> Python Code: import os try: os.mkdir('me') except OSError: pass os.chdir('me') %%bash echo 'How does our directory look like?' ls -al git init echo 'How does our directory look like now?' ls -al git status # Let us create files for tracking. echo 'My Project' > README echo 'pei...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Setting Up Step2: Recording Changes to the Repository Step3: Removing and Moving File Step4: Viewing the Commit History Step5: Adding a Remo...
13,235
<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 scipy as sp import scipy.optimize as scopt import matplotlib.pyplot as plt import seaborn 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: 2. Uso de Pandas para descargar datos de precios de cierre Step2: Una vez cargados los paquetes, es necesario definir los tickers de las accion...
13,236
<ASSISTANT_TASK:> Python Code: import keras from os.path import join from keras.preprocessing import sequence from keras.models import Sequential from keras.layers import Dense, Dropout,Activation, Lambda,Input from keras.layers import Embedding from keras.layers import Convolution1D from keras.datasets import imdb 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: POS当作一个通道。 Step2: 情感极性当作一个通道。 Step3: 构建情感极性强度通道 Step4: 否定词。 Step5: Glove训练好的词向量 Step6: 获取训练好的word embedding 数组,用来初始化 Embedding Step7: 将一个b...
13,237
<ASSISTANT_TASK:> Python Code: def myFun(x): return (x**x)**x myFun(9) timeit(myFun(12)) %timeit 10*1000000 # this syntax allows comments ... note that if you leave off the numeric argument, %timeit seems to do nothing myFun(12) %timeit 10*1000000 # this syntax allows comments ... note that if you leave off 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: For this example, timeit() needs to be the only function in the cell, and then your code is called in as a valid function call as in this demo S...
13,238
<ASSISTANT_TASK:> Python Code: import numpy as np import matplotlib.pyplot as plt import seaborn as sns class CubicSpline(): ''' cubic spline of a function - equally-spaced knots - derivatives specified at endpoints ''' def __init__(self, fn, xmin, xmax, n, df_left, df_right): ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Try it out Step2: Try it out over a range
13,239
<ASSISTANT_TASK:> Python Code: class TestIterator: def __init__(self, max_value): self._current_value = 0 self._max_value = max_value def __next__(self): self._current_value += 1 if self._current_value > self._max_value: raise StopIteration() return ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: When you perform the iteration manually you should use the builtin next function to call the magic __next__ method. Step2: Of course you can al...
13,240
<ASSISTANT_TASK:> Python Code: # Imports for pandas, and numpy import numpy as np import pandas as pd # imports for seaborn to and matplotlib to allow graphing import matplotlib.pyplot as plt import seaborn as sns sns.set(style="whitegrid") %matplotlib inline # import Titanic CSV - NOTE: adjust file path as neccessar...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Distribution of Passengers Step2: Distribution of Genders in pClass populations Step3: Age - Analysis | Graph Step4: Distrbution of Age in pa...
13,241
<ASSISTANT_TASK:> Python Code: import numpy as np import pandas as pd import matplotlib.pyplot as plt %matplotlib inline print("NumPy version:",np.__version__) print("Pandas version:",pd.__version__) %ls steel_df = pd.read_excel("steel1045.xls") al_df = pd.read_excel("aluminum6061.xls") steel_df.head() al_df.head() ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Ensure the two .xls data files are in the same folder as the Jupyter notebook Step2: We can see our Jupyter notebook stress_strain_curve_with_p...
13,242
<ASSISTANT_TASK:> Python Code: import numpy as np import matplotlib.pyplot as plt %matplotlib inline from IPython.display import HTML HTML('../style/course.css') #apply general CSS import matplotlib.image as mpimg from IPython.display import Image from astropy.io import fits import aplpy #Disable astropy/aplpy loggin...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Import section specific modules Step5: 6.4 Residuals and Image Quality<a id='deconv Step6: Figure Step7: Left Step8: Method 1 will always re...
13,243
<ASSISTANT_TASK:> Python Code: %pylab inline from halomod import HaloModel from scipy.interpolate import InterpolatedUnivariateSpline as spline hm = HaloModel(profile_model="Einasto") _ = hm.profile.rho(hm.r,hm.m) hm.update(profile_model="Einasto") plot(hm.r, hm.profile.rho(hm.r,1e12),label="m=12",color="b") plot(hm....
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Density Profile Step2: Now plot versus $r$ Step3: Now plot versus $m$ Step4: Fourier Transform Step5: Now plot against $m$ Step6: We may ha...
13,244
<ASSISTANT_TASK:> Python Code: import matplotlib.pyplot as plt import numpy as np import pandas as pd import metpy.calc as mpcalc from metpy.cbook import get_test_data from metpy.plots import add_metpy_logo, SkewT from metpy.units import units col_names = ['pressure', 'height', 'temperature', 'dewpoint', 'direction', ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Upper air data can be obtained using the siphon package, but for this example we will use Step2: We will pull the data out of the example datas...
13,245
<ASSISTANT_TASK:> Python Code: # initialize hod model model = PrebuiltHodModelFactory('zheng07', threshold=-21) halocat = CachedHaloCatalog(simname='multidark', redshift=0, halo_finder='rockstar') model.populate_mock(halocat, enforce_PBC=False) N_sat = len(np.where(model.mock.galaxy_table['gal_type'] == 'satellites')[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: Note that changing the PBC condition enforce_PBC option does not change the $f_{sat}$ value.
13,246
<ASSISTANT_TASK:> Python Code: # Importamos librerías import numpy as np import pandas as pd import pandas_datareader as data import matplotlib.pyplot as plt %matplotlib inline # Creamos la función def load_adj_close(ticker, data_source, start_date, end_date): panel_data = data.DataReader(ticker, data_source, start...
<SYSTEM_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. Proyección de rendimientos diarios Step2: Habiendo caracterizado los rendimientos diarios como una variable aleatoria normal con la media y ...
13,247
<ASSISTANT_TASK:> Python Code: # To support both python 2 and python 3 from __future__ import division, print_function, unicode_literals # Common imports import numpy as np import os # to make this notebook's output stable across runs np.random.seed(42) # To plot pretty figures %matplotlib inline import matplotlib as 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: MNIST Step2: Binary classifier Step3: Note Step4: Note Step5: ROC curves Step6: Note Step8: Multiclass classification Step9: Multilabel c...
13,248
<ASSISTANT_TASK:> Python Code: # check Python version !python -V import pandas as pd # download library to read data into dataframe pd.set_option('display.max_columns', None) recipes = pd.read_csv("https://ibm.box.com/shared/static/5wah9atr5o1akuuavl2z9tkjzdinr1lv.csv") print("Data read into dataframe!") # takes about...
<SYSTEM_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 data from the IBM server into a pandas dataframe. Step2: Show the first few rows. Step3: Get the dimensions of the dataframe.
13,249
<ASSISTANT_TASK:> Python Code: utc = 0 sma = 1 ecc = 2 inc = 3 raan = 4 aop = 5 ma = 6 ta = 7 #fig1 = plt.figure(figsize = [15,8], facecolor='w') fig_peri = plt.figure(figsize = [15,8], facecolor='w') fig_apo = plt.figure(figsize = [15,8], facecolor='w') fig3 = plt.figure(figsize = [15,8], facecolor='w') fig4 = plt.fi...
<SYSTEM_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 orbital parameters which are vary significantly between different tracking files.
13,250
<ASSISTANT_TASK:> Python Code: %matplotlib inline import pandas as pd import numpy as np import matplotlib.pyplot as plt import bokeh.plotting as bkp from mpl_toolkits.axes_grid1 import make_axes_locatable # read in readmissions data provided hospital_read_df = pd.read_csv('data/cms_hospital_readmissions.csv') hospital...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Preliminary Analysis Step2: Preliminary Report
13,251
<ASSISTANT_TASK:> Python Code: import sqlite3 as sql import os from pprint import pprint class DB: backend = 'sqlite3' # default target_path = os.getcwd() # current directory db_name = ":file:" # lets work directly with a file db_name = os.path.join(target_path, 'shapes_lib.db') @cla...
<SYSTEM_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 DB class contains information for connecting to a SQLite database, which may be accessed directly, as a text file, no need for a special ser...
13,252
<ASSISTANT_TASK:> Python Code: import os import numpy as np import nibabel import matplotlib.pyplot as plt import matplotlib.patheffects as path_effects import mne from mne.transforms import apply_trans from mne.io.constants import FIFF data_path = mne.datasets.sample.data_path() subjects_dir = os.path.join(data_path,...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: MRI coordinate frames Step2: Notice that the axes in the Step3: These data are voxel intensity values. Here they are unsigned integers in the ...
13,253
<ASSISTANT_TASK:> Python Code: def fibonacci(n): a, b = 0, 1 while n: a, b = b, a + b n -= 1 return a for n in range(10): print(fibonacci(n)) [fibonacci(n) for n in range(10)] def gen_fibo(n): a, b = 0, 1 while n: yield a a, b = b, a + b n -= 1 g10 = gen_...
<SYSTEM_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 generator Step2: Fibonacci numbers and the golden ratio
13,254
<ASSISTANT_TASK:> Python Code: !head -n12 $LISA_HOME/logging.conf !head -n30 $LISA_HOME/logging.conf | tail -n5 import logging from conf import LisaLogging LisaLogging.setup(level=logging.INFO) from env import TestEnv te = TestEnv({ 'platform' : 'linux', 'board' : 'juno', 'host' ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Each module has a unique name which can be used to assign a priority level for messages generated by that module. Step2: The default logging le...
13,255
<ASSISTANT_TASK:> Python Code: # Create a SystemML MLContext object from systemml import MLContext, dml ml = MLContext(sc) %%sh mkdir -p data/mnist/ cd data/mnist/ curl -O http://pjreddie.com/media/files/mnist_train.csv curl -O http://pjreddie.com/media/files/mnist_test.csv script_string = source("mnist_lenet.dml") ...
<SYSTEM_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 - MNIST Step3: SystemML "LeNet" Neural Network Step5: 2. Compute Test Accuracy Step6: 3. Extract Model Into Spark DataFrames Fo...
13,256
<ASSISTANT_TASK:> Python Code: import pandas import numpy from folding_group import FoldingGroupClassifier from rep.data import LabeledDataStorage from rep.report import ClassificationReport from rep.report.metrics import RocAuc from sklearn.ensemble import RandomForestClassifier from sklearn.metrics import roc_curve, ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Reading initial data Step2: Remove rows with NAN from data Step3: Add diff_pt and cos(diff_phi) Step4: Add max, sum among PIDs Step5: define...
13,257
<ASSISTANT_TASK:> Python Code: prime_ministers = ['David Ben-Gurion', 'Moshe Sharett', 'David Ben-Gurion', 'Levi Eshkol', 'Yigal Alon', 'Golda Meir'] print(prime_ministers) type(prime_ministers) numbers = [1, 2, 3, 4, 5, 6, 7] wtf = ['The cake is a', False, 42] empty_list = [] # Index 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: <p style="text-align Step2: <p style="text-align Step3: <p style="text-align Step4: <p style="text-align Step5: <p style="text-align Step6: ...
13,258
<ASSISTANT_TASK:> Python Code:: from transformers import AutoTokenizer tokenizer = AutoTokenizer.from_pretrained("distilgpt2") <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:
13,259
<ASSISTANT_TASK:> Python Code: ###ignore this block of code - it is required only to show the map in iPython - you won't need it! from IPython.core.display import display, HTML display(HTML('<iframe width="800" height="600" frameborder="1" scrolling ="no" src="./qgis2threejs/ACT_elevs_test_1.html"></iframe>')) display...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: and there - your first 3D interactive map, made with no coding and using web data services! Step2: Now we have an elevation map coloured by gre...
13,260
<ASSISTANT_TASK:> Python Code: import kfp import kfp.gcp as gcp import kfp.dsl as dsl import kfp.compiler as compiler import kfp.components as comp import datetime import kubernetes as k8s # Required Parameters PROJECT_ID='<ADD GCP PROJECT HERE>' GCS_BUCKET='gs://<ADD STORAGE LOCATION HERE>' # Optional Parameters, but...
<SYSTEM_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 client Step2: Build reusable components Step3: Create a Docker container Step4: Build docker image Step5: If you want to use docker t...
13,261
<ASSISTANT_TASK:> Python Code: stations = pd.read_csv('datasets/divvy_2013/Divvy_Stations_2013.csv', parse_dates=['online date'], index_col='id') stations trips = pd.read_csv('datasets/divvy_2013/Divvy_Trips_2013.csv', parse_dates=['starttime', 'stoptime'], index_col=['trip_id']) trips = trips.sort() trips G = nx.DiGr...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: At this point, we have our stations and trips data loaded into memory. Step2: Then, let's iterate over the stations DataFrame, and add in the ...
13,262
<ASSISTANT_TASK:> Python Code: import numpy as np from astropy.table import Table as tbl import urllib.request import urllib.parse import subprocess import matplotlib.pyplot as plt from cesium import featurize %matplotlib inline import sqlite3 url = "http://irsa.ipac.caltech.edu/cgi-bin/Gator/nph-query?" values = {'ca...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Query for the given objects Step2: Im not sure why subprocess.call doesnt seem to work for this specific case. However, the urllib work below d...
13,263
<ASSISTANT_TASK:> Python Code: def mysum(a, b): return a + b abs(-3.2) help("abs") def mysum(a, b): 내가 정의한 덧셈이다. 인자 a와 b에 각각 두 숫자를 입력받아 합을 되돌려준다. return a + b help(mysum) x = 2 y = 3 z = mysum(x,y) print(z) no_return = print(3) print(no_return) type(no_return) def print42(): 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: 문서화 문자열(docstring) 활용 Step3: 보이는 내용을 설명하면 다음과 같다. Step4: mysum 함수에 대해 알아보자. Step5: mysum 함수를 정의할 때 추가한 문서화 문자열이 그대로 출력됨을 확인할 수 있다. Step6: 주의...
13,264
<ASSISTANT_TASK:> Python Code: df = pd.read_csv(( "https://raw.githubusercontent.com/Thinkful-Ed/data-201-resources/" "master/ESS_practice_data/ESSdata_Thinkful.csv")).dropna() # Define outcome and predictors. # Set our outcome to 0 and 1. y = df['partner'] - 1 X = df.loc[:, ~df.columns.isin(['partner', 'cntry'...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Since we're now working with a binary outcome, we've switched to a classifier. Now our loss function can't be the residuals. Our options are "...
13,265
<ASSISTANT_TASK:> Python Code: x, sr = librosa.load('audio/c_strum.wav') ipd.Audio(x, rate=sr) plt.figure(figsize=(14, 5)) librosa.display.waveplot(x, sr) # Because the autocorrelation produces a symmetric signal, we only care about the "right half". r = numpy.correlate(x, x, mode='full')[len(x)-1:] print(x.shape, r.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: numpy.correlate Step2: Plot the autocorrelation Step3: librosa.autocorrelate Step4: librosa.autocorrelate conveniently only keeps one half of...
13,266
<ASSISTANT_TASK:> Python Code: # General imports import numpy as np import matplotlib.pyplot as plt from matplotlib import colors as mcolors # Figure config colors = dict(mcolors.BASE_COLORS, **mcolors.CSS4_COLORS) LEGEND_SIZE = 15 TITLE_SIZE = 25 AXIS_SIZE = 15 FIGURE_SIZE = (12, 8) # for reproducibility np.random.see...
<SYSTEM_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 SEIR epidemic model Step2: Load SEIR model Step3: <a id='section-task1'></a> Step4: Get initial observations Step5: Create Emukit surrog...
13,267
<ASSISTANT_TASK:> Python Code: import geopandas as gpd denue = gpd.read_file("datos/DENUE_INEGI_09_.shp") denue.head() denue[["codigo_act", "nom_estab"]].head() import pandas as pd import numpy as np df = pd.DataFrame(np.random.randn(3, 3)) df def square(x): return x**2 df[[0]].apply(square) df['squared'] = df[...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Como pueden ver, el archivo tiene 42 columnas, las que nos interesan en este momento son las que describen la actividad de cada unidad Step2: E...
13,268
<ASSISTANT_TASK:> Python Code: %matplotlib inline # plots graphs within the notebook %config InlineBackend.figure_format='svg' # not sure what this does, may be default images to svg format from IPython.display import Image from IPython.core.display import HTML def header(text): raw_html = '<h4>' + str(text) + '</...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Lecture 4 Step2: <p class='alert alert-success'> Step3: <h2>Compact Finite Difference Schemes</h2> Step4: This is the Matrix approach Step5: ...
13,269
<ASSISTANT_TASK:> Python Code: # DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'ncc', 'noresm2-lm', 'ocean') # Set as follows: DOC.set_author("name", "email") # TODO - please enter value(s) # Set as follows: DOC.set_contributor("name", "emai...
<SYSTEM_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...
13,270
<ASSISTANT_TASK:> Python Code: %%capture # install histogrammar (if not installed yet) import sys !"{sys.executable}" -m pip install histogrammar import histogrammar as hg import pandas as pd import numpy as np import matplotlib # open a pandas dataframe for use below from histogrammar import resources df = pd.read_cs...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Dataset Step2: Comparing histogram types Step3: Q Step4: Q Step5: Q Step6: Multi-dimensional histograms Step7: Q
13,271
<ASSISTANT_TASK:> Python Code: retorno = api.update_with_media(filename='fia.jpg',status='Test. Upload media via python') print(retorno.text) print(retorno.id) print(retorno.created_at) print(retorno.lang) print(retorno.text) print(retorno.user.screen_name) print(retorno.user.friends_count) print(retorno.user.time_zon...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Exercício 2 - Salve o retorno do tweet do exercício anterior e imprima as seguintes informações Step2: Exercício 3 - Utilizando o método home_t...
13,272
<ASSISTANT_TASK:> Python Code: from scipy import stats import random import numpy as np def poisson_simul(rate, T): time = random.expovariate(rate) times = [0] while (times[-1] < T): times.append(time+times[-1]) time = random.expovariate(rate) return times[1:] rate = 1.0 T = 100.0 times ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description:
13,273
<ASSISTANT_TASK:> Python Code: import math import numpy as np import matplotlib.pyplot as plt %matplotlib inline def sine(x): return np.sin(2 * math.pi * x) x = np.linspace(0., 1., num=256, endpoint=False) plt.plot(x, sine(x)) import magma as m m.set_mantle_target("ice40") import mantle from loam.boards.icestick im...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: To implement our sine wave generator, we'll use a counter to index into a ROM that is programmed to output the value of discrete points in the s...
13,274
<ASSISTANT_TASK:> Python Code: import time print('Last updated: %s' %time.strftime('%d/%m/%Y')) import platform import multiprocessing def print_sysinfo(): print('\nPython version :', platform.python_version()) print('compiler :', platform.python_compiler()) print('\nsystem :', platfo...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Sorting Algorithms Step2: Bubble sort Step4: Bubble sort implemented in (C)Python Step6: <br> Step7: Verifying that all implementations work...
13,275
<ASSISTANT_TASK:> Python Code: col.find_one({'name': 'Alessandro'}) #find first value equality list(col.find({'name': 'Alessandro'})) #find all value equality cursor = col.find({'name': 'Alessandro'}) #can also use it as a generator cursor.next() col.find_one({'name': 'Alessandro'}, {'phone': True}) #this is a projecti...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Updating the document replaces the whole original document Step2: Here's how to update all doc
13,276
<ASSISTANT_TASK:> Python Code: %matplotlib inline import numpy as np import pandas as pd import sklearn from sklearn.pipeline import Pipeline from sklearn.feature_extraction.text import CountVectorizer, TfidfTransformer from sklearn.ensemble import RandomForestRegressor from sklearn.linear_model import LinearRegression...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Preprocessing Step2: Training the regressor Step3: Results Step4: Classification Step5: Training the classifier Step6: Results Step7: Hype...
13,277
<ASSISTANT_TASK:> Python Code: import matplotlib.pyplot as plt %matplotlib inline import random import numpy as np import pandas as pd from sklearn import datasets, svm, cross_validation, tree, preprocessing, metrics import sklearn.ensemble as ske import tensorflow as tf from tensorflow.contrib import learn as skflow 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: Let's look at the data Step2: Let's look at what percentage of the drivers are using the map? Step3: 47% of the drivers are following the map....
13,278
<ASSISTANT_TASK:> Python Code: bool('ok') bool(8) bool('') num=input('Enter a number:') if num>0: print 'positive' elif num<0: print 'negative' else: print 'zero' x=1 while x<=3: print x x+=1 nums=[1,2,3] for n in nums: print n range(0,10) range(10) range(10,0,-2) #-2表示步长 d ={'x':1,'y':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: 2.2 条件执行和if语句、else子句、elif子句 Step2: 2.3 更复杂的条件 Step3: 3.2 for循环 Step4: 因为迭代(循环的另外一种说法)某范围的数字是很常见的,所以有个内建的范围函数供使用: Step5: range函数的工作方式类似于分片。它包...
13,279
<ASSISTANT_TASK:> Python Code: import numpy as np import numpy.matlib import matplotlib.pyplot as plt import matplotlib.cm as cm %matplotlib inline import math import random import time import os import pickle import tensorflow as tf #built with TensorFlow version 0.9 # in the real project class, we use argparse (http...
<SYSTEM_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 hyperparameters Step2: Model overview Step3: Initialize LSTMs and build LSTM 1 Step4: In the cell above we use the TensorFlow seq2seq ...
13,280
<ASSISTANT_TASK:> Python Code: import yahoo_finance import requests import datetime def print_unix_timestamp_date(timestamp): print( datetime.datetime.fromtimestamp( int(timestamp) ).strftime('%Y-%m-%d %H:%M:%S') ) print_unix_timestamp_date("1420077600") print_unix_timestamp_date("14...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Getting the data Step2: So, Google has a limit of 15 years of data on each query Step3: Keep dictionary or use multiindex?
13,281
<ASSISTANT_TASK:> Python Code:: import cv2 import numpy as np img = cv2.imread('gradient.jpg',0) _,th1 = cv2.threshold(img,127,255,cv2.THRESH_BINARY) _,th2 = cv2.threshold(img,127,255,cv2.THRESH_BINARY_INV) #check every pixel with 127 cv2.imshow("img",img) cv2.imshow("th1",th1) cv2.imshow("th2",th2) <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:
13,282
<ASSISTANT_TASK:> Python Code: ! pip uninstall -y tensorflow ! pip install -q tensorflow-model-optimization ! pip install --upgrade tensorflow==2.6 import tempfile import os import tensorflow as tf from tensorflow import keras # Show the currently installed version of TensorFlow print("TensorFlow version: ",tf.version...
<SYSTEM_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 notebook uses TF2.x. Step2: Train a model for MNIST without quantization aware training Step3: Clone and fine-tune pre-trained model with...
13,283
<ASSISTANT_TASK:> Python Code: %matplotlib inline from matplotlib import pyplot as plt import numpy as np import pymc3 as pm from pymc3.distributions.timeseries import GaussianRandomWalk import seaborn as sns from statsmodels import datasets from theano import tensor as T df = datasets.get_rdataset('mastectomy', 'HSAU...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Fortunately, statsmodels.datasets makes it quite easy to load a number of data sets from R. Step2: Each row represents observations from a woma...
13,284
<ASSISTANT_TASK:> Python Code: %load_ext autoreload %autoreload 2 import lxmls.readers.sentiment_reader as srs from lxmls.deep_learning.utils import AmazonData corpus = srs.SentimentCorpus("books") data = AmazonData(corpus=corpus) from lxmls.deep_learning.utils import Model, glorot_weight_init import numpy as np 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: Step4: Train Log Linear in Pytorch Step5: Once you understand the model you can instantiate it and run it using the standard training loop we have use...
13,285
<ASSISTANT_TASK:> Python Code: # Useful additional packages import matplotlib.pyplot as plt %matplotlib inline import numpy as np from math import pi from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister from qiskit import available_backends, execute, register, get_backend from qiskit.tools.visualizati...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Single Qubit Quantum states Step2: u gates Step3: The $u2(\phi, \lambda) =u3(\pi/2, \phi, \lambda)$ has the matrix form Step4: The $u1(\lambd...
13,286
<ASSISTANT_TASK:> Python Code: import pandas as pd # Read data, sort by year & month dateparse = lambda x: pd.datetime.strptime(x, '%Y%m%d') noaa_monthly = pd.read_csv('mpls-noaa.csv', index_col=2, parse_dates=True, date_parser=dateparse, na_values=-9999) noaa_monthly = noaa_monthly.groupby([...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Definition of variables Step2: The Badness Index of each winter
13,287
<ASSISTANT_TASK:> Python Code: import pandas as pd import matplotlib.pyplot as plt import os from sklearn.datasets import fetch_mldata mnist = fetch_mldata('MNIST original', data_home='datasets/') # Convert sklearn 'datasets bunch' object to Pandas DataFrames y = pd.Series(mnist.target).astype('int').astype('category')...
<SYSTEM_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 Shape, Summary Stats Step2: Below we see min, max, mean and most-common pixel-intensity values for our rows/images. As suggested by the fi...
13,288
<ASSISTANT_TASK:> Python Code: # Authors: Eric Larson <larson.eric.d@gmail.com> # Chris Holdgraf <choldgraf@gmail.com> # # License: BSD (3-clause) import numpy as np import matplotlib.pyplot as plt from scipy.io import loadmat from mayavi import mlab import mne from mne.viz import plot_alignment, snapshot_brai...
<SYSTEM_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 load some ECoG electrode locations and names, and turn them into Step2: Now that we have our electrode positions in MRI coordinates, we c...
13,289
<ASSISTANT_TASK:> Python Code: %matplotlib inline # Import neurom module import neurom as nm # Import neurom visualization module from neurom import viewer # Load a single morphology neuron = nm.load_neuron('../test_data/valid_set/Neuron.swc') # Load a population of morphologies from a set of files pop = nm.load_neu...
<SYSTEM_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. Loading a morphology or a population Step2: 2. Morphology visualization Step3: 3. Morphology analysis Step4: 3.2 Analyze different types o...
13,290
<ASSISTANT_TASK:> Python Code: def tokenize(message): message = message.lower() all_words = re.findall('[a-z0-9]+', message) return set(all_words) from collections import defaultdict def count_words(training_set): training set consists of pairs (message, is_spam) counts = defaultdict(lambda: [0, 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: Step2: Spam Filter Implementation Step3: Download the following files and extract them into a folder which we will reference below
13,291
<ASSISTANT_TASK:> Python Code: import numpy as np from astropy.table import Table, join import matplotlib.pyplot as plt %matplotlib inline idp = "idata/main_pdf_v0.8-b" idp_old = "idata/main_pdf_v0.8" lnew = Table.read(idp+"/lofar_m5.fits") lold = Table.read(idp_old+"/lofar_m5.fits") merged = join(lnew, lold, keys=["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: Load the data Step2: Check the shape of the data Step3: Compute the difference between the LR Step4: Explore the differences Step5: Plot of ...
13,292
<ASSISTANT_TASK:> Python Code: import requests import json #import ibmseti import numpy as np import matplotlib.pyplot as plt %matplotlib inline import tensorflow as tf import pickle import time #!sudo pip install sklearn import os from sklearn.metrics import confusion_matrix from sklearn import metrics ### SET YOUR 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: Set your team folder Step2: Import dataset reader Step3: Download data Step4: Load data SETI Step5: Network Parameters Step6: Inputs Step7:...
13,293
<ASSISTANT_TASK:> Python Code: import time import math import sys import pickle import copy import os import re import numpy as np from chainer import cuda, Variable, FunctionSet, optimizers import chainer.functions as F #-------------Explain7 in the Qiita------------- n_epochs = 30 n_units = 625 batchsize = ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: `導入するライブラリの代表例は下記です。 Step2: 3.データ入力 Step7: 4.リカレントニューラル言語モデル設定(ハンズオン) Step8: RNNLM(リカレントニューラル言語モデルの設定を行っています) Step9: 5.学習を始める前の設定 Step10: 6...
13,294
<ASSISTANT_TASK:> Python Code: import os # The Google Cloud Notebook product has specific requirements IS_GOOGLE_CLOUD_NOTEBOOK = os.path.exists("/opt/deeplearning/metadata/env_version") # Google Cloud Notebook requires dependencies to be installed with '--user' USER_FLAG = "" if IS_GOOGLE_CLOUD_NOTEBOOK: USER_FLAG...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Before you begin Step2: Otherwise, set your project ID here. Step3: Timestamp Step4: Authenticate your Google Cloud account Step5: Create a ...
13,295
<ASSISTANT_TASK:> Python Code: import imaginet.defn.visual as visual import imaginet.task model = imaginet.task.load(path="vis/model.10.zip") reload(visual) emb = visual.embeddings(model) print(emb.shape) symb = visual.symbols(model) print " ".join(symb.values()) %pylab inline from sklearn.decomposition import PCA ...
<SYSTEM_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 model Step2: Symbol embeddings Step3: The table of IPA symbols corresponding to the 49 dimensions Step4: Let's display the embeddin...
13,296
<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: Migrate the SavedModel workflow Step2: TensorFlow 1 Step3: 2. Build a SavedModel for serving Step4: 3. Export the Estimator inference graph a...
13,297
<ASSISTANT_TASK:> Python Code: import numpy as np import matplotlib.pyplot as plt import numpy.linalg as la from scipy.stats import rankdata %matplotlib inline ## Construct a regression model def lm_model( X, Y, intercept = True ) : T = np.array( Y, dtype = float ) M = np.array( X, dtype = float ) if interc...
<SYSTEM_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 continusous random variable $X$ is distributed accorind to the power law (also known as Pareto distibution) if it's probability density functi...
13,298
<ASSISTANT_TASK:> Python Code: import sys sys.path.append('/home/jbourbeau/cr-composition') print('Added to PYTHONPATH') import argparse from collections import defaultdict import numpy as np import pandas as pd import matplotlib.pyplot as plt from matplotlib.colors import ListedColormap import seaborn.apionly as sns 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: Data preprocessing Step2: Feature selection Step3: Feature transform Step4: Produce 10-fold CV learning curve
13,299
<ASSISTANT_TASK:> Python Code: def encode_shift(s: str): return "".join([chr(((ord(ch) + 5 - ord("a")) % 26) + ord("a")) for ch in s])def decode_shift(s: str): takes as input string encoded with encode_shift function. Returns decoded string. return "".join([chr(((ord(ch) - 5 - ord("a")) % 26) + ord...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: