Unnamed: 0 int64 0 15.9k | cleaned_code stringlengths 67 124k ⌀ | cleaned_prompt stringlengths 168 30.3k ⌀ |
|---|---|---|
2,100 | <ASSISTANT_TASK:>
Python Code:
from fidelio_functions import *
message = "Most of the department chiefs are already mine."
print(message)
ints = text_to_ints(message)
print(ints,'\n')
packets = packetize(ints)
print(packets,'\n')
test_ints = unpacketize(packets)
print(test_ints,'\n')
test_text = ints_to_text(test_int... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Public-key encryption
Step2: Packing and padding integers
Step3: Key generation
Step4: RSA encryption
Step5: How decryption works
Step6: Ho... |
2,101 | <ASSISTANT_TASK:>
Python Code:
%%bash
lscpu
%%bash
sudo lshw -C memory
%%bash
uname -ar #r for kernel, a for all
import math
import time
import numpy as np
from pytest import approx
from scipy.integrate import quad
def Rcf(f,a,b,n):
Compute numerical approximation using rectangle or mid-point
method in an... | <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: ```{admonition} Observación
Step3: Objetivo
Step4: Medición de tiempo
Step5: Prueba que se resuelve correctamente el problema
Step6: Comando... |
2,102 | <ASSISTANT_TASK:>
Python Code:
import time
import numpy as np
import tensorflow as tf
import utils
from urllib.request import urlretrieve
from os.path import isfile, isdir
from tqdm import tqdm
import zipfile
dataset_folder_path = 'data'
dataset_filename = 'text8.zip'
dataset_name = 'Text8 Dataset'
class DLProgress(tq... | <SYSTEM_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 text8 dataset, a file of cleaned up Wikipedia articles from Matt Mahoney. The next cell will download the data set to the data folder. ... |
2,103 | <ASSISTANT_TASK:>
Python Code:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline
# Download and get Daily Returns
aapl = pd.read_csv('AAPL_CLOSE',
index_col = 'Date',
parse_dates = True)
cisco = pd.read_csv('CISCO_CLOSE',
... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Simulating Thousands of Possible Allocations
Step2: Log Returns vs Arithmetic Returns
Step3: Single Run for Some Random Allocation
Step4: Gre... |
2,104 | <ASSISTANT_TASK:>
Python Code:
import os
def load_data(filename):
if not os.path.exists(filename + '.hdf5'):
raise FileNotFoundError("Need the S1 metadata dataframe from file %s.hdf5" % filename)
if not os.path.exists(filename + '.npz'):
raise FileNotFoundError("Need the S1 waveforms from 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: Keep only main and second S1
Step2: Select events with good S1 areas
Step3: Process S1s
Step4: There is essentially no difference between SR0... |
2,105 | <ASSISTANT_TASK:>
Python Code:
# Load the sociopatterns network data.
G = cf.load_sociopatterns_network()
# Let's find out the number of neighbors that individual #7 has.
len(G.neighbors(7))
# Possible Answers:
# sorted(G.nodes(), key=lambda x:len(G.neighbors(x)), reverse=True)
sorted([(n, G.neighbors(n)) for n in G... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Hubs
Step2: Exercise
Step3: Approach 2
Step4: If you inspect the dictionary closely, you will find that node 51 is the one that has the highe... |
2,106 | <ASSISTANT_TASK:>
Python Code:
%pylab inline
import scipy as sp
zz = np.loadtxt('wiggleZ_DR1_z.dat',dtype='float'); # Load WiggleZ redshifts
np.min(zz) # Check bounds
np.max(zz)
nbins = 50; # Is this a good choice?
n, bins, patches = hist(zz,nbins)
x = bins[0:nbins] + (bins[2]-bins[1])/2; # Convert bin edges to cent... | <SYSTEM_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 from file
Step2: Construct histogram from data
Step3: Interpolate histogram output -> p(z); n.b. that you can also use numerical qua... |
2,107 | <ASSISTANT_TASK:>
Python Code:
import requests
import pandas as pd
import re
import numpy as np
import pickle
from IPython.core.display import display, HTML
display(HTML("<style>.container {width:90% !important;}</style>"))
NOMADV2url='https://seabass.gsfc.nasa.gov/wiki/NOMAD/nomad_seabass_v2.a_2008200.txt'
def GetNo... | <SYSTEM_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 data can be accessed through a URL that I'll store in a string below.
Step4: Next, I'll write a couple of functions. The first to get the d... |
2,108 | <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: 梯度提升树(Gradient Boosted Trees):模型理解
Step2: 有关特征的描述,请参阅之前的教程。
Step3: 构建输入 pipeline
Step4: 训练模型
Step5: 出于性能原因,当您的数据适合内存时,我们建议在 tf.estimator.Boo... |
2,109 | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
import open_cp.sources.sepp as source_sepp
process = source_sepp.SelfExcitingPointProcess(
background_sampler = source_sepp.HomogeneousPoissonSampler(rate=0.1),
trigger_sampler = source_sepp.ExponentialDecaySam... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Checking the simulation
Step2: Background rate
Step3: Aftershocks
Step4: We only sample the process in a finite time interval, so we'll miss ... |
2,110 | <ASSISTANT_TASK:>
Python Code:
import time
from collections import namedtuple
import numpy as np
import tensorflow as tf
with open('anna.txt', 'r') as f:
text=f.read()
vocab = set(text)
vocab_to_int = {c: i for i, c in enumerate(vocab)}
int_to_vocab = dict(enumerate(vocab))
encoded = np.array([vocab_to_int[c] for ... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: First we'll load the text file and convert it into integers for our network to use. Here I'm creating a couple dictionaries to convert the chara... |
2,111 | <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: 불균형 데이터 분류
Step2: 데이터 처리 및 탐색
Step3: 클래스 레이블 불균형 검사
Step4: 이를 통해 양성 샘플 일부를 확인할 수 있습니다.
Step5: 데이터세트를 학습, 검증 및 테스트 세트로 분할합니다. 검증 세트는 모델 피팅 중에... |
2,112 | <ASSISTANT_TASK:>
Python Code:
%matplotlib notebook
from matplotlib import pyplot
import numpy
tests = []
@tests.append
def f0(x):
return x*x - 2, 2*x
@tests.append
def f1(x):
return numpy.cos(x) - x, -numpy.sin(x) - 1
@tests.append
def f2(x):
return numpy.exp(-numpy.abs(x)) + numpy.sin(x), numpy.exp(-numpy... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Which of these functions have at least one root?
Step2: Notice that we need to define hasroot above.
Step3: We get about 5 digits of accuracy.... |
2,113 | <ASSISTANT_TASK:>
Python Code:
# Import libraries necessary for this project
import numpy as np
import pandas as pd
import visuals as vs # Supplementary code
from sklearn.cross_validation import ShuffleSplit
# Pretty display for notebooks
%matplotlib inline
# Load the Boston housing dataset
data = pd.read_csv('housing.... | <SYSTEM_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 Exploration
Step3: Question 1 - Feature Observation
Step4: Question 2 - Goodness of Fit
Step5: Yes, this model appears to have sufficent... |
2,114 | <ASSISTANT_TASK:>
Python Code:
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
import numpy as np
import scipy.stats as ss
import warnings
warnings.filterwarnings("ignore")
sns.set_style('white')
%matplotlib inline
x = np.array([1, 1, 1,1, 10, 100, 1000])
y = np.array([1000, 100, 10, 1, 1, 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: Ratio and logarithm
Step2: Plot on the linear scale using the scatter() function.
Step3: Plot on the log scale.
Step4: What do you see from t... |
2,115 | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
sns.set()
import pymc3 as pm
from pymc3 import Model, MvNormal, HalfCauchy, sample, traceplot, summary, find_MAP, NUTS, Deterministic
import theano.tensor as T
from theano import shared
from theano... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: This is what our initial covariance matrix looks like. Intuitively, every data point's Y-value correlates with points according to their squared... |
2,116 | <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: Image classification with TensorFlow Lite Model Maker
Step2: Import the required packages.
Step3: Simple End-to-End Example
Step4: You could ... |
2,117 | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
from scipy import integrate
def trapz(f, a, b, N):
Integrate the function f(x) over the range [a,b] with N points.
h = (b-a)/N
xvals = np.linspace(a, b, N+1)
yvals = f(xvals)
return 0.5 * np.su... | <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: Trapezoidal rule
Step3: Now use scipy.integrate.quad to integrate the f and g functions and see how the result compares with your trapz functio... |
2,118 | <ASSISTANT_TASK:>
Python Code:
import os
import time
import json
from pprint import *
import lxml
from lxml import etree
import xmltodict, sys, gc
from pymongo import MongoClient
gc.enable() #Enable Garbadge Collection
# 将指定tag的对象提取,写入json文件。
def process_element(elem):
elem_data = etree.tostring(elem)
elem_dic... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: 执行osm的xml到json转换,一次扫描提取为三个文件。
Step2: 执行转换。
|
2,119 | <ASSISTANT_TASK:>
Python Code:
pip install --user apache-beam[gcp]
import apache_beam as beam
print(beam.__version__)
# change these to try this notebook out
BUCKET = 'cloud-training-demos-ml'
PROJECT = 'cloud-training-demos'
REGION = 'us-central1'
import os
os.environ['BUCKET'] = BUCKET
os.environ['PROJECT'] = PROJE... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Run the command again if you are getting oauth2client error.
Step2: You may receive a UserWarning about the Apache Beam SDK for Python 3 as not... |
2,120 | <ASSISTANT_TASK:>
Python Code:
import numpy as np
# dipole interaction energy
def dd(t1, t2, p1, p2, nu):
return -nu*(2*np.cos(t1)*np.cos(t2) - np.sin(t1)*np.sin(t2)*np.cos(p1-p2))
# anisotropy energy
def anis(t1, t2, sigma):
return sigma*(np.sin(t1)**2 + np.sin(t2)**2)
# total energy
def tot(t1, t2, p1, p2, nu... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Magpy non-interacting case
Step2: System properties
Step3: Magpy model and simulation
Step4: Simulate an ensemble of 10,000 dimers without in... |
2,121 | <ASSISTANT_TASK:>
Python Code:
PUBLIC_KEY = Binary('\x8eB\x11\xd5ht\x93\x05\xee\xed\x10\xad\xb4\x90\xb7]\x92\x04\xac\x82\xb5\xa2"v\xf9[\xd6^\x14\x8b\x12\x1d', 0)
sensitive_subdocument = {"sensitive":"triple pinky swear"}
document = {
"_id":1,
"name":"bsonsearch",
"super_secret_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: but maybe you don't want that tripple pinky swear value available to just anyone to search on
Step2: this document will no longer match the ori... |
2,122 | <ASSISTANT_TASK:>
Python Code:
from tensorflow.python.platform import gfile
import tensorflow as tf
import numpy as np
model='../inception/classify_image_graph_def.pb'
def create_graph():
'''
Function to extract GraphDef of Inception model.
Returns: Extracted GraphDef
'''
with tf.Sessi... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Steps Followed to train
Step1: This will load the TensorFlow's default graph with the Inception's graph.
Step 2
Step2: This is done for all the images... |
2,123 | <ASSISTANT_TASK:>
Python Code:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import pickle
from IPython.core.debugger import Tracer
import seaborn as sns
%matplotlib inline
import tensorflow as tf
import sklearn
import h5py
import keras
from keras.preprocessing import image
from resnet50 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: Running the examples
Step2: Example 2
Step3: Example 3
Step4: His Code
Step5: Creating User Vecs
Step6: Exploring the Data
Step7: candiate... |
2,124 | <ASSISTANT_TASK:>
Python Code:
from pomegranate import *
import random
import math
random.seed(0)
model = HiddenMarkovModel( name="Rainy-Sunny" )
rainy = State( DiscreteDistribution({ 'walk': 0.1, 'shop': 0.4, 'clean': 0.5 }), name='Rainy' )
sunny = State( DiscreteDistribution({ 'walk': 0.6, 'shop': 0.3, 'clean': 0.1... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: We first create a HiddenMarkovModel object, and name it "Rainy-Sunny".
Step2: We then create the two possible states of the model, "rainy" and ... |
2,125 | <ASSISTANT_TASK:>
Python Code:
from __future__ import print_function, unicode_literals
import pandas as pd
import gzip
import csv
import regex as re
import json
import time
import datetime
import requests
import os
import json
import dbpedia_config
from collections import Counter, defaultdict
from cytoolz import parti... | <SYSTEM_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 need to know the children classes of Person in the DBpedia ontology. We use rdflib and networkx to find them.
Step2: There are a variety of ... |
2,126 | <ASSISTANT_TASK:>
Python Code:
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
%matplotlib inline
data = pd.read_csv('weights_heights.csv', index_col='Index')
data.plot(y='Height', kind='hist',
color='red', title='Height (inch.) distribution')
data.head(5)
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: Считаем данные по росту и весу (weights_heights.csv, приложенный в задании) в объект Pandas DataFrame
Step2: Чаще всего первое, что надо надо с... |
2,127 | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
def plot(data, bins=30):
plt.hist(data, bins)
plt.show()
def bernoulli(p=None, size=1):
return np.random.binomial(n=1, p=p, size=size)
bernoulli(p=0.5, size=100)
np.random.binomial(n=10, p=0.5, size=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: Tool functions
Step2: Discrete distributions
Step3: Binomial distribution
Step4: Hypergeometric distribution
Step5: Poisson distribution
Ste... |
2,128 | <ASSISTANT_TASK:>
Python Code:
import os, urllib
def download(url):
filename = url.split("/")[-1]
if not os.path.exists(filename):
urllib.urlretrieve(url, filename)
def get_model(prefix, epoch):
download(prefix+'-symbol.json')
download(prefix+'-%04d.params' % (epoch,))
get_model('http://data.mxn... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Initialization
Step2: We can visualize the neural network by mx.viz.plot_network.
Step3: Both argument parameters and auxiliary parameters (e.... |
2,129 | <ASSISTANT_TASK:>
Python Code:
def H(tau):
g1 = 1; tau1 = 0.03; sd1 = 0.5;
g2 = 7; tau2 = 10; sd2 = 0.5;
term1 = g1/np.sqrt(2*sd1**2*np.pi) * np.exp(-(np.log10(tau/tau1)**2)/(2*sd1**2))
term2 = g2/np.sqrt(2*sd2**2*np.pi) * np.exp(-(np.log10(tau/tau2)**2)/(2*sd2**2))
return term1 + term2
Nfreq = 50
N... | <SYSTEM_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 construct the moduli. We'll have both a true version and a noisy version with some random noise added to simulate experimental varian... |
2,130 | <ASSISTANT_TASK:>
Python Code:
DON'T MODIFY ANYTHING IN THIS CELL
import helper
data_dir = './data/simpsons/moes_tavern_lines.txt'
text = helper.load_data(data_dir)
# Ignore notice, since we don't use it for analysing the data
text = text[81:]
view_sentence_range = (0, 10)
DON'T MODIFY ANYTHING IN THIS CELL
import num... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: TV Script Generation
Step3: Explore the Data
Step6: Implement Preprocessing Functions
Step9: Tokenize Punctuation
Step11: Preprocess all the... |
2,131 | <ASSISTANT_TASK:>
Python Code:
!pip install -q tensorflow_cloud
import tensorflow as tf
import tensorflow_cloud as tfc
from tensorflow import keras
from tensorflow.keras import layers
def create_model():
model = keras.Sequential(
[
keras.Input(shape=(28, 28)),
layers.experimental.pr... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: API overview
Step2: Let's save the TensorBoard logs and model checkpoints generated during training
Step3: Here, we will load our data from Ke... |
2,132 | <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 classification
Step2: Import the Fashion MNIST dataset
Step3: Loading the dataset returns four NumPy arrays
Step4: Explore the data
Ste... |
2,133 | <ASSISTANT_TASK:>
Python Code:
import sqlite3
conn = sqlite3.connect('election_tweets.sqlite')
cur = conn.cursor()
cur.execute("DROP TABLE IF EXISTS Tweets")
cur.execute("CREATE TABLE Tweets(state VARCHAR(10), party VARCHAR(20), sentiment INT2)")
conn.commit()
import pandas as pd
reader = pd.read_table('http://vahidm... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Setup/create a table
Step2: Read data using pandas and store them in sqlite
Step3: Summarizing Queries
|
2,134 | <ASSISTANT_TASK:>
Python Code:
import modin.pandas as pd
import pandas
import time
import modin.config as cfg
cfg.StorageFormat.put("omnisci")
# We download data locally because currently `OmnisciOnNative` doesn't support read files from s3 storage.
# Note that this may take a few minutes to download.
import urllib.re... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Dataset
Step2: pandas.read_csv
Step3: Expect pandas to take >3 minutes on EC2, longer locally
Step4: Are they equals?
Step5: Concept for exe... |
2,135 | <ASSISTANT_TASK:>
Python Code:
from __future__ import print_function, division
% matplotlib inline
import thinkplot
from thinkbayes2 import Hist, Pmf, Suite, Cdf
class Dice(Suite):
def Likelihood(self, data, hypo):
if hypo < data:
return 0
else:
return 1/hypo
suite = Dice([... | <SYSTEM_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 Dice problem
Step2: Here's what the update looks like
Step3: And here's what it looks like after more data
Step4: The train problem
Step5... |
2,136 | <ASSISTANT_TASK:>
Python Code:
def gaussian_function(x, mu=0, sigma=1):
Simple example function to return the probability density of a Gaussian with mean, mu,
and standard deviation, sigma, evaluated at values in x.
Note that a better function is available in scipy.stats.norm - this versi... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Distributions
Step2: Note that the values on the $P(x)$ axis are probability densities rather than probabilities
Step3: If we pick values at r... |
2,137 | <ASSISTANT_TASK:>
Python Code:
Install Data Commons API
We need to install the Data Commons API, since they don't ship natively with
most python installations.
In Colab, we'll be installing the Data Commons python and pandas APIs
through pip.
!pip install datacommons --upgrade --quiet
!pip install datacommons_pandas -... | <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: <a href="https
Step4: We've succesfully loaded our data, but there are still a couple preprocessing steps to go through first. Specifically, we... |
2,138 | <ASSISTANT_TASK:>
Python Code:
graph.set_fontsize('12')
graph.get_fontsize()
graph.set_node_defaults(fillcolor='blue', style='filled')
graph.get_node_defaults()
node1 = pydot.Node(name='node1', label='My first node', shape='box')
node2 = pydot.Node(name='node2', label='My second node', color='red')
edge = pydot.Edge(... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Defaults can be set for nodes and edges.
Step2: Nodes, edges and subgraphs are added and deleted through the respective add_*() and del_*() met... |
2,139 | <ASSISTANT_TASK:>
Python Code:
import pandas as pd
import geopandas as gpd
from preproceso import preprocesa
pd.options.mode.chained_assignment = None
denue = gpd.read_file("datos/DENUE_INEGI_09_.shp")
agebs = gpd.read_file("datos/ageb_urb.shp")
usos_suelo = preprocesa(denue, agebs)
usos_suelo.reset_index(drop=True, 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: Como pueden ver, en la variable usos_suelo tenemos ya calculadas todas nuestras variables de interés, ahora lo que necesitamos es, para cada fil... |
2,140 | <ASSISTANT_TASK:>
Python Code:
def parseRaw(json_map):
url = json_map['url']
content = json_map['html']
return (url,content)
import json
import pprint
pp = pprint.PrettyPrinter(indent=2)
path = "./pixnet.txt"
all_content = sc.textFile(path).map(json.loads).map(parseRaw)
def parseImgSrc(x):
try:
... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: 載入原始 RAW Data
Step2: 利用 LXML Parser 來分析文章結構
Step3: 取出 Image Src 的列表
Step4: 統計 Image Src 的列表
Step5: 請使用 reduceByKey , sortBy 來計算出 img src 排行榜... |
2,141 | <ASSISTANT_TASK:>
Python Code:
mrn_test1 = distlib.MRN_dist(0.005, 0.3, 3.5)
mrn_test2 = distlib.MRN_dist(0.005, 0.25, 3.5)
mrn_test3 = distlib.MRN_dist(0.005, 0.3, 4.0)
mrn_test4 = distlib.MRN_dist(0.005, 0.3, 3.5, na=10, log=True)
print(type(mrn_test1))
print(mrn_test1.__dict__.keys())
plt.plot(mrn_test1.a, mrn_test... | <SYSTEM_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's a quick way to see all the keys in the DustSpectrum object.
Step2: Play with WD01 dust distributions
Step3: The <code>DustSpectrum</cod... |
2,142 | <ASSISTANT_TASK:>
Python Code:
import numpy as np
import csv
%run 'preprocessor.ipynb' #our own preprocessor functions
with open('/Users/timothy/Desktop/Files/data_new/merged.csv', 'r') as f:
reader = csv.reader(f)
data = list(reader)
matrix = obtain_data_matrix(data)
samples = len(matrix)
print("Number 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: Load the dataset from the csv file
Step2: Process the data
Step3: Prepare the individual data axis
Step4: Plot the data in 2D
|
2,143 | <ASSISTANT_TASK:>
Python Code:
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
import pandas as pd
import numpy as np
import tensorflow as tf
!gsutil cp gs://ml-design-patterns/auto-mpg.csv .
data = pd.read_csv('auto-mpg.csv', na_values='?')
data = data.dropna()
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: Explaining simpler models
Step2: Train a Scikit-learn linear regression model on the data and print the learned coefficients
Step3: Feature at... |
2,144 | <ASSISTANT_TASK:>
Python Code:
# Author: Eric Larson <larson.eric.d@gmail.com>
#
# License: BSD-3-Clause
import numpy as np
import mne
from mne.datasets import sample
from mne.source_space import compute_distance_to_sensors
from mne.source_estimate import SourceEstimate
import matplotlib.pyplot as plt
print(__doc__)
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: Compute sensitivity maps
Step2: Show gain matrix a.k.a. leadfield matrix with sensitivity map
Step3: Compare sensitivity map with distribution... |
2,145 | <ASSISTANT_TASK:>
Python Code:
import numpy as np
import pandas as pd
import csv
from sklearn.datasets import fetch_20newsgroups
newsgroups = fetch_20newsgroups(subset='all')
df = pd.DataFrame(newsgroups.data, columns=['text'])
df['categories'] = [newsgroups.target_names[index] for index in newsgroups.target]
df.head(... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Fetch data
Step2: Clean data
Step3: Export to CSV
|
2,146 | <ASSISTANT_TASK:>
Python Code:
import numpy as np
import tensorflow as tf
from tensorflow import keras
layer = keras.layers.Dense(3)
layer.build((None, 4)) # Create the weights
print("weights:", len(layer.weights))
print("trainable_weights:", len(layer.trainable_weights))
print("non_trainable_weights:", len(layer.non... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Introduction
Step2: In general, all weights are trainable weights. The only built-in layer that has
Step3: Layers & models also feature a bool... |
2,147 | <ASSISTANT_TASK:>
Python Code:
# Importing all the required libraries
%matplotlib inline
import sys
import pandas as pd # data manipulation package
import datetime as dt # date tools, used to note current date
import matplotlib.pyplot as plt # graphics package
import matplotlib as m... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: 2.3 | Dataframes
Step2: 3.1.2 | Leisure Activity Data
Step3: 3.1.3 | Age Level Activity Data
Step4: 3.1.4 | Geography Level Activity Data
Ste... |
2,148 | <ASSISTANT_TASK:>
Python Code:
# Sometimes Jan calendar will have counts from days
# at beginning of Feb or end or previous Dec.
# Just checking that they agree w/ numbers in
# those months' calendars before dropping dupe
# dates
poldf = pollen_data(yrmths)
check_one2one(poldf, 'Date', 'Count')
poldf = poldf.drop_dupli... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: cs = requests.session()
Step2: Time series generator
Step3: Extract data
Step4: Sync Sqlite db w/ Redis
Step6: Accumulate and extract data
S... |
2,149 | <ASSISTANT_TASK:>
Python Code:
import os, sys
import iris
import numpy
import iris.plot as iplt
import matplotlib.pyplot as plt
import seaborn
seaborn.set_context('talk')
cwd = os.getcwd()
repo_dir = '/'
for directory in cwd.split('/')[1:]:
repo_dir = os.path.join(repo_dir, directory)
if directory == 'ocean-ana... | <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: 1. Flux integral approach
Step6: GISS-E2-R model
Step7: The OHC and HFDS totals match the corresponding global timeseries.
Step8: CSIRO-Mk3-6... |
2,150 | <ASSISTANT_TASK:>
Python Code:
import findspark; findspark.init()
import sparkhpc
sj = sparkhpc.sparkjob.LSFSparkJob(ncores=4)
sj.wait_to_start()
sj
sj2 = sparkhpc.sparkjob.LSFSparkJob(ncores=10)
sj2.submit()
sj.show_clusters()
from pyspark import SparkContext
sc = SparkContext(master=sj.master_url)
sc.parallelize(ra... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Launch the standalone spark clusters using sparkhpc
Step2: Create a SparkContext and start computing
Step3: Teardown
|
2,151 | <ASSISTANT_TASK:>
Python Code:
data = [
{'price': 850000, 'rooms': 4, 'neighborhood': 'Queen Anne'},
{'price': 700000, 'rooms': 3, 'neighborhood': 'Fremont'},
{'price': 650000, 'rooms': 3, 'neighborhood': 'Wallingford'},
{'price': 600000, 'rooms': 2, 'neighborhood': 'Fremont'}
]
{'Queen Anne': 1, 'Frem... | <SYSTEM_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 might be tempted to encode this data with a straightforward numerical mapping
Step2: It turns out that this is not generally a useful appro... |
2,152 | <ASSISTANT_TASK:>
Python Code:
# 申明一个 class MyData
class MyData(object):
pass
# 实例化 MyData, 实例的名字叫做 obj_math
obj_math = MyData()
obj_math.x = 4
print(obj_math.x)
class MyData(object):
# 定义一个 SayHello 的方法,self 可以理解为必须传递的参数
def SayHello(self):
print('Hello!')
# 实例化
obj_math = MyData()
... | <SYSTEM_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: 这个 NPC 的类,在初始化这里定义了 NPC 拥有的三个属性,name、weapon、blood,其中 name 需要创建实例的时候设置。
Step3: 在子类中,可以覆盖父类的方法。
Step4: 再来看看 show_properties() 这个方法,... |
2,153 | <ASSISTANT_TASK:>
Python Code:
from urllib.request import urlopen
import warnings
import os
import json
URL = 'http://www.oreilly.com/pub/sc/osconfeed'
JSON = '/home/kaka/osconfeed.json'
def load():
if not os.path.exists(JSON):
msg = 'downloading {} to {}'.format(URL, JSON)
warnings.warn(msg)
... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: 使用动态属性访问 JSON 类数据
Step2: FrozenJSON 中,尝试获取其它属性会出发解释器调用 __getattr__ 方法,这个方法首先查看 self.__data 有没有指定属性名(而不是键),这样 FrozenJSON 实例便可以处理字典的所有方法,例如把 item... |
2,154 | <ASSISTANT_TASK:>
Python Code:
import json
import numpy as np
from scipy2017codegen.odesys import ODEsys
from scipy2017codegen.chem import mk_rsys
watrad_data = json.load(open('../scipy2017codegen/data/radiolysis_300_Gy_s.json'))
watrad = mk_rsys(ODEsys, **watrad_data)
tout = np.logspace(-6, 3, 200) # close to one ho... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Again, using the ODEsys convenience class from notebook "35"
Step2: that is still the benchmark to beat. Subclassing ODEsys to have it render, ... |
2,155 | <ASSISTANT_TASK:>
Python Code:
# !pip install pycuda
%reset -f
import numpy
import numpy as np
from __future__ import print_function
from __future__ import division
import math
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
import pandas as pd
import os
import torch
from torch.utils.data.dataset ... | <SYSTEM_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 a CSV file for Binary classification
Step2: Create PyTorch GPU tensors
Step3: Define the NN model
Step4: The cross-entropy loss function... |
2,156 | <ASSISTANT_TASK:>
Python Code:
import pandas as pd
pd.set_option("display.max_rows", 5)
reviews = pd.read_csv("../input/wine-reviews/winemag-data-130k-v2.csv", index_col=0)
from learntools.core import binder; binder.bind(globals())
from learntools.pandas.summary_functions_and_maps import *
print("Setup complete.")
revi... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Exercises
Step2: 2.
Step3: 3.
Step4: 4.
Step5: 5.
Step6: 6.
Step7: 7.
|
2,157 | <ASSISTANT_TASK:>
Python Code:
import pandas as pd
import sklearn
data_dir = '../data/raw/'
data_filename = 'blood_train.csv'
df_blood = pd.read_csv(data_dir+data_filename)
df_blood.head(10)
X = df_blood.iloc[:,1:5].as_matrix()
y = list(df_blood["Made Donation in March 2007"])
from sklearn.model_selection 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: <br><br><br><br>
Step2: <br><br><br><br>
Step3: <br><br><br><br>
Step4: <br><br><br><br><br>
Step5: Submission code for Logistic Regression
... |
2,158 | <ASSISTANT_TASK:>
Python Code:
%run db2.ipynb
%sql -sampledata
%%sql
SELECT COVARIANCE_SAMP(SALARY, BONUS)
FROM EMPLOYEE
WHERE WORKDEPT = 'A00'
%%sql
SELECT STDDEV_SAMP(SALARY)
FROM EMPLOYEE
WHERE WORKDEPT = 'A00'
%%sql
SELECT VARIANCE_SAMP(SALARY)
FROM EMPLOYEE
WHERE WORKDEPT = 'A00'
%%sql
SELECT MEDI... | <SYSTEM_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 populate the database with the EMPLOYEE and DEPARTMENT tables so that we can run the various examples.
Step2: <a id="covariance"></a>
Step3:... |
2,159 | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
from scipy.integrate import odeint
from IPython.html.widgets import interact, fixed
def solve_euler(derivs, y0, x):
Solve a 1d ODE using Euler's method.
Parameters
----------
... | <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: Euler's method
Step4: The midpoint method is another numerical method for solving the above differential equation. In general it is more accura... |
2,160 | <ASSISTANT_TASK:>
Python Code:
# Import all libraries needed for the tutorial
# General syntax to import specific functions in a library:
##from (library) import (specific library function)
from pandas import DataFrame, read_csv
# General syntax to import a library but no functions:
##import (library) as (give the 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: Create Data
Step2: To merge these two lists together we will use the zip function.
Step3: We are basically done creating the data set. We now ... |
2,161 | <ASSISTANT_TASK:>
Python Code:
!wget http://ghdx.healthdata.org/sites/default/files/record-attached-files/IHME_GBD_HEP_C_RESEARCH_ARCHIVE_Y2013M04D12.ZIP
!unzip IHME_GBD_HEP_C_RESEARCH_ARCHIVE_Y2013M04D12.ZIP
# This Python code will export predictions
# for the following region/sex/year:
predict_region = 'USA'
predict... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Load the model, and keep only data for the prediction region/sex/year
Step2: The easiest way to get these predictions into a csv file is to use... |
2,162 | <ASSISTANT_TASK:>
Python Code:
import ast_tools
from ast_tools.transformers.loop_unroller import unroll_for_loops
from ast_tools.passes import begin_rewrite, end_rewrite, loop_unroll
@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 # 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:
Step2: Although we are making an 2-bit adder,
Step3: To generate a Circuit from a Generator, we can directly call the generate static method.
Step4: ... |
2,163 | <ASSISTANT_TASK:>
Python Code:
BUCKET='cs358-bucket' # CHANGE ME
import os
os.environ['BUCKET'] = BUCKET
# Create spark session
from __future__ import print_function
from pyspark.sql import SparkSession
from pyspark import SparkContext
sc = SparkContext('local', 'logistic')
spark = SparkSession \
.builder \
.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: <h2> Read dataset </h2>
Step3: <h2> Clean up </h2>
Step6: Note that the counts for the various columns are all different; We have to remove NU... |
2,164 | <ASSISTANT_TASK:>
Python Code:
import sys
sys.path.append('utils/')
import numpy as np
import loadGlasser as lg
import scipy.stats as stats
import matplotlib.pyplot as plt
import statsmodels.sandbox.stats.multicomp as mc
import sys
import warnings
warnings.filterwarnings('ignore')
%matplotlib inline
import nibabel as n... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: 0.0 Basic parameters
Step2: 1.0 Run Region-to-region information transfer mapping
Step3: 2.1 Visualize Information transfer mapping matrices (... |
2,165 | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
import pandas as pd
import numpy as np
from matplotlib import pyplot as plt
import seaborn as sns
from sklearn import preprocessing
from sklearn.model_selection import train_test_split, cross_val_score, GridSearchCV
from sklearn.feature_selection import SelectKBest, mut... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Abstract
Step2: Preprocessing
Step3: The selected features
Step4: In sklearn the features have to be numerical that we input in this algorith... |
2,166 | <ASSISTANT_TASK:>
Python Code:
# useful additional packages
import numpy as np
import random
# regular expressions module
import re
# importing the QISKit
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute, Aer
# import basic plot tools
from qiskit.tools.visualization import circuit_drawer,... | <SYSTEM_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 one
Step2: Let us assume that qubits qr[0] and qr[1] belong to Alice and Bob respetively.
Step3: Qubits qr[0] and qr[1] are now entangled... |
2,167 | <ASSISTANT_TASK:>
Python Code:
#Import all required libraries
import numpy as np
import pandas as pd
from bokeh.plotting import figure, show, output_file
from bokeh.models import HoverTool, ColumnDataSource
from bokeh.io import output_notebook
import glob
output_notebook()
#Set the variables.
FOLDER = "../results/"
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: Prepare Bokeh
Step2: Variables
Step5: Functions
Step6: Execution
|
2,168 | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
from __future__ import print_function
from statsmodels.compat import lzip
import statsmodels
import numpy as np
import pandas as pd
import statsmodels.formula.api as smf
import statsmodels.stats.api as sms
import matplotlib.pyplot as plt
# Load data
url = 'http://vincen... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Normality of the residuals
Step2: Omni test
Step3: Influence tests
Step4: Explore other options by typing dir(influence_test)
Step5: Other p... |
2,169 | <ASSISTANT_TASK:>
Python Code:
# Import numpy library
import numpy as np
x = [5, 4, 3, 4]
print(type(x[0]))
# Create a list of floats containing the same elements as in x
x_f = []
for element in x:
# <FILL IN>
print(x_f)
print(type(x_f[0]))
# Numpy arrays can be created from numeric lists or using different numpy ... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: 2. Numpy exercises
Step2: If you want to apply a transformation over each element of this list you have to build a loop and operate over each e... |
2,170 | <ASSISTANT_TASK:>
Python Code:
# Author: Alan Leggitt <alan.leggitt@ucsf.edu>
#
# License: BSD (3-clause)
import numpy as np
from scipy.spatial import ConvexHull
from mayavi import mlab
from mne import setup_source_space, setup_volume_source_space
from mne.datasets import sample
print(__doc__)
data_path = sample.data_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: Setup the source spaces
Step2: Plot the positions of each source space
Step3: Compare volume source locations to segmentation file in freeview... |
2,171 | <ASSISTANT_TASK:>
Python Code:
# Author: Tommy Clausner <tommy.clausner@gmail.com>
#
# License: BSD (3-clause)
import os
import nibabel as nib
import mne
from mne.datasets import sample, fetch_fsaverage
from mne.minimum_norm import apply_inverse, read_inverse_operator
from nilearn.plotting import plot_glass_brain
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: Setup paths
Step2: Compute example data. For reference see
Step3: Get a SourceMorph object for VolSourceEstimate
Step4: Apply morph to VolSou... |
2,172 | <ASSISTANT_TASK:>
Python Code:
3 - 2 + 10
2 * 5
10 / 5
print(4 * (2 - 8) + 2)
print(4 * 2 - 8 + 2)
(3 * 2) - 10
3 * (2 - 10)
2 ** 4
2 * 2 * 2 * 2
print(2**8) # 2-to-the-8
print(256**(1.0/8.0)) # 256-to-the-one-eighth
print(1/8)
print(1.0/8.0)
print(9/2)
print(9%2)
8%2
print( (2*3) ** 2 )
print( ... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Multiplication and Division
Step2: A challenge for you!
Step3: The results are different due to the order in which Python runs the operations.... |
2,173 | <ASSISTANT_TASK:>
Python Code:
g = Integer(low=100, high=200)
g.reset(seed=12345); print_generated_sequence(g, num=15)
g.reset(seed=9999); print_generated_sequence(g, num=15)
some_integers = g.generate(5, seed=99999)
for x in some_integers:
print(x)
#g = Integer(low=100, high=200, distribution=None)
g = Float(low... | <SYSTEM_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 default distribution is "uniform", but we can use any(?) of the distributions supported by numpy.
Step2: Class Float
Step3: Class NumpyRan... |
2,174 | <ASSISTANT_TASK:>
Python Code:
%%bash
cd /tmp
rm -rf playground #remove if it exists
git clone https://github.com/dsondak/playground.git
%%bash
cd /tmp/playground
git branch -avv
%%bash
cd /tmp/playground
git branch mybranch1
%%bash
cd /tmp/playground
git branch
%%bash
cd /tmp/playground
git checkout mybranch1
git... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Once you're in your playground repo, you can look at all the branches and print out a lot of information to the screen.
Step2: All of these bra... |
2,175 | <ASSISTANT_TASK:>
Python Code:
%config InlineBackend.figure_format = 'retina'
import matplotlib.pyplot as plt
import numpy as np
from uncertainties import unumpy as unp
import pytheos as eos
eta = np.linspace(1., 0.6, 9)
print(eta)
dorogokupets2015_mgo = eos.periclase.Dorogokupets2015()
help(eos.periclase.Dorogokupet... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: 0. General note
Step2: 3. Compare
Step3: Table is not given in this publication.
|
2,176 | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
import pylab as plt
import networkx as nx
G=nx.Graph()
G.add_node(0, label='A')
G.add_node(1, label='B')
G.add_node(2, label='C')
G.add_edge(0,1, label='x')
G.add_edge(1,2, label='y')
G.add_edge(2,0, label='z')
from eden.util import display
print display.serialize_graph... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Build graphs and then display them
Step2: Create a vector representation
Step3: Compute pairwise similarity matrix
|
2,177 | <ASSISTANT_TASK:>
Python Code:
import ROOT
f = ROOT.TFile.Open("http://indico.cern.ch/event/395198/material/0/0.root")
maxPt=-1
for event in f.events:
maxPt=-1
for track in event.tracks:
pt = track.Pt()
if pt > maxPt: maxPt = pt
if event.evtNum % 100 == 0:
print "Processing event n... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Open a file which is located on the web. No type is to be specified for "f".
Step2: Loop over the TTree called "events" in the file. It is acce... |
2,178 | <ASSISTANT_TASK:>
Python Code:
ch=input('请输入一个字符: ')
n=int(input('请输入打印行数:'))
for i in range(1,n+1):
print(' '*(n-i)+(ch+' ')*i)
for i in range(1,10):
for j in range(1,i+1):
print('{}*{}={:<2}'.format(i,j,i*j),end=' ')
print()
def zhishu(x):
flag=1
for i in range(2,x//2):
if x%i==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: 2、打印如下9*9 乘法口诀表,注意每列左侧竖向对齐。
Step2: 3、写函数,可检查一个数(2-100000之间整数)能不能表示成两个质数之和,如果能,则打印这两个质数。主程序用18及93887分别做测试。
Step3: 4、有一个列表:[1, 2, 3, 4…n],n=20;请... |
2,179 | <ASSISTANT_TASK:>
Python Code:
import os, sys
sys.path.append(os.path.abspath('../../main/python'))
import thalesians.tsa.pypes as pypes
pype = pypes.Pype(pypes.Direction.INCOMING, name='EXAMPLE', port=5758); pype
for x in pype: print(x)
pype.close()
<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: Then run the following cell and send some values from pypeoutgoing.ipynb running in another window. The will be sent over the "pype". Watch them... |
2,180 | <ASSISTANT_TASK:>
Python Code:
from pyhande.data_preparing.hande_ccmc_fciqmc import PrepHandeCcmcFciqmc
from pyhande.extracting.extractor import Extractor
from pyhande.error_analysing.blocker import Blocker
from pyhande.results_viewer.get_results import analyse_data
extra = Extractor() # Keep the defaults, merge using ... | <SYSTEM_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 this is the original default CCMC/FCIQMC HANDE columns/key mapping in preparator.
Step2: Now we execute our executor, preparator and... |
2,181 | <ASSISTANT_TASK:>
Python Code:
with open("MA0099.3.jaspar") as f:
motifs = read_motifs(f, fmt="jaspar")
print(motifs[0])
with open("example.pfm") as f:
motifs = read_motifs(f)
# pwm
print(motifs[0].to_pwm())
# pfm
print(motifs[0].to_pfm())
# consensus sequence
print(motifs[0].to_consensus())
# TRANSFAC
print(m... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: You can convert a motif to several formats.
Step2: Some other useful tidbits.
Step3: To convert a motif to an image, use to_img(). Supported f... |
2,182 | <ASSISTANT_TASK:>
Python Code:
class SolutionMissingError(Exception):
def __init__(self):
Exception.__init__(self,"You need to complete the solution for this code to work!")
def REPLACE_WITH_YOUR_SOLUTION():
raise SolutionMissingError
REMOVE_THIS_LINE = REPLACE_WITH_YOUR_SOLUTION
import numpy as np
imp... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Tutorial
Step2: Load data into global variable y. Each entry is an offset in units of kpc.
Step3: Check out a quick histogram of the data.
Ste... |
2,183 | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
import pickle as pkl
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets('MNIST_data')
def model_inputs(real_dim, z_dim):
inputs_real = tf.placeholde... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Model Inputs
Step2: Generator network
Step3: Discriminator
Step4: Hyperparameters
Step5: Build network
Step6: Discriminator and Generator L... |
2,184 | <ASSISTANT_TASK:>
Python Code:
# DO NOT EDIT !
from pyesdoc.ipython.model_topic import NotebookOutput
# DO NOT EDIT !
DOC = NotebookOutput('cmip6', 'cas', 'fgoals-f3-h', 'land')
# Set as follows: DOC.set_author("name", "email")
# TODO - please enter value(s)
# Set as follows: DOC.set_contributor("name", "emai... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Document Authors
Step2: Document Contributors
Step3: Document Publication
Step4: Document Table of Contents
Step5: 1.2. Model Name
Step6: 1... |
2,185 | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
import datetime
from qutip import Qobj, identity, sigmax, sigmay, sigmaz, tensor
from qutip.qip import hadamard_transform
import qutip.logging_utils as logging
logger = logging.get_logger()
#Set this to None or logging.... | <SYSTEM_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 physics
Step2: Defining the time evolution parameters
Step3: Set the conditions which will cause the pulse optimisation to termin... |
2,186 | <ASSISTANT_TASK:>
Python Code:
#This line is very important: (It turns on the inline visuals!)
%pylab inline
a = [2,9,32,12,14,6,9,23,4,5,13,6,7,92,21,45];
b = [7,21,4,2,92,9,9,6,13,12,45,5,6,23,14,32];
#Please calculate the dot product of the vectors 'a' and 'b'.
#You may use any method you like. If get stuck. Check:
... | <SYSTEM_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 Pearson's test
Step2: Pearson's comparison of microscopy derived images
Step3: Maybe remove so not to clash with Mark's.
|
2,187 | <ASSISTANT_TASK:>
Python Code:
import pandas as pd
import numpy as np
features_df = pd.DataFrame.from_csv("well_data.csv")
labels_df = pd.DataFrame.from_csv("well_labels.csv")
print( labels_df.head(20) )
print( features_df.head() )
def label_map(y):
if y=="functional":
return 2
elif y=="functio... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: One nice feature of ipython notebooks is it's easy to make small changes to code and
Step2: Transforming string labels into integers
Step3: Tr... |
2,188 | <ASSISTANT_TASK:>
Python Code:
from sympy import *
from sympy.solvers.solveset import solveset
init_printing()
a, b, c, d, x, y, z, t = symbols('a b c d x y z t')
f, g, h = symbols('f g h', cls=Function)
def quadratic():
return solveset(a*x**2 + b*x + c, x)
quadratic()
def cubic():
return solveset(x**3 + a*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: For each exercise, fill in the function according to its docstring.
Step2: Algebraic Equations
Step3: Write a function that computes the gener... |
2,189 | <ASSISTANT_TASK:>
Python Code:
import numpy as np
import matplotlib.pyplot as plt; plt.ion()
from scipy.optimize import least_squares
from scipy import stats as st
def receivePowerModel(d, k, n):
return k - 10 * n * np.log10(d)
vx = np.array([[5, 1, 0],
[-1, 5, 0],
[-5, -1, 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: Model Estimation
Step2: When we receive data, we can extract the following information
Step3: To localize the transmitter, we simply take the ... |
2,190 | <ASSISTANT_TASK:>
Python Code:
k_classes = 2
X = [[1., 1.5, 0.2], [1., 0.3, 1.2], [1, 1.6, 0.4], [1., 1.3, 0.25], [1., 0.5, 1.12]]
Y = [1, 2, 1, 1, 2]
%matplotlib inline
import matplotlib.pyplot as plt
plt.figure()
X1 = [x[1] for x in X]
X2 = [x[2] for x in X]
plt.scatter(X1, X2, c=Y) # plot x1, x2, color is defined b... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Let us take a look at the data in 2D (we ignore the intercept which is constantly equal to 1).
Step2: The data was generated so that we have tw... |
2,191 | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
import math
import matplotlib.pyplot as plt
import numpy as np
import openmc
import openmc.mgxs
# 1.6 enriched fuel
fuel = openmc.Material(name='1.6% Fuel')
fuel.set_density('g/cm3', 10.31341)
fuel.add_nuclide('U235', 3.7503e-4)
fuel.add_nuclide('U238', 2.2625e-2)
fuel... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: First we need to define materials that will be used in the problem
Step2: With our three materials, we can now create a Materials object that c... |
2,192 | <ASSISTANT_TASK:>
Python Code:
rjecnik={}
rjecnik={'a':5, 'b':3.8}
rjecnik={'a':5, 'b':3.8}
len(rjecnik)
rjecnik={'a':5, 'b':3.8}
rjecnik['b']=9
print rjecnik
print rjecnik['a']
rjecnik={'a':5, 'b':3.8}
print rjecnik['c']
rjecnik={'a':5, 'b':3.8}
print rjecnik.get('a')
rjecnik={'a':5, 'b':3.8}
print rjecnik.get(... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: Varijabla rjecnik je prazan rječnik, odnosno ne sadrži ni jedan uređeni par (ključ
Step2: Varijabla rjecnik sadrži u dva uređena para. Prvi ur... |
2,193 | <ASSISTANT_TASK:>
Python Code:
%pylab inline
import IPython
import sklearn as sk
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
print 'IPython version:', IPython.__version__
print 'numpy version:', np.__version__
print 'scikit-learn version:', sk.__version__
print 'matplotlib version:', 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: Every method implemented on scikit-learn assumes that data comes in a dataset. Scikit-learn includes a few well-known datasets. The Iris flower ... |
2,194 | <ASSISTANT_TASK:>
Python Code:
import pandas as pd
df = pd.DataFrame({'name': ['matt', 'james', 'adam'],
'status': ['active', 'active', 'inactive'],
'number': [12345, 23456, 34567],
'message': ['[job: , money: none, wife: none]',
'... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
|
2,195 | <ASSISTANT_TASK:>
Python Code:
#!pip install -I "phoebe>=2.4,<2.5"
import phoebe
from phoebe import u # units
import numpy as np
import matplotlib.pyplot as plt
logger = phoebe.logger()
b = phoebe.default_binary()
b.add_dataset('mesh', compute_times=[0.75], dataset='mesh01')
b['requiv@primary@component'] = 1.8
b.ru... | <SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
Step1: As always, let's do imports and initialize a logger and a new bundle.
Step2: Adding Datasets
Step3: Running Compute
Step4: Now we'll compute ... |
2,196 | <ASSISTANT_TASK:>
Python Code:
from hirise_tools.downloads import download_RED_product
from hirise_tools.products import RED_PRODUCT_ID
import logging
from nbtools.logging import setup_live_logging
from planet4 import io, region_data
db = io.DBManager()
roi = region_data.Potsdam()
obsids = roi.all_obsids
obsids
obsids ... | <SYSTEM_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 mosaics
Step2: Parallel production
Step6: xy2latlon
Step7: Execute campt for all obsids
Step8: Combine obsid results and merge with m... |
2,197 | <ASSISTANT_TASK:>
Python Code:
%matplotlib inline
import plot_helper
import cobra.test
from cobra import Reaction, Metabolite, Model
from cobra.flux_analysis.loopless import construct_loopless_model
from cobra.solvers import get_solver_name
plot_helper.plot_loop()
test_model = Model()
test_model.add_metabolites(Metabo... | <SYSTEM_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 demonstrate with a toy model which has a simple loop cycling A -> B -> C -> A, with A allowed to enter the system and C allowed to leave... |
2,198 | <ASSISTANT_TASK:>
Python Code:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap
from sklearn.cross_validation import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.datasets import make_moons, make_circles, make_classification
from sklearn.ne... | <SYSTEM_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: (三)測試分類器並作圖
|
2,199 | <ASSISTANT_TASK:>
Python Code:
# import urllib.request
import urllib
fitsurl="http://dr10.sdss3.org/sas/dr10/sdss/spectro/redux/26/spectra/0651/spec-0651-52141-0569.fits"
#urllib.request.urlretrieve(fitsurl,"spec.fits")
urllib.urlretrieve(fitsurl,"spec.fits")
texturl="http://services.swpc.noaa.gov/text/predicted-sunsp... | <SYSTEM_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 分別演示如何使用 urllib來透過 url 抓取資料
Step2: Lab:請修改 url 為你自己感興趣的資料來源, 下載資料並存在自己命名的檔案中
Step3: hdulist 顧名思義, 就是 a list of Header/Data Unit (廢話)... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.