Unnamed: 0
int64
0
15.9k
cleaned_code
stringlengths
67
124k
cleaned_prompt
stringlengths
168
30.3k
3,500
<ASSISTANT_TASK:> Python Code: %matplotlib inline import matplotlib.pyplot as plt import numpy as np %load_ext Cython %%cython cimport cython cimport numpy as np @cython.wraparound(False) @cython.boundscheck(False) def cython_diff2d(np.ndarray[double, ndim=2] u,np.ndarray[double, ndim=2] v, double dx2, double dy2, doub...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Parametry symulacji Step2: Walidacja wyników Step3: znamy rozwiązanie równania dyfuzji na nieskończonym obszarze startujące z punktu Step5: ...
3,501
<ASSISTANT_TASK:> Python Code: import pandas as pd x=pd.DataFrame() #Mejor hasta ahora for m in range(1995,2018): if m < 2016: o='.xlsx' else: o='.xls' if m < 2000: sK=3 else: sK=2 n='Precio_Bolsa_Nacional_($kwh)_' + str(m) + o y=pd.read_excel(n, skiprows=sK...
<SYSTEM_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.-- Compute e imprima el número de registros con datos faltantes. Step2: 3.-- Compute e imprima el número de registros duplicados. Step3: 4.-...
3,502
<ASSISTANT_TASK:> Python Code: from pymldb import Connection mldb = Connection() %%bash mkdir -p /mldb_data/data curl "file://mldb/mldb_test_data/ml-20m.zip" 2>/dev/null > /mldb_data/data/ml-20m.zip unzip /mldb_data/data/ml-20m.zip -d /mldb_data/data %%bash head /mldb_data/data/ml-20m/README.txt %%bash head /mldb_dat...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Download the MovieLens 20M data Step3: Load the data into MLDB Step4: Take a peek at the dataset Step5: Singular Value Decomposition (SVD) St...
3,503
<ASSISTANT_TASK:> Python Code: N = 6000 known_labels_ratio = 0.1 X, y = make_moons(n_samples=N, noise=0.1, shuffle=True) rp = np.random.permutation(int(N/2)) data_P = X[y==1][rp[:int(len(rp)*known_labels_ratio)]] data_U = np.concatenate((X[y==1][rp[int(len(rp)*known_labels_ratio):]], X[y==0]), axis=0) print("Amount of ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Transductive PU learning
3,504
<ASSISTANT_TASK:> Python Code: DISPLAY_ROWS = 6 # screen is 6 pixels tall DISPLAY_COLS = 50 # screen is 50 pixels wide display = [ # set display pixels to False [False for i in range(0, DISPLAY_COLS)] for i in range(0, DISPLAY_ROWS)] def rect(display, a, b): '''rect AxB turns on all of the pixels in ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Instructions patterns and handlers Step2: Retrieving the input Step3: Counting number of pixels that are ON Step4: Part Two
3,505
<ASSISTANT_TASK:> Python Code: import skrf as rf ring_slot = rf.Network('data/ring slot.s2p') from skrf.data import ring_slot ring_slot short = rf.data.wr2p2_short delayshort = rf.data.wr2p2_delayshort short - delayshort short/delayshort short = rf.data.wr2p2_short line = rf.data.wr2p2_line delayshort = line ** ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: If this produces an error, please see the installation tutorial. Step2: If you cant find ring slot.s2p, then just import it from the skrf.data ...
3,506
<ASSISTANT_TASK:> Python Code: from sklearn.model_selection import train_test_split, KFold from sklearn.linear_model import LinearRegression, Ridge, SGDRegressor, ElasticNet from sklearn.kernel_ridge import KernelRidge from sklearn.svm import SVR from sklearn.ensemble import RandomForestRegressor, GradientBoostingRegre...
<SYSTEM_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 WAS TAKEN FROM https Step2: Women is coded as 1 vs Man being 0 so that's why there is negative correlation between sex and shoe size ...
3,507
<ASSISTANT_TASK:> Python Code: import pandas as pd import numpy as np import matplotlib.pyplot as plt %matplotlib inline # read data df = pd.read_csv('HR_comma_sep.csv') # print first rows df.head() # print info, we have no nulls df.info() # describe numeric columns # satisfaction_level and last_evaluation seems percen...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Probability, Expectation Values, and Variance Step2: There seems to be a difference but before we draw any conclusion we would need to perform ...
3,508
<ASSISTANT_TASK:> Python Code: from dynamite.operators import sigmax, sigmaz, index_sum, op_sum # the None default argument will be important later def build_hamiltonian(L): interaction = op_sum(index_sum(sigmax(0)*sigmax(i), size=L) for i in range(1,L)) uniform_field = 0.5*index_sum(sigmaz(), size=L) retur...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: If we look at the nonzero structure of the matrix, it's not at all clear that it's block diagonal Step2: This is a graphical representation of ...
3,509
<ASSISTANT_TASK:> Python Code: %matplotlib inline import yahoo_finance from yahoo_finance import Share import numpy as np import pandas import matplotlib.pyplot as plt import datetime import cvxopt as opt from cvxopt import blas, solvers # We will do a lot of optimizations, # and don't want to see each step. solvers.o...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: getTimeSeries( ticker, start_date, end_date) Step2: getMultTimeSeries( tickers, start_date, end_date) Step7: markowitzReturns( returns) Step8:...
3,510
<ASSISTANT_TASK:> Python Code: # restart your notebook if prompted on Colab try: import verta except ImportError: !pip install verta HOST = "app.verta.ai" PROJECT_NAME = "Census Income Classification" EXPERIMENT_NAME = "Logistic Regression" WORKSPACE = "XXXXX" import os os.environ['VERTA_EMAIL'] = 'XXXXXXXXXX'...
<SYSTEM_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 example features Step2: Phase 1 Step3: Prepare data Step4: Prepare hyperparameters Step5: Train models Step6: Revisit Workflow Step7: ...
3,511
<ASSISTANT_TASK:> Python Code: %matplotlib inline import matplotlib.pyplot as plt from jyquickhelper import add_notebook_menu add_notebook_menu() from mlstatpy.data.wikipedia import download_pageviews import os from datetime import datetime download_pageviews(datetime(2018,2,1), folder=".") with open("pageviews-20180...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Récupérer un fichier wikipédia Step2: On ne garde que les pages françaises. Step3: Les données sont biaisées car les pages non démandées par l...
3,512
<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: Sparsity preserving clustering Keras example Step2: Train a tf.keras model for MNIST to be pruned and clustered Step3: Evaluate the baseline m...
3,513
<ASSISTANT_TASK:> Python Code: from databaker.framework import * # put your input-output files here inputfile = "example1.xls" outputfile = "example1.csv" previewfile = "preview.html" from databaker.framework import * tab = loadxlstabs("example1.xls", sheetids="stones", verbose=True)[0] print(tab) cellbag = tab 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: Cell bag selection Step2: cellbag.is_XXX() Step3: cellbag.filter(word) Step4: cellbag1.union(cellbag2) Step5: cellbag1.waffle(cellbag2) Step...
3,514
<ASSISTANT_TASK:> Python Code: import math def euclidean_distance(x1, y1, x2, y2): return math.sqrt((x1 - x2) ** 2 + (y1-y2) ** 2) euclidean_distance(0,0,1,1) values_list = [0,0,1,1] euclidean_distance(*values_list) values_tuple = (0,0,1,1) euclidean_distance(*values_tuple) values_dict = { 'x1': 0, 'y1': 0, 'x2':...
<SYSTEM_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 unpack a list or tuple into positional arguments using a star * Step2: Similarly, we can use double star ** to unpack a dictionary into ...
3,515
<ASSISTANT_TASK:> Python Code: import numpy as np from ray import tune def train_function(config, checkpoint_dir=None): for i in range(30): loss = config["mean"] + config["sd"] * np.random.randn() tune.report(loss=loss) api_key = "YOUR_COMET_API_KEY" project_name = "YOUR_COMET_PROJECT_NAME" # This ...
<SYSTEM_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, given that you provide your Comet API key and your project name like so Step2: You can add a Comet logger by specifying the callbacks argu...
3,516
<ASSISTANT_TASK:> Python Code: # Login information (Edit here or be prompted by the next cell) email = None mcurl = "https://materialscommons.org/api" # Construct a Materials Commons client from materials_commons.cli.user_config import make_client_and_login_if_necessary if email is None: print("Account (email):") ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Cloning a project Step2: Example 1 Step3: Example 2 Step4: Example 3 Step5: Using the ClonedProject Step6: File transfer Step7: Upload one...
3,517
<ASSISTANT_TASK:> Python Code: [x**2 for x in range(0,10)] [x for x in range(1,20) if x%2==0 ] [x for x in 'MATHEMATICS' if x in ['A','E','I','O','U']] for i in range(1,101): if int(i**0.5)==i**0.5: print i [i for i in range(1,101) if int(i**0.5)==i**0.5] import numpy as np # matrix = [ range(0,5), range(5...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Eg1 Step2: Eg2 Step3: Eg3 Step4: Additional examples (mentioned as exercise for users) Step5: Eg Step6: Eg Step7: The Time Advantage Step8...
3,518
<ASSISTANT_TASK:> Python Code: import collections print(collections.Counter(['a', 'b', 'c', 'a', 'b', 'b'])) print(collections.Counter({'a': 2, 'b': 3, 'c': 1})) print(collections.Counter(a=2, b=3, c=1)) import collections c = collections.Counter() print('Initial :', c) c.update('abcdaab') print('Sequence:', c) c.upda...
<SYSTEM_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 empty Counter can be constructed with no arguments and populated via the update() method Step2: Accessing Counts Step3: The elements() meth...
3,519
<ASSISTANT_TASK:> Python Code: %matplotlib inline import numpy as np from numpy import nonzero import matplotlib.pyplot as plt # to generate plots from mpl_toolkits.basemap import Basemap # plot on map projections import matplotlib.dates as mdates import datetime from netCDF4 import Dataset # 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: 2. Set and read input NetCDF file info Step2: 2.2 Parse time Step3: 3. Subregion for nino3 area Step4: time Step5: Get Index using np.nonzer...
3,520
<ASSISTANT_TASK:> Python Code: #import modules import numpy as np from matplotlib import pyplot as plt # Help function def is_zero_vector(v): Check whether vector v is a zero vector Arguments: - v : vector Return: - True if v is a nonzero vector. Otherwise, false ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: ★ Eigenvalues And Singular Values ★ Step3: 12.1 power Iteration methods Step4: Example Step6: Theorem Step7: Example Step9: Rayleigh Quotie...
3,521
<ASSISTANT_TASK:> Python Code: import magma as m import mantle @m.circuit.combinational def full_adder(A: m.Bit, B: m.Bit, C: m.Bit) -> (m.Bit, m.Bit): return A ^ B ^ C, A & B | B & C | C & A # sum, carry import fault tester = fault.PythonTester(full_adder) assert tester(1, 0, 0) == (1, 0), "Failed" assert teste...
<SYSTEM_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 full adder has three single bit inputs, and returns the sum and the carry. The sum is the exclusive or of the 3 bits, the carry is 1 if any tw...
3,522
<ASSISTANT_TASK:> Python Code: %matplotlib inline import openpathsampling as paths import numpy as np import matplotlib.pyplot as plt import pandas as pd from openpathsampling.visualize import PathTreeBuilder, PathTreeBuilder from IPython.display import SVG, HTML def ipynb_visualize(movevis): Default settings to sh...
<SYSTEM_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 Replica TIS Step2: Open the storage and load things from it. Step3: One of the points of SRTIS is that we use a bias (which comes from ...
3,523
<ASSISTANT_TASK:> Python Code: from os import path as p, chdir if 'examples' in p.abspath('.'): chdir('..') from riko.modules.fetchpage import pipe url = 'https://news.ycombinator.com/' next(pipe(conf={'url': url, 'start': '<title>', 'end': '</title>'})) from riko.modules.xpathfetchpage import pipe xpath = '/html...
<SYSTEM_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: Fetch a webpage using an xpath Step3: Word Count Step4: Fetching feeds Step5: Please see the FAQ for a complete list of supp...
3,524
<ASSISTANT_TASK:> Python Code: import sys sys.path.append('..') import socnet as sn sn.node_size = 3 sn.node_color = (0, 0, 0) sn.edge_width = 1 sn.edge_color = (192, 192, 192) sn.node_label_position = 'top center' g = sn.load_graph('twitter.gml') sn.show_graph(g, nlab=True) <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: Carregando e visualizando o grafo
3,525
<ASSISTANT_TASK:> Python Code: from sklearn.datasets import load_iris iris = load_iris() X = iris.data y = iris.target from sklearn.cross_validation import cross_val_score from sklearn.svm import LinearSVC cross_val_score(LinearSVC(), X, y, cv=5) cross_val_score(LinearSVC(), X, y, cv=5, scoring="f1_macro") y % 2 cross...
<SYSTEM_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 go to a binary task for a moment Step2: Implementing your own scoring metric Step3: There are other ways to do cross-valiation Step4: E...
3,526
<ASSISTANT_TASK:> Python Code: !sudo chown -R jupyter:jupyter /home/jupyter/training-data-analyst # Ensure the right version of Tensorflow is installed. !pip freeze | grep tensorflow==2.5 import numpy as np from matplotlib import pyplot as plt import tensorflow as tf print(tf.__version__) x = tf.constant([2, 3, 4]) 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: Operations on Tensors Step2: Point-wise operations Step3: NumPy Interoperability Step4: You can convert a native TF tensor to a NumPy array u...
3,527
<ASSISTANT_TASK:> Python Code: # Inicializacao %matplotlib inline import numpy as np from matplotlib import pyplot as plt # Abrindo conjunto de dados import csv with open("biometria.csv", 'rb') as f: dados = list(csv.reader(f)) rotulos_volei = [d[0] for d in dados[1:-1] if d[0] is 'V'] rotulos_futebol = [d[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: Teorema de Bayes Step2: Podemos verificar a estabilidade do modelo para diferentes tamanhos de conjunto de treino de forma semelhante a que fiz...
3,528
<ASSISTANT_TASK:> Python Code: %matplotlib inline %config InlineBackend.figure_format = 'retina' import numpy as np import pandas as pd import matplotlib.pyplot as plt import math data_path = 'Bike-Sharing-Dataset/hour.csv' rides = pd.read_csv(data_path) rides.head() rides[:24*10].plot(x='dteday', y='cnt') 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: Load and prepare the data Step2: Checking out the data Step3: Dummy variables Step4: Scaling target variables Step5: Splitting the data into...
3,529
<ASSISTANT_TASK:> Python Code: %%sh # ls -l ~/Downloads/G20*csv # mv ~/Downloads/G20*csv G20.csv data = pd.read_csv('G20.csv') cols = ['Area', 'Population_2010', 'Population_2011', 'Population_2012', 'Population_2013', 'Population_2014', 'Population_2015', 'GDP_2010', 'GDP_2011', 'GDP_2012', 'GDP_2013', ...
<SYSTEM_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 Cleanup Step2: Experiments Step3: Ideas Step4: IRIS Dataset Step5: Random Forest Step6: SVM
3,530
<ASSISTANT_TASK:> Python Code: %pylab inline import astropy.table import astropy.cosmology import astropy.io.fits as fits import astropy.units as u import os.path assert 'DESIMODEL' in os.environ assert os.path.exists(os.path.join(os.getenv('DESIMODEL'), 'data', 'spectra', 'spec-sky.dat')) import desimodel import spe...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Parts of this notebook assume that the desimodel package is installed (both its git and svn components) and its data/ directory is accessible vi...
3,531
<ASSISTANT_TASK:> Python Code: import os import zipfile from math import log, sqrt import numpy as np import pandas as pd from sklearn import linear_model import matplotlib as mpl import matplotlib.pyplot as plt import seaborn as sns sns.set_style('darkgrid') %matplotlib inline # Put files in current direction into 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: Unzipping files with house sales data Step2: Load in house sales data Step3: Create new features Step4: Squaring bedrooms will increase the s...
3,532
<ASSISTANT_TASK:> Python Code: %matplotlib inline import matplotlib.pyplot as plt import seaborn as sns import numpy as np sns.set_style('white') from scipy.interpolate import griddata xb = np.array([-5,-4,-3,-2,-1,0,1,2,3,4,5]) yb = np.array([-5,-5,-5,-5,-5,-5,-5,-5,-5,-5,-5]) yt = np.array([5]*11) yc = np.array(0) 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: Sparse 2d interpolation Step2: The following plot should show the points on the boundary and the single point in the interior Step3: Use meshg...
3,533
<ASSISTANT_TASK:> Python Code: import random num = [random.randint(0,10) for i in range(1000)] hist = {} for i in num: hist[i] = hist.get(i, 0) + 1 hist def count1(num): hist = {} for i in num: hist[i] = hist.get(i, 0) + 1 return hist %timeit count1(num) def count2(num): hist = {} 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: Mesurer le temps que cela prend Step2: Comparons avec une autre implémentation Step3: Et une dernière version, la plus rapide
3,534
<ASSISTANT_TASK:> Python Code: # DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'dwd', 'sandbox-3', 'aerosol') # Set as follows: DOC.set_author("name", "email") # TODO - please enter value(s) # Set as follows: DOC.set_contributor("name", "ema...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Document Authors Step2: Document Contributors Step3: Document Publication Step4: Document Table of Contents Step5: 1.2. Model Name Step6: 1...
3,535
<ASSISTANT_TASK:> Python Code: year = arange(1955,2005,5) y = array([ -0.0480, -0.0180, -0.0360, -0.0120, -0.0040, 0.1180, 0.2100, 0.3320, 0.3340, 0.4560 ]) fig,ax = subplots() ax.scatter(year,y,color="k",label="data") xlabel("year") ylabel("anomaly (degrees C)") title("World temperature anomaly"); t = (year-1950)...
<SYSTEM_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 polynomial interpolant can be used to fit the data. Here we build one using a Vandermonde matrix. First, though, we express time as decades si...
3,536
<ASSISTANT_TASK:> Python Code: # Copyright 2019 The TensorFlow Hub Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: BigBiGAN으로 이미지 생성하기 Step2: 설정 Step7: 이미지를 표시하는 일부 함수 정의하기 Step8: BigBiGAN TF Hub 모듈을 로드하고 사용 가능한 기능 표시하기 Step19: 다양한 함수에 편리하게 액세스할 수 있도록 래퍼 ...
3,537
<ASSISTANT_TASK:> Python Code: DON'T MODIFY ANYTHING IN THIS CELL import helper import problem_unittests as tests source_path = 'data/small_vocab_en' target_path = 'data/small_vocab_fr' source_text = helper.load_data(source_path) target_text = helper.load_data(target_path) view_sentence_range = (10, 20) DON'T MODIFY 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: Language Translation Step3: Explore the Data Step6: Implement Preprocessing Function Step8: Preprocess all the data and save it Step10: Chec...
3,538
<ASSISTANT_TASK:> Python Code: import numpy as np import matplotlib.pyplot as plt import seaborn as sns sampling_rate = 20 # This quantity is on Hertz step = 1.0 / sampling_rate Tmax = 20.0 time = np.arange(0, Tmax, step) N_to_use = 1024 # Should be a power of two. print("The smalles frequency that the FFT will disce...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Size of the FFT Step2: Analysis of the sampling rate on the limits of what the FFT can tell us. Step3: A word about frequencies units and the ...
3,539
<ASSISTANT_TASK:> Python Code: # Authors: Alexandre Gramfort <alexandre.gramfort@inria.fr> # Stefan Appelhoff <stefan.appelhoff@mailbox.org> # Richard Höchenberger <richard.hoechenberger@gmail.com> # # License: BSD-3-Clause import os.path as op import numpy as np import matplotlib.pyplot as plt import...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Set parameters Step2: Frequency analysis Step3: Now, let's take a look at the spatial distributions of the PSD, averaged Step4: Alternatively...
3,540
<ASSISTANT_TASK:> Python Code: %matplotlib inline import matplotlib.pyplot as plt #Load libraries for data processing import pandas as pd #data processing, CSV file I/O (e.g. pd.read_csv) import numpy as np from scipy.stats import norm ## Supervised learning. from sklearn.preprocessing import StandardScaler from sklear...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Classification with cross-validation Step2: To get a better measure of prediction accuracy (which you can use as a proxy for “goodness of fit” ...
3,541
<ASSISTANT_TASK:> Python Code: # install Pint if necessary try: import pint except ImportError: !pip install pint # download modsim.py if necessary from os.path import exists filename = 'modsim.py' if not exists(filename): from urllib.request import urlretrieve url = 'https://raw.githubusercontent.com/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: To paraphrase two Georges, "All models are wrong, but some models are Step2: When this function is called, it modifies bikeshare. As long as th...
3,542
<ASSISTANT_TASK:> Python Code: import graphlab sales = graphlab.SFrame('kc_house_data.gl/') # In the dataset, 'floors' was defined with type string, # so we'll convert them to int, before using it below sales['floors'] = sales['floors'].astype(int) import numpy as np # note this allows us to refer to numpy as np in...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Load in house sales data Step2: If we want to do any "feature engineering" like creating new features or adjusting existing ones we should do t...
3,543
<ASSISTANT_TASK:> Python Code: def arb(M): for x in M: return x assert False, 'Error: arb called with empty set!' def cart_prod(A, B): return { (x, y) for x in A for y in B } def separate(Pairs, States, Σ, 𝛿): Result = { (q1, q2) for q1 in States for q2 in States ...
<SYSTEM_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 function cart_prod(A, B) computes the Cartesian product $A \times B$ of the sets $A$ and $B$ where $A \times B$ is defined as follows Step2:...
3,544
<ASSISTANT_TASK:> Python Code: %pylab inline np.random.seed(0) p = [3.2, 5.6, 9.2] x = np.arange(-8., 5., 0.1) y = np.polyval(p, x) + np.random.randn(x.shape[0])*1. plt.plot(x, y); # STEP 1 - define your model def my_model(p, x): return np.polyval(p, x) # STEP 2 - define your cost function def my_costfun(p, x, y): ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: MCMC (emcee) Step2: a simple example - draw sample from uniformly distribution Step3: how about Gaussian distribution? Step4: how to use MCMC...
3,545
<ASSISTANT_TASK:> Python Code: import torch from torch.autograd import Variable import torch.nn as nn import torch.nn.functional as F import torch.utils.data as data_utils import numpy as np word_pair = [['고양이', '흰'], ['고양이', '동물'], ['국화', '흰'], ['국화', '식물'], ['선인장',...
<SYSTEM_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. Dataset 준비 Step2: Dataset Loader 설정 Step3: 2. 사전 설정 Step4: 3. Trainning loop Step5: 4. Predict & Evaluate Step6: 5. plot embedding space...
3,546
<ASSISTANT_TASK:> Python Code: import matplotlib.pyplot as plt %matplotlib inline import cartopy import cartopy.crs as ccrs ax = plt.axes(projection=ccrs.PlateCarree()) ax.coastlines() print('axes type:', type(ax)) ax = plt.axes(projection=ccrs.PlateCarree()) ax.coastlines() ax.set_global() plt.plot([-100, 50], [25...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Then let's import the cartopy Step2: In addition, we import cartopy's coordinate reference system submodule Step3: Creating GeoAxes Step4: He...
3,547
<ASSISTANT_TASK:> Python Code: import seaborn as sns import matplotlib.pyplot as plt %matplotlib inline from sklearn.datasets import make_blobs #create data data = make_blobs(n_samples=200,n_features=2,centers=4,cluster_std=1.8,random_state=101) plt.scatter(data[0][:,0],data[0][:,1],c=data[1],cmap='rainbow') from 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: Create some data Step2: Visualize data Step3: Creating Clusters
3,548
<ASSISTANT_TASK:> Python Code: from pytrends.request import TrendReq google_username = "mm.trends.api@gmail.com" google_password = "" path = "" # connect to Google pytrend = TrendReq(google_username, google_password, custom_useragent='Pytrends') trend_payload = {'q': 'Pizza, Italian, Spaghetti, Breadsticks, Sausage', '...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: GOOGLEINDEX_US
3,549
<ASSISTANT_TASK:> Python Code: %run db2.ipynb %%sql -q DROP TABLE CENTRAL_LINE; CREATE TABLE CENTRAL_LINE ( STATION_NO INTEGER GENERATED ALWAYS AS IDENTITY, STATION VARCHAR(31), UPPER_STATION VARCHAR(31) GENERATED ALWAYS AS (UCASE(STATION)) ) ; INSERT INTO CENTRAL_LINE(STATION) VALUES 'West Ruislip','Ruisl...
<SYSTEM_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 of Contents Step2: Back to Top Step3: The pattern 'Ruislip' will look for a match of Ruislip Step4: If you didn't place the % at the be...
3,550
<ASSISTANT_TASK:> Python Code: DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE from urllib.request import urlretrieve from os.path import isfile, isdir from tqdm import tqdm import problem_unittests as tests import tarfile cifar10_dataset_folder_path = 'cifar-10-batches-py' # Use Floyd's cifar-10 dataset if ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Image Classification Step2: Explore the Data Step5: Implement Preprocess Functions Step8: One-hot encode Step10: Randomize Data Step12: Che...
3,551
<ASSISTANT_TASK:> Python Code: import numpy as np import pandas as pd import torch a, b = load_data() ab = torch.cat((a, b), 0) <END_TASK>
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description:
3,552
<ASSISTANT_TASK:> Python Code: import numpy as np import pandas as pd import math import cmath from scipy.optimize import root import matplotlib.pyplot as plt %matplotlib inline a = ("Table1.txt") a class InterfazPolimero: def __init__ (self,a): self.a=a def Lire(self): self.tab = 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: Polymère Step2: Calcul de la concentration finale Step3: Table des valeurs Step4: Calcul de c2 Step5: Graphique Step6: Graphique Step7: ...
3,553
<ASSISTANT_TASK:> Python Code: #@title Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writin...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: 使用 TensorFlow Transform 预处理数据 Step2: 安装 TensorFlow Transform Step3: 是否已重新启动运行时? Step4: 数据:创建一些虚拟数据 Step6: Transform:创建一个预处理函数 Step7: 总结
3,554
<ASSISTANT_TASK:> Python Code: import matplotlib.pyplot as plt import numpy as np import pandas as pd %matplotlib inline # Code here from sklearn.datasets import load_iris iris_dataset = load_iris() features = iris_dataset.feature_names data = iris_dataset.data targets = iris_dataset.target df = pd.DataFrame(data, 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: Question 1 Step2: Question 2 Step3: Create a pair-plot of the iris dataset similar to this figure using only numpy and Step4: Question 3
3,555
<ASSISTANT_TASK:> Python Code: import numpy as np # Configurable test settings channel_count = 3 # Simulate sampling from multiple channels. sample_count = 8 # Number of samples (each sample -> one value per channel). N = channel_count * sample_count src_data = np.arange(1, N + 1, dtype='uint8') src_chunks = [src_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: Simulate concatenate behaviour on host (i.e., using numpy) Step2: Device Step3: Allocate arrays Step4: Create Transfer Control Descriptor (TC...
3,556
<ASSISTANT_TASK:> Python Code: from notebook_preamble import J, V, define define('pair_up == dup uncons swap unit concat zip') J('[1 2 3] pair_up') J('[1 2 2 3] pair_up') define('total_matches == 0 swap [i [=] [pop +] [popop] ifte] step') J('[1 2 3] pair_up total_matches') J('[1 2 2 3] pair_up total_matches') define...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: I'll assume the input is a Joy sequence of integers (as opposed to a string or something else.) Step2: Now we need to derive total_matches. It...
3,557
<ASSISTANT_TASK:> Python Code: import tensorflow as tf import shutil print(tf.__version__) tf.enable_eager_execution() CSV_COLUMN_NAMES = ["fare_amount","dayofweek","hourofday","pickuplon","pickuplat","dropofflon","dropofflat"] CSV_DEFAULTS = [[0.0],[1],[0],[-74.0], [40.0], [-74.0], [40.7]] def parse_row(row): fie...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Input function reading from CSV Step2: Run the following test to make sure your implementation is correct Step3: Exercise 2 Step4: Tests Step...
3,558
<ASSISTANT_TASK:> Python Code: print(conf.toDebugString()) #Instance of SparkConf with options set by the extension conf.setAppName('ExtensionTestingApp') #conf.setMaster('spark://dell-inspiron:7077') # if master is started using command line conf.setMaster('local[*]') from pyspark import SparkContext sc=SparkContext....
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: User adds other options and starts the spark context Step2: Example spark job
3,559
<ASSISTANT_TASK:> Python Code: import sys # system module import pandas as pd # data package import matplotlib.pyplot as plt # graphics module import datetime as dt # date and time module import numpy as np %matplotlib inline plt.style.use("gg...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Quandl <a id=data></a> Step2: We can also pass start_date and end_date parameters to control the dates for the downloaded data Step3: Now, let...
3,560
<ASSISTANT_TASK:> Python Code: %matplotlib inline # Arrays import numpy as np # Plotting import matplotlib.pyplot as plt # pairinteraction :-) from pairinteraction import pireal as pi qd = pi.QuantumDefect("Rb", 50, 0, 0.5) print("Core polarizability: ac =",qd.ac) print("Effective coulomb potential") print(" Z ="...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Our code starts with loading the required modules for the computation. It is irrelevant whether we use the pireal or picomplex modules here, bec...
3,561
<ASSISTANT_TASK:> Python Code: %load_ext autoreload %autoreload 2 import copy import os import pandas as pd import matplotlib.pyplot as plt import tsam.timeseriesaggregation as tsam %matplotlib inline raw = pd.read_csv('testdata.csv', index_col = 0) def plotTS(data, periodlength, vmin, vmax, label = 'T [°C]'): 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: Input data Step2: Create a plot function for the temperature for a visual comparison of the time series Step3: Hierarchical aggregation with m...
3,562
<ASSISTANT_TASK:> Python Code: from os import path as op import numpy as np import matplotlib.pyplot as plt import mne from mne.forward import make_forward_dipole from mne.evoked import combine_evoked from mne.simulation import simulate_evoked data_path = mne.datasets.sample.data_path() subjects_dir = op.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: Let's localize the N100m (using MEG only) Step2: Calculate and visualise magnetic field predicted by dipole with maximum GOF Step3: Estimate t...
3,563
<ASSISTANT_TASK:> Python Code: from os.path import basename, exists def download(url): filename = basename(url) if not exists(filename): from urllib.request import urlretrieve local, _ = urlretrieve(url, filename) print("Downloaded " + local) download("https://github.com/AllenDowney/Thin...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Exponential distribution Step2: Here's the distribution of interarrival times from a dataset of birth times. Step3: Here's what the CCDF looks...
3,564
<ASSISTANT_TASK:> Python Code: config = configparser.ConfigParser() config.sections() config.read('example.ini') config.sections() 'bitbucket.org' in config 'bytebong.com' in config config['bitbucket.org']['User'] config['DEFAULT']['Compression'] topsecret = config['topsecret.server.com'] topsecret['ForwardX11'] topsec...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Please note that default values have precedence over fallback values. For instance, in our example the 'CompressionLevel' key was specified only...
3,565
<ASSISTANT_TASK:> Python Code: import pandas as pd url = 'https://raw.githubusercontent.com/henriquepgomide/caRtola/master/data/2019/2019-medias-jogadores.csv' medias = pd.read_csv(url) medias.head() medias.shape medias.columns qtd_atletas = len(medias['player_id'].unique()) print(qtd_atletas) posicoes = medias['play...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Quantidade única de jogadores é do mesmo tamanho do Dataframe. Step2: Para o contexto desse estudo, vamos analisar cada posição utilizada no Ca...
3,566
<ASSISTANT_TASK:> Python Code: print(" pi ~= 3.14 (two first digits).") print(" pi ~= 22/7 = {} (two first digits).".format(22.0 / 7.0)) print(" pi ~= 355/113 = {} (six first digits).".format(355.0 / 113.0)) def mathpi(): from math import pi return pi print("First method: using math.pi gives pi ~= {:.17f} (17 ...
<SYSTEM_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 method is extremely limited, and will not give you more than 13 correct digits, as math.pi is stored as a float number (limited precision)....
3,567
<ASSISTANT_TASK:> Python Code: # You want to be able to rotate scatterplots in 3D, so don't show them inline %matplotlib tk # 'pip install bunch' if you do not have 'bunch' package import bunch # Our utility code resides in module dim_reduce.py, which we import here: import dim_reduce from sklearn.decomposition impor...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Now let us apply a PCA dimensionality reduction method to the "iris" dataset (which is 4D). Step2: A 3D scatterplot should display in a separat...
3,568
<ASSISTANT_TASK:> Python Code: from auxi.tools.chemistry import thermochemistry as thermo #TODO: The following line of code is not working, and must be fixed. #thermo.convert_fact_file_to_auxi_thermo_file("path/to/factsage_file", "path/to/new_auxi_thermo_file") thermo.list_compounds() thermo.load_data_auxi('data') 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: Loading Thermochemical Data Step2: The result lists all the compounds with the phases for which data are available. Taking the compound SiO2 as...
3,569
<ASSISTANT_TASK:> Python Code: !pip install -q -U apache-beam[gcp] # Automatically restart kernel after installs import IPython app = IPython.Application.instance() app.kernel.do_shutdown(True) import os from datetime import datetime import apache_beam as beam from apache_beam.io.gcp.datastore.v1new.datastoreio impo...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Import libraries Step2: Configure GCP environment settings Step3: Authenticate your GCP account Step4: Copy the public playlist data into you...
3,570
<ASSISTANT_TASK:> Python Code: # TFlearn libraries import tflearn from tflearn.layers.conv import conv_2d, max_pool_2d from tflearn.layers.core import input_data, dropout, fully_connected from tflearn.layers.estimator import regression import tflearn.datasets.mnist as mnist # General purpose libraries import 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: Gathering Data Step2: It looks like each sample (55k samples in the training set and 10k samples in the test set). Let's just try to output 1 i...
3,571
<ASSISTANT_TASK:> Python Code: %%file sq.py def square(n): return n*n import firefly remote_sq = firefly.Client("http://127.0.0.1:8000") remote_sq.square(n=4) %%file add.py # your code here %%file credit_grade.py Program to find the credit grade of a person. import zlib import random def find_credit_grade(email)...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Let us run it as a service using firefly by running the following command in your terminal. Step2: The function will be available with the same...
3,572
<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: Basic regression Step2: Auto MPG 数据集 Step3: 数据清洗 Step4: 为了保证这个初始示例的简单性,删除这些行。 Step5: "Origin" 列实际上是分类的,而不是数字。因此,使用 pd.get_dummies 将其转换为独热码: ...
3,573
<ASSISTANT_TASK:> Python Code: # Load libraries from sklearn.model_selection import cross_val_score from sklearn.linear_model import LogisticRegression from sklearn.datasets import make_classification # Generate features matrix and target vector X, y = make_classification(n_samples = 10000, ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Generate Features And Target Data Step2: Create Logistic Regression Step3: Cross-Validate Model Using F1
3,574
<ASSISTANT_TASK:> Python Code: from ggplot import * import pandas as pd from sklearn import datasets # import iris data iris = datasets.load_iris() df1 = pd.DataFrame(iris.data, columns = iris.feature_names) df2 = pd.DataFrame(iris.target_names[iris.target]) df = pd.concat([df1, df2], axis = 1) df.head() df.columns = ...
<SYSTEM_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 Step2: geom_point (scatter plot) Step3: The plot shows that setosa class can be linearly separated from other two classes. Step4: geom_p...
3,575
<ASSISTANT_TASK:> Python Code: import opsimsummary as oss from opsimsummary import Tiling, HealpixTiles # import snsims import healpy as hp %matplotlib inline import matplotlib.pyplot as plt class NoTile(Tiling): pass noTile = NoTile() class MyTile(Tiling): def __init__(self): pass @property 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: This section pertains to how to write a new Tiling class Step2: ``` Step4: Using the class HealpixTiles
3,576
<ASSISTANT_TASK:> Python Code: import seaborn as sns; sns.set(color_codes=True) tips = sns.load_dataset("tips") ax = sns.barplot(x="day", y="total_bill", data=tips) ax = sns.barplot(x="day", y="total_bill", hue="sex", data=tips) from echarts import Echart, Legend, Bar, Axis, Line from IPython.display import HTML char...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: https
3,577
<ASSISTANT_TASK:> Python Code: import numpy as np import itertools pop_size = 60 seq_length = 100 alphabet = ['A', 'T', 'G', 'C'] base_haplotype = "AAAAAAAAAA" pop = {} pop["AAAAAAAAAA"] = 40 pop["AAATAAAAAA"] = 30 pop["AATTTAAAAA"] = 30 pop["AAATAAAAAA"] mutation_rate = 0.0001 # per gen per individual per site 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: Make population dynamic model Step2: Setup a population of sequences Step3: Add mutation Step4: Walk through population and mutate basepairs....
3,578
<ASSISTANT_TASK:> Python Code: from collatex import * collation = Collation() witness_1707 = open( "../data/sonnet/Lope_soneto_FR_1707.txt", encoding='utf-8' ).read() witness_1822 = open( "../data/sonnet/Lope_soneto_FR_1822.txt", encoding='utf-8' ).read() collation.add_plain_witness( "wit 1707", witness_1707 ) collatio...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Imagine that we are not interested in punctuation and capitalization Step2: Now, let's collate the normalized copies. Step3: Normalization 2. ...
3,579
<ASSISTANT_TASK:> Python Code: import sys sys.path.append('../../metal') import metal %load_ext autoreload %autoreload 2 %matplotlib inline import pickle with open("data/basics_tutorial.pkl", 'rb') as f: X, Y, L, D = pickle.load(f) X.shape Y.shape L.shape from metal.utils import split_data Xs, Ys, Ls, Ds = split_...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Step 1 Step2: If you need to divide your data into splits, you can do so with the provided utility function. We split our data 80/10/10 into tr...
3,580
<ASSISTANT_TASK:> Python Code: import numpy as np import os import matplotlib.pyplot as plt %matplotlib inline from cycler import cycler from pylab import rcParams rcParams['figure.figsize'] = 8, 6 rcParams.update({'font.size': 15}) # color and linestyle cycle #colors = [x['color'] for x in list(rcParams['axes.prop_cyc...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Merge multiple network definitions that share the same data layers into a single definition to train within the same single process Step2: Afte...
3,581
<ASSISTANT_TASK:> Python Code: # Load pickled data import pickle import pandas as pd # TODO: Fill this in based on where you saved the training and testing data training_file = 'data/train.p' validation_file= 'data/valid.p' testing_file = 'data/test.p' with open(training_file, mode='rb') as f: train = pickle.load(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: The MNIST data that TensorFlow pre-loads comes as 28x28x1 images. Step2: Visualize Data Step3: Preprocess Data Step4: Setup TensorFlow Step5:...
3,582
<ASSISTANT_TASK:> Python Code: %matplotlib inline from matplotlib import pyplot as plt import numpy as np def tokenize(s, stop_words=[] or '', punctuation='`~!@#$%^&*()_-+={[}]|\:;"<,>.?/}\t'): Split a string into a list of words, removing punctuation and stop words. a = s.splitlines() b = [] ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step3: Word counting Step5: Write a function count_words that takes a list of words and returns a dictionary where the keys in the dictionary are the ...
3,583
<ASSISTANT_TASK:> Python Code: %load_ext autoreload %autoreload 2 %matplotlib inline import freqopttest.util as util import freqopttest.data as data import freqopttest.kernel as kernel import freqopttest.tst as tst import freqopttest.glo as glo import matplotlib.pyplot as plt import numpy as np import scipy.stats as st...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: mean embedding test. J=2 locations Step2: This showed that if both the test locations are the same at [0, 0], then the covariance matrix is sin...
3,584
<ASSISTANT_TASK:> Python Code: import vcsn %%automaton a context = "lal_char(abc), b" $ -> 0 0 -> 1 a 1 -> $ 2 -> 0 a 1 -> 3 a a.is_accessible() a.accessible() a.accessible().is_accessible() <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: The following automaton has states that cannot be reached from the initial(s) states Step2: Calling accessible returns a copy of the automaton ...
3,585
<ASSISTANT_TASK:> Python Code: import numpy as np from sklearn.model_selection import train_test_split # Let X be our input data consisting of # 5 samples and 2 features X = np.arange(10).reshape(5, 2) # Let y be the target feature y = [0, 1, 2, 3, 4] X_train, X_test, y_train, y_test = train_test_split(X, y, test_size...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Validation Data Step2: Estimators
3,586
<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:
3,587
<ASSISTANT_TASK:> Python Code: # Installs the vit_jax package from Github. !pip install -q git+https://github.com/google-research/vision_transformer import jax import jax.numpy as jnp from matplotlib import pyplot as plt import numpy as np import pandas as pd import tensorflow as tf import tensorflow_datasets as tfds i...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Use model Step2: tfds zero-shot evaluation
3,588
<ASSISTANT_TASK:> Python Code: mondat="A " mondat+="mezőn legelésző " mondat+="bárányok " mondat+="mélyen " mondat+="hallgatnak." print(mondat) kisbetuk='qwertzuiopasdfghjklyxcvbnm' nagybetuk='QWERTZUIOPASDFGHJKLYXCVBNM' extra='+- %=.~' kicsi=['al',9,'+',42.137,'szoveg',69,1j] telefon_konyv={'Alonzo Hinton': '(855) ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: 02-egyszerű számolás Step2: 04-lista manipulálás Step3: 05-szótár kezelés Step4: 06-logikai
3,589
<ASSISTANT_TASK:> Python Code: import pandas as pd import numpy as np s = pd.Series([1,3,5,np.nan,6,8]) s dates = pd.date_range('20130101', periods=6) dates df = pd.DataFrame(np.random.randn(6,4), index=dates, columns=list('ABCD')) df df2 = pd.DataFrame({ 'A' : 1., 'B' : pd.Timestamp('20130102'), 'C' : pd.Seri...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Series Step2: DataFrame Step3: Creating a DataFrame by passing a dict of objects that can be converted to series-like. Step4: Panel Step5: V...
3,590
<ASSISTANT_TASK:> Python Code: # Jupyter setup to expand cell display to 100% width on your screen (optional) from IPython.core.display import display, HTML display(HTML("<style>.container { width:100% !important; }</style>")) # Import relevant modules and setup for calling glmnet %reset -f %matplotlib inline import sy...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: As an example, we set $\alpha = 0.2$ (more like a ridge regression), and give double weights to the latter half of the observations. To avoid to...
3,591
<ASSISTANT_TASK:> Python Code: # from qiita_db.study import Study # from shutil import copy # from os import mkdir # ffp = '/home/qiita/emp-sample-info-files' # study_ids = [ 550, 632, 638, 659, 662, 678, 713, 714, 722, 723, # 755, 776, 804, 805, 807, 808, 809, 810, 829...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Porting refined EMP metadata to Qiita sample info files Step2: Replace or add columns Step3: Export action columns for problem studies
3,592
<ASSISTANT_TASK:> Python Code: import math def funcion(x): return (math.pow(math.e,6*x))+(1.44*math.pow(math.e,2*x))-(2.079*math.pow(math.e,4*x))-(0.333) def biseccion(intA, intB, errorA, noMaxIter): if(funcion(intA)*funcion(intB)<0): noIter = 0 errorTmp = 1 intTmp = 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: <h1>Intento de algoritmo de regla falsa</h1> Step2: <h1>(testing) Intento de algoritmo de Newton - Raphson (en x^10 -1)</h1> Step3: <h1>Intent...
3,593
<ASSISTANT_TASK:> Python Code: from __future__ import division import google.datalab.bigquery as bq import matplotlib.pyplot as plot import numpy as np %bq tables list --project cloud-datalab-samples --dataset httplogs %bq tables describe -n cloud-datalab-samples.httplogs.logs_20140615 %%bq query -n logs SELECT timest...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Understanding the Logs Data Step2: Transforming Logs into a Time Series Step3: Visualizing the Time Series Data Step4: Anomaly Detection Step...
3,594
<ASSISTANT_TASK:> Python Code: from dx import * import numpy as np import pandas as pd from pylab import plt plt.style.use('seaborn') h5 = pd.HDFStore('./data/vstoxx_march_2014.h5', 'r') vstoxx_index = h5['vstoxx_index'] vstoxx_futures = h5['vstoxx_futures'] vstoxx_options = h5['vstoxx_options'] h5.close() %matplot...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: VSTOXX Futures & Options Data Step2: VSTOXX index for the first quarter of 2014. Step3: The VSTOXX futures data (8 futures maturities/quotes p...
3,595
<ASSISTANT_TASK:> Python Code: import numpy as np import matplotlib.pyplot as plt from gatspy.periodic import LombScargle import sys %matplotlib inline from toy_simulator import simulate_LSST from trilegal_models import random_stars import simple_gyro as sg import pandas as pd fname = "output574523944248.dat" N = 100 ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Randomly select targets from a TRILEGAL output. Step2: Calculate periods from ages and colours for cool stars Step3: Draw from a sum of two Ga...
3,596
<ASSISTANT_TASK:> Python Code: import pysal.lib import numpy as np from pysal.explore.giddy.directional import Rose %matplotlib inline f = open(pysal.lib.examples.get_path('spi_download.csv'), 'r') lines = f.readlines() f.close() lines = [line.strip().split(",") for line in lines] names = [line[2] for line in lines[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: Visualization Step2: Inference Step3: Here all the four sector counts are signficantly different from their expectation under the null. Step4:...
3,597
<ASSISTANT_TASK:> Python Code: import matplotlib.pyplot as plt from qutip import * from qutip.piqs import * N = 10 system = Dicke(N = N) [jx, jy, jz] = jspin(N) jp = jspin(N,"+") jm = jp.dag() w0 = 1 h0 = w0 * jz gCE = 1 gP = N * gCE system.hamiltonian = h0 system.collective_emission = gCE system.pumping = gP L = sys...
<SYSTEM_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) Time evolution Step2: Liouvillian and steady state $\rho_\text{ss}$ Step3: Time integration for $g^{(2)}(\tau)$ and $\langle J_{+}J_{-}\ran...
3,598
<ASSISTANT_TASK:> Python Code: %load_ext watermark %watermark -a '' -u -d -v -p numpy,pandas,matplotlib,scipy,sklearn %matplotlib inline # Added version check for recent scikit-learn 0.18 checks from distutils.version import LooseVersion as Version from sklearn import __version__ as sklearn_version import numpy as np ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Load data Step2: Visualize data Step3: Data sets Step4: Answer Step5: Explanation Step6: Use GridSearchCV to tune hyper-parameters. Step7: ...
3,599
<ASSISTANT_TASK:> Python Code: # Setup, just putting together what we will need to do the analysis import pandas as pd import seaborn as sns import matplotlib.pyplot as plt from matplotlib.spines import Spine from matplotlib.projections.polar import PolarAxes from matplotlib.projections import register_projection %matp...
<SYSTEM_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 Matchups Step2: Status Analysis Step3: Archenemies