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 contexts(self):
""" Returns known contexts by exposing as a read-only property. """ |
if not hasattr(self, "_contexts"):
cs = {}
for cr in self.doc["contexts"]:
cs[cr["name"]] = copy.deepcopy(cr["context"])
self._contexts = cs
return self._contexts |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def user(self):
""" Returns the current user set by current context """ |
return self.users.get(self.contexts[self.current_context].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 bytes(self):
""" Returns the provided data as bytes. """ |
if self._filename:
with open(self._filename, "rb") as f:
return f.read()
else:
return self._bytes |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def filename(self):
""" Returns the provided data as a file location. """ |
if self._filename:
return self._filename
else:
with tempfile.NamedTemporaryFile(delete=False) as f:
f.write(self._bytes)
return f.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 object_factory(api, api_version, kind):
""" Dynamically builds a Python class for the given Kubernetes object in an API. For example: NetworkPolicy = pykube.... |
resource_list = api.resource_list(api_version)
resource = next((resource for resource in resource_list["resources"] if resource["kind"] == kind), None)
base = NamespacedAPIObject if resource["namespaced"] else APIObject
return type(kind, (base,), {
"version": api_version,
"endpoint": re... |
<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_info(self, *args, **kwargs):
""" Handles info messages and executed corresponding code """ |
if 'version' in kwargs:
# set api version number and exit
self.api_version = kwargs['version']
print("Initialized API with version %s" % self.api_version)
return
try:
info_code = str(kwargs['code'])
except KeyError:
raise 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 setup(app):
"""When used for sphinx extension.""" |
global _is_sphinx
_is_sphinx = True
app.add_config_value('no_underscore_emphasis', False, 'env')
app.add_config_value('m2r_parse_relative_links', False, 'env')
app.add_config_value('m2r_anonymous_references', False, 'env')
app.add_config_value('m2r_disable_inline_math', False, 'env')
app.ad... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def link(self, link, title, text):
"""Rendering a given link with content and title. :param link: href link for ``<a>`` tag. :param title: title content for `tit... |
if self.anonymous_references:
underscore = '__'
else:
underscore = '_'
if title:
return self._raw_html(
'<a href="{link}" title="{title}">{text}</a>'.format(
link=link, title=title, text=text
)
)... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def events(url=None, file=None, string_content=None, start=None, end=None, fix_apple=False):
""" Get all events form the given iCal URL occurring in the given ti... |
found_events = []
content = None
if url:
content = ICalDownload().data_from_url(url, apple_fix=fix_apple)
if not content and file:
content = ICalDownload().data_from_file(file, apple_fix=fix_apple)
if not content and string_content:
content = ICalDownload().data_from_str... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def request_data(key, url, file, string_content, start, end, fix_apple):
""" Request data, update local data cache and remove this Thread form queue. :param key:... |
data = []
try:
data += events(url=url, file=file, string_content=string_content,
start=start, end=end, fix_apple=fix_apple)
finally:
update_events(key, data)
request_finished(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 events_async(key, url=None, file=None, start=None, string_content=None, end=None, fix_apple=False):
""" Trigger an asynchronous data request. :param key: key... |
t = Thread(target=request_data, args=(key, url, file, string_content, start, end, fix_apple))
with event_lock:
if key not in threads:
threads[key] = []
threads[key].append(t)
if not threads[key][0].is_alive():
threads[key][0].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 request_finished(key):
""" Remove finished Thread from queue. :param key: data source key """ |
with event_lock:
threads[key] = threads[key][1:]
if threads[key]:
threads[key][0].run() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def data_from_url(self, url, apple_fix=False):
""" Download iCal data from URL. :param url: URL to download :param apple_fix: fix Apple bugs (protocol type and t... |
if apple_fix:
url = apple_url_fix(url)
_, content = self.http.request(url)
if not content:
raise ConnectionError('Could not get data from %s!' % url)
return self.decode(content, apple_fix=apple_fix) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def data_from_file(self, file, apple_fix=False):
""" Read iCal data from file. :param file: file to read :param apple_fix: fix wrong Apple tzdata in iCal :return... |
with open(file, mode='rb') as f:
content = f.read()
if not content:
raise IOError("File %f is not readable or is empty!" % file)
return self.decode(content, apple_fix=apple_fix) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def decode(self, content, apple_fix=False):
""" Decode content using the set charset. :param content: content do decode :param apple_fix: fix Apple txdata bug :r... |
content = content.decode(self.encoding)
content = content.replace('\r', '')
if apple_fix:
content = apple_data_fix(content)
return 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 create_event(component, tz=UTC):
""" Create an event from its iCal representation. :param component: iCal component :param tz: timezone for start and end tim... |
event = Event()
event.start = normalize(component.get('dtstart').dt, tz=tz)
if component.get('dtend'):
event.end = normalize(component.get('dtend').dt, tz=tz)
elif component.get('duration'): # compute implicit end as start + duration
event.end = event.start + component.get('durat... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def normalize(dt, tz=UTC):
""" Convert date or datetime to datetime with timezone. :param dt: date to normalize :param tz: the normalized date's timezone :return... |
if type(dt) is date:
dt = dt + relativedelta(hour=0)
elif type(dt) is datetime:
pass
else:
raise ValueError("unknown type %s" % type(dt))
if dt.tzinfo:
dt = dt.astimezone(tz)
else:
dt = dt.replace(tzinfo=tz)
return dt |
<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_events(content, start=None, end=None, default_span=timedelta(days=7)):
""" Query the events occurring in a given time range. :param content: iCal URL/f... |
if not start:
start = now()
if not end:
end = start + default_span
if not content:
raise ValueError('Content is invalid!')
calendar = Calendar.from_ical(content)
# Find the calendar's timezone info, or use UTC
for c in calendar.walk():
if c.name == 'VTIME... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def copy_to(self, new_start=None, uid=None):
""" Create a new event equal to this with new start date. :param new_start: new start date :param uid: UID of new ev... |
if not new_start:
new_start = self.start
if not uid:
uid = "%s_%d" % (self.uid, randint(0, 1000000))
ne = Event()
ne.summary = self.summary
ne.description = self.description
ne.start = new_start
if self.end:
duration... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fetch_public_key(repo):
"""Download RSA public key Travis will use for this repo. Travis API docs: http://docs.travis-ci.com/api/#repository-keys """ |
keyurl = 'https://api.travis-ci.org/repos/{0}/key'.format(repo)
data = json.loads(urlopen(keyurl).read())
if 'key' not in data:
errmsg = "Could not find public key for repo: {}.\n".format(repo)
errmsg += "Have you already added your GitHub repo to Travis?"
raise ValueError(errmsg)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def kill_the_system(self, warning: str):
"""Send an e-mail, and then shut the system down quickly. """ |
log.critical('Kill reason: ' + warning)
if self.DEBUG:
return
try:
self.mail_this(warning)
except socket.gaierror:
current_time = time.localtime()
formatted_time = time.strftime('%Y-%m-%d %I:%M:%S%p', current_time)
with open(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_killer(args):
"""Returns a KillerBase instance subclassed based on the OS.""" |
if POSIX:
log.debug('Platform: POSIX')
from killer.killer_posix import KillerPosix
return KillerPosix(config_path=args.config, debug=args.debug)
elif WINDOWS:
log.debug('Platform: Windows')
from killer.killer_windows import KillerWindows
return KillerWindows(conf... |
<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_devices(device_type: DeviceType) -> Iterator[str]: """Gets names of power devices of the specified type. :param str device_type: the type of the devices t... |
for device in BASE_PATH.iterdir():
with open(str(Path(device, 'type'))) as type_file:
if type_file.readline().strip() == device_type.value:
yield device.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_property(device_path: Union[Path, str], property_name: str) -> str: """Gets the given property for a device.""" |
with open(str(Path(device_path, property_name))) as file:
return file.readline().strip() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_power_status() -> SystemPowerStatus: """Retrieves the power status of the system. The status indicates whether the system is running on AC or DC power, wh... |
get_system_power_status = ctypes.windll.kernel32.GetSystemPowerStatus
get_system_power_status.argtypes = [ctypes.POINTER(SystemPowerStatus)]
get_system_power_status.restype = wintypes.BOOL
status = SystemPowerStatus()
if not get_system_power_status(ctypes.pointer(status)):
raise ctypes.Win... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def abilities(api_key=None, add_headers=None):
"""Fetch a list of permission-like strings for this account.""" |
client = ClientMixin(api_key=api_key)
result = client.request('GET', endpoint='abilities',
add_headers=add_headers,)
return result['abilities'] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def can(ability, add_headers=None):
"""Test whether an ability is allowed.""" |
client = ClientMixin(api_key=None)
try:
client.request('GET', endpoint='abilities/%s' % ability,
add_headers=add_headers)
return True
except Exception:
pass
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 set_api_key_from_file(path, set_global=True):
"""Set the global api_key from a file path.""" |
with open(path, 'r+b') as f:
global api_key
api_key = f.read().strip()
return api_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 resolve(self, from_email, resolution=None):
"""Resolve an incident using a valid email address.""" |
if from_email is None or not isinstance(from_email, six.string_types):
raise MissingFromEmail(from_email)
endpoint = '/'.join((self.endpoint, self.id,))
add_headers = {'from': from_email, }
data = {
'incident': {
'type': 'incident',
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def reassign(self, from_email, user_ids):
"""Reassign an incident to other users using a valid email address.""" |
endpoint = '/'.join((self.endpoint, self.id,))
if from_email is None or not isinstance(from_email, six.string_types):
raise MissingFromEmail(from_email)
if user_ids is None or not isinstance(user_ids, list):
raise InvalidArguments(user_ids)
if not all([isinstan... |
<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_entries(self, time_zone='UTC', is_overview=False, include=None, fetch_all=True):
"""Query for log entries on an incident instance.""" |
endpoint = '/'.join((self.endpoint, self.id, 'log_entries'))
query_params = {
'time_zone': time_zone,
'is_overview': json.dumps(is_overview),
}
if include:
query_params['include'] = include
result = self.logEntryFactory.find(
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 notes(self):
"""Query for notes attached to this incident.""" |
endpoint = '/'.join((self.endpoint, self.id, 'notes'))
return self.noteFactory.find(
endpoint=endpoint,
api_key=self.api_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 create_note(self, from_email, content):
"""Create a note for this incident.""" |
if from_email is None or not isinstance(from_email, six.string_types):
raise MissingFromEmail(from_email)
endpoint = '/'.join((self.endpoint, self.id, 'notes'))
add_headers = {'from': from_email, }
return self.noteFactory.create(
endpoint=endpoint,
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def snooze(self, from_email, duration):
"""Snooze this incident for `duration` seconds.""" |
if from_email is None or not isinstance(from_email, six.string_types):
raise MissingFromEmail(from_email)
endpoint = '/'.join((self.endpoint, self.id, 'snooze'))
add_headers = {'from': from_email, }
return self.__class__.create(
endpoint=endpoint,
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 merge(self, from_email, source_incidents):
"""Merge other incidents into this incident.""" |
if from_email is None or not isinstance(from_email, six.string_types):
raise MissingFromEmail(from_email)
add_headers = {'from': from_email, }
endpoint = '/'.join((self.endpoint, self.id, 'merge'))
incident_ids = [entity['id'] if isinstance(entity, Entity) else entity
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def alerts(self):
"""Query for alerts attached to this incident.""" |
endpoint = '/'.join((self.endpoint, self.id, 'alerts'))
return self.alertFactory.find(
endpoint=endpoint,
api_key=self.api_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 find(cls, *args, **kwargs):
""" Find notifications. Optional kwargs are: since: datetime instance until: datetime instance If not specified, until will defau... |
seconds = 60 * 60 * 24 * 30 # seconds in 30 days
until = kwargs.pop('until', None)
since = kwargs.pop('since', None)
if until is None:
until = datetime.datetime.now()
if since is None:
since = until - datetime.timedelta(seconds=seconds)
dt = 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 services(self):
"""Fetch all instances of services for this EP.""" |
ids = [ref['id'] for ref in self['services']]
return [Service.fetch(id) for id in ids] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fetch(cls, id, incident=None, endpoint=None, *args, **kwargs):
"""Customize fetch because this is a nested resource.""" |
if incident is None and endpoint is None:
raise InvalidArguments(incident, endpoint)
if endpoint is None:
iid = incident['id'] if isinstance(incident, Entity) else incident
endpoint = 'incidents/{0}/alerts'.format(iid)
return getattr(Entity, 'fetch').__func... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def resolve(self, from_email):
"""Resolve an alert using a valid email address.""" |
if from_email is None or not isinstance(from_email, six.string_types):
raise MissingFromEmail(from_email)
parent_incident_id = self['incident']['id']
endpoint_format = 'incidents/{0}/alerts/{1}'
endpoint = endpoint_format.format(parent_incident_id, self['id'])
add_... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def associate(self, from_email, new_parent_incident=None):
"""Associate an alert with an incident using a valid email address.""" |
if from_email is None or not isinstance(from_email, six.string_types):
raise MissingFromEmail(from_email)
if new_parent_incident is None:
raise InvalidArguments(new_parent_incident)
parent_incident_id = self['incident']['id']
endpoint_format = 'incidents/{0}/al... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fetch(cls, id, service=None, endpoint=None, *args, **kwargs):
"""Customize fetch because it lives on a special endpoint.""" |
if service is None and endpoint is None:
raise InvalidArguments(service, endpoint)
if endpoint is None:
sid = service['id'] if isinstance(service, Entity) else service
endpoint = 'services/{0}/integrations'.format(sid)
return getattr(Entity, 'fetch').__func... |
<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, service=None, endpoint=None, data=None, *args, **kwargs):
""" Create an integration within the scope of an service. Make sure that they should re... |
cls.validate(data)
if service is None and endpoint is None:
raise InvalidArguments(service, endpoint)
if endpoint is None:
sid = service['id'] if isinstance(service, Entity) else service
endpoint = 'services/{0}/integrations'.format(sid)
# otherwise... |
<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_oncall(self, **kwargs):
"""Retrieve this schedule's "on call" users.""" |
endpoint = '/'.join((self.endpoint, self.id, 'users'))
return self.request('GET', endpoint=endpoint, query_params=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 _do_request(self, method, *args, **kwargs):
""" Modularized because API was broken. Need to be able to inject Mocked response objects here. """ |
log('Doing HTTP [{3}] request: {0} - headers: {1} - payload: {2}'.format(
args[0], kwargs.get('headers'), kwargs.get('json'), method,),
level=logging.DEBUG,)
requests_method = getattr(requests, method)
return self._handle_response(requests_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 sanitize_ep(endpoint, plural=False):
""" Sanitize an endpoint to a singular or plural form. Used mostly for convenience in the `_parse` method to grab the ra... |
# if we need a plural endpoint (acessing lists)
if plural:
if endpoint.endswith('y'):
endpoint = endpoint[:-1] + 'ies'
elif not endpoint.endswith('s'):
endpoint += 's'
else:
# otherwise make sure it's singular form
... |
<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_endpoint(cls):
""" Accessor method to enable omition of endpoint name. In general we want the class name to be translated to endpoint name, this way unle... |
if cls.endpoint is not None:
return cls.endpoint
s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', cls.__name__)
return cls.sanitize_ep(
re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower(),
plural=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 _fetch_all(cls, api_key, endpoint=None, offset=0, limit=25, **kwargs):
""" Call `self._fetch_page` for as many pages as exist. TODO: should be extended to do... |
output = []
qp = kwargs.copy()
limit = max(1, min(100, limit))
maximum = kwargs.get('maximum')
qp['limit'] = min(limit, maximum) if maximum is not None else limit
qp['offset'] = offset
more, total = None, None
while True:
entities, options = ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _fetch_page(cls, api_key, endpoint=None, page_index=0, offset=None, limit=25, **kwargs):
""" Fetch a single page of `limit` number of results. Optionally pro... |
# if offset is provided have it overwrite the page_index provided
if offset is not None:
page_index = int(offset / limit)
# limit can be maximum MAX_LIMIT_VALUE for most PD queries
limit = max(1, min(cls.MAX_LIMIT_VALUE, limit))
# make an tmp instance to do query w... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fetch(cls, id, api_key=None, endpoint=None, add_headers=None, **kwargs):
""" Fetch a single entity from the API endpoint. Used when you know the exact ID tha... |
if endpoint is None:
endpoint = cls.get_endpoint()
inst = cls(api_key=api_key)
parse_key = cls.sanitize_ep(endpoint).split("/")[-1]
endpoint = '/'.join((endpoint, id))
data = cls._parse(inst.request('GET',
endpoint=endpoint,
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def translate_query_params(cls, **kwargs):
""" Translate an arbirtary keyword argument to the expected query. TODO: refactor this into something less insane. XXX... |
values = []
output = kwargs.copy()
query = kwargs.pop('query', None)
# remove any of the TRANSLATE_QUERY_PARAMs in output
for param in (cls.TRANSLATE_QUERY_PARAM or []):
popped = output.pop(param, None)
if popped is not None:
values.appen... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def find(cls, api_key=None, fetch_all=True, endpoint=None, maximum=None, **kwargs):
""" Find some entities from the API endpoint. If no api_key is provided, the ... |
exclude = kwargs.pop('exclude', None)
# if exclude param was passed a a string, list-ify it
if isinstance(exclude, six.string_types):
exclude = [exclude, ]
query_params = cls.translate_query_params(**kwargs)
# unless otherwise specified use the class variable for ... |
<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, data=None, api_key=None, endpoint=None, add_headers=None, data_key=None, response_data_key=None, method='POST', **kwargs):
""" Create an instance... |
inst = cls(api_key=api_key)
if data_key is None:
data_key = cls.sanitize_ep(cls.get_endpoint())
if response_data_key is None:
response_data_key = cls.sanitize_ep(cls.get_endpoint())
body = {}
body[data_key] = data
if endpoint is None:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _parse(cls, data, key=None):
""" Parse a set of data to extract entity-only data. Use classmethod `parse` if available, otherwise use the `endpoint` class va... |
parse = cls.parse if cls.parse is not None else cls.get_endpoint()
if callable(parse):
data = parse(data)
elif isinstance(parse, str):
data = data[key]
else:
raise Exception('"parse" should be a callable or string got, {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 log(*args, **kwargs):
"""Log things with the global logger.""" |
level = kwargs.pop('level', logging.INFO)
logger.log(level, *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 create(cls, data=None, api_key=None, endpoint=None, add_headers=None, **kwargs):
"""Create an event on your PagerDuty account.""" |
cls.validate(data)
inst = cls(api_key=api_key)
endpoint = ''
return inst.request('POST',
endpoint=endpoint,
data=data,
query_params=kwargs,
add_headers=add_headers,
... |
<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_escalation_policy(self, escalation_policy, **kwargs):
"""Remove an escalation policy from this team.""" |
if isinstance(escalation_policy, Entity):
escalation_policy = escalation_policy['id']
assert isinstance(escalation_policy, six.string_types)
endpoint = '{0}/{1}/escalation_policies/{2}'.format(
self.endpoint,
self['id'],
escalation_policy,
... |
<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_user(self, user, **kwargs):
"""Remove a user from this team.""" |
if isinstance(user, Entity):
user = user['id']
assert isinstance(user, six.string_types)
endpoint = '{0}/{1}/users/{2}'.format(
self.endpoint,
self['id'],
user,
)
return self.request('DELETE', endpoint=endpoint, query_params=kwar... |
<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_user(self, user, **kwargs):
"""Add a user to this team.""" |
if isinstance(user, User):
user = user['id']
assert isinstance(user, six.string_types)
endpoint = '{0}/{1}/users/{2}'.format(
self.endpoint,
self['id'],
user,
)
result = self.request('PUT', endpoint=endpoint, query_params=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 create_integration(self, integration_info, **kwargs):
""" Create an integration for this service. See: https://v2.developer.pagerduty.com/v2/page/api-referen... |
service_info = integration_info.get('service')
vendor_info = integration_info.get('vendor')
if service_info is not None:
self.__class__.validate(service_info)
if vendor_info is not None:
self.vendorFactory.validate(vendor_info)
endpoint = '{0}/{1}/inte... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def integrations(self, **kwargs):
"""Retrieve all this services integrations.""" |
ids = [ref['id'] for ref in self['integrations']]
return [Integration.fetch(id, service=self, query_params=kwargs) for id in ids] |
<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_integration(self, id, **kwargs):
"""Retrieve a single integration by id.""" |
return Integration.fetch(id, service=self, query_params=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 contact_methods(self, **kwargs):
"""Get all contact methods for this user.""" |
endpoint = '{0}/{1}/contact_methods'.format(
self.endpoint,
self['id'],
)
result = self.request('GET', endpoint=endpoint, query_params=kwargs)
return result['contact_methods'] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def delete_contact_method(self, id, **kwargs):
"""Delete a contact method for this user.""" |
endpoint = '{0}/{1}/contact_methods/{2}'.format(
self.endpoint,
self['id'],
id,
)
return self.request('DELETE', endpoint=endpoint, query_params=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 get_contact_method(self, id, **kwargs):
"""Get a contact method for this user.""" |
endpoint = '{0}/{1}/contact_methods/{2}'.format(
self.endpoint,
self['id'],
id,
)
result = self.request('GET', endpoint=endpoint, query_params=kwargs)
return result['contact_method'] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def notification_rules(self, **kwargs):
"""Get all notification rules for this user.""" |
endpoint = '{0}/{1}/notification_rules'.format(
self.endpoint,
self['id'],
)
result = self.request('GET', endpoint=endpoint, query_params=kwargs)
return result['notification_rules'] |
<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_notification_rule(self, data, **kwargs):
"""Create a notification rule for this user.""" |
data = {'notification_rule': data, }
endpoint = '{0}/{1}/notification_rules'.format(
self.endpoint,
self['id'],
)
result = self.request('POST', endpoint=endpoint, data=data,
query_params=kwargs)
self._data['notification_rules... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def delete_notification_rule(self, id, **kwargs):
"""Get a notification rule for this user.""" |
endpoint = '{0}/{1}/notification_rules/{2}'.format(
self.endpoint,
self['id'],
id,
)
return self.request('DELETE', endpoint=endpoint, query_params=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 install(cls, type_, name, src, *args, **kwargs):
"""Install an add-on to this account.""" |
data = kwargs.pop('data', None)
if data is None:
data = {
'addon': {
'type': type_,
'name': name,
'src': src,
}
}
cls.create(data=data, *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 create(cls, data=None, *args, **kwargs):
"""Validate and then create a Vendor entity.""" |
cls.validate(data)
# otherwise endpoint should contain the service path too
getattr(Entity, 'create').__func__(cls, data=data, *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 unstruct_strat(self):
# type: () -> UnstructureStrategy """The default way of unstructuring ``attrs`` classes.""" |
return (
UnstructureStrategy.AS_DICT
if self._unstructure_attrs == self.unstructure_attrs_asdict
else UnstructureStrategy.AS_TUPLE
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def register_structure_hook(self, cl, func):
"""Register a primitive-to-class converter function for a type. The converter function should take two arguments: * ... |
if is_union_type(cl):
self._union_registry[cl] = func
else:
self._structure_func.register_cls_list([(cl, func)]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def structure(self, obj, cl):
# type: (Any, Type[T]) -> T """Convert unstructured Python data structures to structured data.""" |
return self._structure_func.dispatch(cl)(obj, cl) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def unstructure_attrs_asdict(self, obj):
# type: (Any) -> Dict[str, Any] """Our version of `attrs.asdict`, so we can call back to us.""" |
attrs = obj.__class__.__attrs_attrs__
dispatch = self._unstructure_func.dispatch
rv = self._dict_factory()
for a in attrs:
name = a.name
v = getattr(obj, name)
rv[name] = dispatch(v.__class__)(v)
return rv |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def unstructure_attrs_astuple(self, obj):
# type: (Any) -> Tuple """Our version of `attrs.astuple`, so we can call back to us.""" |
attrs = obj.__class__.__attrs_attrs__
return tuple(self.unstructure(getattr(obj, a.name)) for a in attrs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _unstructure_mapping(self, mapping):
"""Convert a mapping of attr classes to primitive equivalents.""" |
# We can reuse the mapping class, so dicts stay dicts and OrderedDicts
# stay OrderedDicts.
dispatch = self._unstructure_func.dispatch
return mapping.__class__(
(dispatch(k.__class__)(k), dispatch(v.__class__)(v))
for k, v in mapping.items()
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _structure_default(self, obj, cl):
"""This is the fallthrough case. Everything is a subclass of `Any`. A special condition here handles ``attrs`` classes. Ba... |
if cl is Any or cl is Optional:
return obj
# We don't know what this is, so we complain loudly.
msg = (
"Unsupported type: {0}. Register a structure hook for "
"it.".format(cl)
)
raise ValueError(msg) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _structure_unicode(self, obj, cl):
"""Just call ``cl`` with the given ``obj``""" |
if not isinstance(obj, (bytes, unicode)):
return cl(str(obj))
else:
return obj |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _structure_attr_from_tuple(self, a, name, value):
"""Handle an individual attrs attribute.""" |
type_ = a.type
if type_ is None:
# No type metadata.
return value
return self._structure_func.dispatch(type_)(value, type_) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _structure_list(self, obj, cl):
"""Convert an iterable to a potentially generic list.""" |
if is_bare(cl) or cl.__args__[0] is Any:
return [e for e in obj]
else:
elem_type = cl.__args__[0]
return [
self._structure_func.dispatch(elem_type)(e, elem_type)
for e in obj
] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _structure_set(self, obj, cl):
"""Convert an iterable into a potentially generic set.""" |
if is_bare(cl) or cl.__args__[0] is Any:
return set(obj)
else:
elem_type = cl.__args__[0]
return {
self._structure_func.dispatch(elem_type)(e, elem_type)
for e in obj
} |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _structure_frozenset(self, obj, cl):
"""Convert an iterable into a potentially generic frozenset.""" |
if is_bare(cl) or cl.__args__[0] is Any:
return frozenset(obj)
else:
elem_type = cl.__args__[0]
dispatch = self._structure_func.dispatch
return frozenset(dispatch(elem_type)(e, elem_type) for e in obj) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _structure_dict(self, obj, cl):
"""Convert a mapping into a potentially generic dict.""" |
if is_bare(cl) or cl.__args__ == (Any, Any):
return dict(obj)
else:
key_type, val_type = cl.__args__
if key_type is Any:
val_conv = self._structure_func.dispatch(val_type)
return {k: val_conv(v, val_type) for k, v in obj.items()}
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _structure_union(self, obj, union):
"""Deal with converting a union.""" |
# Unions with NoneType in them are basically optionals.
# We check for NoneType early and handle the case of obj being None,
# so disambiguation functions don't need to handle NoneType.
union_params = union.__args__
if NoneType in union_params: # type: ignore
if obj... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _structure_tuple(self, obj, tup):
"""Deal with converting to a tuple.""" |
tup_params = tup.__args__
has_ellipsis = tup_params and tup_params[-1] is Ellipsis
if tup_params is None or (has_ellipsis and tup_params[0] is Any):
# Just a Tuple. (No generic information.)
return tuple(obj)
if has_ellipsis:
# We're dealing with a ho... |
<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_dis_func(self, union):
"""Fetch or try creating a disambiguation function for a union.""" |
union_types = union.__args__
if NoneType in union_types: # type: ignore
# We support unions of attrs classes and NoneType higher in the
# logic.
union_types = tuple(
e for e in union_types if e is not NoneType # type: ignore
)
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 create_uniq_field_dis_func(*classes):
# type: (*Type) -> Callable """Given attr classes, generate a disambiguation function. The function is based on unique ... |
if len(classes) < 2:
raise ValueError("At least two classes required.")
cls_and_attrs = [(cl, set(at.name for at in fields(cl))) for cl in classes]
if len([attrs for _, attrs in cls_and_attrs if len(attrs) == 0]) > 1:
raise ValueError("At least two classes have no attributes.")
# TODO: ... |
<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, typ):
""" returns the appropriate handler, for the object passed. """ |
for can_handle, handler in self._handler_pairs:
# can handle could raise an exception here
# such as issubclass being called on an instance.
# it's easier to just ignore that case.
try:
if can_handle(typ):
return handler
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def register_cls_list(self, cls_and_handler):
""" register a class to singledispatch """ |
for cls, handler in cls_and_handler:
self._single_dispatch.register(cls, handler)
self.dispatch.cache_clear() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def register_func_list(self, func_and_handler):
""" register a function to determine if the handle should be used for the type """ |
for func, handler in func_and_handler:
self._function_dispatch.register(func, handler)
self.dispatch.cache_clear() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def resource_uri(self):
"""Return the URI at which the resource can be found. :rtype: string """ |
primary_key_value = getattr(self, self.primary_key(), None)
return '/{}/{}'.format(self.endpoint(), primary_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 primary_key(cls):
"""Return the name of the table's primary key :rtype: string """ |
if cls.__from_class__:
cls = cls.__from_class__
return cls.__table__.primary_key.columns.values()[0].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 links(self):
"""Return a list of links for endpoints related to the resource. :rtype: list """ |
links = []
for foreign_key in self.__table__.foreign_keys:
column = foreign_key.column.name
column_value = getattr(self, column, None)
if column_value:
table = foreign_key.column.table.name
with app.app_context():
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def as_dict(self, depth=0):
"""Return a dictionary containing only the attributes which map to an instance's database columns. :param int depth: Maximum depth to... |
result_dict = {}
for column in self.__table__.columns.keys():
result_dict[column] = getattr(self, column, None)
if isinstance(result_dict[column], Decimal):
result_dict[column] = str(result_dict[column])
result_dict['links'] = self.links()
for for... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def meta(cls):
"""Return a dictionary containing meta-information about the given resource.""" |
if getattr(cls, '__from_class__', None) is not None:
cls = cls.__from_class__
attribute_info = {}
for name, value in cls.__table__.columns.items():
attribute_info[name] = str(value.type).lower()
return {cls.__name__: attribute_info} |
<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_version(ctx, value):
"""Print the current version of sandman and exit.""" |
if not value:
return
import pkg_resources
version = None
try:
version = pkg_resources.get_distribution('sandman').version
finally:
del pkg_resources
click.echo(version)
ctx.exit() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_acceptable_response_type():
"""Return the mimetype for this request.""" |
if ('Accept' not in request.headers or request.headers['Accept'] in
ALL_CONTENT_TYPES):
return JSON
acceptable_content_types = set(
request.headers['ACCEPT'].strip().split(','))
if acceptable_content_types & HTML_CONTENT_TYPES:
return HTML
elif acceptable_content_typ... |
<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_exception(error):
"""Return a response with the appropriate status code, message, and content type when an ``InvalidAPIUsage`` exception is raised.""" |
try:
if _get_acceptable_response_type() == JSON:
response = jsonify(error.to_dict())
response.status_code = error.code
return response
else:
return error.abort()
except InvalidAPIUsage:
# In addition to the original exception, we don't sup... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _single_attribute_html_response(resource, name, value):
"""Return the json representation of a single attribute of a resource. :param :class:`sandman.model.M... |
return make_response(render_template(
'attribute.html',
resource=resource,
name=name, value=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 put_resource(collection, key):
"""Replace the resource identified by the given key and return the appropriate response. :param string collection: a :class:`s... |
resource = retrieve_resource(collection, key)
_validate(endpoint_class(collection), request.method, resource)
resource.replace(get_resource_data(request))
try:
_perform_database_action('add', resource)
except IntegrityError as exception:
raise InvalidAPIUsage(422, FORWARDED_EXCEPT... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.