Unnamed: 0
int64
0
15.9k
cleaned_code
stringlengths
67
124k
cleaned_prompt
stringlengths
168
30.3k
2,500
<ASSISTANT_TASK:> Python Code: from collections import deque queue = deque(["Eric", "John", "Michael"]) queue.append("Terry") # Terry 入队 queue.append("Graham") # Graham 入队 queue.pop() # 队尾元素出队 queue.popleft() # 队首元素出队 queue # 队列中剩下的元素 bas...
<SYSTEM_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. Python的集合 Step2: 在我们的爬虫中, 只是用到其中的快速判断元素是否在集合内的功能, 以及集合的并运算. Step3: re提供了众多模块方法用于完成正则表达式的功能。这些方法可以使用Pattern实例的相应方法替代,唯一的好处是少写一行re.compile()代...
2,501
<ASSISTANT_TASK:> Python Code: from varcode import Variant from pyensembl import ensembl_grch37 myVariant = Variant(contig=7, start=140453136, ref="A", alt="T", ensembl=ensembl_grch37) myVariant.short_description myVariant.coding_genes myEffects = myVariant.effects() myEffects topPriorityEffect = myEffects.top_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: Now let's create a new Variant that will represent our variant of interest Step2: Now that we defined this variant, Step3: this is our variati...
2,502
<ASSISTANT_TASK:> Python Code: x = Variable(T.ones(2,2), requires_grad=True) print x y = T.exp(x + 2) yy = T.exp(-x-2) print y z = (y + yy)/2 out = z.mean() print z, out make_dot(out) out.backward(T.FloatTensor(1), retain_graph=True) x.grad T.randn(1,1) from __future__ import print_function xx = Variable(torch.randn(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: A simple numpy implementation of one hidden layer neural network. Step2: with very slight modifications, we could end up with the implementati...
2,503
<ASSISTANT_TASK:> Python Code: from IPython.display import SVG SVG(filename='mass_spring_damper.svg') import sympy as sym import sympy.physics.mechanics as me from sympy.physics.vector import init_vprinting init_vprinting() x, v = me.dynamicsymbols('x v') m, c, k, g, t = sym.symbols('m c k g t') ceiling = me.Refere...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Start by loading in the core functionality of both SymPy and Mechanics. Step2: We can make use of the pretty printing of our results by loading...
2,504
<ASSISTANT_TASK:> Python Code: %%bash pip freeze | grep tensor !pip3 install tensorflow-hub==0.7.0 !pip3 install --upgrade tensorflow==1.15.3 !pip3 install google-cloud-bigquery==1.10 import os import tensorflow as tf import numpy as np import tensorflow_hub as hub import shutil PROJECT = 'cloud-training-demos' # REP...
<SYSTEM_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 make sure you install the necessary version of tensorflow-hub. After doing the pip install below, click "Restart the kernel" on the notebo...
2,505
<ASSISTANT_TASK:> Python Code: # Authors: Alexandre Gramfort <alexandre.gramfort@inria.fr> # # License: BSD-3-Clause import numpy as np import mne from mne import io from mne.stats import permutation_t_test from mne.datasets import sample print(__doc__) data_path = sample.data_path() meg_path = data_path / 'MEG' / 'sa...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Set parameters Step2: View location of significantly active sensors
2,506
<ASSISTANT_TASK:> Python Code: from sys import version print(version) from typing import List, Any, TypeVar T = TypeVar("T") tableau1 = [5, 4, 1, 2, 3] tableau2 = [1, 1, 2, 3] # avec un doublon def selection_naive(tableau: List[T], k: int) -> T: Sélection du k-ième plus petit élément du tableau, récursivemen...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: J'ai pris l'habitude d'écrire des signatures de fonctions en python qui soient typées Step2: Je ferai les premiers exemples avec ces deux tabl...
2,507
<ASSISTANT_TASK:> Python Code: from pyannote.core import Segment # start time in seconds s = 1. # end time in seconds e = 9. segment = Segment(start=s, end=e) segment start, end = segment print 'from %f to %f' % (start, end) print 'Segment %s ends at %g seconds.' % (segment, segment.end) print 'Its duration is %g sec...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Segment instances are used to describe temporal fragments (e.g. of an audio file). Step2: Segment instances are nothing more than 2-tuples augm...
2,508
<ASSISTANT_TASK:> Python Code: %matplotlib inline import numpy as np import pandas as pd import statsmodels.api as sm import matplotlib.pyplot as plt plt.rc("figure", figsize=(16,8)) plt.rc("font", size=14) # First we'll simulate the synthetic data def simulate_seasonal_term(periodicity, total_cycles, noise_std=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: Synthetic data creation Step2: Unobserved components (frequency domain modeling) Step3: Observe that the fitted variances are pretty close to ...
2,509
<ASSISTANT_TASK:> Python Code: # this line is required to see visualizations inline for Jupyter notebook %matplotlib inline # importing modules that we need for analysis import matplotlib.pyplot as plt import pandas as pd import numpy as np import re # read the data from file and print out first few rows jeopardy = pd....
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Apparently columns have a blank space in the beginning. Let's get rid of them Step2: Hypothesis - "Value of the question is related to its leng...
2,510
<ASSISTANT_TASK:> Python Code: import numpy as np import sympy as sy from sympy.utilities.codegen import codegen import control.matlab as cm import re import matplotlib.pyplot as plt from scipy import signal z = sy.symbols('z', real=False) r1,s0,s1 = sy.symbols('r1,s0,s1', real=True) hh = sy.symbols('h', real=True, pos...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Determine sampling period and desired closed loop poles Step2: Design a 2-DoF controller
2,511
<ASSISTANT_TASK:> Python Code: # Author: Marijn van Vliet <w.m.vanvliet@gmail.com> # Roman Goj <roman.goj@gmail.com> # Denis Engemann <denis.engemann@gmail.com> # Stefan Appelhoff <stefan.appelhoff@mailbox.org> # # License: BSD-3-Clause import os.path as op import numpy as np import mne from mne...
<SYSTEM_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 the raw data and creating epochs Step2: We are interested in the beta band. Define a range of frequencies, using a Step3: Computing th...
2,512
<ASSISTANT_TASK:> Python Code: !pygmentize moviesentiment.yaml !kubectl apply -f moviesentiment.yaml CLUSTER_IPS=!(kubectl -n istio-system get service istio-ingressgateway -o jsonpath='{.status.loadBalancer.ingress[0].ip}') CLUSTER_IP=CLUSTER_IPS[0] print(CLUSTER_IP) SERVICE_HOSTNAMES=!(kubectl get inferenceservice mov...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Get Explanation for Negative Prediction Step2: Show precision. How likely predictions using the Anchor features would produce the same result. ...
2,513
<ASSISTANT_TASK:> Python Code: from pathlib import Path Path.home() import uuid uuid.uuid4() from har2tree import CrawledTree har_path = Path() / '..' / 'tests' / 'capture_samples' / 'http_redirect' / '0.har' my_first_crawled_tree = CrawledTree([har_path], str(uuid.uuid4())) my_first_crawled_tree.root_url print(my_...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Great. Now let's try to create our first tree. As mentioned before, you will also need to pass a uuid as a parameter, but don't worry, python ha...
2,514
<ASSISTANT_TASK:> Python Code: %matplotlib inline from statsmodels.compat import lmap import numpy as np from scipy import stats import matplotlib.pyplot as plt import statsmodels.api as sm norms = sm.robust.norms def plot_weights(support, weights_func, xlabels, xticks): fig = plt.figure(figsize=(12,8)) ax = 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: An M-estimator minimizes the function Step2: Andrew's Wave Step3: Hampel's 17A Step4: Huber's t Step5: Least Squares Step6: Ramsay's Ea St...
2,515
<ASSISTANT_TASK:> Python Code: import numpy as np import pandas as pd import matplotlib.pyplot as plt from __future__ import division capital_base = 100000 r_p = 0.05 # Aggregate performance of assets in the portfolio r_no_lvg = capital_base * r_p print 'Portfolio returns without leverage: {0}'.format(r_no_lvg) debt =...
<SYSTEM_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 is what portfolio returns look like without leverage. Let's add some debt, leveraging the portfolio, and see how the returns change. Step2:...
2,516
<ASSISTANT_TASK:> Python Code: import tensorflow as tf # check tf version print(tf.__version__) a = tf.constant(2) b = tf.constant(5) operation = tf.add(a, b, name='cons_add') with tf.Session() as ses: print ses.run(operation) sub_operation = tf.subtract(a, b, name='cons_subtraction') x = tf.constant([[-1.37 ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Config Contants Step2: en la variable "b" vamos a asignar una constante con el valor inicial de "5" Step3: En la siguiente variable "operation...
2,517
<ASSISTANT_TASK:> Python Code: # Выделяем outdoor'ы и indoor'ы. sample_out = sample[result[:, 0] == 1] sample_in = sample[result[:, 1] == 1] result_out = result[result[:, 0] == 1] result_in = result[result[:, 1] == 1] # Считаем размер indoor- и outdoor-частей в train'е. train_size_in = int(sample_in.shape[0] * 0.75) tr...
<SYSTEM_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_0, p_1)$, вероятностей такой, что $p_i$ - вероятность того, что картинка принадлежит классу $i$ ($...
2,518
<ASSISTANT_TASK:> Python Code: %matplotlib inline %config InlineBackend.figure_format='retina' import warnings warnings.filterwarnings("ignore") import pandas as pd names = ["ID","R","I","J","H","KS","TiO_7140","TiO_8465","NaI_8189","Spectral Type","EW_Ha","Gravity"] tbl1 = pd.read_csv("http://iopscience.iop.org/1538-...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Table 1- Measured Quantities for PMS Candidates with Observed Spectra Step2: Table 2 - Derived Quantities for New USco Members Step3: Save the...
2,519
<ASSISTANT_TASK:> Python Code: import collections import os import StringIO import sys import tarfile import tempfile import urllib from IPython import display from ipywidgets import interact from ipywidgets import interactive from matplotlib import gridspec from matplotlib import pyplot as plt import numpy as np 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: Select and download models Step5: Load model in TensorFlow Step6: Helper methods Step7: Run on sample images Step8: Run on internet images
2,520
<ASSISTANT_TASK:> Python Code: from atmPy.aerosols.instruments.POPS import mie %matplotlib inline import matplotlib.pylab as plt plt.rcParams['figure.dpi'] = 200 d,amp = mie.makeMie_diameter(noOfdiameters=1000) f,a = plt.subplots() a.plot(d,amp) a.loglog() a.set_xlim((0.1,3)) a.set_ylabel('Signal intensity (arb. 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: standard settings Step2: Wavelength dependence Step3: refractive index dependence
2,521
<ASSISTANT_TASK:> Python Code: import numpy as np import itertools import pandas as pd # In Python 2.7 the division of integers is not float. Do this to have 1 / 2 = .5 from __future__ import division # Number of simulations S = 1000 # Number of observations in each sample N = [10, 100, 1000] # True parameter values 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: Define parameters of the simulation Step3: Define the function that returns rejection probabilities Step4: Run simulation study
2,522
<ASSISTANT_TASK:> Python Code: import numpy as np A = np.array([1,1,2,3,3,3,4,5,6,7,8,8]) B = np.array([1,2,8]) C = A[np.in1d(A,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:
2,523
<ASSISTANT_TASK:> Python Code: %cd -q ~/neurokernel/examples/sensory_int/data %run gen_vis_input.py %run gen_olf_input.py %run gen_integrate.py %cd -q ~/neurokernel/examples/sensory_int/ %run sensory_int_demo.py %run visualize_output.py import IPython.display IPython.display.YouTubeVideo('e-eUOtOF9fc') <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: Once the input and the configuration are ready, we execute the entire model. Note that the interconnections between the integration LPU and both...
2,524
<ASSISTANT_TASK:> Python Code: print('abc') print(1, 2, 3) print(1, 2, 3, sep='--') def fibonacci(N): L = [] a, b = 0, 1 while len(L) < N: a, b = b, a + b L.append(a) return L fibonacci(10) def real_imag_conj(val): return val.real, val.imag, val.conjugate() r, i, c = real_imag_co...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Aqui, print() es el nombre de la función, y 'abc' es lo que se llama un argumento (de la función). Step2: Cuando se usan argumentos y argumento...
2,525
<ASSISTANT_TASK:> Python Code: a_set = {1, 2, 3} a_set empty_set = set() # you have to use set() to create an empty set! (we will see why later) print(empty_set) a_set = {1, 2, 1, 1} print(a_set) a_set = {1, 3, 2} print(a_set) {1, 2, 3} == {2, 3, 1} a_set = {1, 'a'} print(a_set) a_set = {1, []} a_set = set() a_se...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Curly brackets surround sets, and commas separate the elements in the set Step2: Please note that sets are unordered. This means that it can oc...
2,526
<ASSISTANT_TASK:> Python Code: import pandas as pd import numpy as np raw_data = {'first_name': ['Jason', np.nan, 'Tina', 'Jake', 'Amy'], 'last_name': ['Miller', np.nan, 'Ali', 'Milner', 'Cooze'], 'age': [42, np.nan, 36, 24, 73], 'sex': ['m', np.nan, 'f', 'm', 'f'], 'preTestScore': ...
<SYSTEM_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 dataframe with missing values Step2: Drop missing observations Step3: Drop rows where all cells in that row is NA Step4: Create a new ...
2,527
<ASSISTANT_TASK:> Python Code: %pylab inline %matplotlib inline import os SHOGUN_DATA_DIR=os.getenv('SHOGUN_DATA_DIR', '../../../data') # import all Shogun classes from shogun import * from matplotlib.patches import Ellipse # a tool for visualisation def get_gaussian_ellipse_artist(mean, cov, nstd=1.96, color="red", li...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Gaussian Mixture Models and Expectation Maximisation in Shogun Step2: Set up the model in Shogun Step3: Sampling from mixture models Step4: E...
2,528
<ASSISTANT_TASK:> Python Code: from pscript import py2js, evalpy js = py2js('for i in range(10): print(i)') print(js) def foo(x): res = [] for i in range(x): res.append(i**2) return res js = py2js(foo) print(js) def foo(x): return [i**2 for i in range(x)] js = py2js(foo) print(js) class Bar:...
<SYSTEM_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 transpile strings of Python code Step2: Or actual Python functions Step3: Let's try that again, but now with a list comprehension. (The...
2,529
<ASSISTANT_TASK:> Python Code: #import pandas for conviently labelled arrays import pandas # import numpy for SVD function import numpy # import matplotlib.pyplot for visualising arrays import matplotlib.pyplot as plt # create a simple word-document matrix as a pandas dataframe, the content values have been normalised...
<SYSTEM_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 Simple Word-Document Matrix Step2: Word-Document Matrix is A Step3: Now Take the SVD Step4: We can see above that the values in the diagona...
2,530
<ASSISTANT_TASK:> Python Code: import numpy as np a = np.array( [[[ 0, 1], [ 2, 3], [ 4, 5]], [[ 6, 7], [ 8, 9], [10, 11]], [[12, 13], [14, 15], [16, 17]]] ) b = np.array( [[0, 1, 1], [1, 0, 1], [1, 1, 0]] ) result = np.take_along_axis(a, b[..., np.newaxis], ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description:
2,531
<ASSISTANT_TASK:> Python Code: %matplotlib inline import pandas as pd import numpy as np import pymc3 as pm import matplotlib.pyplot as plt # from pandas_datareader import data # prices = data.GoogleDailyReader(symbols=['GLD', 'GFI'], end='2014-8-1').read().loc['Open', :, :] prices = pd.read_csv(pm.get_data('stock_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: Lets load the prices of GFI and GLD. Step2: Plotting the prices over time suggests a strong correlation. However, the correlation seems to chan...
2,532
<ASSISTANT_TASK:> Python Code: def execute_notebook(nbfile): with io.open(nbfile) as f: nb = current.read(f, 'json') ip = get_ipython() for cell in nb.worksheets[0].cells: if cell.cell_type != 'code': continue ip.run_cell(cell.input) #execute_notebook("POR...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Notebook Execute Step2: plot_graph(Cotistas , "Pretos Pardos e Indígenas") Step3: IMPORT ALL CANDIDATES CSV Step4: Get CPFs Step5: DELETAR S...
2,533
<ASSISTANT_TASK:> Python Code: from pyesgf.search import SearchConnection conn = SearchConnection('https://esgf-data.dkrz.de/esg-search', distrib=True) ctx = conn.new_context( project='CMIP6', source_id='UKESM1-0-LL', experiment_id='historical', variable='tas', frequency='mon', variant_labe...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Subset single dataset with xarray Step2: Subset over multiple datasets Step3: Download dataset
2,534
<ASSISTANT_TASK:> Python Code: !pip freeze | grep tensorflow-hub==0.7.0 || pip install tensorflow-hub==0.7.0 import os import tensorflow as tf import tensorflow_hub as hub PROJECT = "your-gcp-project-here" # REPLACE WITH YOUR PROJECT NAME BUCKET = "your-gcp-bucket-here" # REPLACE WITH YOUR BUCKET NAME os.environ["PROJ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Replace by your GCP project and bucket Step2: Setting up the Kubeflow cluster Step3: It has very specialized language such as Step 1 Step4: ...
2,535
<ASSISTANT_TASK:> Python Code: %matplotlib inline import numpy as np from scipy import stats import pandas as pd import matplotlib.pyplot as plt import statsmodels.api as sm from statsmodels.tsa.arima.model import ARIMA from statsmodels.graphics.api import qqplot print(sm.datasets.sunspots.NOTE) dta = sm.datasets.suns...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Sunspots Data Step2: Does our model obey the theory? Step3: This indicates a lack of fit. Step4: Exercise Step5: Let's make sure this model ...
2,536
<ASSISTANT_TASK:> Python Code: import naminggamesal.ngpop as ngpop pop_cfg={ 'voc_cfg':{ 'voc_type':'matrix', 'M':5, 'W':10 }, 'strat_cfg':{ 'strat_type':'naive', 'vu_cfg':{'vu_type':'BLIS_epirob'} }, 'interact_cfg':{ 'interact_type':'speakers...
<SYSTEM_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 create a population. Agent creation is here dealt with automatically. Still, it is possible to manually add or remove agents (Hence the ID...
2,537
<ASSISTANT_TASK:> Python Code: #Importation des librairies utilisées import time import pandas as pd import numpy as np import collections import itertools import os import warnings warnings.filterwarnings('ignore') from sklearn.cross_validation import train_test_split data_valid_clean_stem = pd.read_csv("data/cdiscou...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Téléchargement des données Step2: On créé un dossier dans lequel nous allons sauvegarder les DataFrame constitués des features que l'on va cons...
2,538
<ASSISTANT_TASK:> Python Code: # Import the simulation function from pymer4.simulate import simulate_lm # Also fix the random number generator for reproducibility import numpy as np np.random.seed(10) data, b = simulate_lm( 500, 3, coef_vals=[100, 1.2, -40.1, 3], mus=[10, 30, 1], noise_params=(0, 5) ) print(f"True ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Here are some checks you might do to make sure the data were correctly generated Step2: Check correlations between predictors Step3: Check coe...
2,539
<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: Create a TFX pipeline using templates with Local orchestrator Step2: NOTE Step3: Let's check the version of TFX. Step4: And, it's done. We ar...
2,540
<ASSISTANT_TASK:> Python Code: %matplotlib inline import pandas as pd import matplotlib.pyplot as plt import seaborn as sns plt.rcParams['figure.figsize'] = (20.0, 10.0) plt.rcParams['font.family'] = "serif" df = pd.read_csv('../../datasets/movie_metadata.csv') df.head() # split each movie's genre list, then form a se...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: For the bar plot, let's look at the number of movies in each category, allowing each movie to be counted more than once. Step2: Basic plot Step...
2,541
<ASSISTANT_TASK:> Python Code: import numpy as np import matplotlib.pyplot as plt plt.style.use('bmh') %matplotlib inline plt.figure(figsize = (12, 6)) for i in range(10): x = np.arange(i * 10, i * 10 + 10) y_var1 = np.random.randint(1, 5, 10) y_var2 = np.random.randint(5, 8, 10) plt.plot(x, y_var1, 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: Como véis, en la gráfica anterior hay varios problemas pero como esta es una MicroEntrada solo nos vamos a centrar en el problema de las etiquet...
2,542
<ASSISTANT_TASK:> Python Code: %load_ext cypher %%cypher MATCH (t:Type)-[:ANNOTATED_BY]->()-[:OF_TYPE]->(a:Type) WHERE a.fqn="javax.persistence.Entity" SET t:Entity RETURN t.fqn AS Entity %%cypher MATCH (e:Entity)<-[:CONTAINS]-(p:Package) WHERE p.name = "model" RETURN e.fqn as Entity, p.name as Package %%cyp...
<SYSTEM_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 Concerns Step2: Rule Definition Step3: Rule Violations
2,543
<ASSISTANT_TASK:> Python Code: import sys sys.path.append('..') import os import json from time import time import numpy as np from tqdm import tqdm import theano import theano.tensor as T from theano.sandbox.cuda.dnn import dnn_conv from PIL import Image from lib import activations from lib import updates from lib 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: N.B. The code from the following imports is lifted from the original dcgan project Step2: Data Stuff Step3: Check data looks sensible Step4: ...
2,544
<ASSISTANT_TASK:> Python Code: import numpy as np @memory.cache def g(x): print('A long-running calculation, with parameter %s' % x) return np.hamming(x) @memory.cache def h(x): print('A second long-running calculation, using g(x)') return np.vander(x) a = g(3) a g(3) h(a) h(a) cachedir2 = mkdtemp() ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: using memmapping
2,545
<ASSISTANT_TASK:> Python Code: import numpy as np mystr = "100110" result = np.array(list(mystr), dtype = int) <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:
2,546
<ASSISTANT_TASK:> Python Code: from sklearn.datasets import load_digits digits = load_digits() %matplotlib inline import matplotlib.pyplot as plt fig = plt.figure(figsize=(6, 6)) # figure size in inches fig.subplots_adjust(left=0, right=1, bottom=0, top=1, hspace=0.05, wspace=0.05) # plot the digits: each image is 8x...
<SYSTEM_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'll re-use some of our code from before to visualize the data and remind us what Step2: Visualizing the Data Step3: Here we see that the dig...
2,547
<ASSISTANT_TASK:> Python Code: import pandas as pd iris = pd.read_csv('../datasets/iris_without_classes.csv') # Read the file 'datasets/iris_without_classes.csv' # Print the first entries using the head() method to check that there is no Class information anymore iris.head() # Use PCA's fit_transform() method to redu...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Reducing dimensions Step2: How many distinct groups can you see?
2,548
<ASSISTANT_TASK:> Python Code: from pprint import pprint from time import sleep from pynq import PL from pynq import Overlay from pynq.drivers import Trace_Buffer from pynq.iop import Pmod_TMP2 from pynq.iop import PMODA from pynq.iop import PMODB from pynq.iop import ARDUINO ol = Overlay("base.bit") ol.download() tmp...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step 1 Step1: Step 2 Step2: Step 3 Step3: Step 4 Step4: Step 5
2,549
<ASSISTANT_TASK:> Python Code: # Import the FISSA toolbox import fissa # For plotting our results, import numpy and matplotlib import matplotlib.pyplot as plt import numpy as np # Fetch the colormap object for Cynthia Brewer's Paired color scheme colors = plt.get_cmap("Paired") # Define path to imagery and to the ROI...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: We also need to import some plotting dependencies which we'll make use in this notebook to display the results. Step2: Running FISSA Step3: Th...
2,550
<ASSISTANT_TASK:> Python Code: import os import numpy as np import pandas as pd import lmfit from fretbursts import * import matplotlib.pyplot as plt import seaborn as sns %matplotlib inline %config InlineBackend.figure_format='retina' # for hi-dpi displays sns.set_style('whitegrid') #bsearch_ph_sel = 'AND-gate' bsea...
<SYSTEM_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 Raw PR Step2: These are the RAW proximity ratios for the 5 samples (only background correction, no leakage nor direct excitation) Step3: ...
2,551
<ASSISTANT_TASK:> Python Code: import random n = 10 data = [random.randint(1, 10) for _ in range(n)] data # this print out the variable's content def nsqrt(x): # do not change the heading of the function pass # **replace** this line with your code print(nsqrt(11), nsqrt(1369)) import matplotlib import numpy...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Exercise 1 Step2: You can test your implementation using the following code. Step3: Exercise 2 Step4: To find $x$ for the equation, we need t...
2,552
<ASSISTANT_TASK:> Python Code: from __future__ import division, print_function from sklearn.metrics import mean_absolute_error import torch import torch.nn as nn from torch.autograd import Variable import math import matplotlib.pyplot as plt import numpy as np import os import shutil %matplotlib inline def generate_se...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Visualize Input Step2: Define Constants Step3: Generate Training Data Step4: Define Network Step5: Train Network Step6: Test Model
2,553
<ASSISTANT_TASK:> Python Code: environment_directory = "environments/" identifier = "test_all_methods" log_directory = "log/" if not os.path.exists('log'): os.makedirs('log') logging.basicConfig(format='%(asctime)s %(message)s', datefmt='%m/%d/%Y %H:%M:%S', filename=log_directory + identifier +...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Then, after a log folder is created, if it doesn't exist, the logger will be initialized. The log files will contain information about how the s...
2,554
<ASSISTANT_TASK:> Python Code: from IPython.core.display import HTML css_file = 'pynoddy.css' HTML(open(css_file, "r").read()) import sys, os import matplotlib.pyplot as plt # adjust some settings for matplotlib from matplotlib import rcParams # print rcParams rcParams['font.size'] = 15 # determine path of repository 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: Adding features to geological layers Step2: ok, seems to work - now for all
2,555
<ASSISTANT_TASK:> Python Code: import numpy as np import matplotlib import matplotlib.pyplot as plt from __future__ import division %config InlineBackend.figure_formats=['svg'] %matplotlib inline plt.rc('pdf',fonttype=3) # for proper subsetting of fonts plt.rc('axes',linewidth=0.5) # thin axes; the defaul...
<SYSTEM_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 (at least qualitatively), from the plot of the objective funtion that on the interval $0.05 < \alpha < 0.15$ the optimum value lies s...
2,556
<ASSISTANT_TASK:> Python Code: from tensorflow import keras import numpy x = numpy.array([0, 1, 2, 3, 4]) y = x * 2 + 1 model = keras.models.Sequential() model.add(keras.layers.Dense(1,input_shape=(1,))) model.compile('SGD', 'mse') model.fit(x[:2], y[:2], epochs=1000, verbose=0) print(model.predict(x)) import tensorf...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: II. 케라스 인터페이스를 사용하는 텐서플로 2.0 사용법(Tensorflow 2.0 with Keras IO) Step2: 간단한 구성에 진행 결과 보이기 Step3: 클래스를 이용한 네트웍 모델 구성하기
2,557
<ASSISTANT_TASK:> Python Code: from __future__ import print_function import tellurium as te te.setDefaultPlottingEngine('matplotlib') %matplotlib inline import phrasedml antimony_str = ''' model myModel S1 -> S2; k1*S1 S1 = 10; S2 = 0 k1 = 1 end ''' phrasedml_str = ''' model1 = model "myModel" sim1 = simulate...
<SYSTEM_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 / Executing SED-ML Step3: SED-ML L1V2 specification example
2,558
<ASSISTANT_TASK:> Python Code: %matplotlib inline import matplotlib.pyplot as plt import seaborn seaborn.set() import cPickle import numpy as np from keras import backend as K from keras.models import Sequential, model_from_yaml from keras.layers.recurrent import LSTM from keras.layers.core import Activation, Dense, Dr...
<SYSTEM_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 data Step2: Train Step3: Load previous model
2,559
<ASSISTANT_TASK:> Python Code: from openpiv import tools, pyprocess, validation, filters, scaling import numpy as np import matplotlib.pyplot as plt %matplotlib inline import imageio frame_a = tools.imread( '../../examples/test1/exp1_001_a.bmp' ) frame_b = tools.imread( '../../examples/test1/exp1_001_b.bmp' ) fig,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: Reading images Step2: Processing Step3: The function get_coordinates finds the center of each interrogation window. This will be useful later ...
2,560
<ASSISTANT_TASK:> Python Code: %matplotlib inline import sys import os import shutil import numpy as np from subprocess import check_output # Import flopy import flopy # Set the name of the path to the model working directory dirname = "P4-5_Hubbertville" datapath = os.getcwd() modelpath = os.path.join(datapath, dirna...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Setup a New Directory and Change Paths Step2: Define the Model Extent, Grid Resolution, and Characteristics Step3: Create the MODFLOW Model Ob...
2,561
<ASSISTANT_TASK:> Python Code: %pylab inline %matplotlib inline # include all Shogun classes from modshogun import * # generate some ultra easy training data gray() n=20 title('Toy data for binary classification') X=hstack((randn(2,n), randn(2,n)+1)) Y=hstack((-ones(n), ones(n))) _=scatter(X[0], X[1], c=Y , s=100) p1 =...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Types of splitting strategies Step2: Stratified cross-validation Step3: Leave One Out cross-validation Step4: Stratified splitting takes care...
2,562
<ASSISTANT_TASK:> Python Code: # Load image import cv2 import numpy as np from matplotlib import pyplot as plt # Load images image_bgr = cv2.imread('images/plane_256x256.jpg') image_gray = cv2.cvtColor(image_bgr, cv2.COLOR_BGR2GRAY) # Number of corners to detect corners_to_detect = 10 minimum_quality_score = 0.05 min...
<SYSTEM_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 image Step2: Define Corner Parameters Step3: Detect Corners Step4: Mark Corners Step5: View Image
2,563
<ASSISTANT_TASK:> Python Code: import pandas as pd import numpy as np from sklearn.cluster import KMeans from sklearn.metrics import silhouette_score, silhouette_samples import matplotlib.pyplot as plt import matplotlib.cm as cm %matplotlib inline # processing .csv containing county statistics counties = pd.read_csv('...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Importing the .csv files and processing them into a single dataframe. Step2: This creates a dataframe containing all of the counties where Trum...
2,564
<ASSISTANT_TASK:> Python Code: #importing some useful packages import matplotlib.pyplot as plt import matplotlib.image as mpimg import numpy as np import cv2 %matplotlib inline #reading in an image #image = mpimg.imread('test_images/solidWhiteRight.jpg') #printing out some stats and plotting #print('This image is:', 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: Read in an Image Step9: Ideas for Lane Detection Pipeline Step10: Test Images Step11: Build a Lane Finding Pipeline Step12: Test on Videos S...
2,565
<ASSISTANT_TASK:> Python Code: %matplotlib inline from quimb.tensor import * from quimb import * import numpy as np # the initial state n = 50 cyclic = False chi = 4 # intial bond dimension psi = MPS_rand_state(n, chi, cyclic=cyclic, tags='KET', dtype='complex128') # the gates n_gates = 5 * n gates = [rand_uni(4) 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: First we specify how sites we want, how many gates to apply, and some other parameters Step2: We generate a unique tag for each gate we will ap...
2,566
<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: The Basics Step2: Set up training data Step3: Some Machine Learning terminology Step4: Assemble layers into the model Step5: Note Step6: Th...
2,567
<ASSISTANT_TASK:> Python Code: from symbulate import * %matplotlib inline die = list(range(1, 6 + 1)) P = BoxModel(die, size=2) X = RV(P, sum) Y = RV(P, max) die = list(range(1, 6 + 1)) P = BoxModel(die, size=2) X = RV(P, sum) Y = RV(P, max) (X & Y).sim(10000).tabulate(normalize=True) die = list(range(1, 6 + 1)) P =...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: <a id='joint'></a> Step2: <a id='ampersand'></a> Step3: <a id='plot'></a> Step4: See the section on Symbulate graphics for more details on pl...
2,568
<ASSISTANT_TASK:> Python Code: Initialization ''' Standard modules ''' import os import pickle import sqlite3 import time from pprint import pprint ''' Analysis modules ''' import pandas as pd ''' Custom modules ''' import config import utilities ''' Misc ''' nb_name = '20171011-daheng-check_topics_basic_statistics' P...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Check basic statistics of manually selected topics Step3: Manually compile a list of topics with keywords Step5: Check number of associated ne...
2,569
<ASSISTANT_TASK:> Python Code: import rebound sim = rebound.Simulation() sim.add(m=1., x=1., vz = 2.) sim.add(m=1., a=1.) sim.status() sim.add(m=1.e-3, a=100.) sim.add(primary=sim.particles[1], a=0.01) orbits = sim.calculate_orbits() for orbit in orbits: print(orbit) print(sim.particles[3].calculate_orbit(sim,...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Any components not passed automatically default to 0. REBOUND can also accept orbital elements. Step2: We always have to pass a semimajor ax...
2,570
<ASSISTANT_TASK:> Python Code: from sympy import * from sympy.abc import i init_printing() alpha, beta, gamma = symbols(r'\alpha \beta \gamma') x_ave, y_ave = symbols(r'\langle{x}\rangle \langle{y}\rangle') x2_ave, xy_ave = symbols(r'\langle{x^{2}}\rangle \langle{xy}\rangle') x3_ave, x2y_ave = symbols(r'\langle{x^{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: Construct matrix A Step2: Construct b Step3: Solve for $\vec{a}$ Step4: The $a_0$ component Step5: The $a_{1}$ component Step6: The $a_{2}$...
2,571
<ASSISTANT_TASK:> Python Code: # Inicializamos una figura con el tamaño que necesitemos # si no la queremos por defecto # Creamos unos ejes con la proyección que queramos # por ejemplo, Mercator # Y lo que queremos representar en el mapa # Tierra # Océanos # Líneas de costa (podemos modificar el color) # Fronteras # 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: InterruptedGoodeHomolosine Step2: Puede interesarnos poner etiquetas a los ejes. Podemos utilizar entonces las herramientas dentro de Step3: ...
2,572
<ASSISTANT_TASK:> Python Code: %matplotlib inline import os import numpy as np import matplotlib.pyplot as plt import pandas as pd import pyemu la = pyemu.Schur("pest.jco",verbose=False,forecasts=[]) la.drop_prior_information() jco_ord = la.jco.get(la.pst.obs_names,la.pst.adj_par_names) ord_base = "pest_ord" jco_ord.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: instaniate pyemu object and drop prior info. Then reorder the jacobian and save as binary. This is needed because the pest utilities require s...
2,573
<ASSISTANT_TASK:> Python Code: # DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'niwa', 'ukesm1-0-ll', 'aerosol') # 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...
2,574
<ASSISTANT_TASK:> Python Code: import pandas as pd import numpy as np from floweaver import * df1 = pd.read_csv('holiday_data.csv') dataset = Dataset(df1) df1 partition_job = Partition.Simple('Employment Job', np.unique(df1['Employment Job'])) partition_activity = Partition.Simple('Activity', np.unique(df1['Activity'...
<SYSTEM_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 take a look at the dataset we are using. This is a very insightful [made-up] dataset about how different types of people lose weight while o...
2,575
<ASSISTANT_TASK:> Python Code: class RegExp2NFA: def __init__(self, Sigma): self.Sigma = Sigma self.StateCount = 0 def toNFA(self, r): if r == 0: return self.genEmptyNFA() if r == '': return self.genEpsilonNFA() if isinstance(r, str) and len(r) == 1: retu...
<SYSTEM_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 member function toNFA takes an object self of class RegExp2NFA and a regular expression r and returns a finite state machine Step2: The <s...
2,576
<ASSISTANT_TASK:> Python Code: from adaptivemd import mongodb mongodb.MongoDBStorage._db_url mongodb.MongoDBStorage.set_port(27018) mongodb.MongoDBStorage._db_url mongodb.MongoDBStorage.set_host('128.219.191.255') mongodb.MongoDBStorage._db_url mongodb.MongoDBStorage.set_location('localhost:27017') mongodb.MongoDBSt...
<SYSTEM_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 change the port number, use the set_port method of the MongoDBStorage interface class Step2: Likewise, reset the host address with set_host ...
2,577
<ASSISTANT_TASK:> Python Code: import numpy as np import scipy.sparse as sparse np.random.seed(10) max_vector_size = 1000 vectors = [np.random.randint(100,size=900),np.random.randint(100,size=max_vector_size),np.random.randint(100,size=950)] result = sparse.lil_matrix((len(vectors), max_vector_size)) for i, v in enumer...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description:
2,578
<ASSISTANT_TASK:> Python Code: import sys sys.path.append('C:\Anaconda2\envs\dato-env\Lib\site-packages') import graphlab def polynomial_sframe(feature, degree): # assume that degree >= 1 # initialize the SFrame: poly_sframe = graphlab.SFrame() # and set poly_sframe['power_1'] equal to the passed featu...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Polynomial regression, revisited Step2: Let's use matplotlib to visualize what a polynomial regression looks like on the house data. Step3: As...
2,579
<ASSISTANT_TASK:> Python Code: import os import sys # Google Cloud Notebook if os.path.exists("/opt/deeplearning/metadata/env_version"): USER_FLAG = "--user" else: USER_FLAG = "" ! pip3 install -U google-cloud-aiplatform $USER_FLAG ! pip3 install -U google-cloud-storage $USER_FLAG if not os.getenv("IS_TESTING...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Install the latest GA version of google-cloud-storage library as well. Step2: Restart the kernel Step3: Before you begin Step4: Region Step5:...
2,580
<ASSISTANT_TASK:> Python Code: Image(url="http://i.giphy.com/LY1DH1AMbG0tq.gif") Image(url="http://i.giphy.com/12eayhW3TRPCjS.gif") # Charger la lib import pandas as pd #Afficher l'aide #pd.read_csv? data = pd.read_csv('data/train.csv') # Chargement des données. data.head() data.tail() data.shape data.dtypes 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: Titanic dataset Step2: Analyse data Step3: Pour regarder les données Step4: Signification des colonnes Step5: 2) Connaitre les type des ...
2,581
<ASSISTANT_TASK:> Python Code: %matplotlib inline import numpy as np import matplotlib.pyplot as pl from revrand.basis_functions import RandomRBF, RandomLaplace, RandomCauchy, RandomMatern32, RandomMatern52, \ FastFoodRBF, OrthogonalRBF, FastFoodGM, BasisCat from revrand import Parameter, Positive # Style pl.style....
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Settings Step2: Kernel functions Step3: Basis functions Step4: Evaluate kernels and bases Step5: Plot the kernel functions
2,582
<ASSISTANT_TASK:> Python Code: # ionization degree alpha calculated from the Henderson-Hasselbalch equation for an ideal system def ideal_alpha(pH, pK): return 1. / (1 + 10**(pK - pH)) import matplotlib.pyplot as plt import numpy as np import setuptools import pint # module for working with units and dimensions 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: Constant pH Method Step2: The package pint is intended to make handling physical quantities with different units easy. You simply create an ins...
2,583
<ASSISTANT_TASK:> Python Code: responses = {} responses type(responses) responses["hello"] = "world" responses responses["hola"] = "mundo" responses def greet(salutation): try: print(salutation, responses[salutation]) except KeyError: print("Sorry, don't know how to respond to", salutation) gr...
<SYSTEM_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 dictionary can store values for a key. In this example, we will store the value "world", at the key "hello". Step2: One nice property of dict...
2,584
<ASSISTANT_TASK:> Python Code: print("Most billionaires are from the following countries in descending order:") df['countrycode'].value_counts().head(5) us = 903 / 1000000000 ger = 160 / 1000000000 china = 153 / 1000000000 russia = 119 / 1000000000 japan = 96 / 1000000000 print("per billion for us is", us, "for germany...
<SYSTEM_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. What's the average wealth of a billionaire? Male? Female? Step2: 3. Most common source of wealth? Male vs. female? Step3: 4. List top ten b...
2,585
<ASSISTANT_TASK:> Python Code: import matplotlib import matplotlib.pyplot as pyplot import numpy import os import time # tensorflow import tensorflow as tf from tensorflow.python.training import adagrad from tensorflow.python.training import adam from tensorflow.python.training import gradient_descent # python3-6 NCS. ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: pyNCS analysis Step2: pyCNCS analysis Step3: Compare results to reference implementation. Step4: Tensorflow
2,586
<ASSISTANT_TASK:> Python Code: mu = [2, 3] cov = [[2, -1],[2, 4]] rv = sp.stats.multivariate_normal(mu, cov) xx = np.linspace(-1, 5, 150) yy = np.linspace(0, 6, 120) XX, YY = np.meshgrid(xx, yy) ZZ = rv.pdf(np.dstack([XX, YY])) plt.contour(XX, YY, ZZ) plt.xlabel("x") plt.ylabel("y") plt.title("Joint Probability Density...
<SYSTEM_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차원으로 그리면 아래와 같다. Step2: 이산 확률 변수의 결합 확률 질량 함수 Step3: 주변 확률 밀도 함수 Step4: 위에서 예로 든 연속 확률 변수의 경우에 주변 확률 밀도 함수를 계산하면 다음과 같다. St...
2,587
<ASSISTANT_TASK:> Python Code: %matplotlib inline import numpy as np import pandas as pd import xarray as xr from netCDF4 import num2date import matplotlib.pyplot as plt print("numpy version : ", np.__version__) print("pandas version : ", pd.__version__) print("xarray version : ", xr.__version__) dpm = {'noleap': [...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Some calendar information so we can support any netCDF calendar. Step4: A few calendar functions to determine the number of days in each month ...
2,588
<ASSISTANT_TASK:> Python Code: import rebound import reboundx sim = rebound.Simulation() sim.add(m=1.) sim.add(m=1.e-3, a=1., e=0.2) ps = sim.particles rebx = reboundx.Extras(sim) cf = rebx.load_force("central_force") rebx.add_force(cf) ps[0].params["gammacentral"] = -1. # period needed after integer power ps[0].par...
<SYSTEM_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 we add REBOUNDx and our effect as usual Step2: We need to choose a normalization Acentral and power gammacentral for our force law (see abo...
2,589
<ASSISTANT_TASK:> Python Code: # import libraries # linear algebra import numpy as np # data processing import pandas as pd # library of math import math # data visualization from matplotlib import pyplot as plt # datasets from sklearn import datasets # Scikit Learning hierarchical clustering from sklearn.cluster 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: 1.1 Clusterização Hierárquica Step2: 1.2 Dendrograma Step3: É possível fazer um teste de permutação para validar o número de clusters escolhid...
2,590
<ASSISTANT_TASK:> Python Code: from sklearn.datasets import load_files from keras.utils import np_utils import numpy as np from glob import glob # define function to load train, test, and validation datasets def load_dataset(path): data = load_files(path) dog_files = np.array(data['filenames']) dog_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: Import Human Dataset Step2: <a id='step1'></a> Step 1 Step3: Before using any of the face detectors, it is standard procedure to convert the i...
2,591
<ASSISTANT_TASK:> Python Code: import pyspark.sql.functions as sql import pyspark.sql.types as types idb_df_version = "20170130" idb_df = sqlContext.read.parquet("/guoda/data/idigbio-{0}.parquet".format(idb_df_version)) idb_df.count() subset = (idb_df .select(idb_df.catalognumber) .where(idb_df.rec...
<SYSTEM_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 test our code, find one collection that seems to have numeric ids. Go to the search API and find the most common catalog number Step2: Is th...
2,592
<ASSISTANT_TASK:> Python Code: import graphlab products = graphlab.SFrame('amazon_baby_subset.gl/') products['sentiment'] products.head(10)['name'] print '# of positive reviews =', len(products[products['sentiment']==1]) print '# of negative reviews =', len(products[products['sentiment']==-1]) import json with open...
<SYSTEM_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 review dataset Step2: One column of this dataset is 'sentiment', corresponding to the class label with +1 indicating a review with positiv...
2,593
<ASSISTANT_TASK:> Python Code: # Load pickled data import pickle import tensorflow as tf import numpy as np # TODO: Fill this in based on where you saved the training and testing data training_file = 'traffic-signs-data/train.p' validation_file= 'traffic-signs-data/valid.p' testing_file = 'traffic-signs-data/test.p' wi...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Step 1 Step2: Include an exploratory visualization of the dataset Step3: Step 2 Step4: Model Architecture Step5: Train, Validate and Test th...
2,594
<ASSISTANT_TASK:> Python Code: from lxml import etree tree = etree.parse("data/books.xml") print(tree) print(etree.tostring(tree)) print(etree.tostring(tree).decode()) print(etree.tostring(tree, pretty_print=True).decode()) print(len(list(tree.iterfind("//book")))) for node in tree.iterfind("//book"): print(no...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: For the record, we should mention that there exist many other libraries in Python to parse XML, such as minidom or BeautifulSoup which is an int...
2,595
<ASSISTANT_TASK:> Python Code: %matplotlib inline import sys import numpy as np import pandas as pd import json import matplotlib.pyplot as plt from io import StringIO print(sys.version) print("Pandas:", pd.__version__) df = pd.read_csv('C:/Users/Peter/Documents/atlas/atlasdata/obs_types/transect.csv', parse_dates=['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: shift data to correct column Step2: use groupby and transform to fill the row Step3: shift data to correct row using a multi-Index
2,596
<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 HTML HTML('../style/code_toggle.html') #soccer = mpimg.imread('figures/WLA_...
<SYSTEM_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 Step2: 5.1 Spatial Frequencies<a id='imaging Step3: For simplicity convert the RGB-color images to grayscale S...
2,597
<ASSISTANT_TASK:> Python Code: from lightning import Lightning from numpy import random, asarray, concatenate from sklearn import datasets lgn = Lightning(ipython=True, host='http://public.lightning-viz.org') imgs = datasets.load_sample_images().images lgn.image(imgs[0]) imgs = datasets.load_sample_images().images 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: Connect to server Step2: <hr> Basic image viewing Step3: Single-channel images will automatically be presented as grayscale. Step4: The usual...
2,598
<ASSISTANT_TASK:> Python Code: import numpy as np import tensorflow as tf from tensorflow import keras from tensorflow.keras import layers from tqdm import tqdm # Model / data parameters num_classes = 10 input_shape = (28, 28, 1) n_residual_blocks = 5 # The data, split between train and test sets (x, _), (y, _) = kera...
<SYSTEM_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: Create two classes for the requisite Layers for the model Step3: Build the model based on the original paper Step4: D...
2,599
<ASSISTANT_TASK:> Python Code: from __future__ import print_function import openpathsampling as paths try: import openmm as omm import openmm.unit as u except ImportError: # OpenMM < 7.6 import simtk.openmm as omm import simtk.unit as u import mdtraj as md import openpathsampling.engines.openmm as eng #...
<SYSTEM_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 Alanine in Vacuum and run it using OPS. Step2: Let's have a look at the content Step3: An OpenMM simulation in OPS needs 3 ingredients ...