text_prompt stringlengths 157 13.1k | code_prompt stringlengths 7 19.8k ⌀ |
|---|---|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def discrete(cats, name='discrete'):
"""Return a class category that shows the encoding""" |
import json
ks = list(cats)
for key in ks:
if isinstance(key, bytes):
cats[key.decode('utf-8')] = cats.pop(key)
return 'discrete(' + json.dumps([cats, name]) + ')' |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def clear_cache(dataset_name=None):
"""Remove a data set from the cache""" |
dr = data_resources[dataset_name]
if 'dirs' in dr:
for dirs, files in zip(dr['dirs'], dr['files']):
for dir, file in zip(dirs, files):
path = os.path.join(data_path, dataset_name, dir, file)
if os.path.exists(path):
logging.info("clear_cac... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def to_arff(dataset, **kwargs):
"""Take a pods data set and write it as an ARFF file""" |
pods_data = dataset(**kwargs)
vals = list(kwargs.values())
for i, v in enumerate(vals):
if isinstance(v, list):
vals[i] = '|'.join(v)
else:
vals[i] = str(v)
args = '_'.join(vals)
n = dataset.__name__
if len(args)>0:
n += '_' + args
n = n.r... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def epomeo_gpx(data_set='epomeo_gpx', sample_every=4):
"""Data set of three GPS traces of the same movement on Mt Epomeo in Ischia. Requires gpxpy to run.""" |
import gpxpy
import gpxpy.gpx
if not data_available(data_set):
download_data(data_set)
files = ['endomondo_1', 'endomondo_2', 'garmin_watch_via_endomondo','viewranger_phone', 'viewranger_tablet']
X = []
for file in files:
gpx_file = open(os.path.join(data_path, 'epomeo_gpx', fi... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def pmlr(volumes='all', data_set='pmlr'):
"""Abstracts from the Proceedings of Machine Learning Research""" |
if not data_available(data_set):
download_data(data_set)
proceedings_file = open(os.path.join(data_path, data_set, 'proceedings.yaml'), 'r')
import yaml
proceedings = yaml.load(proceedings_file)
# Create a new resources entry for downloading contents of proceedings.
data_n... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def lee_yeast_ChIP(data_set='lee_yeast_ChIP'):
"""Yeast ChIP data from Lee et al.""" |
if not data_available(data_set):
download_data(data_set)
from pandas import read_csv
dir_path = os.path.join(data_path, data_set)
filename = os.path.join(dir_path, 'binding_by_gene.tsv')
S = read_csv(filename, header=1, index_col=0, sep='\t')
transcription_factors = [col for col in S.co... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def osu_run1(data_set='osu_run1', sample_every=4):
"""Ohio State University's Run1 motion capture data set.""" |
path = os.path.join(data_path, data_set)
if not data_available(data_set):
import zipfile
download_data(data_set)
zip = zipfile.ZipFile(os.path.join(data_path, data_set, 'run1TXT.ZIP'), 'r')
for name in zip.namelist():
zip.extract(name, path)
from . import mocap
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def toy_linear_1d_classification(seed=default_seed):
"""Simple classification data in one dimension for illustrating models.""" |
def sample_class(f):
p = 1. / (1. + np.exp(-f))
c = np.random.binomial(1, p)
c = np.where(c, 1, -1)
return c
np.random.seed(seed=seed)
x1 = np.random.normal(-3, 5, 20)
x2 = np.random.normal(3, 5, 20)
X = (np.r_[x1, x2])[:, None]
return {'X': X, 'Y': sample_clas... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def airline_delay(data_set='airline_delay', num_train=700000, num_test=100000, seed=default_seed):
"""Airline delay data used in Gaussian Processes for Big Data ... |
if not data_available(data_set):
download_data(data_set)
dir_path = os.path.join(data_path, data_set)
filename = os.path.join(dir_path, 'filtered_data.pickle')
# 1. Load the dataset
import pandas as pd
data = pd.read_pickle(filename)
# WARNING: removing year
data.pop('Year')... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def olympic_sprints(data_set='rogers_girolami_data'):
"""All olympics sprint winning times for multiple output prediction.""" |
X = np.zeros((0, 2))
Y = np.zeros((0, 1))
cats = {}
for i, dataset in enumerate([olympic_100m_men,
olympic_100m_women,
olympic_200m_men,
olympic_200m_women,
olympic_400m_men,
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def movielens100k(data_set='movielens100k'):
"""Data set of movie ratings collected by the University of Minnesota and 'cleaned up' for use.""" |
if not data_available(data_set):
import zipfile
download_data(data_set)
dir_path = os.path.join(data_path, data_set)
zip = zipfile.ZipFile(os.path.join(dir_path, 'ml-100k.zip'), 'r')
for name in zip.namelist():
zip.extract(name, dir_path)
import pandas as pd
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def ceres(data_set='ceres'):
"""Twenty two observations of the Dwarf planet Ceres as observed by Giueseppe Piazzi and published in the September edition of Monat... |
if not data_available(data_set):
download_data(data_set)
import pandas as pd
data = pd.read_csv(os.path.join(data_path, data_set, 'ceresData.txt'), index_col = 'Tag', header=None, sep='\t',names=['Tag', 'Mittlere Sonnenzeit', 'Gerade Aufstig in Zeit', 'Gerade Aufstiegung in Graden', 'Nordlich Abwei... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def access_elementusers(self, elementuser_id, access_id=None, tenant_id=None, api_version="v2.0"):
""" Get all accesses for a particular user **Parameters:**: - ... |
if tenant_id is None and self._parent_class.tenant_id:
# Pull tenant_id from parent namespace cache.
tenant_id = self._parent_class.tenant_id
elif not tenant_id:
# No value for tenant_id.
raise TypeError("tenant_id is required but not set or cached.")
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def logout(self, api_version="v2.0"):
""" Logout current session **Parameters:**: - **api_version**: API version to use (default v2.0) **Returns:** requests.Resp... |
cur_ctlr = self._parent_class.controller
url = str(cur_ctlr) + "/{}/api/logout".format(api_version)
api_logger.debug("URL = %s", url)
return self._parent_class.rest_call(url, "get") |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def use_token(self, token=None):
""" Function to use static AUTH_TOKEN as auth for the constructor instead of full login process. **Parameters:**: - **token**: S... |
api_logger.info('use_token function:')
# check token is a string.
if not isinstance(token, (text_type, binary_type)):
api_logger.debug('"token" was not a text-style string: {}'.format(text_type(token)))
return False
# Start setup of constructor.
session... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def interactive_tenant_update_vars(self):
""" Function to update the `cloudgenix.API` object with tenant login info. Run after login or client login. **Returns:*... |
api_logger.info('interactive_tenant_update_vars function:')
tenant_resp = self._parent_class.get.tenants(self._parent_class.tenant_id)
status = tenant_resp.cgx_status
tenant_dict = tenant_resp.cgx_content
if status:
api_logger.debug("new tenant_dict: %s", tenant_di... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def interactive_update_profile_vars(self):
""" Function to update the `cloudgenix.API` object with profile info. Run after login or client login. **Returns:** Bo... |
profile = self._parent_class.get.profile()
if profile.cgx_status:
# if successful, save tenant id and email info to cli state.
self._parent_class.tenant_id = profile.cgx_content.get('tenant_id')
self._parent_class.email = profile.cgx_content.get('email')
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def quick_menu(self, banner, list_line_format, choice_list):
""" Function to display a quick menu for user input **Parameters:** - **banner:** Text to display be... |
# Setup menu
invalid = True
menu_int = -1
# loop until valid
while invalid:
print(banner)
for item_index, item_value in enumerate(choice_list):
print(list_line_format.format(item_index + 1, *item_value))
menu_choice = compat... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def check_sso_login(self, operator_email, request_id):
""" Login to the CloudGenix API, and see if SAML SSO has occurred. This function is used to check and see ... |
data = {
"email": operator_email,
"requestId": request_id
}
# If debug is set..
api_logger.info('check_sso_login function:')
response = self._parent_class.post.login(data=data)
# If valid response, but no token.
if not response.cgx_con... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def quick_confirm(prompt, default_value):
""" Function to display a quick confirmation for user input **Parameters:** - **prompt:** Text to display before confir... |
valid = False
value = default_value.lower()
while not valid:
input_val = compat_input(prompt + "[{0}]: ".format(default_value))
if input_val == "":
value = default_value.lower()
valid = True
else:
try:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def quick_int_input(prompt, default_value, min_val=1, max_val=30):
""" Function to display a quick question for integer user input **Parameters:** - **prompt:** ... |
valid = False
num_val = default_value
while not valid:
input_val = compat_input(prompt + "[{0}]: ".format(default_value))
if input_val == "":
num_val = default_value
valid = True
else:
try:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def quick_str_input(prompt, default_value):
""" Function to display a quick question for text input. **Parameters:** - **prompt:** Text / question to display - *... |
valid = False
str_val = default_value
while not valid:
input_val = raw_input(prompt + "[{0}]: ".format(default_value))
if input_val == "":
str_val = default_value
valid = True
else:
try:
str... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def tran_hash(self, a, b, c, n):
"""implementation of the tran53 hash function""" |
return (((TRAN[(a+n)&255]^TRAN[b]*(n+n+1))+TRAN[(c)^TRAN[n]])&255) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def process(self, chunk):
""" computes the hash of all of the trigrams in the chunk using a window of length 5 """ |
self._digest = None
if isinstance(chunk, text_type):
chunk = chunk.encode('utf-8')
# chunk is a byte string
for char in chunk:
self.num_char += 1
if PY3:
# In Python 3, iterating over bytes yields integers
c = char
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def from_file(self, fname):
"""read in a file and compute digest""" |
f = open(fname, "rb")
data = f.read()
self.update(data)
f.close() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def compare(self, digest_2, is_hex = False):
""" returns difference between the nilsimsa digests between the current object and a given digest """ |
# convert hex string to list of ints
if is_hex:
digest_2 = convert_hex_to_ints(digest_2)
bit_diff = 0
for i in range(len(self.digest)):
bit_diff += POPC[self.digest[i] ^ digest_2[i]] #computes the bit diff between the i'th position of the digests
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def tenant_forgot_password_login(self, data, tenant_id=None, api_version="v2.0"):
""" Forgot password API **Parameters:**: - **data**: Dictionary containing data... |
if tenant_id is None and self._parent_class.tenant_id:
# Pull tenant_id from parent namespace cache.
tenant_id = self._parent_class.tenant_id
elif not tenant_id:
# No value for tenant_id.
raise TypeError("tenant_id is required but not set or cached.")
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def is_valid_file(parser,arg):
"""verify the validity of the given file. Never trust the End-User""" |
if not os.path.exists(arg):
parser.error("File %s not found"%arg)
else:
return arg |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def getID(code_file):
"""Get the language ID of the input file language""" |
json_path = ghostfolder+'/'+json_file
if os.path.exists(json_path):
pass
else:
download_file('https://ghostbin.com/languages.json')
lang = detect_lang(code_file)
json_data = json.load(file(json_path))#don't think i need this though
ID = ''
for i in range(len(json_data)):
temp = len(json_data[i]['langua... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def detect_lang(path):
"""Detect the language used in the given file.""" |
blob = FileBlob(path, os.getcwd())
if blob.is_text:
print('Programming language of the file detected: {0}'.format(blob.language.name))
return blob.language.name
else:#images, binary and what-have-you won't be pasted
print('File not a text file. Exiting...')
sys.exit() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def screenshot(self, scale=None, quality=None):
""" Take a screenshot of device and log in the report with timestamp, scale for screenshot size and quality for s... |
output_dir = BuiltIn().get_variable_value('${OUTPUTDIR}')
ts = time.time()
st = datetime.datetime.fromtimestamp(ts).strftime('%Y%m%d%H%M%S')
screenshot_path = '%s%s%s.png' % (output_dir, os.sep, st)
self.device.screenshot(screenshot_path, scale, quality)
logger.info('\n<... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def call(self, obj, method, *args, **selectors):
""" This keyword can use object method from original python uiautomator See more details from https://github.com... |
func = getattr(obj, method)
return func(**selectors) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def merge_sims(oldsims, newsims, clip=None):
"""Merge two precomputed similarity lists, truncating the result to `clip` most similar items.""" |
if oldsims is None:
result = newsims or []
elif newsims is None:
result = oldsims
else:
result = sorted(oldsims + newsims, key=lambda item: -item[1])
if clip is not None:
result = result[:clip]
return result |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def terminate(self):
"""Delete all files created by this index, invalidating `self`. Use with care.""" |
try:
self.id2sims.terminate()
except:
pass
import glob
for fname in glob.glob(self.fname + '*'):
try:
os.remove(fname)
logger.info("deleted %s" % fname)
except Exception, e:
logger.warning("f... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def update_ids(self, docids):
"""Update id->pos mapping with new document ids.""" |
logger.info("updating %i id mappings" % len(docids))
for docid in docids:
if docid is not None:
pos = self.id2pos.get(docid, None)
if pos is not None:
logger.info("replacing existing document %r in %s" % (docid, self))
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def vec_by_id(self, docid):
"""Return indexed vector corresponding to document `docid`.""" |
pos = self.id2pos[docid]
return self.qindex.vector_by_id(pos) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def merge(self, other):
"""Merge documents from the other index. Update precomputed similarities in the process.""" |
other.qindex.normalize, other.qindex.num_best = False, self.topsims
# update precomputed "most similar" for old documents (in case some of
# the new docs make it to the top-N for some of the old documents)
logger.info("updating old precomputed values")
pos, lenself = 0, len(self... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def doc2vec(self, doc):
"""Convert a single SimilarityDocument to vector.""" |
bow = self.dictionary.doc2bow(doc['tokens'])
if self.method == 'lsi':
return self.lsi[self.tfidf[bow]]
elif self.method == 'lda':
return self.lda[bow]
elif self.method == 'lda_tfidf':
return self.lda[self.tfidf[bow]]
elif self.method == 'logen... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def flush(self, save_index=False, save_model=False, clear_buffer=False):
"""Commit all changes, clear all caches.""" |
if save_index:
if self.fresh_index is not None:
self.fresh_index.save(self.location('index_fresh'))
if self.opt_index is not None:
self.opt_index.save(self.location('index_opt'))
if save_model:
if self.model is not None:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def close(self):
"""Explicitly close open file handles, databases etc.""" |
try:
self.payload.close()
except:
pass
try:
self.model.close()
except:
pass
try:
self.fresh_index.close()
except:
pass
try:
self.opt_index.close()
except:
pass... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def train(self, corpus=None, method='auto', clear_buffer=True, params=None):
""" Create an indexing model. Will overwrite the model if it already exists. All ind... |
if corpus is not None:
# use the supplied corpus only (erase existing buffer, if any)
self.flush(clear_buffer=True)
self.buffer(corpus)
if not self.fresh_docs:
msg = "train called but no training corpus specified for %s" % self
logger.error(ms... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def index(self, corpus=None, clear_buffer=True):
""" Permanently index all documents previously added via `buffer`, or directly index documents from `corpus`, if... |
if not self.model:
msg = 'must initialize model for %s before indexing documents' % self.basename
logger.error(msg)
raise AttributeError(msg)
if corpus is not None:
# use the supplied corpus only (erase existing buffer, if any)
self.flush(cle... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def drop_index(self, keep_model=True):
"""Drop all indexed documents. If `keep_model` is False, also dropped the model.""" |
modelstr = "" if keep_model else "and model "
logger.info("deleting similarity index " + modelstr + "from %s" % self.basename)
# delete indexes
for index in [self.fresh_index, self.opt_index]:
if index is not None:
index.terminate()
self.fresh_index,... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def delete(self, docids):
"""Delete specified documents from the index.""" |
logger.info("asked to drop %i documents" % len(docids))
for index in [self.opt_index, self.fresh_index]:
if index is not None:
index.delete(docids)
self.flush(save_index=True) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def find_similar(self, doc, min_score=0.0, max_results=100):
""" Find `max_results` most similar articles in the index, each having similarity score of at least ... |
logger.debug("received query call with %r" % doc)
if self.is_locked():
msg = "cannot query while the server is being updated"
logger.error(msg)
raise RuntimeError(msg)
sims_opt, sims_fresh = None, None
for index in [self.fresh_index, self.opt_index]:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def keys(self):
"""Return ids of all indexed documents.""" |
result = []
if self.fresh_index is not None:
result += self.fresh_index.keys()
if self.opt_index is not None:
result += self.opt_index.keys()
return result |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def check_session(self):
""" Make sure a session is open. If it's not and autosession is turned on, create a new session automatically. If it's not and autosessi... |
if self.session is None:
if self.autosession:
self.open_session()
else:
msg = "must open a session before modifying %s" % self
raise RuntimeError(msg) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def open_session(self):
""" Open a new session to modify this server. You can either call this fnc directly, or turn on autosession which will open/commit sessio... |
if self.session is not None:
msg = "session already open; commit it or rollback before opening another one in %s" % self
logger.error(msg)
raise RuntimeError(msg)
logger.info("opening a new session")
logger.info("removing %s" % self.loc_session)
try:... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def buffer(self, *args, **kwargs):
"""Buffer documents, in the current session""" |
self.check_session()
result = self.session.buffer(*args, **kwargs)
return result |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def index(self, *args, **kwargs):
"""Index documents, in the current session""" |
self.check_session()
result = self.session.index(*args, **kwargs)
if self.autosession:
self.commit()
return result |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def drop_index(self, keep_model=True):
"""Drop all indexed documents from the session. Optionally, drop model too.""" |
self.check_session()
result = self.session.drop_index(keep_model)
if self.autosession:
self.commit()
return result |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def delete(self, docids):
"""Delete documents from the current session.""" |
self.check_session()
result = self.session.delete(docids)
if self.autosession:
self.commit()
return result |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def optimize(self):
"""Optimize index for faster by-document-id queries.""" |
self.check_session()
result = self.session.optimize()
if self.autosession:
self.commit()
return result |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def commit(self):
"""Commit changes made by the latest session.""" |
if self.session is not None:
logger.info("committing transaction in %s" % self)
tmp = self.stable
self.stable, self.session = self.session, None
self.istable = 1 - self.istable
self.write_istable()
tmp.close() # don't wait for gc, release ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def terminate(self):
"""Delete all files created by this server, invalidating `self`. Use with care.""" |
logger.info("deleting entire server %s" % self)
self.close()
try:
shutil.rmtree(self.basedir)
logger.info("deleted server under %s" % self.basedir)
# delete everything from self, so that using this object fails results
# in an error as quickly as ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def find_similar(self, *args, **kwargs):
""" Find similar articles. With autosession off, use the index state *before* current session started, so that changes m... |
if self.session is not None and self.autosession:
# with autosession on, commit the pending transaction first
self.commit()
return self.stable.find_similar(*args, **kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| async def profile(self, ctx, platform, name):
'''Fetch a profile.'''
player = await self.client.get_player(platform, name)
solos = await player.get_solos()
await ctx.send("# of kills in solos for {}: {}".format(name,solos.kills.value)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def generate_chunks(data, chunk_size=DEFAULT_CHUNK_SIZE):
"""Yield 'chunk_size' items from 'data' at a time.""" |
iterator = iter(repeated.getvalues(data))
while True:
chunk = list(itertools.islice(iterator, chunk_size))
if not chunk:
return
yield chunk |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def reduce(reducer, data, chunk_size=DEFAULT_CHUNK_SIZE):
"""Repeatedly call fold and merge on data and then finalize. Arguments: data: Input for the fold functi... |
if not chunk_size:
return finalize(reducer, fold(reducer, data))
# Splitting the work up into chunks allows us to, e.g. reduce a large file
# without loading everything into memory, while still being significantly
# faster than repeatedly calling the fold function for every element.
chunks... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def conditions(self):
"""The if-else pairs.""" |
for idx in six.moves.range(1, len(self.children), 2):
yield (self.children[idx - 1], self.children[idx]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def handle_noargs(self, **options):
"""Send Report E-mails.""" |
r = get_r()
since = datetime.utcnow() - timedelta(days=1)
metrics = {}
categories = r.metric_slugs_by_category()
for category_name, slug_list in categories.items():
metrics[category_name] = []
for slug in slug_list:
metric_values = r.get_... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add_tasks(self, value):
""" Adds tasks to the existing set of tasks of the Stage :argument: set of tasks """ |
tasks = self._validate_entities(value)
self._tasks.update(tasks)
self._task_count = len(self._tasks) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def to_dict(self):
""" Convert current Stage into a dictionary :return: python dictionary """ |
stage_desc_as_dict = {
'uid': self._uid,
'name': self._name,
'state': self._state,
'state_history': self._state_history,
'parent_pipeline': self._p_pipeline
}
return stage_desc_as_dict |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def from_dict(self, d):
""" Create a Stage from a dictionary. The change is in inplace. :argument: python dictionary :return: None """ |
if 'uid' in d:
if d['uid']:
self._uid = d['uid']
if 'name' in d:
if d['name']:
self._name = d['name']
if 'state' in d:
if isinstance(d['state'], str) or isinstance(d['state'], unicode):
if d['state'] in state... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _make_spec_file(self):
"""Generates the text of an RPM spec file. Returns: A list of strings containing the lines of text. """ |
# Note that bdist_rpm can be an old style class.
if issubclass(BdistRPMCommand, object):
spec_file = super(BdistRPMCommand, self)._make_spec_file()
else:
spec_file = bdist_rpm._make_spec_file(self)
if sys.version_info[0] < 3:
python_package = "python... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def resolve(self, name):
"""Call IStructured.resolve across all scopes and return first hit.""" |
for scope in reversed(self.scopes):
try:
return structured.resolve(scope, name)
except (KeyError, AttributeError):
continue
raise AttributeError(name) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def reflect(self, name):
"""Reflect 'name' starting with local scope all the way up to global. This method will attempt both static and runtime reflection. This ... |
# Return whatever the most local scope defines this as, or bubble all
# the way to the top.
result = None
for scope in reversed(self.scopes):
try:
if isinstance(scope, type):
result = structured.reflect_static_member(scope, name)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def reflect_runtime_member(self, name):
"""Reflect 'name' using ONLY runtime reflection. You most likely want to use ScopeStack.reflect instead. Returns: Type of... |
for scope in reversed(self.scopes):
try:
return structured.reflect_runtime_member(scope, name)
except (NotImplementedError, KeyError, AttributeError):
continue
return protocol.AnyType |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def reflect_static_member(cls, name):
"""Reflect 'name' using ONLY static reflection. You most likely want to use ScopeStack.reflect instead. Returns: Type of 'n... |
for scope in reversed(cls.scopes):
try:
return structured.reflect_static_member(scope, name)
except (NotImplementedError, KeyError, AttributeError):
continue
return protocol.AnyType |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def get_hostmap(profile):
'''
We abuse the profile combination to also derive a pilot-host map, which
will tell us on what exact host each pilot has been running. To do so, we
check for the PMGR_ACTIVE advance event in agent_0.prof, and use the NTP
sync info to associate a hostname.
'''
# F... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def get_hostmap_deprecated(profiles):
'''
This method mangles combine_profiles and get_hostmap, and is deprecated. At
this point it only returns the hostmap
'''
hostmap = dict() # map pilot IDs to host names
for pname, prof in profiles.iteritems():
if not len(prof):
conti... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def categorize_metrics(self):
"""Called only on a valid form, this method will place the chosen metrics in the given catgory.""" |
category = self.cleaned_data['category_name']
metrics = self.cleaned_data['metrics']
self.r.reset_category(category, metrics) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def match(self, f, *args):
"""Match grammar function 'f' against next token and set 'self.matched'. Arguments: f: A grammar function - see efilter.parsers.common... |
try:
match = f(self.tokenizer, *args)
except StopIteration:
# The grammar function might have tried to access more tokens than
# are available. That's not really an error, it just means it didn't
# match.
return
if match is None:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def reject(self, f, *args):
"""Like 'match', but throw a parse error if 'f' matches. This is useful when a parser wants to be strict about specific things being ... |
match = self.match(f, *args)
if match:
token = self.peek(0)
raise errors.EfilterParseError(
query=self.tokenizer.source, token=token,
message="Was not expecting a %s here." % token.name) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def expect(self, f, *args):
"""Like 'accept' but throws a parse error if 'f' doesn't match.""" |
match = self.accept(f, *args)
if match:
return match
try:
func_name = f.func_name
except AttributeError:
func_name = "<unnamed grammar function>"
start, end = self.current_position()
raise errors.EfilterParseError(
query=... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def solve_var(expr, vars):
"""Returns the value of the var named in the expression.""" |
try:
return Result(structured.resolve(vars, expr.value), ())
except (KeyError, AttributeError) as e:
# Raise a better exception for accessing a non-existent member.
raise errors.EfilterKeyError(root=expr, key=expr.value, message=e,
query=expr.source)... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def solve_repeat(expr, vars):
"""Build a repeated value from subexpressions.""" |
try:
result = repeated.meld(*[solve(x, vars).value for x in expr.children])
return Result(result, ())
except TypeError:
raise errors.EfilterTypeError(
root=expr, query=expr.source,
message="All values in a repeated value must be of the same type.") |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def solve_tuple(expr, vars):
"""Build a tuple from subexpressions.""" |
result = tuple(solve(x, vars).value for x in expr.children)
return Result(result, ()) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def solve_ifelse(expr, vars):
"""Evaluate conditions and return the one that matches.""" |
for condition, result in expr.conditions():
if boolean.asbool(solve(condition, vars).value):
return solve(result, vars)
return solve(expr.default(), vars) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def solve_map(expr, vars):
"""Solves the map-form, by recursively calling its RHS with new vars. let-forms are binary expressions. The LHS should evaluate to an ... |
lhs_values, _ = __solve_for_repeated(expr.lhs, vars)
def lazy_map():
try:
for lhs_value in repeated.getvalues(lhs_values):
yield solve(expr.rhs,
__nest_scope(expr.lhs, vars, lhs_value)).value
except errors.EfilterNoneError as error:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def solve_let(expr, vars):
"""Solves a let-form by calling RHS with nested scope.""" |
lhs_value = solve(expr.lhs, vars).value
if not isinstance(lhs_value, structured.IStructured):
raise errors.EfilterTypeError(
root=expr.lhs, query=expr.original,
message="The LHS of 'let' must evaluate to an IStructured. Got %r."
% (lhs_value,))
return solve(expr... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def solve_filter(expr, vars):
"""Filter values on the LHS by evaluating RHS with each value. Returns any LHS values for which RHS evaluates to a true value. """ |
lhs_values, _ = __solve_for_repeated(expr.lhs, vars)
def lazy_filter():
for lhs_value in repeated.getvalues(lhs_values):
if solve(expr.rhs, __nest_scope(expr.lhs, vars, lhs_value)).value:
yield lhs_value
return Result(repeated.lazy(lazy_filter), ()) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def solve_sort(expr, vars):
"""Sort values on the LHS by the value they yield when passed to RHS.""" |
lhs_values = repeated.getvalues(__solve_for_repeated(expr.lhs, vars)[0])
sort_expression = expr.rhs
def _key_func(x):
return solve(sort_expression, __nest_scope(expr.lhs, vars, x)).value
results = ordered.ordered(lhs_values, key_func=_key_func)
return Result(repeated.meld(*results), ()) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def solve_each(expr, vars):
"""Return True if RHS evaluates to a true value with each state of LHS. If LHS evaluates to a normal IAssociative object then this is... |
lhs_values, _ = __solve_for_repeated(expr.lhs, vars)
for lhs_value in repeated.getvalues(lhs_values):
result = solve(expr.rhs, __nest_scope(expr.lhs, vars, lhs_value))
if not result.value:
# Each is required to return an actual boolean.
return result._replace(value=Fals... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def solve_cast(expr, vars):
"""Get cast LHS to RHS.""" |
lhs = solve(expr.lhs, vars).value
t = solve(expr.rhs, vars).value
if t is None:
raise errors.EfilterTypeError(
root=expr, query=expr.source,
message="Cannot find type named %r." % expr.rhs.value)
if not isinstance(t, type):
raise errors.EfilterTypeError(
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def solve_isinstance(expr, vars):
"""Typecheck whether LHS is type on the RHS.""" |
lhs = solve(expr.lhs, vars)
try:
t = solve(expr.rhs, vars).value
except errors.EfilterKeyError:
t = None
if t is None:
raise errors.EfilterTypeError(
root=expr.rhs, query=expr.source,
message="Cannot find type named %r." % expr.rhs.value)
if not is... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_version(mod_root):
""" mod_root a VERSION file containes the version strings is created in mod_root, during installation. That file is used at runtime to... |
try:
version_base = None
version_detail = None
# get version from './VERSION'
src_root = os.path.dirname(__file__)
if not src_root:
src_root = '.'
with open(src_root + '/VERSION', 'r') as f:
version_base = f.readline().strip()
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def isgood(name):
""" Whether name should be installed """ |
if not isbad(name):
if name.endswith('.py') or name.endswith('.json') or name.endswith('.tar'):
return True
return False |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def meld(*values):
"""Return the repeated value, or the first value if there's only one. This is a convenience function, equivalent to calling getvalue(repeated(... |
values = [x for x in values if x is not None]
if not values:
return None
result = repeated(*values)
if isrepeating(result):
return result
return getvalue(result) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def getvalue(x):
"""Return the single value of x or raise TypError if more than one value.""" |
if isrepeating(x):
raise TypeError(
"Ambiguous call to getvalue for %r which has more than one value."
% x)
for value in getvalues(x):
return value |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def to_dict(self):
""" Convert current Task into a dictionary :return: python dictionary """ |
task_desc_as_dict = {
'uid': self._uid,
'name': self._name,
'state': self._state,
'state_history': self._state_history,
'pre_exec': self._pre_exec,
'executable': self._executable,
'arguments': self._arguments,
'po... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def keyword(tokens, expected):
"""Case-insensitive keyword match.""" |
try:
token = next(iter(tokens))
except StopIteration:
return
if token and token.name == "symbol" and token.value.lower() == expected:
return TokenMatch(None, token.value, (token,)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def multi_keyword(tokens, keyword_parts):
"""Match a case-insensitive keyword consisting of multiple tokens.""" |
tokens = iter(tokens)
matched_tokens = []
limit = len(keyword_parts)
for idx in six.moves.range(limit):
try:
token = next(tokens)
except StopIteration:
return
if (not token or token.name != "symbol" or
token.value.lower() != keyword_part... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def prefix(tokens, operator_table):
"""Match a prefix of an operator.""" |
operator, matched_tokens = operator_table.prefix.match(tokens)
if operator:
return TokenMatch(operator, None, matched_tokens) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def infix(tokens, operator_table):
"""Match an infix of an operator.""" |
operator, matched_tokens = operator_table.infix.match(tokens)
if operator:
return TokenMatch(operator, None, matched_tokens) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def suffix(tokens, operator_table):
"""Match a suffix of an operator.""" |
operator, matched_tokens = operator_table.suffix.match(tokens)
if operator:
return TokenMatch(operator, None, matched_tokens) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def match_tokens(expected_tokens):
"""Generate a grammar function that will match 'expected_tokens' only.""" |
if isinstance(expected_tokens, Token):
# Match a single token.
def _grammar_func(tokens):
try:
next_token = next(iter(tokens))
except StopIteration:
return
if next_token == expected_tokens:
return TokenMatch(None, ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def expression(self, previous_precedence=0):
"""An expression is an atom or an infix expression. Grammar (sort of, actually a precedence-climbing parser):
expre... |
lhs = self.atom()
return self.operator(lhs, previous_precedence) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def accept_operator(self, precedence):
"""Accept the next binary operator only if it's of higher precedence.""" |
match = grammar.infix(self.tokens)
if not match:
return
if match.operator.precedence < precedence:
return
# The next thing is an operator that we want. Now match it for real.
return self.tokens.accept(grammar.infix) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def operator(self, lhs, min_precedence):
"""Climb operator precedence as long as there are operators. This function implements a basic precedence climbing parser... |
# Spin as long as the next token is an operator of higher
# precedence. (This may not do anything, which is fine.)
while self.accept_operator(precedence=min_precedence):
operator = self.tokens.matched.operator
# If we're parsing a mixfix operator we can keep going unti... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.