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.object_factory(api, "networking.k8s.io/v1", "NetworkPolicy") This enables construction of any Kubernetes object kind without explicit support from pykube. Currently, the HTTPClient passed to this function will not be bound to the returned type. It is planned to fix this, but in the mean time pass it as you would normally. """ |
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": resource["name"],
"kind": kind
}) |
<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 FaultyPayloadError("_handle_info: %s" % kwargs)
if not info_code.startswith('2'):
raise ValueError("Info Code must start with 2! %s", kwargs)
output_msg = "_handle_info(): %s" % kwargs
log.info(output_msg)
try:
self._code_handlers[info_code]()
except KeyError:
raise UnknownWSSInfo(output_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 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.add_source_parser('.md', M2RParser)
app.add_directive('mdinclude', MdInclude)
metadata = dict(
version=__version__,
parallel_read_safe=True,
parallel_write_safe=True,
)
return metadata |
<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 `title` attribute. :param text: text content for description. """ |
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
)
)
if not self.parse_relative_links:
return '\ `{text} <{target}>`{underscore}\ '.format(
target=link,
text=text,
underscore=underscore
)
else:
url_info = urlparse(link)
if url_info.scheme:
return '\ `{text} <{target}>`{underscore}\ '.format(
target=link,
text=text,
underscore=underscore
)
else:
link_type = 'doc'
anchor = url_info.fragment
if url_info.fragment:
if url_info.path:
# Can't link to anchors via doc directive.
anchor = ''
else:
# Example: [text](#anchor)
link_type = 'ref'
doc_link = '{doc_name}{anchor}'.format(
# splittext approach works whether or not path is set. It
# will return an empty string if unset, which leads to
# anchor only ref.
doc_name=os.path.splitext(url_info.path)[0],
anchor=anchor
)
return '\ :{link_type}:`{text} <{doc_link}>`\ '.format(
link_type=link_type,
doc_link=doc_link,
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 time range. :param url: iCal URL :param file: iCal file path :param string_content: iCal content as string :param start: start date (see dateutils.date) :param end: end date (see dateutils.date) :param fix_apple: fix known Apple iCal issues :return: events as list of dictionaries """ |
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_string(string_content,
apple_fix=fix_apple)
found_events += parse_events(content, start=start, end=end)
return found_events |
<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: key for data source to get result later :param url: iCal URL :param file: iCal file path :param string_content: iCal content as string :param start: start date :param end: end date :param fix_apple: fix known Apple iCal issues """ |
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 for data source to get result later :param url: iCal URL :param file: iCal file path :param string_content: iCal content as string :param start: start date :param end: end date :param fix_apple: fix known Apple iCal issues """ |
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 tzdata in iCal) :return: decoded (and fixed) iCal data """ |
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: decoded (and fixed) iCal data """ |
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 :return: decoded (and fixed) content """ |
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 times :return: event """ |
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('duration').dt
else: # compute implicit end as start + 0
event.end = event.start
try:
event.summary = str(component.get('summary'))
except UnicodeEncodeError as e:
event.summary = str(component.get('summary').encode('utf-8'))
try:
event.description = str(component.get('description'))
except UnicodeEncodeError as e:
event.description = str(component.get('description').encode('utf-8'))
event.all_day = type(component.get('dtstart').dt) is date
if component.get('rrule'):
event.recurring = True
try:
event.location = str(component.get('location'))
except UnicodeEncodeError as e:
event.location = str(component.get('location').encode('utf-8'))
if component.get('attendee'):
event.attendee = component.get('attendee')
if type(event.attendee) is list:
temp = []
for a in event.attendee:
temp.append(a.encode('utf-8').decode('ascii'))
event.attendee = temp
else:
event.attendee = event.attendee.encode('utf-8').decode('ascii')
if component.get('uid'):
event.uid = component.get('uid').encode('utf-8').decode('ascii')
if component.get('organizer'):
event.organizer = component.get('organizer').encode('utf-8').decode('ascii')
return event |
<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: date as datetime with timezone """ |
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/file content as String :param start: start date for search, default today :param end: end date for search :param default_span: default query length (one week) :return: events as list """ |
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 == 'VTIMEZONE':
cal_tz = gettz(str(c['TZID']))
break;
else:
cal_tz = UTC
start = normalize(start, cal_tz)
end = normalize(end, cal_tz)
found = []
for component in calendar.walk():
if component.name == "VEVENT":
e = create_event(component)
if e.recurring:
# Unfold recurring events according to their rrule
rule = parse_rrule(component, cal_tz)
dur = e.end - e.start
found.extend(e.copy_to(dt) for dt in rule.between(start - dur, end, inc=True))
elif e.end >= start and e.start <= end:
found.append(e)
return found |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def 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 event :return: new event """ |
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 = self.end - self.start
ne.end = (new_start + duration)
ne.all_day = self.all_day
ne.recurring = self.recurring
ne.location = self.location
ne.uid = uid
return ne |
<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)
return data['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 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(self.config['global']['killer_file'], 'a', encoding='utf-8') as killer_file:
killer_file.write('Time: {0}\nInternet is out.\n'
'Failure: {1}\n\n'.format(formatted_time, warning)) |
<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(config_path=args.config, debug=args.debug)
else:
# TODO: WSL
# TODO: OSX
# TODO: BSD
raise NotImplementedError("Your platform is not currently supported."
"If you would like support to be added, or "
"if your platform is supported and this is "
"a bug, please open an issue on GitHub!") |
<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 to retrieve :return: the device names :rtype: Iterator[str] """ |
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, whether the battery is currently charging, how much battery life remains, and if battery saver is on or off. :raises OSError: if the call to GetSystemPowerStatus fails :return: the power status :rtype: SystemPowerStatus """ |
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.WinError()
else:
return status |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def 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',
'status': 'resolved',
}
}
if resolution is not None:
data['resolution'] = resolution
result = self.request('PUT',
endpoint=endpoint,
add_headers=add_headers,
data=data,)
return result |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def 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([isinstance(i, six.string_types) for i in user_ids]):
raise InvalidArguments(user_ids)
assignees = [
{
'assignee': {
'id': user_id,
'type': 'user_reference',
}
}
for user_id in user_ids
]
add_headers = {'from': from_email, }
data = {
'incident': {
'type': 'incident',
'assignments': assignees,
}
}
result = self.request('PUT',
endpoint=endpoint,
add_headers=add_headers,
data=data,)
return result |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def 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(
endpoint=endpoint,
api_key=self.api_key,
fetch_all=fetch_all,
**query_params
)
return result |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def 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,
api_key=self.api_key,
add_headers=add_headers,
data={'content': 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 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,
api_key=self.api_key,
add_headers=add_headers,
data_key='duration',
data=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 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
for entity in source_incidents]
incident_references = [{'type': 'incident_reference', 'id': id_}
for id_ in incident_ids]
return self.__class__.create(
endpoint=endpoint,
api_key=self.api_key,
add_headers=add_headers,
data_key='source_incidents',
data=incident_references,
method='PUT',
) |
<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 default to now(), and since will default to 30 days prior to until. As per PD spec, date range must not exceed 1 month. """ |
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 = until - since
if dt > datetime.timedelta(seconds=seconds):
raise InvalidArguments(until, since)
kwargs['since'] = since.isoformat()
kwargs['until'] = until.isoformat()
return getattr(Entity, 'find').__func__(cls, *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 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__(cls, id, endpoint=endpoint,
*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 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_headers = {'from': from_email, }
data = {
'alert': {
'id': self['id'],
'type': 'alert',
'status': 'resolved',
}
}
result = self.request('PUT',
endpoint=endpoint,
add_headers=add_headers,
data=data,)
return result |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def 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}/alerts/{1}'
endpoint = endpoint_format.format(parent_incident_id, self['id'])
if isinstance(new_parent_incident, Entity):
new_parent_incident_id = new_parent_incident['id']
else:
new_parent_incident_id = new_parent_incident
add_headers = {'from': from_email, }
data = {
'alert': {
'id': self['id'],
'type': 'alert',
'incident': {
'type': 'incident',
'id': new_parent_incident_id,
}
}
}
result = self.request('PUT',
endpoint=endpoint,
add_headers=add_headers,
data=data,)
return result |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def 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__(cls, id, endpoint=endpoint,
*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, service=None, endpoint=None, data=None, *args, **kwargs):
""" Create an integration within the scope of an service. Make sure that they should reasonably be able to query with an service or endpoint that knows about an service. """ |
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 endpoint should contain the service path too
return getattr(Entity, 'create').__func__(cls, endpoint=endpoint,
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 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 raw data from queried datasets. XXX: this is el cheapo (no bastante bien) """ |
# 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
if endpoint.endswith('ies'):
endpoint = endpoint[:-3] + 'y'
elif endpoint.endswith('s'):
endpoint = endpoint[:-1]
return 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 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 unless otherwise specified will translate class name to endpoint name. """ |
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 async page fetches if API allows it via exposing total value. Returns a list of `cls` instances. """ |
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 = cls._fetch_page(
api_key=api_key, endpoint=endpoint, **qp
)
output += entities
more = options.get('more')
limit = options.get('limit')
offset = options.get('offset')
total = options.get('total')
if more is None:
if total is None or offset is None:
break
more = (limit + offset) < total
if not more or (maximum is not None and len(output) >= maximum):
break
qp['limit'] = limit
qp['offset'] = offset + limit
return output |
<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 provide `page_index` an integer (0-based) index for the page to return. Calculated based on `limit` and `offset`. Optionally provide `offset` which will override `page_index` if both are passed, will be used to calculate the integer offset of items. Optionally provide `limit` integer describing how many items pages ought to have. Returns a tuple containing a list of `cls` instances and response options. """ |
# 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 work
inst = cls(api_key=api_key)
kwargs['offset'] = int(page_index * limit)
maximum = kwargs.pop('maximum', None)
# if maximum is valid, make the limit <= maximum
kwargs['limit'] = min(limit, maximum) if maximum is not None else limit
ep = parse_key = cls.sanitize_ep(cls.get_endpoint(), plural=True)
# if an override to the endpoint is provided use that instead
# this is useful for nested value searches ie. for
# `incident_log_entries` but instead of /log_entries querying with
# context of /incident/INCIDENTID/log_entries.
# XXX: could be cleaner
if endpoint is not None:
ep = endpoint
response = inst.request('GET', endpoint=ep, query_params=kwargs)
# XXX: this is a little gross right now. Seems like the best way
# to do the parsing out of something and then return everything else
datas = cls._parse(response, key=parse_key)
response.pop(parse_key, None)
entities = [cls(api_key=api_key, _data=d) for d in datas]
# return a tuple
return entities, response |
<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 that must be queried. """ |
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,
add_headers=add_headers,
query_params=kwargs),
key=parse_key)
inst._set(data)
return 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 translate_query_params(cls, **kwargs):
""" Translate an arbirtary keyword argument to the expected query. TODO: refactor this into something less insane. XXX: Clean this up. It's *too* flexible. In the v2 API, many endpoints expect a particular query argument to be in the form of `query=xxx` where `xxx` would be the name of perhaps the name, ID or otherwise. This function ought to take a more aptly named parameter specified in `TRANSLATE_QUERY_PARAM`, and substitute it into the `query` keyword argument. The purpose is so that some models (optionally) have nicer named keyword arguments than `query` for easier to read python. If a query argument is given then the output should be that value. If a substitute value is given as a keyword specified in `TRANSLATE_QUERY_PARAM`(and query is not) then the `query` argument will be that keyword argument. Eg. No query param TRANSLATE_QUERY_PARAM = ('name',) kwargs = {'name': 'PagerDuty',} output = {'query': 'PagerDuty'} or, query param explicitly TRANSLATE_QUERY_PARAM = ('name',) kwargs = {'name': 'PagerDuty', 'query': 'XXXXPlopperDuty'} output = {'query': 'XXXXPlopperDuty'} or, TRANSLATE_QUERY_PARAM is None TRANSLATE_QUERY_PARAM = None kwargs = {'name': 'PagerDuty', 'query': 'XXXXPlopperDuty'} output = {'output': 'XXXXPlopperDuty', 'name': 'PagerDuty'} """ |
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.append(popped)
# if query is provided, just use it
if query is not None:
output['query'] = query
return output
# if query is not provided, use the first parameter we removed from
# the kwargs
try:
output['query'] = next(iter(values))
except StopIteration:
pass
return output |
<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 global api key will be used. If fetch_all is True, page through all the data and find every record that exists. If add_headers is provided (as a dict) use it to add headers to the HTTP request, eg. {'host': 'some.hidden.host'} Capitalizing header keys does not matter. Remaining keyword arguments will be passed as `query_params` to the instant method `request` (ClientMixin). """ |
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 the endpoint
if endpoint is None:
endpoint = cls.get_endpoint()
if fetch_all:
result = cls._fetch_all(api_key=api_key, endpoint=endpoint,
maximum=maximum,
**query_params)
else:
result = cls._fetch_page(api_key=api_key, endpoint=endpoint,
maximum=maximum,
**query_params)
# for each result run it through an exlcusion filter
collection = [r for r in result
if not cls._find_exclude_filter(exclude, r)]
return collection |
<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 of the Entity model by calling to the API endpoint. This ensures that server knows about the creation before returning the class instance. NOTE: The server must return a response with the schema containing the entire entity value. A True or False response is no bueno. """ |
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:
endpoint = cls.get_endpoint()
inst._set(cls._parse(inst.request(method,
endpoint=endpoint,
data=body,
query_params=kwargs,
add_headers=add_headers,
),
key=response_data_key))
return 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 _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 variable to extract data from a data blob. """ |
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}'
.format(parse))
return data |
<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,
)
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 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=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 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)
return result |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def create_integration(self, integration_info, **kwargs):
""" Create an integration for this service. See: https://v2.developer.pagerduty.com/v2/page/api-reference#!/ Services/post_services_id_integrations """ |
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}/integrations'.format(
self.endpoint,
self['id'],
)
return self.integrationFactory.create(
endpoint=endpoint,
api_key=self.api_key,
data=integration_info,
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 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'].append(result['notification_rule'])
return result |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def delete_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: * a Python object to be converted, * the type to convert to and return the instance of the class. The type may seem redundant, but is sometimes needed (for example, when dealing with generic classes). """ |
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. Bare optionals end here too (optionals with arguments are unions.) We treat bare optionals as Any. """ |
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()}
elif val_type is Any:
key_conv = self._structure_func.dispatch(key_type)
return {key_conv(k, key_type): v for k, v in obj.items()}
else:
key_conv = self._structure_func.dispatch(key_type)
val_conv = self._structure_func.dispatch(val_type)
return {
key_conv(k, key_type): 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 is None:
return None
if len(union_params) == 2:
# This is just a NoneType and something else.
other = (
union_params[0]
if union_params[1] is NoneType # type: ignore
else union_params[1]
)
# We can't actually have a Union of a Union, so this is safe.
return self._structure_func.dispatch(other)(obj, other)
# Check the union registry first.
handler = self._union_registry.get(union)
if handler is not None:
return handler(obj, union)
# Getting here means either this is not an optional, or it's an
# optional with more than one parameter.
# Let's support only unions of attr classes for now.
cl = self._dis_func_cache(union)(obj)
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 _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 homogenous tuple, Tuple[int, ...]
tup_type = tup_params[0]
conv = self._structure_func.dispatch(tup_type)
return tuple(conv(e, tup_type) for e in obj)
else:
# We're dealing with a heterogenous tuple.
return tuple(
self._structure_func.dispatch(t)(e, t)
for t, e in zip(tup_params, 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 _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
)
if not all(hasattr(e, "__attrs_attrs__") for e in union_types):
raise ValueError(
"Only unions of attr classes supported "
"currently. Register a loads hook manually."
)
return create_uniq_field_dis_func(*union_types) |
<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 fields.""" |
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: Deal with a single class having no required attrs.
# For each class, attempt to generate a single unique required field.
uniq_attrs_dict = OrderedDict() # type: Dict[str, Type]
cls_and_attrs.sort(key=lambda c_a: -len(c_a[1]))
fallback = None # If none match, try this.
for i, (cl, cl_reqs) in enumerate(cls_and_attrs):
other_classes = cls_and_attrs[i + 1 :]
if other_classes:
other_reqs = reduce(or_, (c_a[1] for c_a in other_classes))
uniq = cl_reqs - other_reqs
if not uniq:
m = "{} has no usable unique attributes.".format(cl)
raise ValueError(m)
uniq_attrs_dict[next(iter(uniq))] = cl
else:
fallback = cl
def dis_func(data):
# type: (Mapping) -> Optional[Type]
if not isinstance(data, Mapping):
raise ValueError("Only input mappings are supported.")
for k, v in uniq_attrs_dict.items():
if k in data:
return v
return fallback
return dis_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 _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
except Exception:
pass
raise KeyError("unable to find handler for {0}".format(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 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():
endpoint = current_app.class_references[table]
links.append({'rel': 'related', 'uri': '/{}/{}'.format(
endpoint.__name__, column_value)})
links.append({'rel': 'self', 'uri': self.resource_uri()})
return links |
<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 recurse subobjects :rtype: dict """ |
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 foreign_key in self.__table__.foreign_keys:
column_name = foreign_key.column.name
column_value = getattr(self, column_name, None)
if column_value:
table = foreign_key.column.table.name
with app.app_context():
endpoint = current_app.class_references[table]
session = db.session()
resource = session.query(endpoint).get(column_value)
if depth > 0:
result_dict.update({
'rel': endpoint.__name__,
endpoint.__name__.lower(): resource.as_dict(depth - 1)
})
else:
result_dict[
endpoint.__name__.lower() + '_url'] = '/{}/{}'.format(
endpoint.__name__, column_value)
result_dict['self'] = self.resource_uri()
return result_dict |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def 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_types & JSON_CONTENT_TYPES:
return JSON
else:
# HTTP 406 Not Acceptable
raise InvalidAPIUsage(406) |
<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 support the content
# type in the request's 'Accept' header, which is a more important
# error, so return that instead of what was originally raised.
response = jsonify(error.to_dict())
response.status_code = 415
return response |
<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.Model` resource: resource for attribute :param string name: name of the attribute :param string value: string value of the attribute :rtype: :class:`flask.Response` """ |
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:`sandman.model.Model` endpoint :rtype: :class:`flask.Response` """ |
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_EXCEPTION_MESSAGE.format(
exception))
return no_content_response() |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.