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 hasOption(self, name):
""" Check whether this CLI has an option with a given name. :param name: the name of the option to check; can be short or long name. :... |
name = name.strip()
for o in self.options:
if o.short == name or o.long == name:
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 addOption(self, o):
""" Add a new Option to this CLI. :param o: the option to add :raise InterfaceException: if an option with that name already exists. """ |
if self.hasOption(o.short):
raise InterfaceException("Failed adding option - already have " + str(o))
self.options.append(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 optionIsSet(self, name):
""" Check whether an option with a given name exists and has been set. :param name: the name of the option to check; can be short or... |
name = name.strip()
if not self.hasOption(name):
return False
return self.getOption(name).isSet() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def getArgument(self, num):
""" Get the num^th argument. :param num: Which argument to get; indexing here is from 0. :return: The num^th agument; arguments are a... |
if not self.hasArgument(num):
raise InterfaceException("Failed to retrieve argument " + str(num) +
" -- not enough arguments provided")
return self.args[num] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _optlist(self):
"""Get a string representation of the options in short format.""" |
res = ""
for o in self.options:
res += o.short
if o.argName is not None:
res += ":"
return res |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _longoptl(self):
"""Get a list of string representations of the options in long format.""" |
res = []
for o in self.options:
nm = o.long
if o.argName is not None:
nm += "="
res.append(nm)
return res |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def pull(self):
"""Pull from the origin.""" |
repo_root = settings.REPO_ROOT
pull_from_origin(join(repo_root, self.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 to_package(self, repo_url):
"""Return the package representation of this repo.""" |
return Package(name=self.name, url=repo_url + self.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 get_storage(clear=False):
"""helper function to get annotation storage on the portal :param clear: If true is passed in, annotations will be cleared :returns... |
portal = getUtility(ISiteRoot)
annotations = IAnnotations(portal)
if ANNOTATION_KEY not in annotations or clear:
annotations[ANNOTATION_KEY] = OOBTree()
return annotations[ANNOTATION_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 send_email(recipient, subject, message, sender="ploneintranet@netsight.co.uk"):
"""helper function to send an email with the sender preset """ |
try:
api.portal.send_email(
recipient=recipient,
sender=sender,
subject=subject,
body=message)
except ValueError, e:
log.error("MailHost error: {0}".format(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 parent_workspace(context):
""" Return containing workspace Returns None if not found. """ |
if IWorkspaceFolder.providedBy(context):
return context
for parent in aq_chain(context):
if IWorkspaceFolder.providedBy(parent):
return parent |
<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_workspace_activities(brain, limit=1):
""" Return the workspace activities sorted by reverse chronological order Regarding the time value: - the datetime ... |
mb = queryUtility(IMicroblogTool)
items = mb.context_values(brain.getObject(), limit=limit)
return [
{
'subject': item.creator,
'verb': 'published',
'object': item.text,
'time': {
'datetime': item.date.strftime('%Y-%m-%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 my_workspaces(context):
""" The list of my workspaces """ |
pc = api.portal.get_tool('portal_catalog')
brains = pc(
portal_type="ploneintranet.workspace.workspacefolder",
sort_on="modified",
sort_order="reversed",
)
workspaces = [
{
'id': brain.getId,
'title': brain.Title,
'description': brain.... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def existing_users(context):
""" Look up the full user details for current workspace members """ |
members = IWorkspace(context).members
info = []
for userid, details in members.items():
user = api.user.get(userid)
if user is None:
continue
user = user.getUser()
title = user.getProperty('fullname') or user.getId() or userid
# XXX tbd, we don't know wha... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def random_weighted_choice(choices):
""" Return a random key of choices, weighted by their value. :param choices: a dictionary of keys and positive integer pairs... |
choices, weights = zip(*choices.items())
cumdist = list(accumulate(weights))
x = random.random() * cumdist[-1]
element = bisect.bisect(cumdist, x)
return choices[element] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def extract_words(lines):
""" Extract from the given iterable of lines the list of words. :param lines: an iterable of lines; :return: a generator of words of li... |
for line in lines:
for word in re.findall(r"\w+", line):
yield word |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def absolute_urls(html):
""" Converts relative URLs into absolute URLs. Used for RSS feeds to provide more complete HTML for item descriptions, but could also be... |
from bs4 import BeautifulSoup
from yacms.core.request import current_request
request = current_request()
if request is not None:
dom = BeautifulSoup(html, "html.parser")
for tag, attr in ABSOLUTE_URL_TAGS.items():
for node in dom.findAll(tag):
url = node.ge... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def escape(html):
""" Escapes HTML according to the rules defined by the settings ``RICHTEXT_FILTER_LEVEL``, ``RICHTEXT_ALLOWED_TAGS``, ``RICHTEXT_ALLOWED_ATTRIB... |
from yacms.conf import settings
from yacms.core import defaults
if settings.RICHTEXT_FILTER_LEVEL == defaults.RICHTEXT_FILTER_LEVEL_NONE:
return html
tags = settings.RICHTEXT_ALLOWED_TAGS
attrs = settings.RICHTEXT_ALLOWED_ATTRIBUTES
styles = settings.RICHTEXT_ALLOWED_STYLES
if setti... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def thumbnails(html):
""" Given a HTML string, converts paths in img tags to thumbnail paths, using yacms's ``thumbnail`` template tag. Used as one of the defaul... |
from django.conf import settings
from bs4 import BeautifulSoup
from yacms.core.templatetags.yacms_tags import thumbnail
# If MEDIA_URL isn't in the HTML string, there aren't any
# images to replace, so bail early.
if settings.MEDIA_URL.lower() not in html.lower():
return html
dom ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def request(self, url, method, body=None, headers=None, **kwargs):
"""Request without authentication.""" |
content_type = kwargs.pop('content_type', None) or 'application/json'
headers = headers or {}
headers.setdefault('Accept', content_type)
if body:
headers.setdefault('Content-Type', content_type)
headers['User-Agent'] = self.USER_AGENT
resp = requests.requ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _extract_service_catalog(self, body):
"""Set the client's service catalog from the response data.""" |
self.auth_ref = access.create(body=body)
self.service_catalog = self.auth_ref.service_catalog
self.auth_token = self.auth_ref.auth_token
self.auth_tenant_id = self.auth_ref.tenant_id
self.auth_user_id = self.auth_ref.user_id
if not self.endpoint_url:
self.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 show_partitioning(rdd, show=True):
"""Seems to be significantly more expensive on cluster than locally""" |
if show:
partitionCount = rdd.getNumPartitions()
try:
valueCount = rdd.countApprox(1000, confidence=0.50)
except:
valueCount = -1
try:
name = rdd.name() or None
except:
pass
name = name or "anonymous"
logging.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 normal_case(name):
"""Converts "CamelCaseHere" to "camel case here".""" |
s1 = re.sub(r'(.)([A-Z][a-z]+)', r'\1 \2', name)
return re.sub(r'([a-z0-9])([A-Z])', r'\1 \2', s1).lower() |
<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_config(self):
""" install supervisor main config file """ |
text = templ_config.render(**self.options)
config = Configuration(self.buildout, 'supervisord.conf', {
'deployment': self.deployment_name,
'text': text})
return [config.install()] |
<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_program(self):
""" install supervisor program config file """ |
text = templ_program.render(**self.options)
config = Configuration(self.buildout, self.program + '.conf', {
'deployment': self.deployment_name,
'directory': os.path.join(self.options['etc-directory'], 'conf.d'),
'text': text})
return [config.install()] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def linreg_ols_lu(y, X):
"""Linear Regression, OLS, by solving linear equations and LU decomposition Properties * based on LAPACK's _gesv what applies LU decompo... |
import numpy as np
try: # solve OLS formula
return np.linalg.solve(np.dot(X.T, X), np.dot(X.T, y))
except np.linalg.LinAlgError:
print("LinAlgError: X*X' is singular or not square.")
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 _time_to_minutes(self, time_str):
""" Convert a time string to the equivalent number in minutes as an int. Return 0 if the time_str is not a valid amou... |
minutes = 0
try:
call_time_obj = parser.parse(time_str)
minutes = call_time_obj.minute
minutes += call_time_obj.hour * 60
except ValueError:
minutes = 0
return minutes |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def jumping(self, _loads=None):
""" Return True if this dropzone is still making new loads, False otherwise. :param _loads: The output of the `departing_lo... |
if _loads is None:
_loads = self.departing_loads()
if len(_loads) < 1:
return False
last_load = _loads[-1:][0]
if last_load['state'].lower() in ('departed', 'closed', 'on hold'):
return False
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 devices_by_subsystem(subsys, only=lambda x: True):
""" Iterator that yields devices that belong to specified subsystem. Returned values are ``pydev.Device`` ... |
ctx = pyudev.Context()
for d in ctx.list_devices():
if d.subsystem != subsys:
continue
if not only(d):
continue
yield 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 check_infile(filename):
"""Check text file exisitense. Argument: filename: text file of bulk updating """ |
if os.path.isfile(filename):
domain = os.path.basename(filename).split('.txt')[0]
return domain
else:
sys.stderr.write("ERROR: %s : No such file\n" % filename)
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 set_json(domain, action, filename=False, record=False):
"""Convert text file to JSON. Arguments: domain: domain name of updating target action: True ; for PU... |
o = JSONConverter(domain)
if filename:
# for 'bulk_create/bulk_delete'
with open(filename, 'r') as f:
o.separate_input_file(f)
for item in o.separated_list:
o.read_records(item.splitlines())
o.generata_data(action)
elif 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 get_record_params(args):
"""Get record parameters from command options. Argument: args: arguments object """ |
name, rtype, content, ttl, priority = (
args.name, args.rtype, args.content, args.ttl, args.priority)
return name, rtype, content, ttl, priority |
<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(args):
"""Create records. Argument: args: arguments object """ |
# for PUT HTTP method
action = True
if ((args.__dict__.get('domain') and args.__dict__.get('name')
and args.__dict__.get('rtype') and args.__dict__.get('content'))):
# for create sub-command
domain = args.domain
o = JSONConverter(domain)
name, rtype, content, ttl... |
<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_option(prs, keyword, required=False):
"""Set options of command line. Arguments: prs: parser object of argparse keyword: processing keyword required: Tru... |
if keyword == 'server':
prs.add_argument(
'-s', dest='server', required=True,
help='specify TonicDNS Server hostname or IP address')
if keyword == 'username':
prs.add_argument('-u', dest='username', required=True,
help='TonicDNS username')
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def conn_options(prs, conn):
"""Set options of connecting to TonicDNS API server Arguments: prs: parser object of argparse conn: dictionary of connection informa... |
if conn.get('server') and conn.get('username') and conn.get('password'):
prs.set_defaults(server=conn.get('server'),
username=conn.get('username'),
password=conn.get('password'))
elif conn.get('server') and conn.get('username'):
prs.set_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 parse_options():
"""Define sub-commands and command line options.""" |
server, username, password, auto_update_soa = False, False, False, False
prs = argparse.ArgumentParser(description='usage')
prs.add_argument('-v', '--version', action='version',
version=__version__)
if os.environ.get('HOME'):
config_file = os.environ.get('HOME') + '/.tdcl... |
<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_create(prs, conn):
"""Create record. Arguments: prs: parser object of argparse conn: dictionary of connection information """ |
prs_create = prs.add_parser(
'create', help='create record of specific zone')
set_option(prs_create, 'domain')
conn_options(prs_create, conn)
prs_create.set_defaults(func=create) |
<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_bulk_create(prs, conn):
"""Create bulk_records. Arguments: prs: parser object of argparse conn: dictionary of connection information """ |
prs_create = prs.add_parser(
'bulk_create', help='create bulk records of specific zone')
set_option(prs_create, 'infile')
conn_options(prs_create, conn)
prs_create.add_argument('--domain', action='store',
help='create records with specify zone')
prs_create.set_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 parse_delete(prs, conn):
"""Delete record. Arguments: prs: parser object of argparse conn: dictionary of connection information """ |
prs_delete = prs.add_parser(
'delete', help='delete a record of specific zone')
set_option(prs_delete, 'domain')
conn_options(prs_delete, conn)
prs_delete.set_defaults(func=delete) |
<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_bulk_delete(prs, conn):
"""Delete bulk_records. Arguments: prs: parser object of argparse conn: dictionary of connection information """ |
prs_delete = prs.add_parser(
'bulk_delete', help='delete bulk records of specific zone')
set_option(prs_delete, 'infile')
conn_options(prs_delete, conn)
prs_delete.add_argument('--domain', action='store',
help='delete records with specify zone')
prs_delete.set_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 check_config(filename):
"""Check configuration file of TonicDNS CLI. Argument: filename: config file name (default is ~/.tdclirc) """ |
conf = configparser.SafeConfigParser(allow_no_value=False)
conf.read(filename)
try:
server = conf.get('global', 'server')
except configparser.NoSectionError:
server = False
except configparser.NoOptionError:
server = False
try:
username = conf.get('auth', 'userna... |
<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_example_config(example_file_path: str):
""" Writes an example config file using the config values declared so far :param example_file_path: path to wri... |
document = tomlkit.document()
for header_line in _get_header():
document.add(tomlkit.comment(header_line))
config_keys = _aggregate_config_values(ConfigValue.config_values)
_add_config_values_to_toml_object(document, config_keys)
_doc_as_str = document.as_string().replace(f'"{_NOT_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 prepare_message(self, message):
""" Prepares the message before sending it out Returns: - message.Message: the message """ |
message.meta.update(path=self.path)
for handler in self.handlers:
handler.outgoing(message, self)
return message |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def on_receive(self, message=None, wire=None, event_origin=None):
""" event handler bound to the receive event of the link the server is wired too. Arguments: - ... |
self.trigger("before_call", message)
fn_name = message.data
pmsg = self.prepare_message
try:
for handler in self.handlers:
handler.incoming(message, self)
fn = self.get_function(fn_name, message.path)
except Exception as inst:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def detach_remote(self, id, name):
""" destroy remote instance of widget Arguments: - id (str):
widget id - name (str):
widget type name """ |
if name in self.widgets:
if id in self.widgets[name]:
del self.widgets[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 attach_remote(self, id, name, **kwargs):
""" create remote instance of widget Arguments: - id (str):
widget id - name (str):
widget type name Keyword Argum... |
client_id = id.split(".")[0]
widget = self.make_widget(
id,
name,
dispatcher=ProxyDispatcher(
self,
link=getattr(self.clients[client_id], "link", None)
),
**kwargs
)
self.store_widget(widget)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def on_api_error(self, error_status=None, message=None, event_origin=None):
""" API error handling """ |
if message.meta["error"].find("Widget instance not found on server") > -1:
# widget is missing on the other side, try to re-attach
# then try again
error_status["retry"] = True
self.comm.attach_remote(
self.id,
self.remote_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 write_message(self, message):
""" Writes a message to this chat connection's handler """ |
logging.debug("Sending message {mes} to {usr}".format(mes=message, usr=self.id))
self.handler.write_message(message) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def join_room(self, room_name):
""" Connects to a given room
If it does not exist it is created""" |
logging.debug('Joining room {ro}'.format(ro=room_name))
for room in self.rooms:
if room.name == room_name:
room.add_user(self)
self._rooms[room_name] = room
room.welcome(self)
break
else:
roo... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def send_to_room(self, message, room_name):
""" Sends a given message to a given room """ |
room = self.get_room(room_name)
if room is not None:
room.send_message(message) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _send_to_all_rooms(self, message):
""" Send a message to all connected rooms """ |
for room in self._rooms.values():
room.send_message(message) |
<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):
""" Closes the connection by removing the user from all rooms """ |
logging.debug('Closing for user {user}'.format(user=self.id.name))
self.id.release_name()
for room in self._rooms.values():
room.disconnect(self) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_parents(obj, **kwargs):
|
num_of_mro = kwargs.get("num_of_mro", 5)
mro = getmro(obj.__class__)
mro_string = ', '.join([extract_type(str(t)) for t in mro[:num_of_mro]])
return "Hierarchy: {}".format(mro_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 lpad(s, N, char='\0'):
"""pads a string to the left with null-bytes or any other given character. ..note:: This is used by the :py:func:`xor` function. :para... |
assert isinstance(char, bytes) and len(char) == 1, 'char should be a string with length 1'
return s.rjust(N, char) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def rpad(s, N, char='\0'):
"""pads a string to the right with null-bytes or any other given character. ..note:: This is used by the :py:func:`xor` function. :par... |
assert isinstance(char, bytes) and len(char) == 1, 'char should be a string with length 1'
return s.ljust(N, char) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def xor(left, right):
"""xor 2 strings. They can be shorter than each other, in which case the shortest will be padded with null bytes at its right. :param left:... |
maxlength = max(map(len, (left, right)))
ileft = string_to_int(rpad(left, maxlength))
iright = string_to_int(rpad(right, maxlength))
xored = ileft ^ iright
return int_to_string(xored) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def slugify(string, repchar='_'):
"""replaces all non-alphanumeric chars in the string with the given repchar. :param string: the source string :param repchar: "... |
slug_regex = re.compile(r'(^[{0}._-]+|[^a-z-A-Z0-9_.-]+|[{0}._-]+$)'.format(repchar))
strip_regex = re.compile(r'[{0}._-]+'.format(repchar))
transformations = [
lambda x: slug_regex.sub(repchar, x),
lambda x: strip_regex.sub(repchar, x),
lambda x: x.strip(repchar),
lambda x... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def dispatch(self, *args, **kwargs):
"""Find and call local method.""" |
action = kwargs.pop('action', 'default')
action_method = getattr(self, str(action), self.default)
return action_method(*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 update(self, **kwargs):
"""Creates or updates a property for the instance for each parameter.""" |
for key, value in kwargs.items():
setattr(self, key, 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 template_ds(basedir, varname, vars, lookup_fatal=True, depth=0):
''' templates a data structure by traversing it and substituting for other data structures '''
if isinstance(varname, basestring):
m = _varFind(basedir, varname, vars, lookup_fatal, depth)
if not m:
return varname
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def template(basedir, text, vars, lookup_fatal=True, expand_lists=False):
''' run a text buffer through the templating engine until it no longer changes '''
try:
text = text.decode('utf-8')
except UnicodeEncodeError:
pass # already unicode
text = varReplace(basedir, unicode(text), vars,... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def template_from_file(basedir, path, vars):
''' run a file through the templating engine '''
from cirruscluster.ext.ansible import utils
realpath = utils.path_dwim(basedir, path)
loader=jinja2.FileSystemLoader([basedir,os.path.dirname(realpath)])
environment = jinja2.Environment(loader=loader, tri... |
<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_locals(self, locals):
'''
If locals are provided, create a copy of self containing those
locals in addition to what is already in this variable proxy.
'''
if locals is None:
return self
return _jinja2_vars(self.basedir, self.vars, self.globals, locals,... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def expire_cache(fragment_name, *args):
""" Expire a cache item. @param url: The url object @param product_names: A list of product names @param start: The date ... |
cache_key = make_template_fragment_key(fragment_name, args)
cache.delete(cache_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 start(self):
""" Start the installation wizard """ |
self.log.debug('Starting the installation process')
self.browser.open(self.url)
self.system_check() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def admin(self):
""" Provide admin login credentials """ |
self._check_title(self.browser.title())
self.browser.select_form(nr=0)
# Get the admin credentials
prompted = []
user = self.ctx.config.get('User', 'AdminUser')
if not user:
user = click.prompt('Admin display name')
prompted.append('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 _start_install(self):
""" Start the installation """ |
self._check_title(self.browser.title())
continue_link = next(self.browser.links(text_regex='Start Installation'))
self.browser.follow_link(continue_link) |
<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):
""" Run the actual installation """ |
self._start_install()
mr_link = self._get_mr_link()
# Set up the progress bar
pbar = ProgressBar(100, 'Running installation...')
pbar.start()
mr_j, mr_r = self._ajax(mr_link)
# Loop until we get a redirect json response
while True:
mr_link =... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def pipe_cloexec():
"""Create a pipe with FDs set CLOEXEC.""" |
# Pipes' FDs are set CLOEXEC by default because we don't want them
# to be inherited by other subprocesses: the CLOEXEC flag is removed
# from the child's FDs by _dup2(), between fork() and exec().
# This is not atomic: we would need the pipe2() syscall for that.
r, w = os.pipe()
_set_cloexec_f... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_signature(self, base_commit=None):
"""Get the signature of the current state of the repository TODO right now `get_signature` is an effectful process in ... |
if base_commit is None:
base_commit = 'HEAD'
self.run('add', '-A', self.path)
sha = self.run('rev-parse', '--verify', base_commit).strip()
diff = self.run('diff', sha).strip()
if len(diff) == 0:
try:
return self.get_signature(base_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 install_hook(self, hook_name, hook_content):
"""Install the repository hook for this repo. Args: hook_name (str) hook_content (str) """ |
hook_path = os.path.join(self.path, '.git/hooks', hook_name)
with open(hook_path, 'w') as f:
f.write(hook_content)
os.chmod(hook_path, stat.S_IEXEC | stat.S_IREAD | stat.S_IWRITE) |
<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_ignored_files(self):
"""Returns the list of files being ignored in this repository. Note that file names, not directories, are returned. So, we will get ... |
return [os.path.join(self.path, p) for p in
self.run('ls-files', '--ignored', '--exclude-standard',
'--others').strip().split()
] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def path_is_ignored(self, path):
"""Given a path, check if the path would be ignored. Returns: boolean """ |
try:
self.run('check-ignore', '--quiet', path)
except CommandError as e:
if e.retcode == 1:
# path is ignored
return False
else:
# fatal error
raise e
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 _get_object_pydoc_page_name(obj):
"""Returns fully qualified name, including module name, except for the built-in module.""" |
page_name = fullqualname.fullqualname(obj)
if page_name is not None:
page_name = _remove_builtin_prefix(page_name)
return page_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 _remove_builtin_prefix(name):
"""Strip name of builtin module from start of name.""" |
if name.startswith('builtins.'):
return name[len('builtins.'):]
elif name.startswith('__builtin__.'):
return name[len('__builtin__.'):]
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 _get_user_ns_object(shell, path):
"""Get object from the user namespace, given a path containing zero or more dots. Return None if the path is not valid. """ |
parts = path.split('.', 1)
name, attr = parts[0], parts[1:]
if name in shell.user_ns:
if attr:
try:
return _getattr(shell.user_ns[name], attr[0])
except AttributeError:
return None
else:
return shell.user_ns[name]
retur... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _stop_process(p, name):
"""Stop process, by applying terminate and kill.""" |
# Based on code in IPython.core.magics.script.ScriptMagics.shebang
if p.poll() is not None:
print("{} is already stopped.".format(name))
return
p.terminate()
time.sleep(0.1)
if p.poll() is not None:
print("{} is terminated.".format(name))
return
p.kill()
prin... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def pydoc_cli_monkey_patched(port):
"""In Python 3, run pydoc.cli with builtins.input monkey-patched so that pydoc can be run as a process. """ |
# Monkey-patch input so that input does not raise EOFError when
# called by pydoc.cli
def input(_): # pylint: disable=W0622
"""Monkey-patched version of builtins.input"""
while 1:
time.sleep(1.0)
import builtins
builtins.input = input
sys.argv += ["-p", 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 start_server_background(port):
"""Start the newtab server as a background process.""" |
if sys.version_info[0] == 2:
lines = ('import pydoc\n'
'pydoc.serve({port})')
cell = lines.format(port=port)
else:
# The location of newtabmagic (normally $IPYTHONDIR/extensions)
# needs to be added to sys.path.
path = repr(os.path.dirname(os.path.realp... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _port_not_in_use():
"""Use the port 0 trick to find a port not in use.""" |
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
port = 0
s.bind(('', port))
_, port = s.getsockname()
return 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 start(self):
"""Start server if not previously started.""" |
msg = ''
if not self.running():
if self._port == 0:
self._port = _port_not_in_use()
self._process = start_server_background(self._port)
else:
msg = 'Server already started\n'
msg += 'Server running at {}'.format(self.url())
pri... |
<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):
"""Read stdout and stdout pipes if process is no longer running.""" |
if self._process and self._process.poll() is not None:
ip = get_ipython()
err = ip.user_ns['error'].read().decode()
out = ip.user_ns['output'].read().decode()
else:
out = ''
err = ''
return out, err |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def stop(self):
"""Stop server process.""" |
msg = ''
if self._process:
_stop_process(self._process, 'Server process')
else:
msg += 'Server not started.\n'
if msg:
print(msg, end='') |
<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(self):
"""Show state.""" |
msg = ''
if self._process:
msg += 'server pid: {}\n'.format(self._process.pid)
msg += 'server poll: {}\n'.format(self._process.poll())
msg += 'server running: {}\n'.format(self.running())
msg += 'server port: {}\n'.format(self._port)
msg += 'server root 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 start(self):
"""! Start all receiving threads. """ |
if self.isThreadsRunning:
raise ThreadManagerException("Broker threads are already running")
self.isThreadsRunning = True
for client in self.clients:
threading.Thread(target = client).start() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def stop(self):
"""! Stop all receving threads. """ |
if not self.isThreadsRunning:
raise ThreadManagerException("Broker threads are already stopped")
self.isThreadsRunning = False
for client in self.clients:
client.stop() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def onConnect(self, client, userdata, flags, rc):
"""! The callback for when the client receives a CONNACK response from the server. @param client @param userdat... |
for sub in self.subsciption:
(result, mid) = self.client.subscribe(sub) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def onMessage(self, client, userdata, msg):
"""! The callback for when a PUBLISH message is received from the server. @param client @param userdata @param msg ""... |
dataIdentifier = DataIdentifier(self.broker, msg.topic)
self.dataHandler.onNewData(dataIdentifier, msg.payload) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def createReceiverID(self):
"""! Create new receiver ID. @return Receiver ID. """ |
_receiverID = self.receiverCounter
self.receiverCounter += 1
return BrokerReceiverID(self.hostname, self.pid, _receiverID) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def determine_actions(self, request, view):
"""Allow all allowed methods""" |
from rest_framework.generics import GenericAPIView
actions = {}
excluded_methods = {'HEAD', 'OPTIONS', 'PATCH', 'DELETE'}
for method in set(view.allowed_methods) - excluded_methods:
view.request = clone_request(request, method)
try:
if isinstance(... |
<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_within_content_length_limit(payload, api_config):
""" Check that the message content is within the configured length limit. """ |
length_limit = api_config.get('content_length_limit')
if (length_limit is not None) and (payload["content"] is not None):
content_length = len(payload["content"])
if content_length > length_limit:
return "Payload content too long: %s > %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_option(name, key_options, global_options, default=None):
""" Search the key-specific options and the global options for a given setting. Either dictionar... |
if key_options:
try:
return key_options[name]
except KeyError:
pass
if global_options:
try:
return global_options[name]
except KeyError:
pass
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 set_quiet(mres, parent, global_options):
""" Sets the 'quiet' property on the MultiResult """ |
quiet = global_options.get('quiet')
if quiet is not None:
mres._quiet = quiet
else:
mres._quiet = parent.quiet |
<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_cas(key_options, global_options, item):
""" Get the CAS from various inputs. This will properly honor the ``ignore_cas`` flag, if present. :param key_opt... |
if item:
ign_cas = get_option('ignore_cas', key_options, globals(), False)
return 0 if ign_cas else item.cas
else:
try:
cas = key_options['cas']
except KeyError:
try:
cas = global_options['cas']
except KeyError:
... |
<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(context, subject, debug, no_colors):
""" Eh is a terminal program that will provide you with quick reminders about a subject. To get started run: eh hel... |
eho = Eh(debug, no_colors)
if subject == 'list':
eho.subject_list()
exit(0)
if subject == 'update':
eho.update_subject_repo()
exit(0)
eho.run(subject)
exit(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 store_data(data):
"""Use this function to store data in a JSON file. This function is used for loading up a JSON file and appending additional data to the JS... |
with open(url_json_path) as json_file:
try:
json_file_data = load(json_file)
json_file_data.update(data)
except (AttributeError, JSONDecodeError):
json_file_data = data
with open(url_json_path, 'w') as json_file:
dump(json_file_data, json_file, 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 default_to_hashed_rows(self, default=None):
""" Gets the current setting with no parameters, sets it if a boolean is passed in :param default: the value to s... |
if default is not None:
self._default_to_hashed_rows = (default is True)
return self._default_to_hashed_rows |
<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_dict_row(self, feature_dict, key=None):
""" Add a dict row to the matrix :param str key: key used when rows is a dict rather than an array :param dict f... |
self._update_internal_column_state(set(feature_dict.keys()))
# reset the row memoization
self._row_memo = {}
if key is not None:
if key in self._row_name_idx:
self._rows[self._row_name_idx[key]] = feature_dict
return
else:
... |
<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_list_row(self, feature_list, key=None):
""" Add a list row to the matrix :param str key: key used when rows is a dict rather than an array :param featur... |
if len(feature_list) > len(self._column_name_list):
raise IndexError("Input list must have %s columns or less" % len(self._column_name_list))
# reset the row memoization
self._row_memo = {}
if key is not None:
if key in self._row_name_idx:
self.... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add_row(self, list_or_dict, key=None):
""" Adds a list or dict as a row in the FVM data structure :param str key: key used when rows is a dict rather than an... |
if isinstance(list_or_dict, list):
self._add_list_row(list_or_dict, key)
else:
self._add_dict_row(list_or_dict, key) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.