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 pts_scale(pts=[], f=1.0):
'''Return given points scaled by factor f from origin.
'''
assert isinstance(pts, list) and len(pts) > 0
l_pt_prev = None
for pt in pts:
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstanc... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def angle_diff(start_a=[0.0], end_a=[0.0], direction=True):
'''Return difference in angle from start_a to end_a.
Direction follows the right-hand-rule so positive is counter-clockwise.
'''
assert isinstance(start_a, list)
assert isinstance(end_a, list)
l_angle = len(start_a)
assert l_angle > 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 gen_polygon_pts(n_pts=3, radius=[1.0]):
'''Generate points for a polygon with a number of radiuses.
This makes it easy to generate shapes with an arbitrary number of sides,
regularly angled around the origin.
A single radius will give a simple shape such as a square, hexagon, etc.
Multiple radiuses will give ... |
<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_params_docstring(params):
""" Add params to doc string """ |
p_string = "\nAccepts the following paramters: \n"
for param in params:
p_string += "name: %s, required: %s, description: %s \n" % (param['name'], param['required'], param['description'])
return p_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 _create_api_method(cls, name, api_method):
""" Create dynamic class methods based on the Cloudmonkey precached_verbs """ |
def _api_method(self, **kwargs):
# lookup the command
command = api_method['name']
if kwargs:
return self._make_request(command, kwargs)
else:
kwargs = {}
return self._make_request(command, kwargs)
_api_method.__doc__ = api_method['description... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def validate(backup):
"""Use this endpoint to start a backup validation. You must specify the backup type in the endpoint. Specify JSON data for backup archive i... |
data = request.json
if not data:
abort(400, 'No data received')
try:
archive_path = data['archive_path']
except KeyError:
abort(400, 'Missing key \'archive_path\' in data')
try:
config['extension'][backup]
except KeyError:
abort(404, 'No extension confi... |
<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(conf):
"""Main function, entry point of the program.""" |
global config
config = load_configuration(conf)
app.conf.update(config['celery'])
run(host=config['valigator']['bind'], port=config['valigator']['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 record_variant_id(record):
"""Get variant ID from pyvcf.model._Record""" |
if record.ID:
return record.ID
else:
return record.CHROM + ':' + str(record.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 wasp_snp_directory(vcf, directory, sample_name=None):
""" Convert VCF file into input for WASP. Only bi-allelic heterozygous sites are used. Parameters: vcf ... |
chrom = []
pos = []
ref = []
alt = []
vcf_reader = pyvcf.Reader(open(vcf, 'r'))
if sample_name:
def condition(record, sample_name):
return sample_name in [x.sample for x in record.get_hets()]
else:
def condition(record, sample_name):
return len(record... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def vcf_as_df(fn):
""" Read VCF file into pandas DataFrame. Parameters: fn : str Path to VCF file. Returns ------- df : pandas.DataFrame The VCF file as a data f... |
header_lines = 0
with open(fn, 'r') as f:
line = f.readline().strip()
header_lines += 1
while line[0] == '#':
line = f.readline().strip()
header_lines += 1
header_lines -= 2
df = pd.read_table(fn, skiprows=header_lines, header=0)
df.columns = ['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 make_het_matrix(fn):
""" Make boolean matrix of samples by variants. One indicates that the sample is heterozygous for that variant. Parameters: vcf : str Pa... |
# TODO: parallelize?
vcf_df = vcf_as_df(fn)
variant_ids = vcf_df.apply(lambda x: df_variant_id(x), axis=1)
vcf_reader = pyvcf.Reader(open(fn, 'r'))
record = vcf_reader.next()
hets = pd.DataFrame(0, index=variant_ids,
columns=[x.sample for x in record.samples])
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 current(self):
"""Returns the current user """ |
if not has_request_context():
return self.no_req_ctx_user_stack.top
user_stack = getattr(_request_ctx_stack.top, 'user_stack', None)
if user_stack and user_stack.top:
return user_stack.top
return _get_user() |
<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_user_token(self, user, salt=None):
"""Generates a unique token associated to the user """ |
return self.token_serializer.dumps(str(user.id), salt=salt) |
<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_password(self, user, password, skip_validation=False):
"""Updates the password of a user """ |
pwcol = self.options["password_column"]
pwhash = self.bcrypt.generate_password_hash(password)
if not skip_validation:
self.validate_password(user, password, pwhash)
if self.options['prevent_password_reuse']:
user.previous_passwords = [getattr(user, pwcol)] + (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 login_required(self, fresh=False, redirect_to=None):
"""Ensures that a user is authenticated """ |
if not self.logged_in() or (fresh and not self.login_manager.login_fresh()):
if redirect_to:
resp = redirect(redirect_to)
else:
resp = self.login_manager.unauthorized()
current_context.exit(resp, trigger_action_group="missing_user") |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _login(self, user, provider=None, remember=False, force=False, **attrs):
"""Updates user attributes and login the user in flask-login """ |
user.last_login_at = datetime.datetime.now()
user.last_login_provider = provider or self.options["default_auth_provider_name"]
user.last_login_from = request.remote_addr
populate_obj(user, attrs)
save_model(user)
flask_login.login_user(user, remember=remember, force=forc... |
<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_password_confirm(self, form, trigger_action_group=None):
"""Checks that the password and the confirm password match in the provided form. Won't do anyt... |
pwcol = self.options['password_column']
pwconfirmfield = pwcol + "_confirm"
if pwcol in form and pwconfirmfield in form and form[pwconfirmfield].data != form[pwcol].data:
if self.options["password_confirm_failed_message"]:
flash(self.options["password_confirm_failed_... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def reset_password(self, token=None, login_user=None):
"""Resets the password of the user identified by the token """ |
pwcol = self.options['password_column']
if not token:
if "token" in request.view_args:
token = request.view_args["token"]
elif "token" in request.values:
token = request.values["token"]
else:
raise OptionMissingError(("... |
<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_password_from_form(self, user=None, form=None):
"""Updates the user password using a form """ |
user = user or self.current
if not form and "form" in current_context.data and request.method == "POST":
form = current_context.data.form
elif not form:
raise OptionMissingError("Missing a form in 'update_user_password' action")
self._update_password_from_form(u... |
<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_user_password(self, user, password=None, form=None):
"""Checks if the password matches the one of the user. If no password is provided, the current for... |
pwcol = self.options['password_column']
if password is None:
if not form and "form" in current_context.data and request.method == "POST":
form = current_context.data.form
if form:
password = form[pwcol].data
else:
raise... |
<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_unique_attr(self, attrs, user=None, form=None, flash_msg=None):
"""Checks that an attribute of the current user is unique amongst all users. If no valu... |
user = user or self.current
ucol = self.options["username_column"]
email = self.options["email_column"]
if not isinstance(attrs, (list, tuple, dict)):
attrs = [attrs]
for name in attrs:
if isinstance(attrs, dict):
value = attrs[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 oauth_signup(self, provider, attrs, defaults, redirect_url=None):
"""Start the signup process after having logged in via oauth """ |
session["oauth_user_defaults"] = defaults
session["oauth_user_attrs"] = dict(provider=provider, **attrs)
if not redirect_url:
redirect_url = request.args.get("next")
return redirect(url_for('users.oauth_signup', next=redirect_url)) |
<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_valid_format_order(cls, format_target, format_order=None):
""" Checks to see if the target format string follows the proper style """ |
format_order = format_order or cls.parse_format_order(format_target)
cls.validate_no_token_duplicates(format_order)
format_target = cls.remove_tokens(format_target, format_order)
format_target = cls.remove_static_text(format_target)
cls.validate_separator_characters(format_targe... |
<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_errors(self, errors_list):
""" Handles errors list Output Format: [(DOMIAN, LINE, COLUMN, LEVEL, TYPE_NAME, MESSAGE),] Ex.: [(PARSER, 3, 51, FATAL, E... |
errors = []
for error in errors_list:
errors.append((error.domain_name, error.line, error.column,
error.level_name, error.type_name, error.message))
return errors |
<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_validation_errors(self, xml_input):
""" This method returns a list of validation errors. If there are no errors an empty list is returned """ |
errors = []
try:
parsed_xml = etree.parse(self._handle_xml(xml_input))
self.xmlschema.assertValid(parsed_xml)
except (etree.DocumentInvalid, etree.XMLSyntaxError), e:
errors = self._handle_errors(e.error_log)
except AttributeError:
raise 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 validate(self, xml_input):
""" This method validate the parsing and schema, return a boolean """ |
parsed_xml = etree.parse(self._handle_xml(xml_input))
try:
return self.xmlschema.validate(parsed_xml)
except AttributeError:
raise CannotValidate('Set XSD to validate the XML') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def deserialize(self, xml_input, *args, **kwargs):
""" Convert XML to dict object """ |
return xmltodict.parse(xml_input, *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 _import_all_modules():
"""dynamically imports all modules in the package""" |
import traceback
import os
global results
globals_, locals_ = globals(), locals()
def load_module(modulename, package_module):
try:
names = []
module = __import__(package_module, globals_, locals_, [modulename])
for name in module.__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 compress_folder_dump(path, target):
'''
Compress folder dump to tar.gz file
'''
import tarfile
if not path or not os.path.isdir(path):
raise SystemExit(_error_codes.get(105))
name_out_file = (target + 'dump-' +
datetime.datetime.now().strftime('%Y-%m-%d-%H-%M-%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 encrypt_file(path, output, password=None):
'''
Encrypt file with AES method and password.
'''
if not password:
password = PASSWORD_FILE
query = 'openssl aes-128-cbc -salt -in {0} -out {1} -k {2}'
with hide('output'):
local(query.format(path, output, password))
os.remo... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def decrypt_file(path, password=None):
'''
Decrypt file with AES method and password.
'''
global PASSWORD_FILE
if not password:
password = PASSWORD_FILE
if path and not os.path.isfile(path):
raise SystemExit(_error_codes.get(106))
query = 'openssl aes-128-cbc -d -salt -in {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 optional_actions(encrypt, path, compress_file, **kwargs):
'''
Optional actions about of AWS S3 and encrypt file.
'''
yes = ('y', 'Y')
file_to_upload = normalize_path(path) + compress_file[1]
if encrypt in yes:
encrypt_file(compress_file[1], compress_file[0])
file_to_upload = ... |
<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():
'''Main entry point for the mongo_backups CLI.'''
args = docopt(__doc__, version=__version__)
if args.get('backup'):
backup_database(args)
if args.get('backup_all'):
backup_all(args)
if args.get('decrypt'):
decrypt_file(args.get('<path>'))
if args.get('configu... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def backup_database(args):
'''
Backup one database from CLI
'''
username = args.get('<user>')
password = args.get('<password>')
database = args['<database>']
host = args.get('<host>') or '127.0.0.1'
path = args.get('--path') or os.getcwd()
s3 = args.get('--upload_s3')
glacier = 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 backup_all(args):
'''
Backup all databases with access user.
'''
username = None
password = None
auth = args.get('--auth')
path = args.get('--path')
s3 = args.get('--upload_s3')
glacier = args.get('--upload_glacier')
dropbox = args.get('--upload_dropbox')
swift = args.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 get_history(self):
"""Returns the history from cache or DB or a newly created one.""" |
if hasattr(self, '_history'):
return self._history
try:
self._history = APICallDayHistory.objects.get(
user=self.user, creation_date=now().date())
except APICallDayHistory.DoesNotExist:
self._history = APICallDayHistory(user=self.user)
... |
<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_rate_limit_exceeded(self):
"""Returns ``True`` if the rate limit is exceeded, otherwise False.""" |
history = self.get_history()
if history.amount_api_calls >= settings.UNSHORTEN_DAILY_LIMIT:
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 log_api_call(self):
"""Increases the amount of logged API calls for the user by 1.""" |
history = self.get_history()
history.amount_api_calls += 1
self._history = history.save()
return history |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def de_duplicate(items):
"""Remove any duplicate item, preserving order [1, 2] """ |
result = []
for item in items:
if item not in result:
result.append(item)
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 read_configs(__pkg: str, __name: str = 'config', *, local: bool = True) -> ConfigParser: """Process configuration file stack. We export the time parsing funct... |
configs = get_configs(__pkg, __name)
if local:
localrc = path.abspath('.{}rc'.format(__pkg))
if path.exists(localrc):
configs.append(localrc)
cfg = ConfigParser(converters={
'datetime': parse_datetime,
'humandelta': parse_timedelta,
'timedelta': parse_de... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _start(self):
""" Starts the underlying send and receive threads. """ |
# Initialize the locks
self._recv_lock = coros.Semaphore(0)
self._send_lock = coros.Semaphore(0)
# Boot the threads
self._recv_thread = gevent.spawn(self._recv)
self._send_thread = gevent.spawn(self._send)
# Link the threads such that we get notified if one or... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _recv(self):
""" Implementation of the receive thread. Waits for data to arrive on the socket, then passes the data through the defined receive framer and se... |
# Outer loop: receive some data
while True:
# Wait until we can go
self._recv_lock.release()
gevent.sleep() # Yield to another thread
self._recv_lock.acquire()
recv_buf = self._sock.recv(self.recv_bufsize)
# If it's empty, the ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _thread_error(self, thread):
""" Handles the case that the send or receive thread exit or throw an exception. """ |
# Avoid double-killing the thread
if thread == self._send_thread:
self._send_thread = None
if thread == self._recv_thread:
self._recv_thread = None
# Figure out why the thread exited
if thread.successful():
exception = socket.error('thread e... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def wrap(self, wrapper):
""" Allows the underlying socket to be wrapped, as by an SSL connection. :param wrapper: A callable taking, as its first argument, a soc... |
if self._recv_thread and self._send_thread:
# Have to suspend the send/recv threads
self._recv_lock.acquire()
self._send_lock.acquire()
# Wrap the socket
self._sock = wrapper(self._sock)
# OK, restart the send/recv threads
if self._recv_thr... |
<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):
""" Close the connection. Kills the send and receive threads, as well as closing the underlying socket. """ |
if self._recv_thread:
self._recv_thread.kill()
self._recv_thread = None
if self._send_thread:
self._send_thread.kill()
self._send_thread = None
if self._sock:
self._sock.close()
self._sock = None
# Make sure to ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def connect(self, target, acceptor, wrapper=None):
""" Initiate a connection from the tendril manager's endpoint. Once the connection is completed, a TCPTendril ... |
# Call some common sanity-checks
super(TCPTendrilManager, self).connect(target, acceptor, wrapper)
# Set up the socket
sock = socket.socket(self.addr_family, socket.SOCK_STREAM)
with utils.SocketCloser(sock, ignore=[application.RejectConnection]):
# Bind to our en... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def listener(self, acceptor, wrapper):
""" Listens for new connections to the manager's endpoint. Once a new connection is received, a TCPTendril object is gener... |
# If we have no acceptor, there's nothing for us to do here
if not acceptor:
# Not listening on anything
self.local_addr = None
# Just sleep in a loop
while True:
gevent.sleep(600)
return # Pragma: nocover
# OK, set... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def getdim(lsp):
'''
Obtain the dimensionality of a .lsp file. This should work for all well
formatted .lsp files.
Parameters:
-----------
lsp : .lsp string
Returns a list of dimensions.
'''
dims= ['x','y', 'z'];
rxs = ['{}-cells *([0-9]+)'.format(x) for x in ['x','y','... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def getpexts(lsp):
'''
Get information from pext planes. This might or might not work, use with
caution!
Parameters:
-----------
lsp : .lsp string
Returns a list of dicts with information for all pext planes
'''
lines=lsp.split('\n');
#unfortunately regex doesn't work ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def percentile(sorted_list, percent, key=lambda x: x):
"""Find the percentile of a sorted list of values. Arguments --------- sorted_list : list A sorted (ascend... |
if not sorted_list:
return None
if percent == 1:
return float(sorted_list[-1])
if percent == 0:
return float(sorted_list[0])
n = len(sorted_list)
i = percent * n
if ceil(i) == i:
i = int(i)
return (sorted_list[i-1] + sorted_list[i]) / 2
return float(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_driver_api_catalog(driver):
# noqa: E501 """Retrieve the api catalog Retrieve the api catalog # noqa: E501 :param driver: The driver to use for the reque... |
response = errorIfUnauthorized(role='developer')
if response:
return response
else:
response = ApitaxResponse()
driver: Driver = LoadedDrivers.getDriver(driver)
response.body.add(driver.getApiEndpointCatalog())
return Response(status=200, body=response.getResponseBody()) |
<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_driver_api_status(driver):
# noqa: E501 """Retrieve the status of an api backing a driver Retrieve the status of an api backing a driver # noqa: E501 :pa... |
response = errorIfUnauthorized(role='developer')
if response:
return response
else:
response = ApitaxResponse()
driver: Driver = LoadedDrivers.getDriver(driver)
response.body.add({"format": driver.getApiFormat()})
response.body.add({"description": driver.getApiDescription()})
... |
<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_engine(engine):
""" Parse the engine uri to determine where to store loggs """ |
engine = (engine or '').strip()
backend, path = URI_RE.match(engine).groups()
if backend not in SUPPORTED_BACKENDS:
raise NotImplementedError(
"Logg supports only {0} for now.".format(SUPPORTED_BACKENDS))
log.debug('Found engine: {0}'.format(engine))
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _init_repo(self):
""" create and initialize a new Git Repo """ |
log.debug("initializing new Git Repo: {0}".format(self._engine_path))
if os.path.exists(self._engine_path):
log.error("Path already exists! Aborting!")
raise RuntimeError
else:
# create the repo if it doesn't already exist
_logg_repo = git.Repo.in... |
<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_repo(self):
""" Load git repo using GitPython """ |
if self._logg_repo:
return self._logg_repo
try:
_logg_repo = git.Repo(self._engine_path)
log.debug('Loaded git repo [{0}]'.format(self._engine_path))
except Exception:
# FIXME: should this be automatic?
# log.error("Git repo doesn't e... |
<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_arguments(self, parser):
'''Add generic command-line arguments to a top-level argparse parser.
After running this, the results from ``argparse.parse_args()``
can be passed to :meth:`main`.
'''
commands = set(name[3:] for name in dir(self) if name.startswith('do_'))
... |
<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(self, args):
'''Run a single command, or else the main shell loop.
`args` should be the :class:`argparse.Namespace` object after
being set up via :meth:`add_arguments`.
'''
if args.action:
self.runcmd(args.action, args.arguments)
else:
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 runcmd(self, cmd, args):
'''Run a single command from pre-parsed arguments.
This is intended to be run from :meth:`main` or somewhere else
"at the top level" of the program. It may raise
:exc:`exceptions.SystemExit` if an argument such as ``--help``
that normally causes exe... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def do_help(self, args):
'''print help on a command'''
if args.command:
f = getattr(self, 'help_' + args.command, None)
if f:
f()
return
f = getattr(self, 'do_' + args.command, None)
if not f:
msg = self.noh... |
<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_kb_mappings_file(kbname, kbfile, separator):
"""Add KB values from file to given KB returning rows added.""" |
num_added = 0
with open(kbfile) as kb_fd:
for line in kb_fd:
if not line.strip():
continue
try:
key, value = line.split(separator)
except ValueError:
# bad split, pass
current_app.logger.error("Error spl... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def by_id(cls, semantictag_id, autoflush=True):
'''Return the semantic tag with the given id, or None.
:param semantictag_id: the id of the semantic tag to return
:type semantictag_id: string
:returns: the semantic tag with the given id, or None if there is no tag with
that id
:rtype: ckan.model.semantic... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def by_URI(cls, URI, label=None, autoflush=True):
'''Return the semantic ag with the given URI, or None.
:param URI: the URI of the semantic tag to return
:type URI: string (URI format)
:param label: URI's label (optional, default: None)
:type label: string
:returns: the semantic tag object with the given... |
<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(cls, tag_id_or_URI, label=None):
'''Return the tag with the given id or URI, or None.
:param tag_id_or_name: the id or name of the tag to return
:type tag_id_or_name: string
:returns: the tag object with the given id or name, or None if there is
no tag with that id or name
:rtype: ckan.model.tag.... |
<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_by_URI(cls, search_term):
'''Return all tags whose URI or label contain a given string.
:param search_term: the string to search for in the URI or label names
:type search_term: string
:returns: a list of semantictags that match the search term
:rtype: list of ckan.model.semantictag.SemanticTag o... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def all(cls):
'''Return all tags that are currently applied to any dataset.
:returns: a list of all tags that are currently applied to any dataset
:rtype: list of ckan.model.tag.Tag objects
'''
# if vocab_id_or_name:
# vocab = vocabulary.Vocabulary.get(vocab_id_or_name)
# if vocab is None:
# # The 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 tags(self):
'''Return a list of all tags that have this semantic tag, sorted by name.
:rtype: list of ckan.model.tag.Tag objects
'''
q = meta.Session.query(_tag.Tag)
q = q.join(TagSemanticTag)
q = q.filter_by(tag_id=self.id)
# q = q.filter_by(state='active')
q = q.order_by(_tag.Tag.name)
tags = q... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def by_id(cls, predicate_id, autoflush=True):
'''Return the predicate with the given id, or None.
:param predicate_id: the id of the predicate to return
:type predicate_id: string
:returns: the predicate with the given id, or None if there is no predicate with
that id
:rtype: ckan.model.semantictag.Predi... |
<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_unique(cls):
'''Return all unique namespaces
:returns: a list of all predicates
:rtype: list of ckan.model.semantictag.Predicate objects
'''
query = meta.Session.query(Predicate).distinct(Predicate.namespace)
return query.all() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def by_name(self, tag_name, semantictag_URI,
autoflush=True):
'''Return the TagSemanticTag for the given tag name and semantic tag URI, or None.
:param tag_name: the name of the tag to look for
:type tag_name: string
:param tag_URI: the name of the tag to look for
:type tag_URI: string
:returns: the Ta... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def temp_directory(*args, **kwargs):
""" Context manager returns a path created by mkdtemp and cleans it up afterwards. """ |
path = tempfile.mkdtemp(*args, **kwargs)
try:
yield path
finally:
shutil.rmtree(path) |
<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(self):
"""Parse command line arguments and options. Returns: Dictionary containing all given command line arguments and options. """ |
(options, args) = self.parser.parse_args()
self._set_attributes(args, options)
return self._create_dictionary() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def prt_detail(self):
"""Nicely print stats information. """ |
screen = [
"Detail info of %s: " % self.abspath,
"total size = %s" % string_SizeInBytes(self.size_total),
"number of sub folders = %s" % self.num_folder_total,
"number of total files = %s" % self.num_file_total,
"lvl 1 file size = %s" % string_SizeInB... |
<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(self, abspath_or_winfile, enable_verbose=True):
"""Add absolute path or WinFile to FileCollection. """ |
if isinstance(abspath_or_winfile, str): # abspath
if abspath_or_winfile in self.files:
if enable_verbose:
print("'%s' already in this collections" %
abspath_or_winfile)
else:
self.files.setdefault(abspath_or_... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def remove(self, abspath_or_winfile, enable_verbose=True):
"""Remove absolute path or WinFile from FileCollection. """ |
if isinstance(abspath_or_winfile, str): # abspath
try:
del self.files[abspath_or_winfile]
except KeyError:
if enable_verbose:
print("'%s' are not in this file collections" %
abspath_or_winfile)
elif i... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def iterfiles(self):
"""Yield all WinFile object. """ |
try:
for path in self.order:
yield self.files[path]
except:
for winfile in self.files.values():
yield winfile |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def iterpaths(self):
"""Yield all WinFile's absolute path. """ |
try:
for path in self.order:
yield path
except:
for path in self.files:
yield path |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def show_patterned_file(dir_path, pattern=list(), filename_only=True):
"""Print all file that file name contains ``pattern``. """ |
pattern = [i.lower() for i in pattern]
if filename_only:
def filter(winfile):
for p in pattern:
if p in winfile.fname.lower():
return True
return False
else:
def filter(winfile):
... |
<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 _get(self, url: str) -> str: """A small wrapper method which makes a quick GET request Parameters url : str The URL to get. Returns ------- str The raw ... |
async with self.session.get(url, headers=self.HEADERS) as r:
if r.status == 200:
return await r.text()
else:
raise RuneConnectionError(r.status) |
<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(self):
""" Update the state """ |
vm = self._cs_api.list_virtualmachines(id=self.id)[0]
self.is_running = self._is_running(vm.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 unlock_keychain(username):
""" If the user is running via SSH, their Keychain must be unlocked first. """ |
if 'SSH_TTY' not in os.environ:
return
# Don't unlock if we've already seen this user.
if username in _unlocked:
return
_unlocked.add(username)
if sys.platform == 'darwin':
sys.stderr.write("You are running under SSH. Please unlock your local OS X KeyChain:\n")
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 save_password(entry, password, username=None):
""" Saves the given password in the user's keychain. :param entry: The entry in the keychain. This is a caller... |
if username is None:
username = get_username()
has_keychain = initialize_keychain()
if has_keychain:
try:
keyring.set_password(entry, username, password)
except Exception as e:
log.warn("Unable to set password in keyring. Continuing..")
log.deb... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def remove_password(entry, username=None):
""" Removes the password for the specific user in the user's keychain. :param entry: The entry in the keychain. This i... |
if username is None:
username = get_username()
has_keychain = initialize_keychain()
if has_keychain:
try:
keyring.delete_password(entry, username)
except Exception as e:
print e
log.warn("Unable to delete password in keyring. Continuing..")
... |
<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_password(entry=None, username=None, prompt=None, always_ask=False):
""" Prompt the user for a password on stdin. :param username: The username to get the... |
password = None
if username is None:
username = get_username()
has_keychain = initialize_keychain()
# Unlock the user's keychain otherwise, if running under SSH, 'security(1)' will thrown an error.
unlock_keychain(username)
if prompt is None:
prompt = "Enter %s's password: ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def validate_password(entry, username, check_function, password=None, retries=1, save_on_success=True, prompt=None, **check_args):
""" Validate a password with a... |
if password is None:
password = get_password(entry, username, prompt)
for _ in xrange(retries + 1):
if check_function(username, password, **check_args):
if save_on_success:
save_password(entry, password, username)
return True
log.error("Could... |
<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_exception(exc, indent=0, pad=' '):
""" Take an exception object and return a generator with vtml formatted exception traceback lines. """ |
from_msg = None
if exc.__cause__ is not None:
indent += yield from format_exception(exc.__cause__, indent)
from_msg = traceback._cause_message.strip()
elif exc.__context__ is not None and not exc.__suppress_context__:
indent += yield from format_exception(exc.__context__, indent)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def print_exception(*args, file=None, **kwargs):
""" Print the formatted output of an exception object. """ |
for line in format_exception(*args, **kwargs):
vtml.vtmlprint(line, file=file) |
<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(cls, config_file=None):
""" Return the default configuration. """ |
if cls.instance is None:
cls.instance = cls(config_file)
# Load config file, possibly overwriting the defaults
cls.instance.load_ini()
if config_file and config_file != cls.instance.config_file:
raise RuntimeError("Configuration initialized a second tim... |
<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_ini(self):
""" Load the given .INI file. """ |
if not self.config_file:
return
# Load INI file
ini_file = ConfigParser.SafeConfigParser()
if not ini_file.read(self.config_file):
raise ConfigParser.ParsingError("Global configuration file %r not found!" % (
self.config_file,
))
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def multiple_chunks(self, chunk_size=None):
""" Returns ``True`` if you can expect multiple chunks. NB: If a particular file representation is in memory, subclas... |
if not chunk_size:
chunk_size = self.DEFAULT_CHUNK_SIZE
return self.size > chunk_size |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def content(self, value):
""" Set content to byte string, encoding if necessary """ |
if isinstance(value, bytes):
self._content = value
else:
self._content = value.encode(ENCODING)
self.size = len(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 md5hash(self):
"""Return the MD5 hash string of the file content""" |
digest = hashlib.md5(self.content).digest()
return b64_string(digest) |
<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(self, chunk_size=None):
""" Return chunk_size of bytes, starting from self.pos, from self.content. """ |
if chunk_size:
data = self.content[self.pos:self.pos + chunk_size]
self.pos += len(data)
return data
else:
return self.content |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def import_egg(string):
""" Import a controller class from an egg. Uses the entry point group "appathy.controller". """ |
# Split the string into a distribution and a name
dist, _sep, name = string.partition('#')
return pkg_resources.load_entry_point(dist, 'appathy.controller', 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 first(sequence, message=None):
"""The first item in that sequence If there aren't any, raise a ValueError with that message """ |
try:
return next(iter(sequence))
except StopIteration:
raise ValueError(message or ('Sequence is empty: %s' % sequence)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def last(sequence, message=None):
"""The last item in that sequence If there aren't any, raise a ValueError with that message """ |
try:
return sequence.pop()
except AttributeError:
return list(sequence).pop()
except IndexError:
raise ValueError(message or f'Sequence is empty: {sequence}') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def first_that(predicate, sequence, message=None):
"""The first item in that sequence that matches that predicate If none matches raise a KeyError with that mess... |
try:
return next(ifilter(predicate, sequence))
except StopIteration:
raise KeyError(message or 'Not Found') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def expand_window(center, window_size, array_size):
"""Generate a bounded windows. maxlength = 2 * window_size + 1, lower bound is 0 and upper bound is ``array_s... |
if center - window_size < 0:
lower = 0
else:
lower = center - window_size
if center + window_size + 1 > array_size:
upper = array_size
else:
upper = center + window_size + 1
return np.array(range(lower, upper)) |
<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_populate(self, data):
""" Populate a newly created config object with data. If it was populated, this returns True. If it wasn't, this returns False.... |
if self.config.parsed:
return False
# Otherwise, create a new ConfigKey.
self.config.load_from_dict(data)
return 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 apply_defaults(self, other_config):
""" Applies default values from a different ConfigObject or ConfigKey object to this ConfigObject. If there are any value... |
if isinstance(other_config, self.__class__):
self.config.load_from_dict(other_config.config, overwrite=False)
else:
self.config.load_from_dict(other_config, overwrite=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 reload(self):
""" Automatically reloads the config file. This is just an alias for self.load().""" |
if not self.fd.closed: self.fd.close()
self.fd = open(self.fd.name, 'r')
self.load() |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.