text_prompt
stringlengths
168
30.3k
code_prompt
stringlengths
67
124k
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Decorators with arguments Step2: Decorators with arguments Step3: Debug with arguments Step4: Decorators with arguments Step5: Class decorat...
<ASSISTANT_TASK:> Python Code: from functools import wraps def debug(func): msg = func.__name__ # wraps is used to keep the metadata of the original function @wraps(func) def wrapper(*args, **kwargs): print(msg) return func(*args, **kwargs) return wrapper @debug def add(x,y): ret...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Load the arm library-- see the Chapter 3.1 notebook if you need help. Step2: Regression-- to demonstrate reports of fit, Pg38 Step3: Display, ...
<ASSISTANT_TASK:> Python Code: %%R # I had to import foreign to get access to read.dta library("foreign") kidiq <- read.dta("../../ARM_Data/child.iq/kidiq.dta") # I won't attach kidiq-- i generally don't attach to avoid confusion(s) #attach(kidiq) %%R library("arm") %%R fit.3 <- lm(kidiq$kid_score ~ kidiq$mom_hs + ki...
<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: Create the Code Step4: Create the Nose Tests Step5: Run the Nose Tests
<ASSISTANT_TASK:> Python Code: !pip install nose %%file type_util.py class TypeUtil: @classmethod def is_iterable(cls, obj): Determines if obj is iterable. Useful when writing functions that can accept multiple types of input (list, tuple, ndarray, iterator). Pairs well with 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: Use xmltodict Step2: Use untangle
<ASSISTANT_TASK:> Python Code: # import the appropriate libraries import xml.etree.ElementTree as ET # xml processing # read the XML file tree = ET.parse('input/menu.xml') print('tree element:\t', tree) # get the root of the tree root = tree.getroot() print 'root element:\t ', root # here is the name of the root elemen...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description:
<ASSISTANT_TASK:> Python Code: from scipy import sparse V = sparse.random(10, 10, density = 0.05, format = 'coo', random_state = 42) x = 100 y = 99 V = V.copy() V.data += x V.eliminate_zeros() V.data += y V.eliminate_zeros() <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: Document Authors Step2: Document Contributors Step3: Document Publication Step4: Document Table of Contents Step5: 1.2. Model Name Step6: 2...
<ASSISTANT_TASK:> Python Code: # DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'nerc', 'ukesm1-0-ll', 'seaice') # Set as follows: DOC.set_author("name", "email") # TODO - please enter value(s) # Set as follows: DOC.set_contributor("name", "e...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Loading Model Results Step2: Using os.path.join and os.path.basename Step3: Iterating through model run directories
<ASSISTANT_TASK:> Python Code: # Imports import matplotlib.pyplot as plt import numpy import pandas import scipy import scipy.stats import os # Using os.listdir to show the current directory os.listdir("./") # Using os.listdir to show the output directory os.listdir("output")[0:5] import glob # Using glob to list the ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: KISS-GP for 1D Data Step2: Set up the model Step3: Train the model hyperparameters Step4: Make predictions Step5: KISS-GP for 2D-4D Data Ste...
<ASSISTANT_TASK:> Python Code: import math import torch import gpytorch from matplotlib import pyplot as plt # Make plots inline %matplotlib inline train_x = torch.linspace(0, 1, 1000) train_y = torch.sin(train_x * (4 * math.pi) + torch.randn(train_x.size()) * 0.2) class GPRegressionModel(gpytorch.models.ExactGP): ...
<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: The notMNIST dataset is too large for many computers to handle. It contains 500,000 images for just training. You'll be using a subset of this...
<ASSISTANT_TASK:> Python Code: import hashlib import os import pickle from urllib.request import urlretrieve import numpy as np from PIL import Image from sklearn.model_selection import train_test_split from sklearn.preprocessing import LabelBinarizer from sklearn.utils import resample from tqdm import tqdm from zipfil...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: <font size="4">Load the Data</font> Step2: <font size="4">1. Model</font> Step3: <font size="4">2. Identify</font> Step4: <font size="4">3. E...
<ASSISTANT_TASK:> Python Code: import pandas as pd import numpy as np import dowhy from dowhy import CausalModel from dowhy import causal_estimators # Config dict to set the logging level import logging.config DEFAULT_LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'loggers': { '': { ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Perplexity on Each Dataset Step2: Loss vs. Epoch Step3: Perplexity vs. Epoch Step4: Generations Step5: BLEU Analysis Step6: N-pairs BLEU An...
<ASSISTANT_TASK:> Python Code: report_file = '/Users/bking/IdeaProjects/LanguageModelRNN/reports/encdec_noing_250_512_025dr.json' log_file = '/Users/bking/IdeaProjects/LanguageModelRNN/logs/encdec_noing_250_512_025dr_logs.json' import json import matplotlib.pyplot as plt with open(report_file) as f: report = json.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: 주요 내용 Step2: 아니면, 반복문을 활용할 수 있다. Step3: for 반복문 Step4: 예제 Step5: 반면에 반복문을 활용하는 것은 언제든지 가능하다. Step6: 0과 20 사이의 홀수들의 리스트는 다음과 같다. Step7: 이제...
<ASSISTANT_TASK:> Python Code: from __future__ import division, print_function odd_20 = [1, 3, 5, 7, 9, 11, 13, 15, 17, 19] i = 0 odd_20 = [] while i <= 20: if i % 2 == 1: odd_20.append(i) i += 1 print(odd_20) odd_20 = [] for i in range(21): if i % 2 == 1: odd_20.append(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: Processing the dataset Step2: In each directory, there is one or more images corresponding to the identity. We map each image path with an inte...
<ASSISTANT_TASK:> Python Code: import tensorflow as tf # If you have a GPU, execute the following lines to restrict the amount of VRAM used: gpus = tf.config.experimental.list_physical_devices('GPU') if len(gpus) > 1: print("Using GPU {}".format(gpus[0])) tf.config.experimental.set_visible_devices(gpus[0], 'GPU...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Biomodels repository hosts a number of published models. Step2: This model can be parsed into MEANS Model object using means.io.read_sbml funct...
<ASSISTANT_TASK:> Python Code: import means import urllib __ = urllib.urlretrieve("http://www.ebi.ac.uk/biomodels/models-main/publ/" "BIOMD0000000010/BIOMD0000000010.xml.origin", filename="autoreg.xml") # Requires: libsbml autoreg_model, autoreg_parameters, autoreg_ini...
<SYSTEM_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 DataFrame also performs automatic alignment of the data for each Series passed in by a dictionary. For example, the following code adds a thir...
<ASSISTANT_TASK:> Python Code: # import NumPy and pandas import numpy as np import pandas as pd # set some pandas options pd.set_option('display.notebook_repr_html', False) pd.set_option('display.max_columns', 10) pd.set_option('display.max_rows',10) # create a DataFrame from a 2-d array pd.DataFrame(np.array([[10,11],...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Pulso cuadrado Step2: Definimos 1000 puntos en el intervalo $[-\pi,\pi]$ Step3: Función Guassiana
<ASSISTANT_TASK:> Python Code: %matplotlib inline import numpy as np import matplotlib.pyplot as plt from ipywidgets import interact plt.style.use('classic') def p(x,a): if abs(x)<a: return 1. else: return 0. pulso = np.vectorize(p) #vectorizando la función pulso x = np.linspace(-10,10,1000) k...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Note Step2: Load in the stopwords file. These are common words which we wish to exclude when performing comparisons (a, an, the, etc). Every ...
<ASSISTANT_TASK:> Python Code: import re from gensim import models from scipy import spatial import numpy as np import os.path import urllib import gzip import json import pandas as pd def search_tags(entity, search): This function searches through all the 'tags' (semantic content) of a data set and return...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Now let's load the Iris Dataset for a demo. Step2: Let's just assume class 2 as the anomaly for test purposes. Step3: Now we have 100 normal e...
<ASSISTANT_TASK:> Python Code: import math import numpy as np import scipy class AnomalyDetection(): def __init__(self, multi_variate=False): # if multi_variate is True, we will use multivariate Gaussian distribution # to estimate the probabilities self.multi_variate = multi_variate ...
<SYSTEM_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 some house value vs. crime rate data Step2: Exploring the data Step3: Fit the regression model using crime as the feature Step4: Let's s...
<ASSISTANT_TASK:> Python Code: %matplotlib inline import graphlab sales = graphlab.SFrame.read_csv('Philadelphia_Crime_Rate_noNA.csv/') sales graphlab.canvas.set_target('ipynb') sales.show(view="Scatter Plot", x="CrimeRate", y="HousePrice") crime_model = graphlab.linear_regression.create(sales, target='HousePrice', ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Scatter Plots with plt.plot Step2: The third argument in the function call is a character that represents the type of symbol used for the plott...
<ASSISTANT_TASK:> Python Code: %matplotlib inline import matplotlib.pyplot as plt plt.style.use('seaborn-whitegrid') import numpy as np x = np.linspace(0, 10, 30) y = np.sin(x) plt.plot(x, y, 'o', color='black'); rng = np.random.RandomState(0) for marker in ['o', '.', ',', 'x', '+', 'v', '^', '<', '>', 's', '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: Specify list of dates Step2: Enter Research Data Archive (NCAR) credentials Step3: Create data fetcher Step4: Access data Step5: Plot temper...
<ASSISTANT_TASK:> Python Code: %matplotlib inline import matplotlib.pyplot as plt plt.rcParams['figure.dpi'] = 150 from getpass import getpass import pandas as pd from skdaccess.framework.param_class import * from skdaccess.geo.era_interim.cache import DataFetcher as EDF date_list = pd.date_range('2015-06-06 00:00:00'...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: TODO Step2: Convert the data to Web Mercator Step3: Contextily helper function Step4: Add background tiles to plot Step5: Save selected depa...
<ASSISTANT_TASK:> Python Code: import pandas as pd import geopandas as gpd df = gpd.read_file("communes-20181110.shp") !head test.csv # https://gis.stackexchange.com/questions/114066/handling-kml-csv-with-geopandas-drivererror-unsupported-driver-ucsv df_tracks = pd.read_csv("test.csv", skiprows=3) df_tracks.head() df_...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: we'll use the gutenberg corpus as test data, which is available through the nltk library. Step2: files in test data Step3: creating test corpu...
<ASSISTANT_TASK:> Python Code: import os import json from nltk.corpus import gutenberg import corpushash as ch import base64 import hashlib import random import nltk #nltk.download('gutenberg') # comment (uncomment) if you have (don't have) the data gutenberg.fileids() base_path = os.getcwd() base_path corpus_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: We can compute a derivative symbolically, but it is of course horrendous (see below). Think of how much worse it would be if we chose a functio...
<ASSISTANT_TASK:> Python Code: from math import sin, cos def func(x): y = x for i in range(30): y = sin(x + y) return y from sympy import diff, Symbol, sin from __future__ import print_function x = Symbol('x') dexp = diff(func(x), x) print(dexp) xpt = 0.1 dfdx = dexp.subs(x, xpt) print('dfdx =', 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: Step2: Synthesizing fake data Step3: Setting up a factor analysis pipeline Step4: Demo Step5: Demo Step6: Demo Step7: Demo
<ASSISTANT_TASK:> Python Code: import os import sys sys.path.append(os.path.pardir) %matplotlib inline import numpy as np from fa_kit import FactorAnalysis from fa_kit import plotting as fa_plotting def make_random_data(n_samp=10000, n_feat=100): make some random data with correlated features data = ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: 1. Regular linear regression Step2: 1b. Outliers and normality of errors Step3: 1c. Importance of independence of samples Step5: 2. Multiple ...
<ASSISTANT_TASK:> Python Code: import numpy as np import statsmodels.formula.api as smf import pandas as pd import scipy as sp %matplotlib notebook %config InlineBackend.figure_format = 'retina' %matplotlib inline import matplotlib.pyplot as plt # Define true statistics relating x and y N_points = 10 true_beta0 = 0 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: Problem 1c Step2: Probelm 2) Fitting a Line to Data Step3: There is a very good chance, though, again, I am not specifically assuming anything...
<ASSISTANT_TASK:> Python Code: y = np.array([203, 58, 210, 202, 198, 158, 165, 201, 157, 131, 166, 160, 186, 125, 218, 146]) x = np.array([495, 173, 479, 504, 510, 416, 393, 442, 317, 311, 400, 337, 423, 334, 533, 344]) plt.scatter( # complete # complete # 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: In order to get you familiar with graph ideas, Step2: Firstly, we need to unzip the dataset Step3: Now, let's load in both tables. Step4: Now...
<ASSISTANT_TASK:> Python Code: from IPython.display import YouTubeVideo YouTubeVideo(id="3sJnTpeFXZ4", width="100%") from pyprojroot import here import zipfile import os from nams.load_data import datasets # This block of code checks to make sure that a particular directory is present. if "divvy_2013" not in os.listd...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: From now on, we will refer to this table using this variable ($miRNA_BQtable), but we could just as well explicitly give the table name each tim...
<ASSISTANT_TASK:> Python Code: import gcp.bigquery as bq miRNA_BQtable = bq.Table('isb-cgc:tcga_201607_beta.miRNA_Expression') %bigquery schema --table $miRNA_BQtable %%sql --module count_unique DEFINE QUERY q1 SELECT COUNT (DISTINCT $f, 25000) AS n FROM $t fieldList = ['ParticipantBarcode', 'SampleBarcode', 'Aliquot...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Lesson Step2: Project 1 Step3: Transforming Text into Numbers Step4: Project 2 Step5: Project 3 Step6: Understanding Neural Noise Step7: P...
<ASSISTANT_TASK:> Python Code: def pretty_print_review_and_label(i): print(labels[i] + "\t:\t" + reviews[i][:80] + "...") g = open('reviews.txt','r') # What we know! reviews = list(map(lambda x:x[:-1],g.readlines())) g.close() g = open('labels.txt','r') # What we WANT to know! labels = list(map(lambda x:x[:-1].uppe...
<SYSTEM_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 version of the Google Cloud Storage library. Step2: Restart the kernel Step3: Before you begin Step4: Otherwise, set your ...
<ASSISTANT_TASK:> Python Code: import os # The Google Cloud Notebook product has specific requirements IS_GOOGLE_CLOUD_NOTEBOOK = os.path.exists("/opt/deeplearning/metadata/env_version") # Google Cloud Notebook requires dependencies to be installed with '--user' USER_FLAG = "" if IS_GOOGLE_CLOUD_NOTEBOOK: USER_FLAG...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Next, let's define a vertical coordinate system that minimises missing data values, and gives good resolution at the (orographic) surface. Step2...
<ASSISTANT_TASK:> Python Code: %matplotlib inline import numpy as np nx, ny = 6, 3 np.random.seed(0) orography = np.random.normal(1000, 600, size=(ny, nx)) - 400 sea_level_temp = np.random.normal(290, 5, size=(ny, nx)) # Now visualise: import matplotlib.pyplot as plt plt.set_cmap('viridis') fig = plt.figure(figsize=(8,...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Now, let use the Neural Network with 1 hidden layers. The number of neurons in each layer is X_train.shape[1] which is 400 in our example (exclu...
<ASSISTANT_TASK:> Python Code: data = pd.read_csv('fer2013/fer2013.csv') df = shuffle(df) X = data['pixels'] y = data['emotion'] X = pd.Series([np.array(x.split()).astype(int) for x in X]) # convert one column as list of ints into dataframe where each item in array is a column X = pd.DataFrame(np.matrix(X.tolist())) df...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Displaying widgets Step2: Widgets have many properties to modify their appearance and behavior Step3: Layout Step4: Events Step5: Compound w...
<ASSISTANT_TASK:> Python Code: %gui asyncio from flexx import flx flx.init_notebook() b = flx.Button(text='foo') b b.set_text('click me!') None # suppress output with flx.HBox() as hbox: slider = flx.Slider(flex=1) progress = flx.ProgressBar(flex=3, value=0.7) hbox @slider.reaction('value') def show_slider...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Extract Images Step2: Image Properties Step3: This tells us that this image is 24x24 pixels in size, and that the datatype of the values it st...
<ASSISTANT_TASK:> Python Code: import cv2 import numpy as np import matplotlib.pyplot as plt import matplotlib.cm as cm %matplotlib inline rect_image = cv2.imread('data/I/27.png', cv2.IMREAD_GRAYSCALE) circle_image = cv2.imread('data/O/11527.png', cv2.IMREAD_GRAYSCALE) queen_image = cv2.imread('data/Q/18027.png'...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Overview Step2: b) Step3: Model 2 Step4: b) Step5: Model 3 Step6: b)
<ASSISTANT_TASK:> Python Code: from symbulate import * %matplotlib inline # Type all of your code for this problem in this cell. # Feel free to add additional cells for scratch work, but they will not be graded. # Type all of your code for this problem in this cell. # Feel free to add additional cells for scratch wor...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Validate lab package version installation Step2: Note Step3: Note Step4: The config.py module configures the default values for the environme...
<ASSISTANT_TASK:> Python Code: import yaml # Set `PATH` to include the directory containing TFX CLI and skaffold. PATH=%env PATH %env PATH=/home/jupyter/.local/bin:{PATH} !python -c "import tensorflow; print('TF version: {}'.format(tensorflow.__version__))" !python -c "import tfx; print('TFX version: {}'.format(tfx.__...
<SYSTEM_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 $\alpha=1$, sRVI does not converge on the (periodic) 3-loop problem.
<ASSISTANT_TASK:> Python Code: alphas = [1.0, 0.999, 0.99, 0.9, 0.7, 0.5, 0.3, 0.1, 0.01, 0.001] max_iters = 50000 epsilon = 0.001 init_v = np.zeros(env.num_states()) init_r_bar_scalar = 0 convergence_flags = np.zeros(alphas.__len__()) for i, alpha in enumerate(alphas): alg = RVI_Evaluation(env, init_v, alpha, ref_...
<SYSTEM_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: b. Spearman Rank Correlation Step3: Check your results against scipy's Spearman rank function. stats.spearmanr Step4: Exerc...
<ASSISTANT_TASK:> Python Code: import numpy as np import pandas as pd import scipy.stats as stats import matplotlib.pyplot as plt import math n = 100 x = np.linspace(1, n, n) y = x**5 #Your code goes here #Your code goes here # Your code goes here n = 100 a = np.random.normal(0, 1, n) #Your code goes here 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: The spike times of all descending commands along the 5000 ms of simulation is shown in Fig. \ref{fig Step2: The spike times of the MNs along th...
<ASSISTANT_TASK:> Python Code: import sys sys.path.insert(0, '..') import time import matplotlib.pyplot as plt %matplotlib inline from IPython.display import set_matplotlib_formats set_matplotlib_formats('pdf', 'png') plt.rcParams['savefig.dpi'] = 75 plt.rcParams['figure.autolayout'] = False plt.rcParams['figure.figs...
<SYSTEM_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 Step2: No more setup needed! We can run the simulation and plot our observables. Step4: The Mean Square Displacement of an active par...
<ASSISTANT_TASK:> Python Code: import tqdm import numpy as np import espressomd.observables import espressomd.accumulators import matplotlib.pyplot as plt plt.rcParams.update({'font.size': 18}) %matplotlib inline espressomd.assert_features( ["ENGINE", "ROTATION", "MASS", "ROTATIONAL_INERTIA", "CUDA"]) ED_PARAMS = {...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: TF简介 Step2: LR算法 Step3: LR算法简介: Step4: 添加一个隐藏层 Step5: 比较
<ASSISTANT_TASK:> Python Code: import numpy as np import pandas as pd import tensorflow as tf from sklearn.model_selection import train_test_split # 例1: a+b a = tf.placeholder(dtype=tf.float32, shape=[2]) # 定义占位符,可以feed满足相应条件的数据 b = tf.placeholder(dtype=tf.float32, shape=[2]) c = a + b with tf.Session() as sess: # 创...
<SYSTEM_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 cyc1.gb sequence file only contains the ORF, so we can use it directly. The sequence file can be inspected using the ling above. Step2: The...
<ASSISTANT_TASK:> Python Code: from pydna.readers import read cyc1 = read("cyc1.gb") cyc1 cyc1.isorf() pUG35 = read("pUG35.gb") pUG35 p426GPD = read("p426GPD.gb") p426GPD pUG35.list_features() gfp=pUG35.extract_feature(5) gfp.seq gfp.isorf() from Bio.Restriction import SmaI linear_vector= p426GPD.linearize(SmaI) 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: 1. import and plot data Step2: 2. Create a timeseries model Step3: 3. Adding river water levels
<ASSISTANT_TASK:> Python Code: import pandas as pd import pastas as ps import matplotlib.pyplot as plt ps.show_versions() ps.set_log_level("INFO") oseries = pd.read_csv("../data/nb5_head.csv", parse_dates=True, squeeze=True, index_col=0) rain = pd.read_csv("../data/nb5_prec.csv", parse_dates=Tru...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Lab 1 Step2: $\newcommand{\bPhi}{\mathbf{\Phi}}$ Step3: 1.2 Polynomial regression (10 points) Step4: 1.3 Plot (5 points) Step5: 1.4 Regulari...
<ASSISTANT_TASK:> Python Code: NAME = "Michelle Appel" NAME2 = "Verna Dankers" NAME3 = "Yves van Montfort" EMAIL = "michelle.appel@student.uva.nl" EMAIL2 = "verna.dankers@student.uva.nl" EMAIL3 = "yves.vanmontfort@student.uva.nl" %pylab inline plt.rcParams["figure.figsize"] = [20,10] import numpy as np import 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: You can add a header row like this Step2: Table also accepts dicts (or any mapping) with keys as column headers and values as column contents. ...
<ASSISTANT_TASK:> Python Code: Table((4, 1, 8), (9, 7, 3), (5, 2, 6)) Table(TableHeaderRow('a','b','c'), (1, 2, 3), (2, 4, 6), ) Table({'a': (1, 2), 'b': (2, 4), 'c': (3, 6)}) Table({'a': (1, 2), 'b': (2,), 'c': (3, 6)}) # Computing values t = Table(Table...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Training and Test Data Sets Step2: Linear Support Vector Machine Classification Step3: Evaluating performance of the model
<ASSISTANT_TASK:> Python Code: import numpy as np import pandas as pd def load_data(filename): import csv with open(filename, 'rb') as csvfile: csvreader = csv.reader(csvfile, delimiter=',') df = pd.DataFrame([[-1 if el == '?' else int(el) for el in r] for r in csvreader]) df.columns=["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: D3.js Step2: What's D3.js? Step3: A website inside a web presentation Step4: What is D3.js Step5: Scott Murray (@alignedleft) Step6: Jérôme...
<ASSISTANT_TASK:> Python Code: # Some styling from IPython.display import display, HTML from IPython.display import IFrame, Image s= <style> .rendered_html h1{ font-family: "Roboto", helvetica; color: #8896B4; !important } .rendered_html h2{ font-family: "Roboto", helvetica; color: #5C6E95; !important...
<SYSTEM_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 define a domain from -5 to 5, of 100 points, and plot some XY curves that show some functions. Step2: Now that we've plotted some data, le...
<ASSISTANT_TASK:> Python Code: import pandas as pd import numpy as np from matplotlib import pyplot as plt domain = np.linspace(-5.0,5.0,100) y = np.power(domain, 2) %matplotlib inline # "magic" command telling Jupyter NB to embed plots # always label and title your plot, at minimum plt.xlabel("X") plt.ylabel("Y") 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: Here we have a set of values, $X$, and another set of values $y$. The values of $X$ are related to $y$ by a function $f(x)$, which is described ...
<ASSISTANT_TASK:> Python Code: %matplotlib inline import numpy as np import matplotlib.pyplot as plt rng = np.random.RandomState(1999) n_samples = 1000 X = rng.rand(n_samples) y = np.sin(20 * X) + .05 * rng.randn(X.shape[0]) X_t = np.linspace(0, 1, 100) y_t = np.sin(20 * X_t) plt.scatter(X, y, color='steelblue', label=...
<SYSTEM_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. ANALYTICAL SOLUTION VS. NUMERICAL SOLUTION Step2: 2. EMPTYING AND FILLING THE UNSATURATED ZONE Step3: 3. RANDOM FORCINGS Step4: Compare pe...
<ASSISTANT_TASK:> Python Code: import numpy as np import matplotlib.pyplot as plt import timeit import pstats, cProfile from GWTSA import * print 'packages succesfully imported!' %matplotlib inline # Provide the forcings precipitation and potential evapotransapiration n = 50 P = E = np.zeros(n) # Provide the model 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: <font color=teal>2. Atomic String Function (AString) is an Integral and Composing Branch of Atomic Function up(x) (introduced in 2017 by S. Yu. ...
<ASSISTANT_TASK:> Python Code: import numpy as np import pylab as pl pl.rcParams["figure.figsize"] = 9,6 ################################################################### ##This script calculates the values of Atomic Function up(x) (1971) ################################################################### ###########...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: numpy.ndarray.tofile Step2: numpy.fromfile Step3: Then go to CUDA C++14 file binIO_playground.cu or the C++14 version (serial version), binIO_...
<ASSISTANT_TASK:> Python Code: import numpy import numpy as np # find out where we are in the file directory import os, sys print(os.getcwd()) datafilefolder = "./data/" m=5 n=4 A = 11.111111*np.array(range(m*n),dtype=np.float32).reshape((m,n)) print(A) Afilename = "A_mat_5_4.npy" try: A.tofile(datafilefolder+ Afi...
<SYSTEM_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 drawing routines Step2: Pascal VOC dataset Step3: Test SSD-300 model using TFRecords pipeline Step4: Test SSD-300 model using sample ima...
<ASSISTANT_TASK:> Python Code: def colors_subselect(colors, num_classes=21): dt = len(colors) // num_classes sub_colors = [] for i in range(num_classes): color = colors[i*dt] if isinstance(color[0], float): sub_colors.append([int(c * 255) for c in color]) else: ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Label Step2: Classification accuracy Step3: Le taux de prédiction est 0.6927, ce qui à première vue peut sembler satisfaisant Mais est-ce l...
<ASSISTANT_TASK:> Python Code: # charger les données dans un dataframe de Pandas import pandas as pd col_names = ['pregnant', 'glucose', 'bp', 'skin', 'insulin', 'bmi', 'pedigree', 'age', 'label'] pima = pd.read_csv('./pima-indians-diabetes.data.txt', header=None, names=col_names) # afficher les 5 premières lignes pima...
<SYSTEM_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 run this a second time, on the second (b) feature table that has removed all epithets with fewer than 27 representative documents. The re...
<ASSISTANT_TASK:> Python Code: import os from sklearn import preprocessing from sklearn.tree import DecisionTreeClassifier from sklearn.cross_validation import train_test_split from sklearn.ensemble import RandomForestClassifier from sklearn.externals import joblib from sklearn.feature_extraction.text import CountVecto...
<SYSTEM_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 the notebook runtime environment devices / settings Step2: There are two run modes Step3: Data Reading Step4: The random noise we will...
<ASSISTANT_TASK:> Python Code: import matplotlib as mpl import matplotlib.pyplot as plt import numpy as np import os import cntk as C from cntk import Trainer from cntk.layers import default_options from cntk.device import set_default_device, gpu, cpu from cntk.initializer import normal from cntk.io import (MinibatchSo...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Images are 224x224 pixels, with 3 channels. Batch size is 50. This is specified in the caffemodel but not in the tf class (mynet.py) Step2: Now...
<ASSISTANT_TASK:> Python Code: import numpy as np import tensorflow as tf import os.path as osp input_size = {50, 3, 224, 224} fake_data = np.random.rand(2, 224, 224, 3) from mynet import CaffeNet images = tf.placeholder(tf.float32, [None, 224, 224, 3]) net = CaffeNet({'data':images}) sesh = tf.Session() sesh.run(tf...
<SYSTEM_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...
<ASSISTANT_TASK:> Python Code: import magma as m import mantle def fulladder(A, B, C): return A^B^C, A&B|B&C|C&A # sum, carry assert fulladder(1, 0, 0) == (1, 0), "Failed" assert fulladder(0, 1, 0) == (1, 0), "Failed" assert fulladder(1, 1, 0) == (0, 1), "Failed" assert fulladder(1, 0, 1) == (0, 1), "Failed" asse...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: 時間太長!
<ASSISTANT_TASK:> Python Code: import itertools 屋子 = 第一間, _, 中間, _, _ = [1, 2, 3, 4, 5] 所有順序 = list(itertools.permutations(屋子)) 所有順序 def 在右邊(h1, h2): "h1 緊鄰 h2 的右邊." return h1-h2 == 1 def 隔壁(h1, h2): "h1 h2 在隔壁" return abs(h1-h2) == 1 def zebra_puzzle(): return [locals() 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: From SQL to DataFrames Step2: Data Manipulation Step3: Or it can be inspected for schema, Step4: or further transformed locally, for example ...
<ASSISTANT_TASK:> Python Code: import google.datalab.bigquery as bq import pandas as pd %%bq query -n requests SELECT timestamp, latency, endpoint FROM `cloud-datalab-samples.httplogs.logs_20140615` WHERE endpoint = 'Popular' OR endpoint = 'Recent' %%bq sample --count 5 --query requests df = requests.execute(output_op...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: GitHub workflow Step2: PR ready!? What now?
<ASSISTANT_TASK:> Python Code: %%bash git status %%bash git log %%bash git show %%writefile foo.md Fetchez la vache %%bash git add foo.md %%bash git st %%bash git diff foo.md %%bash git diff git_intro.ipynb %%bash git rm -f foo.md %%bash git st %%bash git branch new_post %%bash git checkout new_post %%writefile my_new...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step2: Lorenz system Step4: Write a function solve_lorenz that solves the Lorenz system above for a particular initial condition $[x(0),y(0),z(0)]$. Y...
<ASSISTANT_TASK:> Python Code: %matplotlib inline import matplotlib.pyplot as plt import numpy as np from scipy.integrate import odeint from IPython.html.widgets import interact, fixed def lorentz_derivs(yvec, t, sigma, rho, beta): Compute the the derivatives for the Lorentz system at yvec(t). x = yvec[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: Now, we add a plane at z=0. Step2: By holding the shift key and hovering the mouse at the edges of the bounding box (or activate slice mode in ...
<ASSISTANT_TASK:> Python Code: import ipyvolume as ipv fig = ipv.figure() scatter = ipv.examples.gaussian(show=False) ipv.show() plane = ipv.plot_plane("z"); import ipywidgets as widgets widgets.jslink((fig, 'slice_z'), (plane, 'z_offset')); ## Uncomment to try # import vaex # import matplotlib.pylab 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: Spinning Symmetric Rigid Body setup Step2: $\left[{}^\mathcal{I}\boldsymbol{\omega}^\mathcal{B}\right]_\mathcal{B}$ Step3: ${}^\mathcal{I}\bol...
<ASSISTANT_TASK:> Python Code: from miscpy.utils.sympyhelpers import * init_printing() th,psi,thd,psidd,thdd,psidd,Omega,I1,I2,t,M1,C = \ symbols('theta,psi,thetadot,psidot,thetaddot,psiddot,Omega,I_1,I_2,t,M_1,C') diffmap = {th:thd,psi:psid,thd:thdd,psid:psidd} bCa = rotMat(1,th);bCa iWb_B = bCa*Matrix([0,0,psid])+ ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: We will use this helper function to write lists containing article ids, categories, and authors for each article in our database to local file. ...
<ASSISTANT_TASK:> Python Code: import os import tensorflow as tf import numpy as np from google.cloud import bigquery PROJECT = 'cloud-training-demos' # REPLACE WITH YOUR PROJECT ID BUCKET = 'cloud-training-demos-ml' # REPLACE WITH YOUR BUCKET NAME REGION = 'us-central1' # REPLACE WITH YOUR BUCKET REGION e.g. us-centr...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Test data Step2: Regression Step3: Test for Outliers Step4: Figure Step5: Create a function and test it
<ASSISTANT_TASK:> Python Code: import numpy as np import statsmodels.api as sm # For some reason this import is necessary... import statsmodels.formula.api as smapi import statsmodels.graphics as smgraph import matplotlib.pyplot as plt %matplotlib inline x = np.arange(30, dtype=float) # Make some y data with random 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: Modeling Step2: Visualization
<ASSISTANT_TASK:> Python Code: from ozapfdis import jdeps deps = jdeps.read_jdeps_file( "../dataset/jdeps_dropover.txt", filter_regex="at.dropover") deps.head() deps = deps[['from', 'to']] deps['group_from'] = deps['from'].str.split(".").str[2] deps['group_to'] = deps['to'].str.split(".").str[2] deps.head() 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: record schedules for 2 weeks, then augment count with weekly flight numbers. Step2: good dates Step3: Save
<ASSISTANT_TASK:> Python Code: L=json.loads(file('../json/L.json','r').read()) M=json.loads(file('../json/M.json','r').read()) N=json.loads(file('../json/N.json','r').read()) import requests AP={} for c in M: if c not in AP:AP[c]={} for i in range(len(L[c])): AP[c][N[c][i]]=L[c][i] baseurl='https://www...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Hamilton (1989) switching model of GNP Step2: We plot the filtered and smoothed probabilities of a recession. Filtered refers to an estimate of...
<ASSISTANT_TASK:> Python Code: %matplotlib inline import numpy as np import pandas as pd import statsmodels.api as sm import matplotlib.pyplot as plt import requests from io import BytesIO # NBER recessions from pandas_datareader.data import DataReader from datetime import datetime usrec = DataReader('USREC', 'fred', 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: Defining the refugee Step2: I gave the Person class a simple constructor (see the _init_() function), which sets a number of parameters specifi...
<ASSISTANT_TASK:> Python Code: import random class Person: def __init__(self, location): self.ill = False self.injured = False self.age = 35 self.location = location self.location.numAgents += 1 # Set to true when an agent resides on a link. self.travelling = False def select...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Training and visualizing Step2: Predicting classes and class probabilities Step3: Sensitivity to training set details Step4: Regression trees...
<ASSISTANT_TASK:> Python Code: # To support both python 2 and python 3 from __future__ import division, print_function, unicode_literals # Common imports import numpy as np import os # to make this notebook's output stable across runs np.random.seed(42) # To plot pretty figures %matplotlib inline import matplotlib 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: Get the model and extract the data. Step2: Download the embeddings and the tokenizer Step3: Load the embeddings and create functions for encod...
<ASSISTANT_TASK:> Python Code: from mmlspark import CNTKModel, ModelDownloader from pyspark.sql.functions import udf, col from pyspark.sql.types import IntegerType, ArrayType, FloatType, StringType from pyspark.sql import Row from os.path import abspath, join import numpy as np import pickle from nltk.tokenize import s...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Getting insights Step2: Build a model from the default schema
<ASSISTANT_TASK:> Python Code: # Load PredicSis.ai SDK from predicsis import PredicSis prj = PredicSis.project('Outbound Mail Campaign') mdl = prj.default_schema().fit('My first model') mdl.auc() <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: Programa principal Step2: Ha funcionat a la primera? Fer un quadrat perfecte no és fàcil, i el més normal és que calga ajustar un parell de cos...
<ASSISTANT_TASK:> Python Code: from functions import connect, forward, stop, left, right, disconnect, next_notebook from time import sleep connect() # Executeu, polsant Majúscules + Enter # avançar # girar # avançar # girar # avançar # girar # avançar # girar # parar for i in range(4): # avançar # girar # pa...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Interesting... We wanted to change two elements (line 7), but added four instead! Rather, we mutated list a with list b. "Mutability" means, sim...
<ASSISTANT_TASK:> Python Code: a = list(range(5)) print ("The list we created:", a, "of length", len(a)) b = list(range(6,10)) print ("The second list we created:", b, "of length", len(b)) a[1:3] = b # Line 7 print ("The first list after we changed a couple of elements is", a, "with length", len(a)) print ("hash of 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: Step2: Problem 1) Create a galaxy class Step3: Problem 1c Step5: Problem 1d Step7: Problem 2) Make a more interesting galaxy class that can evolve w...
<ASSISTANT_TASK:> Python Code: import matplotlib.pyplot as plt import random import numpy as np %matplotlib inline class Galaxy(): Galaxy class for simply representing a galaxy. def __init__(self, total_mass, cold_gas_mass, stellar_mass, age=0): self.total_mass = total_mass self.cold_...
<SYSTEM_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...
<ASSISTANT_TASK:> Python Code: # DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'mri', 'sandbox-2', 'land') # Set as follows: DOC.set_author("name", "email") # TODO - please enter value(s) # Set as follows: DOC.set_contributor("name", "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 compute simple things like the contrast and the Doppler velocity field Step2: Now let us compute the velocity field. To this end, we com...
<ASSISTANT_TASK:> Python Code: sn.set_style("dark") f, ax = pl.subplots(figsize=(9,9)) ax.imshow(stI[:,:,0], aspect='auto', cmap=pl.cm.gray) contrastFull = np.std(stI[:,:,0]) / np.mean(stI[:,:,0]) contrastQuiet = np.std(stI[400:,100:300,0]) / np.mean(stI[400:,100:300,0]) print("Contrast in the image : {0}%".format(con...
<SYSTEM_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. Map Step2: 2. Profile
<ASSISTANT_TASK:> Python Code: import numpy as np from scipy.interpolate import interp1d import travelmaps2 as tm from matplotlib import pyplot as plt tm.setup(dpi=200) fig_x = tm.plt.figure(figsize=(tm.cm2in([11, 6]))) # Locations MDF = [19.433333, -99.133333] # Mexico City OAX = [16.898056, -96.414167] # Oaxaca PES ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Description Step2: If the slip is 0.05, find the following quantities for this motor Step3: $$Z_B = \frac{(R_2/(2-s) + jX_2)(jX_M)}{R_2/(2-s) ...
<ASSISTANT_TASK:> Python Code: %pylab notebook %precision %.4g V = 120 # [V] p = 4 R1 = 2.0 # [Ohm] R2 = 2.8 # [Ohm] X1 = 2.56 # [Ohm] X2 = 2.56 # [Ohm] Xm = 60.5 # [Ohm] s = 0.05 Prot = 51 # [W] Zf = ((R2/s + X2*1j)*(Xm*1j)) / (R2/s + X2*1j + Xm*1j) Zf Zb = ((R2/(2-s) + X2*1j)*(Xm*1j)) / (R2...
<SYSTEM_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_ Advanced firewalking using IP options is sometimes useful to perform network enumeration. Here is a more complicated one-liner Step2: Now th...
<ASSISTANT_TASK:> Python Code: send(IP(dst="1.2.3.4")/TCP(dport=502, options=[("MSS", 0)])) ans = sr([IP(dst="8.8.8.8", ttl=(1, 8), options=IPOption_RR())/ICMP(seq=RandShort()), IP(dst="8.8.8.8", ttl=(1, 8), options=IPOption_Traceroute())/ICMP(seq=RandShort()), IP(dst="8.8.8.8", ttl=(1, 8))/ICMP(seq=RandShort())], ver...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Step2: By series convolution Step3: By recurrence relation Step4: By $A, Z$ sequences Step5: $\mathcal{C}$ Step6: $\mathcal{R}$ Step7: Co...
<ASSISTANT_TASK:> Python Code: from sympy import * from sympy.abc import n, i, N, x, lamda, phi, z, j, r, k, a, t, alpha from sequences import * init_printing() m = 5 d_fn, h_fn = Function('d'), Function('h') d, h = IndexedBase('d'), IndexedBase('h') rows, cols = 5, 5 ctor = lambda i,j: d[i,j] Matrix(rows, cols, ctor)...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Variables to set before running Step2: Set date index to a special DatetimeIndex and then Reindex the dataframe so Step3: interpolate missing ...
<ASSISTANT_TASK:> Python Code: !wget -P ../output -qN ftp://sidads.colorado.edu/pub/DATASETS/NOAA/G02135/north/daily/data/NH_seaice_extent_final.csv !wget -P ../output -qN ftp://sidads.colorado.edu/pub/DATASETS/NOAA/G02135/north/daily/data/NH_seaice_extent_nrt.csv !wget -P ../output -qN ftp://sidads.colorado.edu/pub/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: 4.1. Checking the loss.out file. Step2: 4.2. Checking the energy_test.out file Step3: 4.3. Checking the force_test.out file Step4: 4.4. Check...
<ASSISTANT_TASK:> Python Code: from pylab import * loss = loadtxt('loss.out') loglog(loss[:, 1:6]) loglog(loss[:, 7:9]) xlabel('Generation/100') ylabel('Loss') legend(['Total', 'L1-regularization', 'L2-regularization', 'Energy-train', 'Force-train', 'Energy-test', 'Force-test']) tight_layout() energy_test = loadtxt('...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Python Statistics Step2: Some simpler exercises based on common python function Step3: Question Step4: Question Step5: `` Step6: Question S...
<ASSISTANT_TASK:> Python Code: import math import numpy as np import pandas as pd import re from operator import itemgetter, attrgetter def median(dataPoints): "computer median of given data points" if not dataPoints: raise 'no datapoints passed' sortedpoints=sorted(dataPoints) mid=len(dataPoi...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Creating a ScaleBar object Step2: Geographic coordinate system (degrees) Step3: After the conversion, we can calculate the distance between th...
<ASSISTANT_TASK:> Python Code: import geopandas as gpd from matplotlib_scalebar.scalebar import ScaleBar nybb = gpd.read_file(gpd.datasets.get_path('nybb')) nybb = nybb.to_crs(32619) # Convert the dataset to a coordinate # system which uses meters ax = nybb.plot() ax.add_artist(ScaleBar(1)) from shapely.geometry.poi...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step5: Copyright 2021 DeepMind Technologies Limited. Step6: Dataset and environment Step7: DQN learner Step8: Training loop Step9: Evaluation
<ASSISTANT_TASK:> Python Code: # @title Installation !pip install dm-acme !pip install dm-acme[reverb] !pip install dm-acme[tf] !pip install dm-sonnet !pip install dopamine-rl==3.1.2 !pip install atari-py !pip install dm_env !git clone https://github.com/deepmind/deepmind-research.git %cd deepmind-research !git clone h...
<SYSTEM_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 re-run the above cell if you are getting any incompatible warnings and errors. Step2: There are a couple of key features here Step3: Th...
<ASSISTANT_TASK:> Python Code: !pip install -q --upgrade tensorflow-datasets import pprint import tensorflow_datasets as tfds ratings = tfds.load("movielens/100k-ratings", split="train") for x in ratings.take(1).as_numpy_iterator(): pprint.pprint(x) import numpy as np import tensorflow as tf movie_title_lookup = tf...
<SYSTEM_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 source is http Step2: Can also migrate it to a sqlite database Step3: Can perform queries
<ASSISTANT_TASK:> Python Code: import Quandl import pandas as pd import numpy as np import blaze as bz with open('../.quandl_api_key.txt', 'r') as f: api_key = f.read() db = Quandl.get("EOD/DB", authtoken=api_key) bz.odo(db['Rate'].reset_index(), '../data/db.bcolz') fx = Quandl.get("CURRFX/EURUSD", authtoken=api_k...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step2: Number of New Followers Step4: At First Glance... Step8: Statuses -vs- Followers -vs- Friends
<ASSISTANT_TASK:> Python Code: df = sqlContext.read.json('/home/anaconda/md0/data/2016_potus/users_all') df.registerTempTable('followers') %matplotlib inline import seaborn as sns import matplotlib import warnings query = select candidate, count(*) as new_followers from followers group by candidate dfp = sqlCont...
<SYSTEM_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 setup Step2: This sample data has way too many stations to plot all of them. The number Step3: Now that we have the data we want, we need ...
<ASSISTANT_TASK:> Python Code: import cartopy.crs as ccrs import cartopy.feature as cfeature import matplotlib.pyplot as plt import numpy as np import pandas as pd from metpy.calc import reduce_point_density from metpy.calc import wind_components from metpy.cbook import get_test_data from metpy.plots import add_metpy_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: We have to define a threshold on the p-value of the statistical test to decide how many features to keep. There are several strategies implement...
<ASSISTANT_TASK:> Python Code: from sklearn.datasets import load_breast_cancer, load_digits from sklearn.model_selection import train_test_split cancer = load_breast_cancer() # get deterministic random numbers rng = np.random.RandomState(42) noise = rng.normal(size=(len(cancer.data), 50)) # add noise features to the 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: Plotting 1/2 light radius from GIM2D vs NSA Step2: Conclusion two measures of radius are comparable, expect for the NSA galaxies with very lar...
<ASSISTANT_TASK:> Python Code: import numpy as np from matplotlib import pyplot as plt %matplotlib inline import warnings warnings.filterwarnings('ignore') import sys sys.path.append("/Users/rfinn/Dropbox/pythonCode/") sys.path.append("/anaconda/lib/python2.7/site-packages") sys.path.append("/Users/rfinn/Ureka/variants...
<SYSTEM_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. Model-based parametric regression Step2: have been generated by a linear Gaussian model (i.e., with $z = T(x) = x$) with noise variance Step...
<ASSISTANT_TASK:> Python Code: # Import some libraries that will be necessary for working with data and displaying plots # To visualize plots in the notebook %matplotlib inline import matplotlib import matplotlib.pyplot as plt import numpy as np import scipy.io # To read matlab files import pylab X = np.array([...
<SYSTEM_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 will specify the site(s) we want to query for available data types. Step2: The next code segment will query the FITS database for data o...
<ASSISTANT_TASK:> Python Code: import pandas as pd import matplotlib.pyplot as plt import datetime import numpy as np # Create list of all typeIDs available in the FITS database all_type_URL = 'https://fits.geonet.org.nz/type' all_types = pd.read_json(all_type_URL).iloc[:,0] all_typeIDs= [] for row in all_types: ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Data preparation Step2: Check time sequence and inputs/outputs Step3: Input $\delta_T$ and focused time ranges Step4: Resample and filter dat...
<ASSISTANT_TASK:> Python Code: %run matt_startup %run -i matt_utils button_qtconsole() #import other needed modules in all used engines #with dview.sync_imports(): # import os filename = 'FIWT_Exp015_20150601145005.dat.npz' def loadData(): # Read and parse raw data global exp_data exp_data = np.load(file...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: 选着一张空闲的卡 Step2: 1. Classifying Names with a Character-Level RNN Step3: Now we have category_lines, a dictionary mapping each category Step4: ...
<ASSISTANT_TASK:> Python Code: import torch is_cuda = True if torch.cuda.is_available() else False print(is_cuda) id = 1 torch.cuda.set_device(id) print( torch.cuda.current_device() ) from __future__ import unicode_literals, print_function, division from io import open import glob import os def findFiles(path): 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: 对于变量x来说,不需要知道它是字符串还是列表,就可以调用它的count方法—不用管它是什么类型(只要提供一个字符作为参数即可)。 Step2: 1.2 封装 Step3: 注意 尽管可能使用的是新版的Python,但一些功能不会在旧式类上起作用。为了确保类是新型的,需要在模块或者...
<ASSISTANT_TASK:> Python Code: 'abc'.count('a') [1,2,'a'].count('a') 1+2 'Fish '+'license' __metaclass__=type #确定使用新式类 class Person: def setName(self, name): self.name=name def getName(self): return self.name def greet(self): print "Hello, world! I'm %s" % self.name foo=Person() ...
<SYSTEM_TASK:> Given the following text description, write Python code to implement the functionality described below step by step <END_TASK> <USER_TASK:> Description: Step1: Note that a similar transformation can be applied with compute_ems
<ASSISTANT_TASK:> Python Code: # Author: Denis Engemann <denis.engemann@gmail.com> # Jean-Remi King <jeanremi.king@gmail.com> # # License: BSD (3-clause) import numpy as np import matplotlib.pyplot as plt import mne from mne import io, EvokedArray from mne.datasets import sample from mne.decoding import EMS, co...