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 process(specs):
""" Executes the passed in list of specs """ |
pout, pin = chain_specs(specs)
LOG.info("Processing")
sw = StopWatch().start()
r = pout.process(pin)
if r:
print(r)
LOG.info("Finished in %s", sw.read()) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def smartquotes(text):
""" Runs text through pandoc for smartquote correction. """ |
command = shlex.split('pandoc --smart -t plain')
com = Popen(command, shell=False, stdin=PIPE, stdout=PIPE, stderr=PIPE)
out, err = com.communicate(text.encode('utf-8'))
com_out = out.decode('utf-8')
text = com_out.replace(u'\n', u' ').strip()
return text |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def shell(cmd, **kwargs):
"""Execute cmd, check exit code, return stdout""" |
logger.debug("$ %s", cmd)
return subprocess.check_output(cmd, shell=True, **kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def main(argv=None):
""" Script execution. The project repo will be cloned to a temporary directory, and the desired branch, tag, or commit will be checked out. ... |
@contextmanager
def tmpdir():
""" Create a self-deleting temporary directory. """
path = mkdtemp()
try:
yield path
finally:
rmtree(path)
return
def test():
""" Execute the test suite. """
install = "{:s} install -r requirement... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _create_user(self, email, password, is_superuser, **extra_fields):
"""Create new user""" |
now = timezone.now()
if not email:
raise ValueError('The given email must be set')
email = self.normalize_email(email)
user = self.model(
email=email,
password=password,
is_active=True,
is_superuser=is_superuser, last_login=no... |
<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_full_name(self):
"""Get full username if no name is set email is given""" |
if self.first_name and self.last_name:
return "{} {}".format(self.first_name, self.last_name)
return self.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 set_attribute(self, code, value):
"""Set attribute for user""" |
attr, _ = self.get_or_create(code=code)
attr.value = value
attr.save() |
<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_attribute(self, code, default=None):
"""Get attribute for user""" |
try:
return self.get(code=code).value
except models.ObjectDoesNotExist:
return default |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def next(self):
""" fetch the chart identified by this chart's next_id attribute if the next_id is either null or not present for this chart return None returns ... |
try:
if self.next_id:
return Chart(self.next_id)
else:
log.debug('attempted to get next chart, but none was found')
return
except AttributeError:
#chart does not implement next pointer
log.debug('attempted t... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def previous(self):
""" fetch the chart identified by this chart's previous_id attribute if the previous_id is either null or not present for this chart return N... |
try:
if self.previous_id:
return Chart(self.previous_id)
else:
log.debug('attempted to get previous chart, but none was found')
return
except AttributeError:
#chart does not implement next pointer
lo... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def now(self):
""" fetch the chart identified by this chart's now_id attribute if the now_id is either null or not present for this chart return None returns the... |
try:
if self.now_id:
return Chart(self.now_id)
else:
log.debug('attempted to get current chart, but none was found')
return
except AttributeError:
#chart does not implement next pointer
log.debug('attempted ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def initial(key, **kwarg):
"""Create an empty dicttree. The root node has a special attribute "_rootname". Because root node is the only dictionary doesn't have ... |
d = dict()
DictTree.setattr(d, _rootname = key, **kwarg)
return d |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def setattr(d, **kwarg):
"""Set an attribute. set attributes is actually add a special key, value pair in this dict under key = "_meta". Usage:: {'_meta': {'popu... |
if _meta not in d:
d[_meta] = dict()
for k, v in kwarg.items():
d[_meta][k] = v |
<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_children(d, key, **kwarg):
"""Add a children with key and attributes. If children already EXISTS, OVERWRITE it. Usage:: {'_meta': {'population': 27800000... |
if kwarg:
d[key] = {_meta: kwarg}
else:
d[key] = 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 del_depth(d, depth):
"""Delete all the nodes on specific depth in this dict """ |
for node in DictTree.v_depth(d, depth-1):
for key in [key for key in DictTree.k(node)]:
del node[key] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def prettyprint(d):
"""Print dicttree in Json-like format. keys are sorted """ |
print(json.dumps(d, sort_keys=True,
indent=4, separators=("," , ": "))) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def stats_on_depth(d, depth):
"""Display the node stats info on specific depth in this dict """ |
root_nodes, leaf_nodes = 0, 0
for _, node in DictTree.kv_depth(d, depth):
if DictTree.length(node) == 0:
leaf_nodes += 1
else:
root_nodes += 1
total = root_nodes + leaf_nodes
print("On depth %s, having %s root nodes, %s leaf nodes.... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def db_for_read(self, model, **hints):
""" If the app has its own database, use it for reads """ |
if model._meta.app_label in self._apps:
return getattr(model, '_db_alias', model._meta.app_label)
return 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 db_for_write(self, model, **hints):
""" If the app has its own database, use it for writes """ |
if model._meta.app_label in self._apps:
return getattr(model, '_db_alias', model._meta.app_label)
return 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 allow_migrate(self, db, model):
""" Make sure self._apps go to their own db """ |
if model._meta.app_label in self._apps:
return getattr(model, '_db_alias', model._meta.app_label) == db
return 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 check(path_dir, requirements_name='requirements.txt'):
'''Look for unused packages listed on project requirements'''
requirements = _load_requirements(requirements_name, path_dir)
imported_modules = _iter_modules(path_dir)
installed_packages = _list_installed_packages()
imported_modules.update(... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def pre(cond):
""" Add a precondition check to the annotated method. The condition is passed the arguments from the annotated method. It does not need to accept ... |
cond_args, cond_varargs, cond_varkw, cond_defaults = inspect.getargspec(cond)
source = inspect.getsource(cond).strip()
def inner(f):
if enabled:
# deal with the real function, not a wrapper
f = getattr(f, 'wrapped_fn', f)
# need to check if 'self' is the first ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def post(cond):
""" Add a postcondition check to the annotated method. The condition is passed the return value of the annotated method. """ |
source = inspect.getsource(cond).strip()
def inner(f):
if enabled:
# deal with the real function, not a wrapper
f = getattr(f, 'wrapped_fn', f)
def check_condition(result):
if not cond(result):
raise AssertionError('Postcondition... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def takes(*type_list):
""" Decorates a function with type checks. Examples @takes(int):
take an int as the first param @takes(int, str):
take and int as first,... |
def inner(f):
if enabled:
# deal with the real function, not a wrapper
f = getattr(f, 'wrapped_fn', f)
# need to check if 'self' is the first arg,
# since @pre doesn't want the self param
member_function = is_member_function(f)
# nee... |
<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_conditions(f, args, kwargs):
""" This is what runs all of the conditions attached to a method, along with the conditions on the superclasses. """ |
member_function = is_member_function(f)
# check the functions direct pre conditions
check_preconditions(f, args, kwargs)
# for member functions check the pre conditions up the chain
base_classes = []
if member_function:
base_classes = inspect.getmro(type(args[0]))[1:-1]
for cl... |
<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_preconditions(f, args, kwargs):
""" Runs all of the preconditions. """ |
f = getattr(f, 'wrapped_fn', f)
if f and hasattr(f, 'preconditions'):
for cond in f.preconditions:
cond(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:
def check_postconditions(f, return_value):
""" Runs all of the postconditions. """ |
f = getattr(f, 'wrapped_fn', f)
if f and hasattr(f, 'postconditions'):
for cond in f.postconditions:
cond(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 is_member_function(f):
""" Checks if the first argument to the method is 'self'. """ |
f_args, f_varargs, f_varkw, f_defaults = inspect.getargspec(f)
return 1 if 'self' in f_args else 0 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def list_of(cls):
""" Returns a function that checks that each element in a list is of a specific type. """ |
return lambda l: isinstance(l, list) and all(isinstance(x, cls) for x in l) |
<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_of(cls):
""" Returns a function that checks that each element in a set is of a specific type. """ |
return lambda l: isinstance(l, set) and all(isinstance(x, cls) for x in l) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def swallow_stdout(stream=None):
"""Divert stdout into the given stream """ |
saved = sys.stdout
if stream is None:
stream = StringIO()
sys.stdout = stream
try:
yield
finally:
sys.stdout = saved |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def read_sj_out_tab(filename):
"""Read an SJ.out.tab file as produced by the RNA-STAR aligner into a pandas Dataframe. Parameters filename : str of filename or f... |
def int_to_intron_motif(n):
if n == 0:
return 'non-canonical'
if n == 1:
return 'GT/AG'
if n == 2:
return 'CT/AC'
if n == 3:
return 'GC/AG'
if n == 4:
return 'CT/GC'
if n == 5:
return 'AT/AC'
... |
<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_sj_out_dict(fns, jxns=None, define_sample_name=None):
"""Read multiple sj_outs, return dict with keys as sample names and values as sj_out dataframes. ... |
if define_sample_name == None:
define_sample_name = lambda x: x
else:
assert len(set([define_sample_name(x) for x in fns])) == len(fns)
sj_outD = dict()
for fn in fns:
sample = define_sample_name(fn)
df = read_sj_out_tab(fn)
# Remove any junctions that don't hav... |
<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_sj_out_panel(sj_outD, total_jxn_cov_cutoff=20):
"""Filter junctions from many sj_out files and make panel. Parameters sj_outD : dict Dict whose keys ar... |
# num_jxns = dict()
# # set of all junctions
# jxnS = reduce(lambda x,y: set(x) | set(y),
# [ sj_outD[k].index for k in sj_outD.keys() ])
# jxn_keepS = set()
# jxn_setsD = dict()
# for k in sj_outD.keys():
# jxn_setsD[k] = frozenset(sj_outD[k].index)
# for j in jx... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def read_external_annotation(fn):
"""Read file with junctions from some database. This does not have to be the same splice junction database used with STAR. Para... |
assert os.path.exists(fn)
extDF = pd.read_table(fn, index_col=0, header=0)
total_num = extDF.shape[0]
# In rare cases, a splice junction might be used by more than one gene. For
# my purposes, these cases are confounding, so I will remove all such splice
# junctions.
intron_count = ex... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def combine_sj_out( fns, external_db, total_jxn_cov_cutoff=20, define_sample_name=None, verbose=False, ):
"""Combine SJ.out.tab files from STAR by filtering base... |
if verbose:
import sys
# I'll start by figuring out which junctions we will keep.
counts = _total_jxn_counts(fns)
jxns = set(counts[counts >= total_jxn_cov_cutoff].index)
if verbose:
sys.stderr.write('Counting done\n')
stats = []
sj_outD = _make_sj_out_dict(fns, jxns=jxns,... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _total_jxn_counts(fns):
"""Count the total unique coverage junction for junctions in a set of SJ.out.tab files.""" |
df = pd.read_table(fns[0], header=None, names=COLUMN_NAMES)
df.index = (df.chrom + ':' + df.start.astype(int).astype(str) + '-' +
df.end.astype(int).astype(str))
counts = df.unique_junction_reads
for fn in fns[1:]:
df = pd.read_table(fn, header=None, names=COLUMN_NAMES)
... |
<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_splice_targets_dict(df, feature, strand):
"""Make dict mapping each donor to the location of all acceptors it splices to or each acceptor to all donors... |
g = df[df.strand == strand].groupby(feature)
d = dict()
if strand == '+':
if feature == 'donor':
target = 'end'
if feature == 'acceptor':
target = 'start'
if strand == '-':
if feature == 'donor':
target = 'start'
if feature == 'accepto... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _read_log(fn, define_sample_name=None):
"""Read STAR Log.final.out file. Parameters fn : string Path to Log.final.out file. define_sample_name : function tha... |
if define_sample_name == None:
define_sample_name = lambda x: x
df = pd.read_table(fn, '|', header=None).dropna()
df.index = df.ix[:,0].apply(lambda x: x.strip())
df = pd.DataFrame(df.ix[:,1].apply(lambda x: x.strip()))
if define_sample_name:
df.columns = [define_sample_name(fn)]
... |
<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_logs_df(fns, define_sample_name=None):
"""Make pandas DataFrame from multiple STAR Log.final.out files. Parameters fns : string List of paths to Log.fin... |
dfs = []
for fn in fns:
dfs.append(_read_log(fn,
define_sample_name=define_sample_name))
df = pd.concat(dfs,axis=1)
df = df.T
for label in [
'Mapping speed, Million of reads per hour',
'Number of input reads',
'Average input ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def uptime():
"""Uptime of the host machine""" |
from datetime import timedelta
with open('/proc/uptime', 'r') as f:
uptime_seconds = float(f.readline().split()[0])
uptime_string = str(timedelta(seconds=uptime_seconds))
bob.says(uptime_string) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def value_to_sql_str(v):
""" transform a python variable to the appropriate representation in SQL """ |
if v is None:
return 'null'
if type(v) in (types.IntType, types.FloatType, types.LongType):
return str(v)
if type(v) in (types.StringType, types.UnicodeType):
return "'%s'" %(v.replace(u"'", u"\\'"))
if isinstance(v, datetime):
return "'%s'" %(v.strftime("%Y-%m-%d %H:... |
<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_component_tarball(bucket, comp_name, comp_config):
""" Returns True if the component tarball is found in the bucket. Otherwise, returns False. """ |
values = {
'name': comp_name,
'version': comp_config['version'],
'platform': comp_config['platform'],
}
template = comp_config.get('archive_template')
if template:
key_name = template % values
else:
key_name = '%(name)s/%(name)s-%(version)... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _prepare_servers(self):
""" Prepare the variables that are exposed to the servers. Most attributes in the server config are used directly. However, due to va... |
stack = {
A.NAME: self[A.NAME],
A.VERSION: self[A.VERSION],
}
for server in self.get(R.SERVERS, []):
# default cloud values
if A.PROVIDER in server:
if A.server.LAUNCH_TIMEOUT not in server:
serv... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _prepare_load_balancers(self):
""" Prepare load balancer variables """ |
stack = {
A.NAME: self[A.NAME],
A.VERSION: self[A.VERSION],
}
for load_balancer in self.get(R.LOAD_BALANCERS, []):
svars = {A.STACK: stack}
load_balancer[A.loadbalancer.VARS] = svars |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def prepare(self):
""" Reorganizes the data such that the deployment logic can find it all where it expects to be. The raw configuration file is intended to be a... |
# TODO: take server_common_attributes and disperse it among the various
# server stanzas
# First stage - turn all the dicts (SERVER, SECGROUP, DATABASE, LOADBAL)
# into lists now they're merged properly
for stanza_key, name_key in (
(R.SERVERS, A.server.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 autoinc(self):
""" Conditionally updates the stack version in the file associated with this config. This handles both official releases (i.e. QA configs), an... |
if not self.get('autoinc_version'):
return
oldver = self['version']
newver = bump_version_tail(oldver)
config_path = self.filepath
temp_fd, temp_name = tempfile.mkstemp(
dir=os.path.dirname(config_path),
)
with open(config_pa... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def setup(name, path='log', enable_debug=False):
""" Prepare a NestedSetup. :param name: the channel name :param path: the path where the logs will be written :p... |
path_tmpl = os.path.join(path, '{name}_{level}.log')
info = path_tmpl.format(name=name, level='info')
warn = path_tmpl.format(name=name, level='warn')
err = path_tmpl.format(name=name, level='err')
crit = path_tmpl.format(name=name, level='crit')
# a nested handler setup can be used to configur... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def mail_setup(path):
""" Set the variables to be able to send emails. :param path: path to the config file """ |
global dest_mails
global smtp_server
global smtp_port
global src_server
config = configparser.RawConfigParser()
config.readfp(path)
dest_mails = config.get('mail', 'dest_mail').split(',')
smtp_server = config.get('mail', 'smtp_server')
smtp_port = config.get('mail', 'smtp_port')
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def run(log_name, path, debug=False, mail=None, timeout=0):
""" Run a subscriber and pass the messages to the logbook setup. Stays alive as long as the pubsub in... |
global pubsub
global channel
channel = log_name
if use_tcp_socket:
r = redis.StrictRedis(host=hostname, port=port)
else:
r = redis.StrictRedis(unix_socket_path=unix_socket)
pubsub = r.pubsub()
pubsub.psubscribe(channel + '.*')
if timeout != 0:
deadline = time.ti... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def parse_options(cls, options):
"""Pass options through to this plugin.""" |
cls.ignore_decorators = options.ignore_decorators
cls.exclude_from_doctest = options.exclude_from_doctest
if not isinstance(cls.exclude_from_doctest, list):
cls.exclude_from_doctest = [cls.exclude_from_doctest] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def load_source(self):
"""Load the source for the specified file.""" |
if self.filename in self.STDIN_NAMES:
self.filename = 'stdin'
self.source = pycodestyle.stdin_get_value()
else:
with pep257.tokenize_open(self.filename) as fd:
self.source = fd.read() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def prepare(self, data_source):
""" Called with the training data. @param data_source: Either a pandas.DataFrame or a file-like object. """ |
dataframe = self.__get_dataframe(data_source, use_target=True)
self.__config.get_data_model().set_features_types_from_dataframe(dataframe)
dataframe = self.__cleaner.prepare(dataframe)
return self.__transformer.prepare(dataframe) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fix_rst_heading(heading, below):
"""If the 'below' line looks like a reST line, give it the correct length. This allows for different characters being used a... |
if len(below) == 0:
return below
first = below[0]
if first not in '-=`~':
return below
if not len(below) == len([char for char in below
if char == first]):
# The line is not uniformly the same character
return below
below = first * len(h... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def sanity_check(vcs):
"""Do sanity check before making changes Check that we are not on a tag and/or do not have local changes. Returns True when all is fine. "... |
if not vcs.is_clean_checkout():
q = ("This is NOT a clean checkout. You are on a tag or you have "
"local changes.\n"
"Are you sure you want to continue?")
if not ask(q, default=False):
sys.exit(1) |
<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_recommended_files(data, vcs):
"""Do check for recommended files. Returns True when all is fine. """ |
main_files = os.listdir(data['workingdir'])
if not 'setup.py' in main_files and not 'setup.cfg' in main_files:
# Not a python package. We have no recommendations.
return True
if not 'MANIFEST.in' in main_files and not 'MANIFEST' in main_files:
q = ("This package is missing a MANIFE... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def cleanup_version(version):
"""Check if the version looks like a development version.""" |
for w in WRONG_IN_VERSION:
if version.find(w) != -1:
logger.debug("Version indicates development: %s.", version)
version = version[:version.find(w)].strip()
logger.debug("Removing debug indicators: %r", version)
version = version.rstrip('.') # 1.0.dev0 -> 1.0. -... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def pager(__text: str, *, pager: Optional[str] = 'less'):
"""Pass output through pager. See :manpage:`less(1)`, if you wish to configure the default pager. For e... |
if pager:
run([pager, ], input=__text.encode())
else:
print(__text) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def listen(self, **kwargs: Any) -> Server: """ bind host, port or sock """ |
loop = cast(asyncio.AbstractEventLoop, self._loop)
return (yield from loop.create_server(
lambda: self._protocol(
loop=loop,
handle=self._handle,
requset_charset=self.requset_charset,
response_charset=self.response_charset,
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def type_and_model_to_query(self, request):
""" Return JSON for an individual Model instance If the required parameters are wrong, return 400 Bad Request If the ... |
try:
content_type_id = request.GET["content_type_id"]
object_id = request.GET["object_id"]
except KeyError:
return HttpResponseBadRequest()
try:
content_type = ContentType.objects.get(pk=content_type_id)
model = content_type.model_cla... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def load(self, paths, params=None):
""" Load data from configuration files. Configuration values are read from a sequence of one or more YAML files. Files are re... |
def replace(match):
""" Callback for re.sub to do parameter replacement. """
# This allows for multi-pattern substitution in a single pass.
return params[match.group(0)]
params = {r"%{:s};".format(key): val for (key, val)
in params.iteritems()} if ... |
<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_repositories(path):
""" Return an array of tuples with the name and path for repositories found in a directory. :param str path: The path to find reposit... |
return [get_repository(os.path.join(path, subdir))
for subdir in os.listdir(path)
if os.path.isdir(
os.path.join(path, subdir, '.git'))] |
<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_repository_names(path):
""" Return an array of the path name for repositories found in a directory. :param str path: The path to find repositories in :re... |
return [subdir
for subdir in os.listdir(path)
if os.path.isdir(os.path.join(path, subdir, '.git'))] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def list_schemas(repo):
""" Return a list of parsed avro schemas as dictionaries. :param Repo repo: The git repository. :returns: dict """ |
schema_files = glob.glob(
os.path.join(repo.working_dir, '_schemas', '*.avsc'))
schemas = {}
for schema_file in schema_files:
with open(schema_file, 'r') as fp:
schema = json.load(fp)
schemas['%(namespace)s.%(name)s' % schema] = schema
return schemas |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def list_content_types(repo):
""" Return a list of content types in a repository. :param Repo repo: The git repository. :returns: list """ |
schema_files = glob.glob(
os.path.join(repo.working_dir, '_schemas', '*.avsc'))
return [os.path.splitext(os.path.basename(schema_file))[0]
for schema_file in schema_files] |
<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_schema(repo, content_type):
""" Return a schema for a content type in a repository. :param Repo repo: The git repository. :returns: dict """ |
try:
with open(
os.path.join(repo.working_dir,
'_schemas',
'%s.avsc' % (content_type,)), 'r') as fp:
data = fp.read()
return avro.schema.parse(data)
except IOError: # pragma: no cover
raise NotFou... |
<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_mapping(repo, content_type):
""" Return an ES mapping for a content type in a repository. :param Repo repo: This git repository. :returns: dict """ |
try:
with open(
os.path.join(repo.working_dir,
'_mappings',
'%s.json' % (content_type,)), 'r') as fp:
return json.load(fp)
except IOError:
raise NotFound('Mapping does not exist.') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def format_repo(repo):
""" Return a dictionary representing the repository It returns ``None`` for things we do not support or are not relevant. :param str repo_... |
commit = repo.commit()
return {
'name': os.path.basename(repo.working_dir),
'branch': repo.active_branch.name,
'commit': commit.hexsha,
'timestamp': datetime.fromtimestamp(
commit.committed_date).isoformat(),
'author': '%s <%s>' % (commit.author.name, commit.... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def format_diffindex(diff_index):
""" Return a JSON formattable representation of a DiffIndex. Returns a generator that returns dictionaries representing the cha... |
for diff in diff_index:
if diff.new_file:
yield format_diff_A(diff)
elif diff.deleted_file:
yield format_diff_D(diff)
elif diff.renamed:
yield format_diff_R(diff)
elif diff.a_blob and diff.b_blob and diff.a_blob != diff.b_blob:
yield 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 format_content_type(repo, content_type):
""" Return a list of all content objects for a given content type in a repository. :param Repo repo: The git reposit... |
storage_manager = StorageManager(repo)
model_class = load_model_class(repo, content_type)
return [dict(model_obj)
for model_obj in storage_manager.iterate(model_class)] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def format_content_type_object(repo, content_type, uuid):
""" Return a content object from a repository for a given content_type and uuid :param Repo repo: The g... |
try:
storage_manager = StorageManager(repo)
model_class = load_model_class(repo, content_type)
return dict(storage_manager.get(model_class, uuid))
except GitCommandError:
raise NotFound('Object does not exist.') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def format_repo_status(repo):
""" Return a dictionary representing the repository status It returns ``None`` for things we do not support or are not relevant. :p... |
commit = repo.commit()
return {
'name': os.path.basename(repo.working_dir),
'commit': commit.hexsha,
'timestamp': datetime.fromtimestamp(
commit.committed_date).isoformat(),
} |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def save_content_type_object(repo, schema, uuid, data):
""" Save an object as a certain content type """ |
storage_manager = StorageManager(repo)
model_class = deserialize(schema,
module_name=schema['namespace'])
model = model_class(data)
commit = storage_manager.store(model, 'Updated via PUT request.')
return commit, model |
<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_content_type_object(repo, content_type, uuid):
""" Delete an object of a certain content type """ |
storage_manager = StorageManager(repo)
model_class = load_model_class(repo, content_type)
model = storage_manager.get(model_class, uuid)
commit = storage_manager.delete(model, 'Deleted via DELETE request.')
return commit, model |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def load_model_class(repo, content_type):
""" Return a model class for a content type in a repository. :param Repo repo: The git repository. :param str content_t... |
schema = get_schema(repo, content_type).to_json()
return deserialize(schema, module_name=schema['namespace']) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def search_composite(self, query, source, payload=None):
'''Shortcut search with composite source'''
source = '+'.join(source)
if payload is None:
payload = dict(Sources=quote(source))
else:
payload['Sources'] = quote(source)
return self.search(query, 'C... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def key_of(d):
""" Returns the key of a single element dict. """ |
if len(d) > 1 and not type(d) == dict():
raise ValueError('key_of(d) may only except single element dict')
else:
return keys_of(d)[0] |
<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_grindstone(self):
""" Opens a grindstone file and populates the grindstone with it's contents. Returns an empty grindstone json object if a file does no... |
try:
with open(self.grindstone_path, 'r') as f:
# Try opening the file
return json.loads(f.read())
# If the file is empty
except json.decoder.JSONDecodeError:
# Default return empty object with empty tasks list
return {'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 delete_task(self, task=None):
""" Deletes a given task by name. """ |
# Iterate over the list of tasks
for t in self.grindstone['tasks']:
# If they key of the task matches the task given
if key_of(t) == task:
# Remove that task
self.grindstone['tasks'].remove(t)
# Return True because something did ha... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def write_grindstone(self):
""" Writes self.gs to self.grindstone_path. """ |
with open(self.grindstone_path, 'w') as f:
# Write the JSON dump of the file
f.write(json.dumps(self.grindstone)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def datetime2unix(T):
""" converts datetime to UT1 unix epoch time """ |
T = atleast_1d(T)
ut1_unix = empty(T.shape, dtype=float)
for i, t in enumerate(T):
if isinstance(t, (datetime, datetime64)):
pass
elif isinstance(t, str):
try:
ut1_unix[i] = float(t) # it was ut1_unix in a string
continue
... |
<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_iterable(val):
"""Ensure that a value is iterable and not some sort of string""" |
try:
iter(val)
except (ValueError, TypeError):
return False
else:
return not isinstance(val, basestring) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def download_url(url, destination, retries=None, retry_delay=None, runner=None):
"""Download the given URL with wget to the provided path. The command is run via... |
runner = runner if runner is not None else FabRunner()
return try_repeatedly(
lambda: runner.run("wget --quiet --output-document '{0}' '{1}'".format(destination, url)),
max_retries=retries,
delay=retry_delay
) |
<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_install_sources(self):
"""Construct arguments to use alternative package indexes if there were sources supplied, empty string if there were not. """ |
if not self._sources:
return ''
parts = ['--no-index']
for source in self._sources:
parts.append("--find-links '{0}'".format(source))
return ' '.join(parts) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def install(self, release_id, upgrade=False):
"""Install target packages into a virtual environment. If the virtual environment for the given release ID does not... |
release_path = os.path.join(self._releases, release_id)
if not self._runner.exists(release_path):
self._runner.run("{0} '{1}'".format(self._venv_path, release_path))
cmd = [os.path.join(release_path, 'bin', 'pip'), 'install']
if upgrade:
cmd.append('--upgrade')
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def install(self, release_id):
"""Install the contents of the local directory into a release directory. If the directory for the given release ID does not exist ... |
release_path = os.path.join(self._releases, release_id)
if not self._runner.exists(release_path):
self._runner.run("mkdir -p '{0}'".format(release_path))
# Make sure to remove any user supplied globs or trailing slashes
# so that we can ensure exactly the glob behavior we w... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def install(self, release_id):
"""Install the local artifact into the remote release directory, optionally with a different name than the artifact had locally. I... |
release_path = os.path.join(self._releases, release_id)
if not self._runner.exists(release_path):
self._runner.run("mkdir -p '{0}'".format(release_path))
# The artifact can optionally be renamed when being uploaded to
# remote server. Useful for when we need a consistent na... |
<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_file_from_url(url):
"""Get the filename part of the path component from a URL.""" |
path = urlparse(url).path
if not path:
raise ValueError("Could not extract path from URL '{0}'".format(url))
name = os.path.basename(path)
if not name:
raise ValueError("Could not extract file name from path '{0}'".format(path))
return 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 install(self, release_id):
"""Download and install an artifact into the remote release directory, optionally with a different name the the artifact had. If t... |
release_path = os.path.join(self._releases, release_id)
if not self._runner.exists(release_path):
self._runner.run("mkdir -p '{0}'".format(release_path))
# The artifact can optionally be renamed to something specific when
# downloaded on the remote server. In that case use ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def pool_process(func, iterable, process_name='Pool processing', cpus=cpu_count()):
""" Apply a function to each element in an iterable and return a result list.... |
with Timer('\t{0} ({1}) completed in'.format(process_name, str(func))):
pool = Pool(cpus)
vals = pool.map(func, iterable)
pool.close()
return vals |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def remover(file_path):
"""Delete a file or directory path only if it exists.""" |
if os.path.isfile(file_path):
os.remove(file_path)
return True
elif os.path.isdir(file_path):
shutil.rmtree(file_path)
return True
else:
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 creation_date(path_to_file, return_datetime=True):
""" Retrieve a file's creation date. Try to get the date that a file was created, falling back to when it ... |
if platform.system() == 'Windows':
created_at = os.path.getctime(path_to_file)
else:
stat = os.stat(path_to_file)
try:
created_at = stat.st_birthtime
except AttributeError:
# We're probably on Linux. No easy way to get creation dates here,
# s... |
<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_filepaths(self):
"""Filters list of file paths to remove non-included, remove excluded files and concatenate full paths.""" |
self._printer(str(self.__len__()) + " file paths have been parsed in " + str(self.timer.end))
if self._hash_files:
return pool_hash(self.filepaths)
else:
return self.filepaths |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def files(self):
"""Return list of files in root directory""" |
self._printer('\tFiles Walk')
for directory in self.directory:
for path in os.listdir(directory):
full_path = os.path.join(directory, path)
if os.path.isfile(full_path):
if not path.startswith('.'):
self.filepaths.a... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def folders(self):
"""Return list of folders in root directory""" |
for directory in self.directory:
for path in os.listdir(directory):
full_path = os.path.join(directory, path)
if os.path.isdir(full_path):
if not path.startswith('.'):
self.filepaths.append(full_path)
return self._g... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def url(self, pattern, method=None, name=None):
"""Decorator to map url pattern to the callable. Args: pattern (:obj:`str`):
URL pattern to add. This is usually... |
def _inner(call):
self._url_manager.add(pattern, method, call, name)
return call
return _inner |
<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_exif_data(self, image):
"""Returns a dictionary from the exif data of an PIL Image item. Also converts the GPS Tags""" |
exif_data = {}
info = image._getexif()
if info:
for tag, value in info.items():
decoded = TAGS.get(tag, tag)
if decoded == "GPSInfo":
gps_data = {}
for t in value:
sub_decoded = GPSTAGS.g... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _convert_to_degress(self, value):
"""Helper function to convert the GPS coordinates stored in the EXIF to degress in float format""" |
d0 = value[0][0]
d1 = value[0][1]
d = float(d0) / float(d1)
m0 = value[1][0]
m1 = value[1][1]
m = float(m0) / float(m1)
s0 = value[2][0]
s1 = value[2][1]
s = float(s0) / float(s1)
return d + (m / 60.0) + (s / 3600.0) |
<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_reader( self, fd: IFileLike, callback: typing.Callable[[IFileLike], typing.Any], ) -> None: """Add a file descriptor to the processor and wait for READ. A... |
raise NotImplementedError() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _load(self, path='config', filetype=None, relaxed=False, ignore=False):
""" load key value pairs from a file Parameters: path - path to configuration data (s... |
for num, line in enumerate(
un_comment(load_lines_from_path(path, filetype)),
start=1,
):
if not line:
continue
try:
key, val = line.split('=', 1)
key = key.strip()
va... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.