text_prompt
stringlengths 100
17.7k
⌀ | code_prompt
stringlengths 7
9.86k
⌀ |
---|---|
<SYSTEM_TASK:>
Expand descendants from list of branches
<END_TASK>
<USER_TASK:>
Description:
def expandDescendants(self, branches):
"""
Expand descendants from list of branches
:param list branches: list of immediate children as TreeOfContents objs
:return: list of all descendants
""" |
return sum([b.descendants() for b in branches], []) + \
[b.source for b in branches] |
<SYSTEM_TASK:>
Parse top level of markdown
<END_TASK>
<USER_TASK:>
Description:
def parseBranches(self, descendants):
"""
Parse top level of markdown
:param list elements: list of source objects
:return: list of filtered TreeOfContents objects
""" |
parsed, parent, cond = [], False, lambda b: (b.string or '').strip()
for branch in filter(cond, descendants):
if self.getHeadingLevel(branch) == self.depth:
parsed.append({'root':branch.string, 'source':branch})
parent = True
elif not parent:
parsed.append({'root':branch.string, 'source':branch})
else:
parsed[-1].setdefault('descendants', []).append(branch)
return [TOC(depth=self.depth+1, **kwargs) for kwargs in parsed] |
<SYSTEM_TASK:>
Create an attachment from data.
<END_TASK>
<USER_TASK:>
Description:
def from_data(cls, type, **data):
"""Create an attachment from data.
:param str type: attachment type
:param kwargs data: additional attachment data
:return: an attachment subclass object
:rtype: `~groupy.api.attachments.Attachment`
""" |
try:
return cls._types[type](**data)
except KeyError:
return cls(type=type, **data)
except TypeError as e:
error = 'could not create {!r} attachment'.format(type)
raise TypeError('{}: {}'.format(error, e.args[0])) |
<SYSTEM_TASK:>
Create a new image attachment from an image file.
<END_TASK>
<USER_TASK:>
Description:
def from_file(self, fp):
"""Create a new image attachment from an image file.
:param file fp: a file object containing binary image data
:return: an image attachment
:rtype: :class:`~groupy.api.attachments.Image`
""" |
image_urls = self.upload(fp)
return Image(image_urls['url'], source_url=image_urls['picture_url']) |
<SYSTEM_TASK:>
Upload image data to the image service.
<END_TASK>
<USER_TASK:>
Description:
def upload(self, fp):
"""Upload image data to the image service.
Call this, rather than :func:`from_file`, you don't want to
create an attachment of the image.
:param file fp: a file object containing binary image data
:return: the URLs for the image uploaded
:rtype: dict
""" |
url = utils.urljoin(self.url, 'pictures')
response = self.session.post(url, data=fp.read())
image_urls = response.data
return image_urls |
<SYSTEM_TASK:>
Download the binary data of an image attachment.
<END_TASK>
<USER_TASK:>
Description:
def download(self, image, url_field='url', suffix=None):
"""Download the binary data of an image attachment.
:param image: an image attachment
:type image: :class:`~groupy.api.attachments.Image`
:param str url_field: the field of the image with the right URL
:param str suffix: an optional URL suffix
:return: binary image data
:rtype: bytes
""" |
url = getattr(image, url_field)
if suffix is not None:
url = '.'.join(url, suffix)
response = self.session.get(url)
return response.content |
<SYSTEM_TASK:>
Downlaod the binary data of an image attachment at preview size.
<END_TASK>
<USER_TASK:>
Description:
def download_preview(self, image, url_field='url'):
"""Downlaod the binary data of an image attachment at preview size.
:param str url_field: the field of the image with the right URL
:return: binary image data
:rtype: bytes
""" |
return self.download(image, url_field=url_field, suffix='preview') |
<SYSTEM_TASK:>
Downlaod the binary data of an image attachment at large size.
<END_TASK>
<USER_TASK:>
Description:
def download_large(self, image, url_field='url'):
"""Downlaod the binary data of an image attachment at large size.
:param str url_field: the field of the image with the right URL
:return: binary image data
:rtype: bytes
""" |
return self.download(image, url_field=url_field, suffix='large') |
<SYSTEM_TASK:>
Downlaod the binary data of an image attachment at avatar size.
<END_TASK>
<USER_TASK:>
Description:
def download_avatar(self, image, url_field='url'):
"""Downlaod the binary data of an image attachment at avatar size.
:param str url_field: the field of the image with the right URL
:return: binary image data
:rtype: bytes
""" |
return self.download(image, url_field=url_field, suffix='avatar') |
<SYSTEM_TASK:>
Iterate through results from all pages.
<END_TASK>
<USER_TASK:>
Description:
def autopage(self):
"""Iterate through results from all pages.
:return: all results
:rtype: generator
""" |
while self.items:
yield from self.items
self.items = self.fetch_next() |
<SYSTEM_TASK:>
Detect which listing mode of the given params.
<END_TASK>
<USER_TASK:>
Description:
def detect_mode(cls, **params):
"""Detect which listing mode of the given params.
:params kwargs params: the params
:return: one of the available modes
:rtype: str
:raises ValueError: if multiple modes are detected
""" |
modes = []
for mode in cls.modes:
if params.get(mode) is not None:
modes.append(mode)
if len(modes) > 1:
error_message = 'ambiguous mode, must be one of {}'
modes_csv = ', '.join(list(cls.modes))
raise ValueError(error_message.format(modes_csv))
return modes[0] if modes else cls.default_mode |
<SYSTEM_TASK:>
Set the params so that the next page is fetched.
<END_TASK>
<USER_TASK:>
Description:
def set_next_page_params(self):
"""Set the params so that the next page is fetched.""" |
if self.items:
index = self.get_last_item_index()
self.params[self.mode] = self.get_next_page_param(self.items[index]) |
<SYSTEM_TASK:>
List the users you have blocked.
<END_TASK>
<USER_TASK:>
Description:
def list(self):
"""List the users you have blocked.
:return: a list of :class:`~groupy.api.blocks.Block`'s
:rtype: :class:`list`
""" |
params = {'user': self.user_id}
response = self.session.get(self.url, params=params)
blocks = response.data['blocks']
return [Block(self, **block) for block in blocks] |
<SYSTEM_TASK:>
Check if there is a block between you and the given user.
<END_TASK>
<USER_TASK:>
Description:
def between(self, other_user_id):
"""Check if there is a block between you and the given user.
:return: ``True`` if the given user has been blocked
:rtype: bool
""" |
params = {'user': self.user_id, 'otherUser': other_user_id}
response = self.session.get(self.url, params=params)
return response.data['between'] |
<SYSTEM_TASK:>
Block the given user.
<END_TASK>
<USER_TASK:>
Description:
def block(self, other_user_id):
"""Block the given user.
:param str other_user_id: the ID of the user to block
:return: the block created
:rtype: :class:`~groupy.api.blocks.Block`
""" |
params = {'user': self.user_id, 'otherUser': other_user_id}
response = self.session.post(self.url, params=params)
block = response.data['block']
return Block(self, **block) |
<SYSTEM_TASK:>
Unblock the given user.
<END_TASK>
<USER_TASK:>
Description:
def unblock(self, other_user_id):
"""Unblock the given user.
:param str other_user_id: the ID of the user to unblock
:return: ``True`` if successful
:rtype: bool
""" |
params = {'user': self.user_id, 'otherUser': other_user_id}
response = self.session.delete(self.url, params=params)
return response.ok |
<SYSTEM_TASK:>
List a page of chats.
<END_TASK>
<USER_TASK:>
Description:
def list(self, page=1, per_page=10):
"""List a page of chats.
:param int page: which page
:param int per_page: how many chats per page
:return: chats with other users
:rtype: :class:`~groupy.pagers.ChatList`
""" |
return pagers.ChatList(self, self._raw_list, per_page=per_page,
page=page) |
<SYSTEM_TASK:>
Return a page of group messages.
<END_TASK>
<USER_TASK:>
Description:
def list(self, before_id=None, since_id=None, after_id=None, limit=20):
"""Return a page of group messages.
The messages come in reversed order (newest first). Note you can only
provide _one_ of ``before_id``, ``since_id``, or ``after_id``.
:param str before_id: message ID for paging backwards
:param str after_id: message ID for paging forwards
:param str since_id: message ID for most recent messages since
:param int limit: maximum number of messages per page
:return: group messages
:rtype: :class:`~groupy.pagers.MessageList`
""" |
return pagers.MessageList(self, self._raw_list, before_id=before_id,
after_id=after_id, since_id=since_id,
limit=limit) |
<SYSTEM_TASK:>
Return a page of group messages created since a message.
<END_TASK>
<USER_TASK:>
Description:
def list_since(self, message_id, limit=None):
"""Return a page of group messages created since a message.
This is used to fetch the most recent messages after another. There
may exist messages between the one given and the ones returned. Use
:func:`list_after` to retrieve newer messages without skipping any.
:param str message_id: the ID of a message
:param int limit: maximum number of messages per page
:return: group messages
:rtype: :class:`~groupy.pagers.MessageList`
""" |
return self.list(since_id=message_id, limit=limit) |
<SYSTEM_TASK:>
Return a page of group messages created after a message.
<END_TASK>
<USER_TASK:>
Description:
def list_after(self, message_id, limit=None):
"""Return a page of group messages created after a message.
This is used to page forwards through messages.
:param str message_id: the ID of a message
:param int limit: maximum number of messages per page
:return: group messages
:rtype: :class:`~groupy.pagers.MessageList`
""" |
return self.list(after_id=message_id, limit=limit) |
<SYSTEM_TASK:>
Return all group messages created before a message.
<END_TASK>
<USER_TASK:>
Description:
def list_all_before(self, message_id, limit=None):
"""Return all group messages created before a message.
:param str message_id: the ID of a message
:param int limit: maximum number of messages per page
:return: group messages
:rtype: generator
""" |
return self.list_before(message_id, limit=limit).autopage() |
<SYSTEM_TASK:>
Return all group messages created after a message.
<END_TASK>
<USER_TASK:>
Description:
def list_all_after(self, message_id, limit=None):
"""Return all group messages created after a message.
:param str message_id: the ID of a message
:param int limit: maximum number of messages per page
:return: group messages
:rtype: generator
""" |
return self.list_after(message_id, limit=limit).autopage() |
<SYSTEM_TASK:>
Create a new message in the group.
<END_TASK>
<USER_TASK:>
Description:
def create(self, text=None, attachments=None, source_guid=None):
"""Create a new message in the group.
:param str text: the text of the message
:param attachments: a list of attachments
:type attachments: :class:`list`
:param str source_guid: a unique identifier for the message
:return: the created message
:rtype: :class:`~groupy.api.messages.Message`
""" |
message = {
'source_guid': source_guid or str(time.time()),
}
if text is not None:
message['text'] = text
if attachments is not None:
message['attachments'] = [a.to_json() for a in attachments]
payload = {'message': message}
response = self.session.post(self.url, json=payload)
message = response.data['message']
return Message(self, **message) |
<SYSTEM_TASK:>
Return a page of direct messages.
<END_TASK>
<USER_TASK:>
Description:
def list(self, before_id=None, since_id=None, **kwargs):
"""Return a page of direct messages.
The messages come in reversed order (newest first). Note you can only
provide _one_ of ``before_id``, ``since_id``.
:param str before_id: message ID for paging backwards
:param str since_id: message ID for most recent messages since
:return: direct messages
:rtype: :class:`~groupy.pagers.MessageList`
""" |
return pagers.MessageList(self, self._raw_list, before_id=before_id,
since_id=since_id, **kwargs) |
<SYSTEM_TASK:>
Return all direct messages.
<END_TASK>
<USER_TASK:>
Description:
def list_all(self, before_id=None, since_id=None, **kwargs):
"""Return all direct messages.
The messages come in reversed order (newest first). Note you can only
provide _one_ of ``before_id``, ``since_id``.
:param str before_id: message ID for paging backwards
:param str since_id: message ID for most recent messages since
:return: direct messages
:rtype: generator
""" |
return self.list(before_id=before_id, since_id=since_id, **kwargs).autopage() |
<SYSTEM_TASK:>
Add a user to the group.
<END_TASK>
<USER_TASK:>
Description:
def add(self, nickname, email=None, phone_number=None, user_id=None):
"""Add a user to the group.
You must provide either the email, phone number, or user_id that
uniquely identifies a user.
:param str nickname: new name for the user in the group
:param str email: email address of the user
:param str phone_number: phone number of the user
:param str user_id: user_id of the user
:return: a membership request
:rtype: :class:`MembershipRequest`
""" |
member = {
'nickname': nickname,
'email': email,
'phone_number': phone_number,
'user_id': user_id,
}
return self.add_multiple(member) |
<SYSTEM_TASK:>
Add multiple users to the group at once.
<END_TASK>
<USER_TASK:>
Description:
def add_multiple(self, *users):
"""Add multiple users to the group at once.
Each given user must be a dictionary containing a nickname and either
an email, phone number, or user_id.
:param args users: the users to add
:return: a membership request
:rtype: :class:`MembershipRequest`
""" |
guid = uuid.uuid4()
for i, user_ in enumerate(users):
user_['guid'] = '{}-{}'.format(guid, i)
payload = {'members': users}
url = utils.urljoin(self.url, 'add')
response = self.session.post(url, json=payload)
return MembershipRequest(self, *users, group_id=self.group_id,
**response.data) |
<SYSTEM_TASK:>
Check for results of a membership request.
<END_TASK>
<USER_TASK:>
Description:
def check(self, results_id):
"""Check for results of a membership request.
:param str results_id: the ID of a membership request
:return: successfully created memberships
:rtype: :class:`list`
:raises groupy.exceptions.ResultsNotReady: if the results are not ready
:raises groupy.exceptions.ResultsExpired: if the results have expired
""" |
path = 'results/{}'.format(results_id)
url = utils.urljoin(self.url, path)
response = self.session.get(url)
if response.status_code == 503:
raise exceptions.ResultsNotReady(response)
if response.status_code == 404:
raise exceptions.ResultsExpired(response)
return response.data['members'] |
<SYSTEM_TASK:>
Remove a member from the group.
<END_TASK>
<USER_TASK:>
Description:
def remove(self, membership_id):
"""Remove a member from the group.
:param str membership_id: the ID of a member in this group
:return: ``True`` if the member was successfully removed
:rtype: bool
""" |
path = '{}/remove'.format(membership_id)
url = utils.urljoin(self.url, path)
payload = {'membership_id': membership_id}
response = self.session.post(url, json=payload)
return response.ok |
<SYSTEM_TASK:>
Post a direct message to the user.
<END_TASK>
<USER_TASK:>
Description:
def post(self, text=None, attachments=None, source_guid=None):
"""Post a direct message to the user.
:param str text: the message content
:param attachments: message attachments
:param str source_guid: a client-side unique ID for the message
:return: the message sent
:rtype: :class:`~groupy.api.messages.DirectMessage`
""" |
return self.messages.create(text=text, attachments=attachments,
source_guid=source_guid) |
<SYSTEM_TASK:>
Add the member to another group.
<END_TASK>
<USER_TASK:>
Description:
def add_to_group(self, group_id, nickname=None):
"""Add the member to another group.
If a nickname is not provided the member's current nickname is used.
:param str group_id: the group_id of a group
:param str nickname: a new nickname
:return: a membership request
:rtype: :class:`MembershipRequest`
""" |
if nickname is None:
nickname = self.nickname
memberships = Memberships(self.manager.session, group_id=group_id)
return memberships.add(nickname, user_id=self.user_id) |
<SYSTEM_TASK:>
Check for and fetch the results if ready.
<END_TASK>
<USER_TASK:>
Description:
def check_if_ready(self):
"""Check for and fetch the results if ready.""" |
try:
results = self.manager.check(self.results_id)
except exceptions.ResultsNotReady as e:
self._is_ready = False
self._not_ready_exception = e
except exceptions.ResultsExpired as e:
self._is_ready = True
self._expired_exception = e
else:
failures = self.get_failed_requests(results)
members = self.get_new_members(results)
self.results = self.__class__.Results(list(members), list(failures))
self._is_ready = True
self._not_ready_exception = None |
<SYSTEM_TASK:>
Return the requests that failed.
<END_TASK>
<USER_TASK:>
Description:
def get_failed_requests(self, results):
"""Return the requests that failed.
:param results: the results of a membership request check
:type results: :class:`list`
:return: the failed requests
:rtype: generator
""" |
data = {member['guid']: member for member in results}
for request in self.requests:
if request['guid'] not in data:
yield request |
<SYSTEM_TASK:>
Return the newly added members.
<END_TASK>
<USER_TASK:>
Description:
def get_new_members(self, results):
"""Return the newly added members.
:param results: the results of a membership request check
:type results: :class:`list`
:return: the successful requests, as :class:`~groupy.api.memberships.Members`
:rtype: generator
""" |
for member in results:
guid = member.pop('guid')
yield Member(self.manager, self.group_id, **member)
member['guid'] = guid |
<SYSTEM_TASK:>
Return ``True`` if the results are ready.
<END_TASK>
<USER_TASK:>
Description:
def is_ready(self, check=True):
"""Return ``True`` if the results are ready.
If you pass ``check=False``, no attempt is made to check again for
results.
:param bool check: whether to query for the results
:return: ``True`` if the results are ready
:rtype: bool
""" |
if not self._is_ready and check:
self.check_if_ready()
return self._is_ready |
<SYSTEM_TASK:>
Return the results when they become ready.
<END_TASK>
<USER_TASK:>
Description:
def poll(self, timeout=30, interval=2):
"""Return the results when they become ready.
:param int timeout: the maximum time to wait for the results
:param float interval: the number of seconds between checks
:return: the membership request result
:rtype: :class:`~groupy.api.memberships.MembershipResult.Results`
""" |
time.sleep(interval)
start = time.time()
while time.time() - start < timeout and not self.is_ready():
time.sleep(interval)
return self.get() |
<SYSTEM_TASK:>
Return the results now.
<END_TASK>
<USER_TASK:>
Description:
def get(self):
"""Return the results now.
:return: the membership request results
:rtype: :class:`~groupy.api.memberships.MembershipResult.Results`
:raises groupy.exceptions.ResultsNotReady: if the results are not ready
:raises groupy.exceptions.ResultsExpired: if the results have expired
""" |
if self._expired_exception:
raise self._expired_exception
if self._not_ready_exception:
raise self._not_ready_exception
return self.results |
<SYSTEM_TASK:>
List groups by page.
<END_TASK>
<USER_TASK:>
Description:
def list(self, page=1, per_page=10, omit=None):
"""List groups by page.
The API allows certain fields to be excluded from the results so that
very large groups can be fetched without exceeding the maximum
response size. At the time of this writing, only 'memberships' is
supported.
:param int page: page number
:param int per_page: number of groups per page
:param int omit: a comma-separated list of fields to exclude
:return: a list of groups
:rtype: :class:`~groupy.pagers.GroupList`
""" |
return pagers.GroupList(self, self._raw_list, page=page,
per_page=per_page, omit=omit) |
<SYSTEM_TASK:>
List all former groups.
<END_TASK>
<USER_TASK:>
Description:
def list_former(self):
"""List all former groups.
:return: a list of groups
:rtype: :class:`list`
""" |
url = utils.urljoin(self.url, 'former')
response = self.session.get(url)
return [Group(self, **group) for group in response.data] |
<SYSTEM_TASK:>
Get a single group by ID.
<END_TASK>
<USER_TASK:>
Description:
def get(self, id):
"""Get a single group by ID.
:param str id: a group ID
:return: a group
:rtype: :class:`~groupy.api.groups.Group`
""" |
url = utils.urljoin(self.url, id)
response = self.session.get(url)
return Group(self, **response.data) |
<SYSTEM_TASK:>
Update the details of a group.
<END_TASK>
<USER_TASK:>
Description:
def update(self, id, name=None, description=None, image_url=None,
office_mode=None, share=None, **kwargs):
"""Update the details of a group.
.. note::
There are significant bugs in this endpoint!
1. not providing ``name`` produces 400: "Topic can't be blank"
2. not providing ``office_mode`` produces 500: "sql: Scan error on
column index 14: sql/driver: couldn't convert <nil> (<nil>) into
type bool"
Note that these issues are "handled" automatically when calling
update on a :class:`~groupy.api.groups.Group` object.
:param str id: group ID
:param str name: group name (140 characters maximum)
:param str description: short description (255 characters maximum)
:param str image_url: GroupMe image service URL
:param bool office_mode: (undocumented)
:param bool share: whether to generate a share URL
:return: an updated group
:rtype: :class:`~groupy.api.groups.Group`
""" |
path = '{}/update'.format(id)
url = utils.urljoin(self.url, path)
payload = {
'name': name,
'description': description,
'image_url': image_url,
'office_mode': office_mode,
'share': share,
}
payload.update(kwargs)
response = self.session.post(url, json=payload)
return Group(self, **response.data) |
<SYSTEM_TASK:>
Join a group using a share token.
<END_TASK>
<USER_TASK:>
Description:
def join(self, group_id, share_token):
"""Join a group using a share token.
:param str group_id: the group_id of a group
:param str share_token: the share token
:return: the group
:rtype: :class:`~groupy.api.groups.Group`
""" |
path = '{}/join/{}'.format(group_id, share_token)
url = utils.urljoin(self.url, path)
response = self.session.post(url)
group = response.data['group']
return Group(self, **group) |
<SYSTEM_TASK:>
Rejoin a former group.
<END_TASK>
<USER_TASK:>
Description:
def rejoin(self, group_id):
"""Rejoin a former group.
:param str group_id: the group_id of a group
:return: the group
:rtype: :class:`~groupy.api.groups.Group`
""" |
url = utils.urljoin(self.url, 'join')
payload = {'group_id': group_id}
response = self.session.post(url, json=payload)
return Group(self, **response.data) |
<SYSTEM_TASK:>
Change the owner of a group.
<END_TASK>
<USER_TASK:>
Description:
def change_owners(self, group_id, owner_id):
"""Change the owner of a group.
.. note:: you must be the owner to change owners
:param str group_id: the group_id of a group
:param str owner_id: the ID of the new owner
:return: the result
:rtype: :class:`~groupy.api.groups.ChangeOwnersResult`
""" |
url = utils.urljoin(self.url, 'change_owners')
payload = {
'requests': [{
'group_id': group_id,
'owner_id': owner_id,
}],
}
response = self.session.post(url, json=payload)
result, = response.data['results'] # should be exactly one
return ChangeOwnersResult(**result) |
<SYSTEM_TASK:>
Update the details of the group.
<END_TASK>
<USER_TASK:>
Description:
def update(self, name=None, description=None, image_url=None,
office_mode=None, share=None, **kwargs):
"""Update the details of the group.
:param str name: group name (140 characters maximum)
:param str description: short description (255 characters maximum)
:param str image_url: GroupMe image service URL
:param bool office_mode: (undocumented)
:param bool share: whether to generate a share URL
:return: an updated group
:rtype: :class:`~groupy.api.groups.Group`
""" |
# note we default to the current values for name and office_mode as a
# work-around for issues with the group update endpoint
if name is None:
name = self.name
if office_mode is None:
office_mode = self.office_mode
return self.manager.update(id=self.id, name=name, description=description,
image_url=image_url, office_mode=office_mode,
share=share, **kwargs) |
<SYSTEM_TASK:>
Refresh the group from the server in place.
<END_TASK>
<USER_TASK:>
Description:
def refresh_from_server(self):
"""Refresh the group from the server in place.""" |
group = self.manager.get(id=self.id)
self.__init__(self.manager, **group.data) |
<SYSTEM_TASK:>
Get your membership.
<END_TASK>
<USER_TASK:>
Description:
def get_membership(self):
"""Get your membership.
Note that your membership may not exist. For example, you do not have
a membership in a former group. Also, the group returned by the API
when rejoining a former group does not contain your membership. You
must call :func:`refresh_from_server` to update the list of members.
:return: your membership in the group
:rtype: :class:`~groupy.api.memberships.Member`
:raises groupy.exceptions.MissingMembershipError: if your membership is
not in the group data
""" |
user_id = self._user.me['user_id']
for member in self.members:
if member.user_id == user_id:
return member
raise exceptions.MissingMembershipError(self.group_id, user_id) |
<SYSTEM_TASK:>
Create a filter from keyword arguments.
<END_TASK>
<USER_TASK:>
Description:
def make_filter(**tests):
"""Create a filter from keyword arguments.""" |
tests = [AttrTest(k, v) for k, v in tests.items()]
return Filter(tests) |
<SYSTEM_TASK:>
Find exactly one match in the list of objects.
<END_TASK>
<USER_TASK:>
Description:
def find(self, objects):
"""Find exactly one match in the list of objects.
:param objects: objects to filter
:type objects: :class:`list`
:return: the one matching object
:raises groupy.exceptions.NoMatchesError: if no objects match
:raises groupy.exceptions.MultipleMatchesError: if multiple objects match
""" |
matches = list(self.__call__(objects))
if not matches:
raise exceptions.NoMatchesError(objects, self.tests)
elif len(matches) > 1:
raise exceptions.MultipleMatchesError(objects, self.tests,
matches=matches)
return matches[0] |
<SYSTEM_TASK:>
Return a list of bots.
<END_TASK>
<USER_TASK:>
Description:
def list(self):
"""Return a list of bots.
:return: all of your bots
:rtype: :class:`list`
""" |
response = self.session.get(self.url)
return [Bot(self, **bot) for bot in response.data] |
<SYSTEM_TASK:>
Post a new message as a bot to its room.
<END_TASK>
<USER_TASK:>
Description:
def post(self, bot_id, text, attachments=None):
"""Post a new message as a bot to its room.
:param str bot_id: the ID of the bot
:param str text: the text of the message
:param attachments: a list of attachments
:type attachments: :class:`list`
:return: ``True`` if successful
:rtype: bool
""" |
url = utils.urljoin(self.url, 'post')
payload = dict(bot_id=bot_id, text=text)
if attachments:
payload['attachments'] = [a.to_json() for a in attachments]
response = self.session.post(url, json=payload)
return response.ok |
<SYSTEM_TASK:>
Destroy a bot.
<END_TASK>
<USER_TASK:>
Description:
def destroy(self, bot_id):
"""Destroy a bot.
:param str bot_id: the ID of the bot to destroy
:return: ``True`` if successful
:rtype: bool
""" |
url = utils.urljoin(self.url, 'destroy')
payload = {'bot_id': bot_id}
response = self.session.post(url, json=payload)
return response.ok |
<SYSTEM_TASK:>
Post a message as the bot.
<END_TASK>
<USER_TASK:>
Description:
def post(self, text, attachments=None):
"""Post a message as the bot.
:param str text: the text of the message
:param attachments: a list of attachments
:type attachments: :class:`list`
:return: ``True`` if successful
:rtype: bool
""" |
return self.manager.post(self.bot_id, text, attachments) |
<SYSTEM_TASK:>
Flatten a nested sequence. A sequence could be a nested list of lists
<END_TASK>
<USER_TASK:>
Description:
def flatten_until(is_leaf, xs):
"""
Flatten a nested sequence. A sequence could be a nested list of lists
or tuples or a combination of both
:param is_leaf: Predicate. Predicate to determine whether an item
in the iterable `xs` is a leaf node or not.
:param xs: Iterable. Nested lists or tuples
:return: list.
""" |
def _flatten_until(items):
if isinstance(Iterable, items) and not is_leaf(items):
for item in items:
for i in _flatten_until(item):
yield i
else:
yield items
return list(_flatten_until(xs)) |
<SYSTEM_TASK:>
Calls the function f by flipping the first two positional
<END_TASK>
<USER_TASK:>
Description:
def flip(f):
"""
Calls the function f by flipping the first two positional
arguments
""" |
def wrapped(*args, **kwargs):
return f(*flip_first_two(args), **kwargs)
f_spec = make_func_curry_spec(f)
return curry_by_spec(f_spec, wrapped) |
<SYSTEM_TASK:>
A persistent, stale-free memoization decorator.
<END_TASK>
<USER_TASK:>
Description:
def cachier(stale_after=None, next_time=False, pickle_reload=True,
mongetter=None):
"""A persistent, stale-free memoization decorator.
The positional and keyword arguments to the wrapped function must be
hashable (i.e. Python's immutable built-in objects, not mutable
containers). Also, notice that since objects which are instances of
user-defined classes are hashable but all compare unequal (their hash
value is their id), equal objects across different sessions will not yield
identical keys.
Arguments
---------
stale_after (optional) : datetime.timedelta
The time delta afterwhich a cached result is considered stale. Calls
made after the result goes stale will trigger a recalculation of the
result, but whether a stale or fresh result will be returned is
determined by the optional next_time argument.
next_time (optional) : bool
If set to True, a stale result will be returned when finding one, not
waiting for the calculation of the fresh result to return. Defaults to
False.
pickle_reload (optional) : bool
If set to True, in-memory cache will be reloaded on each cache read,
enabling different threads to share cache. Should be set to False for
faster reads in single-thread programs. Defaults to True.
mongetter (optional) : callable
A callable that takes no arguments and returns a pymongo.Collection
object with writing permissions. If unset a local pickle cache is used
instead.
""" |
# print('Inside the wrapper maker')
# print('mongetter={}'.format(mongetter))
# print('stale_after={}'.format(stale_after))
# print('next_time={}'.format(next_time))
if mongetter:
core = _MongoCore(mongetter, stale_after, next_time)
else:
core = _PickleCore( # pylint: disable=R0204
stale_after, next_time, pickle_reload)
def _cachier_decorator(func):
core.set_func(func)
@wraps(func)
def func_wrapper(*args, **kwds): # pylint: disable=C0111,R0911
# print('Inside general wrapper for {}.'.format(func.__name__))
ignore_cache = kwds.pop('ignore_cache', False)
overwrite_cache = kwds.pop('overwrite_cache', False)
verbose_cache = kwds.pop('verbose_cache', False)
_print = lambda x: None
if verbose_cache:
_print = print
if ignore_cache:
return func(*args, **kwds)
key, entry = core.get_entry(args, kwds)
if overwrite_cache:
return _calc_entry(core, key, func, args, kwds)
if entry is not None: # pylint: disable=R0101
_print('Entry found.')
if entry.get('value', None) is not None:
_print('Cached result found.')
if stale_after:
now = datetime.datetime.now()
if now - entry['time'] > stale_after:
_print('But it is stale... :(')
if entry['being_calculated']:
if next_time:
_print('Returning stale.')
return entry['value'] # return stale val
_print('Already calc. Waiting on change.')
try:
return core.wait_on_entry_calc(key)
except RecalculationNeeded:
return _calc_entry(core, key, func, args, kwds)
if next_time:
_print('Async calc and return stale')
try:
core.mark_entry_being_calculated(key)
_get_executor().submit(
_function_thread, core, key, func,
args, kwds)
finally:
core.mark_entry_not_calculated(key)
return entry['value']
_print('Calling decorated function and waiting')
return _calc_entry(core, key, func, args, kwds)
_print('And it is fresh!')
return entry['value']
if entry['being_calculated']:
_print('No value but being calculated. Waiting.')
try:
return core.wait_on_entry_calc(key)
except RecalculationNeeded:
return _calc_entry(core, key, func, args, kwds)
_print('No entry found. No current calc. Calling like a boss.')
return _calc_entry(core, key, func, args, kwds)
def clear_cache():
"""Clear the cache."""
core.clear_cache()
def clear_being_calculated():
"""Marks all entries in this cache as not being calculated."""
core.clear_being_calculated()
func_wrapper.clear_cache = clear_cache
func_wrapper.clear_being_calculated = clear_being_calculated
return func_wrapper
return _cachier_decorator |
<SYSTEM_TASK:>
Loads triangular mesh from vertex and face numpy arrays.
<END_TASK>
<USER_TASK:>
Description:
def load_arrays(self, v, f):
"""Loads triangular mesh from vertex and face numpy arrays.
Both vertex and face arrays should be 2D arrays with each
vertex containing XYZ data and each face containing three
points.
Parameters
----------
v : np.ndarray
n x 3 vertex array.
f : np.ndarray
n x 3 face array.
""" |
# Check inputs
if not isinstance(v, np.ndarray):
try:
v = np.asarray(v, np.float)
if v.ndim != 2 and v.shape[1] != 3:
raise Exception('Invalid vertex format. Shape ' +
'should be (npoints, 3)')
except BaseException:
raise Exception(
'Unable to convert vertex input to valid numpy array')
if not isinstance(f, np.ndarray):
try:
f = np.asarray(f, ctypes.c_int)
if f.ndim != 2 and f.shape[1] != 3:
raise Exception('Invalid face format. ' +
'Shape should be (nfaces, 3)')
except BaseException:
raise Exception('Unable to convert face input to valid' +
' numpy array')
self.v = v
self.f = f |
<SYSTEM_TASK:>
Plot the mesh.
<END_TASK>
<USER_TASK:>
Description:
def plot(self, show_holes=True):
"""
Plot the mesh.
Parameters
----------
show_holes : bool, optional
Shows boundaries. Default True
""" |
if show_holes:
edges = self.mesh.extract_edges(boundary_edges=True,
feature_edges=False,
manifold_edges=False)
plotter = vtki.Plotter()
plotter.add_mesh(self.mesh, label='mesh')
plotter.add_mesh(edges, 'r', label='edges')
plotter.plot()
else:
self.mesh.plot(show_edges=True) |
<SYSTEM_TASK:>
Performs mesh repair using MeshFix's default repair
<END_TASK>
<USER_TASK:>
Description:
def repair(self, verbose=False, joincomp=False,
remove_smallest_components=True):
"""Performs mesh repair using MeshFix's default repair
process.
Parameters
----------
verbose : bool, optional
Enables or disables debug printing. Disabled by default.
joincomp : bool, optional
Attempts to join nearby open components.
remove_smallest_components : bool, optional
Remove all but the largest isolated component from the
mesh before beginning the repair process. Default True
Notes
-----
Vertex and face arrays are updated inplace. Access them with:
meshfix.v
meshfix.f
""" |
assert self.f.shape[1] == 3, 'Face array must contain three columns'
assert self.f.ndim == 2, 'Face array must be 2D'
self.v, self.f = _meshfix.clean_from_arrays(self.v, self.f,
verbose, joincomp,
remove_smallest_components) |
<SYSTEM_TASK:>
Execute an arbitrary SQL query given by query, returning any
<END_TASK>
<USER_TASK:>
Description:
def execute(query, data=None):
"""
Execute an arbitrary SQL query given by query, returning any
results as a list of OrderedDicts. A list of values can be supplied as an,
additional argument, which will be substituted into question marks in the
query.
""" |
connection = _State.connection()
_State.new_transaction()
if data is None:
data = []
result = connection.execute(query, data)
_State.table = None
_State.metadata = None
try:
del _State.table_pending
except AttributeError:
pass
if not result.returns_rows:
return {u'data': [], u'keys': []}
return {u'data': result.fetchall(), u'keys': list(result.keys())} |
<SYSTEM_TASK:>
Specify the table to work on.
<END_TASK>
<USER_TASK:>
Description:
def _set_table(table_name):
"""
Specify the table to work on.
""" |
_State.connection()
_State.reflect_metadata()
_State.table = sqlalchemy.Table(table_name, _State.metadata,
extend_existing=True)
if list(_State.table.columns.keys()) == []:
_State.table_pending = True
else:
_State.table_pending = False |
<SYSTEM_TASK:>
Return the names of the tables currently in the database.
<END_TASK>
<USER_TASK:>
Description:
def show_tables():
"""
Return the names of the tables currently in the database.
""" |
_State.connection()
_State.reflect_metadata()
metadata = _State.metadata
response = select('name, sql from sqlite_master where type="table"')
return {row['name']: row['sql'] for row in response} |
<SYSTEM_TASK:>
Save a variable to the table specified by _State.vars_table_name. Key is
<END_TASK>
<USER_TASK:>
Description:
def save_var(name, value):
"""
Save a variable to the table specified by _State.vars_table_name. Key is
the name of the variable, and value is the value.
""" |
connection = _State.connection()
_State.reflect_metadata()
vars_table = sqlalchemy.Table(
_State.vars_table_name, _State.metadata,
sqlalchemy.Column('name', sqlalchemy.types.Text, primary_key=True),
sqlalchemy.Column('value_blob', sqlalchemy.types.LargeBinary),
sqlalchemy.Column('type', sqlalchemy.types.Text),
keep_existing=True
)
vars_table.create(bind=connection, checkfirst=True)
column_type = get_column_type(value)
if column_type == sqlalchemy.types.LargeBinary:
value_blob = value
else:
value_blob = unicode(value).encode('utf-8')
values = dict(name=name,
value_blob=value_blob,
# value_blob=Blob(value),
type=column_type.__visit_name__.lower())
vars_table.insert(prefixes=['OR REPLACE']).values(**values).execute() |
<SYSTEM_TASK:>
Returns the variable with the provided key from the
<END_TASK>
<USER_TASK:>
Description:
def get_var(name, default=None):
"""
Returns the variable with the provided key from the
table specified by _State.vars_table_name.
""" |
alchemytypes = {"text": lambda x: x.decode('utf-8'),
"big_integer": lambda x: int(x),
"date": lambda x: x.decode('utf-8'),
"datetime": lambda x: x.decode('utf-8'),
"float": lambda x: float(x),
"large_binary": lambda x: x,
"boolean": lambda x: x==b'True'}
connection = _State.connection()
_State.new_transaction()
if _State.vars_table_name not in list(_State.metadata.tables.keys()):
return None
table = sqlalchemy.Table(_State.vars_table_name, _State.metadata)
s = sqlalchemy.select([table.c.value_blob, table.c.type])
s = s.where(table.c.name == name)
result = connection.execute(s).fetchone()
if not result:
return None
return alchemytypes[result[1]](result[0])
# This is to do the variable type conversion through the SQL engine
execute = connection.execute
execute("CREATE TEMPORARY TABLE _sw_tmp ('value' {})".format(result.type))
execute("INSERT INTO _sw_tmp VALUES (:value)", value=result.value_blob)
var = execute('SELECT value FROM _sw_tmp').fetchone().value
execute("DROP TABLE _sw_tmp")
return var.decode('utf-8') |
<SYSTEM_TASK:>
Create a new index of the columns in column_names, where column_names is
<END_TASK>
<USER_TASK:>
Description:
def create_index(column_names, unique=False):
"""
Create a new index of the columns in column_names, where column_names is
a list of strings. If unique is True, it will be a
unique index.
""" |
connection = _State.connection()
_State.reflect_metadata()
table_name = _State.table.name
table = _State.table
index_name = re.sub(r'[^a-zA-Z0-9]', '', table_name) + '_'
index_name += '_'.join(re.sub(r'[^a-zA-Z0-9]', '', x)
for x in column_names)
if unique:
index_name += '_unique'
columns = []
for column_name in column_names:
columns.append(table.columns[column_name])
current_indices = [x.name for x in table.indexes]
index = sqlalchemy.schema.Index(index_name, *columns, unique=unique)
if index.name not in current_indices:
index.create(bind=_State.engine) |
<SYSTEM_TASK:>
Takes a row and checks to make sure it fits in the columns of the
<END_TASK>
<USER_TASK:>
Description:
def fit_row(connection, row, unique_keys):
"""
Takes a row and checks to make sure it fits in the columns of the
current table. If it does not fit, adds the required columns.
""" |
new_columns = []
for column_name, column_value in list(row.items()):
new_column = sqlalchemy.Column(column_name,
get_column_type(column_value))
if not column_name in list(_State.table.columns.keys()):
new_columns.append(new_column)
_State.table.append_column(new_column)
if _State.table_pending:
create_table(unique_keys)
return
for new_column in new_columns:
add_column(connection, new_column) |
<SYSTEM_TASK:>
Save the table currently waiting to be created.
<END_TASK>
<USER_TASK:>
Description:
def create_table(unique_keys):
"""
Save the table currently waiting to be created.
""" |
_State.new_transaction()
_State.table.create(bind=_State.engine, checkfirst=True)
if unique_keys != []:
create_index(unique_keys, unique=True)
_State.table_pending = False
_State.reflect_metadata() |
<SYSTEM_TASK:>
Add a column to the current table.
<END_TASK>
<USER_TASK:>
Description:
def add_column(connection, column):
"""
Add a column to the current table.
""" |
stmt = alembic.ddl.base.AddColumn(_State.table.name, column)
connection.execute(stmt)
_State.reflect_metadata() |
<SYSTEM_TASK:>
Drop the current table if it exists
<END_TASK>
<USER_TASK:>
Description:
def drop():
"""
Drop the current table if it exists
""" |
# Ensure the connection is up
_State.connection()
_State.table.drop(checkfirst=True)
_State.metadata.remove(_State.table)
_State.table = None
_State.new_transaction() |
<SYSTEM_TASK:>
Extracts attributes and attaches them to element.
<END_TASK>
<USER_TASK:>
Description:
def attach_attrs_table(key, value, fmt, meta):
"""Extracts attributes and attaches them to element.""" |
# We can't use attach_attrs_factory() because Table is a block-level element
if key in ['Table']:
assert len(value) == 5
caption = value[0] # caption, align, x, head, body
# Set n to the index where the attributes start
n = 0
while n < len(caption) and not \
(caption[n]['t'] == 'Str' and caption[n]['c'].startswith('{')):
n += 1
try:
attrs = extract_attrs(caption, n)
value.insert(0, attrs)
except (ValueError, IndexError):
pass |
<SYSTEM_TASK:>
Processes the attributed tables.
<END_TASK>
<USER_TASK:>
Description:
def process_tables(key, value, fmt, meta):
"""Processes the attributed tables.""" |
global has_unnumbered_tables # pylint: disable=global-statement
# Process block-level Table elements
if key == 'Table':
# Inspect the table
if len(value) == 5: # Unattributed, bail out
has_unnumbered_tables = True
if fmt in ['latex']:
return [RawBlock('tex', r'\begin{no-prefix-table-caption}'),
Table(*value),
RawBlock('tex', r'\end{no-prefix-table-caption}')]
return None
# Process the table
table = _process_table(value, fmt)
# Context-dependent output
attrs = table['attrs']
if table['is_unnumbered']:
if fmt in ['latex']:
return [RawBlock('tex', r'\begin{no-prefix-table-caption}'),
AttrTable(*value),
RawBlock('tex', r'\end{no-prefix-table-caption}')]
elif fmt in ['latex']:
if table['is_tagged']: # Code in the tags
tex = '\n'.join([r'\let\oldthetable=\thetable',
r'\renewcommand\thetable{%s}'%\
references[attrs[0]]])
pre = RawBlock('tex', tex)
tex = '\n'.join([r'\let\thetable=\oldthetable',
r'\addtocounter{table}{-1}'])
post = RawBlock('tex', tex)
return [pre, AttrTable(*value), post]
elif table['is_unreferenceable']:
attrs[0] = '' # The label isn't needed any further
elif fmt in ('html', 'html5') and LABEL_PATTERN.match(attrs[0]):
# Insert anchor
anchor = RawBlock('html', '<a name="%s"></a>'%attrs[0])
return [anchor, AttrTable(*value)]
elif fmt == 'docx':
# As per http://officeopenxml.com/WPhyperlink.php
bookmarkstart = \
RawBlock('openxml',
'<w:bookmarkStart w:id="0" w:name="%s"/>'
%attrs[0])
bookmarkend = \
RawBlock('openxml', '<w:bookmarkEnd w:id="0"/>')
return [bookmarkstart, AttrTable(*value), bookmarkend]
return None |
<SYSTEM_TASK:>
Send a SMS message, or an array of SMS messages
<END_TASK>
<USER_TASK:>
Description:
def send(self, messages):
"""Send a SMS message, or an array of SMS messages""" |
tmpSms = SMS(to='', message='')
if str(type(messages)) == str(type(tmpSms)):
messages = [messages]
xml_root = self.__init_xml('Message')
wrapper_id = 0
for m in messages:
m.wrapper_id = wrapper_id
msg = self.__build_sms_data(m)
sms = etree.SubElement(xml_root, 'SMS')
for sms_element in msg:
element = etree.SubElement(sms, sms_element)
element.text = msg[sms_element]
# print etree.tostring(xml_root)
response = clockwork_http.request(SMS_URL, etree.tostring(xml_root, encoding='utf-8'))
response_data = response['data']
# print response_data
data_etree = etree.fromstring(response_data)
# Check for general error
err_desc = data_etree.find('ErrDesc')
if err_desc is not None:
raise clockwork_exceptions.ApiException(err_desc.text, data_etree.find('ErrNo').text)
# Return a consistent object
results = []
for sms in data_etree:
matching_sms = next((s for s in messages if str(s.wrapper_id) == sms.find('WrapperID').text), None)
new_result = SMSResponse(
sms = matching_sms,
id = '' if sms.find('MessageID') is None else sms.find('MessageID').text,
error_code = 0 if sms.find('ErrNo') is None else sms.find('ErrNo').text,
error_message = '' if sms.find('ErrDesc') is None else sms.find('ErrDesc').text,
success = True if sms.find('ErrNo') is None else (sms.find('ErrNo').text == 0)
)
results.append(new_result)
if len(results) > 1:
return results
return results[0] |
<SYSTEM_TASK:>
Init a etree element and pop a key in there
<END_TASK>
<USER_TASK:>
Description:
def __init_xml(self, rootElementTag):
"""Init a etree element and pop a key in there""" |
xml_root = etree.Element(rootElementTag)
key = etree.SubElement(xml_root, "Key")
key.text = self.apikey
return xml_root |
<SYSTEM_TASK:>
Helper to convert serialized pstats back to a list of raw entries.
<END_TASK>
<USER_TASK:>
Description:
def pstats2entries(data):
"""Helper to convert serialized pstats back to a list of raw entries.
Converse operation of cProfile.Profile.snapshot_stats()
""" |
# Each entry's key is a tuple of (filename, line number, function name)
entries = {}
allcallers = {}
# first pass over stats to build the list of entry instances
for code_info, call_info in data.stats.items():
# build a fake code object
code = Code(*code_info)
# build a fake entry object. entry.calls will be filled during the
# second pass over stats
cc, nc, tt, ct, callers = call_info
entry = Entry(code, callcount=cc, reccallcount=nc - cc, inlinetime=tt,
totaltime=ct, calls=[])
# collect the new entry
entries[code_info] = entry
allcallers[code_info] = list(callers.items())
# second pass of stats to plug callees into callers
for entry in entries.values():
entry_label = cProfile.label(entry.code)
entry_callers = allcallers.get(entry_label, [])
for entry_caller, call_info in entry_callers:
cc, nc, tt, ct = call_info
subentry = Subentry(entry.code, callcount=cc, reccallcount=nc - cc,
inlinetime=tt, totaltime=ct)
# entry_caller has the same form as code_info
entries[entry_caller].calls.append(subentry)
return list(entries.values()) |
<SYSTEM_TASK:>
Return whether or not a given executable is installed on the machine.
<END_TASK>
<USER_TASK:>
Description:
def is_installed(prog):
"""Return whether or not a given executable is installed on the machine.""" |
with open(os.devnull, 'w') as devnull:
try:
if os.name == 'nt':
retcode = subprocess.call(['where', prog], stdout=devnull)
else:
retcode = subprocess.call(['which', prog], stdout=devnull)
except OSError as e:
# If where or which doesn't exist, a "ENOENT" error will occur (The
# FileNotFoundError subclass on Python 3).
if e.errno != errno.ENOENT:
raise
retcode = 1
return retcode == 0 |
<SYSTEM_TASK:>
Execute the converter using parameters provided on the command line
<END_TASK>
<USER_TASK:>
Description:
def main():
"""Execute the converter using parameters provided on the command line""" |
parser = argparse.ArgumentParser()
parser.add_argument('-o', '--outfile', metavar='output_file_path',
help="Save calltree stats to <outfile>")
parser.add_argument('-i', '--infile', metavar='input_file_path',
help="Read Python stats from <infile>")
parser.add_argument('-k', '--kcachegrind',
help="Run the kcachegrind tool on the converted data",
action="store_true")
parser.add_argument('-r', '--run-script',
nargs=argparse.REMAINDER,
metavar=('scriptfile', 'args'),
dest='script',
help="Name of the Python script to run to collect"
" profiling data")
args = parser.parse_args()
outfile = args.outfile
if args.script is not None:
# collect profiling data by running the given script
if not args.outfile:
outfile = '%s.log' % os.path.basename(args.script[0])
fd, tmp_path = tempfile.mkstemp(suffix='.prof', prefix='pyprof2calltree')
os.close(fd)
try:
cmd = [
sys.executable,
'-m', 'cProfile',
'-o', tmp_path,
]
cmd.extend(args.script)
subprocess.check_call(cmd)
kg = CalltreeConverter(tmp_path)
finally:
os.remove(tmp_path)
elif args.infile is not None:
# use the profiling data from some input file
if not args.outfile:
outfile = '%s.log' % os.path.basename(args.infile)
if args.infile == outfile:
# prevent name collisions by appending another extension
outfile += ".log"
kg = CalltreeConverter(pstats.Stats(args.infile))
else:
# at least an input file or a script to run is required
parser.print_usage()
sys.exit(2)
if args.outfile is not None or not args.kcachegrind:
# user either explicitly required output file or requested by not
# explicitly asking to launch kcachegrind
sys.stderr.write("writing converted data to: %s\n" % outfile)
with open(outfile, 'w') as f:
kg.output(f)
if args.kcachegrind:
sys.stderr.write("launching kcachegrind\n")
kg.visualize() |
<SYSTEM_TASK:>
convert `profiling_data` to calltree format and dump it to `outputfile`
<END_TASK>
<USER_TASK:>
Description:
def convert(profiling_data, outputfile):
"""convert `profiling_data` to calltree format and dump it to `outputfile`
`profiling_data` can either be:
- a pstats.Stats instance
- the filename of a pstats.Stats dump
- the result of a call to cProfile.Profile.getstats()
`outputfile` can either be:
- a file() instance open in write mode
- a filename
""" |
converter = CalltreeConverter(profiling_data)
if is_basestring(outputfile):
with open(outputfile, "w") as f:
converter.output(f)
else:
converter.output(outputfile) |
<SYSTEM_TASK:>
Launch kcachegrind on the converted entries.
<END_TASK>
<USER_TASK:>
Description:
def visualize(self):
"""Launch kcachegrind on the converted entries.
One of the executables listed in KCACHEGRIND_EXECUTABLES
must be present in the system path.
""" |
available_cmd = None
for cmd in KCACHEGRIND_EXECUTABLES:
if is_installed(cmd):
available_cmd = cmd
break
if available_cmd is None:
sys.stderr.write("Could not find kcachegrind. Tried: %s\n" %
", ".join(KCACHEGRIND_EXECUTABLES))
return
if self.out_file is None:
fd, outfile = tempfile.mkstemp(".log", "pyprof2calltree")
use_temp_file = True
else:
outfile = self.out_file.name
use_temp_file = False
try:
if use_temp_file:
with io.open(fd, "w") as f:
self.output(f)
subprocess.call([available_cmd, outfile])
finally:
# clean the temporary file
if use_temp_file:
os.remove(outfile)
self.out_file = None |
<SYSTEM_TASK:>
Initializes the Flask-Bouncer extension for the specified application.
<END_TASK>
<USER_TASK:>
Description:
def init_app(self, app, **kwargs):
""" Initializes the Flask-Bouncer extension for the specified application.
:param app: The application.
""" |
self.app = app
self._init_extension()
self.app.before_request(self.check_implicit_rules)
if kwargs.get('ensure_authorization', False):
self.app.after_request(self.check_authorization) |
<SYSTEM_TASK:>
checks that an authorization call has been made during the request
<END_TASK>
<USER_TASK:>
Description:
def check_authorization(self, response):
"""checks that an authorization call has been made during the request""" |
if not hasattr(request, '_authorized'):
raise Unauthorized
elif not request._authorized:
raise Unauthorized
return response |
<SYSTEM_TASK:>
if you are using flask classy are using the standard index,new,put,post, etc ... type routes, we will
<END_TASK>
<USER_TASK:>
Description:
def check_implicit_rules(self):
""" if you are using flask classy are using the standard index,new,put,post, etc ... type routes, we will
automatically check the permissions for you
""" |
if not self.request_is_managed_by_flask_classy():
return
if self.method_is_explictly_overwritten():
return
class_name, action = request.endpoint.split(':')
clazz = [classy_class for classy_class in self.flask_classy_classes if classy_class.__name__ == class_name][0]
Condition(action, clazz.__target_model__).test() |
<SYSTEM_TASK:>
Rotates the given texture by a given angle.
<END_TASK>
<USER_TASK:>
Description:
def rotate_texture(texture, rotation, x_offset=0.5, y_offset=0.5):
"""Rotates the given texture by a given angle.
Args:
texture (texture): the texture to rotate
rotation (float): the angle of rotation in degrees
x_offset (float): the x component of the center of rotation (optional)
y_offset (float): the y component of the center of rotation (optional)
Returns:
texture: A texture.
""" |
x, y = texture
x = x.copy() - x_offset
y = y.copy() - y_offset
angle = np.radians(rotation)
x_rot = x * np.cos(angle) + y * np.sin(angle)
y_rot = x * -np.sin(angle) + y * np.cos(angle)
return x_rot + x_offset, y_rot + y_offset |
<SYSTEM_TASK:>
Makes a texture from a turtle program.
<END_TASK>
<USER_TASK:>
Description:
def turtle_to_texture(turtle_program, turn_amount=DEFAULT_TURN,
initial_angle=DEFAULT_INITIAL_ANGLE, resolution=1):
"""Makes a texture from a turtle program.
Args:
turtle_program (str): a string representing the turtle program; see the
docstring of `branching_turtle_generator` for more details
turn_amount (float): amount to turn in degrees
initial_angle (float): initial orientation of the turtle
resolution (int): if provided, interpolation amount for visible lines
Returns:
texture: A texture.
""" |
generator = branching_turtle_generator(
turtle_program, turn_amount, initial_angle, resolution)
return texture_from_generator(generator) |
<SYSTEM_TASK:>
Chains a transformation a given number of times.
<END_TASK>
<USER_TASK:>
Description:
def transform_multiple(sequence, transformations, iterations):
"""Chains a transformation a given number of times.
Args:
sequence (str): a string or generator onto which transformations are applied
transformations (dict): a dictionary mapping each char to the string that is
substituted for it when the rule is applied
iterations (int): how many times to repeat the transformation
Yields:
str: the next character in the output sequence.
""" |
for _ in range(iterations):
sequence = transform_sequence(sequence, transformations)
return sequence |
<SYSTEM_TASK:>
Generates a texture by running transformations on a turtle program.
<END_TASK>
<USER_TASK:>
Description:
def l_system(axiom, transformations, iterations=1, angle=45, resolution=1):
"""Generates a texture by running transformations on a turtle program.
First, the given transformations are applied to the axiom. This is
repeated `iterations` times. Then, the output is run as a turtle
program to get a texture, which is returned.
For more background see: https://en.wikipedia.org/wiki/L-system
Args:
axiom (str): the axiom of the Lindenmeyer system (a string)
transformations (dict): a dictionary mapping each char to the string that is
substituted for it when the rule is applied
iterations (int): the number of times to apply the transformations
angle (float): the angle to use for turns when interpreting the string
as a turtle graphics program
resolution (int): the number of midpoints to create in each turtle step
Returns:
A texture
""" |
turtle_program = transform_multiple(axiom, transformations, iterations)
return turtle_to_texture(turtle_program, angle, resolution=resolution) |
<SYSTEM_TASK:>
Returns the path corresponding to the node i.
<END_TASK>
<USER_TASK:>
Description:
def get_path(self, i):
"""Returns the path corresponding to the node i.""" |
index = (i - 1) // 2
reverse = (i - 1) % 2
path = self.paths[index]
if reverse:
return path.reversed()
else:
return path |
<SYSTEM_TASK:>
Returns the distance between the end of path i
<END_TASK>
<USER_TASK:>
Description:
def cost(self, i, j):
"""Returns the distance between the end of path i
and the start of path j.""" |
return dist(self.endpoints[i][1], self.endpoints[j][0]) |
<SYSTEM_TASK:>
Returns the starting coordinates of node i as a pair,
<END_TASK>
<USER_TASK:>
Description:
def get_coordinates(self, i, end=False):
"""Returns the starting coordinates of node i as a pair,
or the end coordinates iff end is True.""" |
if end:
endpoint = self.endpoints[i][1]
else:
endpoint = self.endpoints[i][0]
return (endpoint.real, endpoint.imag) |
<SYSTEM_TASK:>
Preview a plot in a jupyter notebook.
<END_TASK>
<USER_TASK:>
Description:
def show_plot(plot, width=PREVIEW_WIDTH, height=PREVIEW_HEIGHT):
"""Preview a plot in a jupyter notebook.
Args:
plot (list): the plot to display (list of layers)
width (int): the width of the preview
height (int): the height of the preview
Returns:
An object that renders in Jupyter as the provided plot
""" |
return SVG(data=plot_to_svg(plot, width, height)) |
<SYSTEM_TASK:>
Calculates the size of the SVG viewBox to use.
<END_TASK>
<USER_TASK:>
Description:
def calculate_view_box(layers, aspect_ratio, margin=DEFAULT_VIEW_BOX_MARGIN):
"""Calculates the size of the SVG viewBox to use.
Args:
layers (list): the layers in the image
aspect_ratio (float): the height of the output divided by the width
margin (float): minimum amount of buffer to add around the image, relative
to the total dimensions
Returns:
tuple: a 4-tuple of floats representing the viewBox according to SVG
specifications ``(x, y, width, height)``.
""" |
min_x = min(np.nanmin(x) for x, y in layers)
max_x = max(np.nanmax(x) for x, y in layers)
min_y = min(np.nanmin(y) for x, y in layers)
max_y = max(np.nanmax(y) for x, y in layers)
height = max_y - min_y
width = max_x - min_x
if height > width * aspect_ratio:
adj_height = height * (1. + margin)
adj_width = adj_height / aspect_ratio
else:
adj_width = width * (1. + margin)
adj_height = adj_width * aspect_ratio
width_buffer = (adj_width - width) / 2.
height_buffer = (adj_height - height) / 2.
return (
min_x - width_buffer,
min_y - height_buffer,
adj_width,
adj_height
) |
<SYSTEM_TASK:>
Generates an SVG path from a given layer.
<END_TASK>
<USER_TASK:>
Description:
def _layer_to_path_gen(layer):
"""Generates an SVG path from a given layer.
Args:
layer (layer): the layer to convert
Yields:
str: the next component of the path
""" |
draw = False
for x, y in zip(*layer):
if np.isnan(x) or np.isnan(y):
draw = False
elif not draw:
yield 'M {} {}'.format(x, y)
draw = True
else:
yield 'L {} {}'.format(x, y) |
<SYSTEM_TASK:>
Writes a plot SVG to a file.
<END_TASK>
<USER_TASK:>
Description:
def write_plot(plot, filename, width=DEFAULT_PAGE_WIDTH, height=DEFAULT_PAGE_HEIGHT, unit=DEFAULT_PAGE_UNIT):
"""Writes a plot SVG to a file.
Args:
plot (list): a list of layers to plot
filename (str): the name of the file to write
width (float): the width of the output SVG
height (float): the height of the output SVG
unit (str): the unit of the height and width
""" |
svg = plot_to_svg(plot, width, height, unit)
with open(filename, 'w') as outfile:
outfile.write(svg) |
<SYSTEM_TASK:>
Draws a layer on the given matplotlib axis.
<END_TASK>
<USER_TASK:>
Description:
def draw_layer(ax, layer):
"""Draws a layer on the given matplotlib axis.
Args:
ax (axis): the matplotlib axis to draw on
layer (layer): the layers to plot
""" |
ax.set_aspect('equal', 'datalim')
ax.plot(*layer)
ax.axis('off') |
<SYSTEM_TASK:>
Returns values on a surface for points on a texture.
<END_TASK>
<USER_TASK:>
Description:
def map_texture_to_surface(texture, surface):
"""Returns values on a surface for points on a texture.
Args:
texture (texture): the texture to trace over the surface
surface (surface): the surface to trace along
Returns:
an array of surface heights for each point in the
texture. Line separators (i.e. values that are ``nan`` in
the texture) will be ``nan`` in the output, so the output
will have the same dimensions as the x/y axes in the
input texture.
""" |
texture_x, texture_y = texture
surface_h, surface_w = surface.shape
surface_x = np.clip(
np.int32(surface_w * texture_x - 1e-9), 0, surface_w - 1)
surface_y = np.clip(
np.int32(surface_h * texture_y - 1e-9), 0, surface_h - 1)
surface_z = surface[surface_y, surface_x]
return surface_z |
<SYSTEM_TASK:>
Creates a texture by adding z-values to an existing texture and projecting.
<END_TASK>
<USER_TASK:>
Description:
def project_texture(texture_xy, texture_z, angle=DEFAULT_ANGLE):
"""Creates a texture by adding z-values to an existing texture and projecting.
When working with surfaces there are two ways to accomplish the same thing:
1. project the surface and map a texture to the projected surface
2. map a texture to the surface, and then project the result
The first method, which does not use this function, is preferred because
it is easier to do occlusion removal that way. This function is provided
for cases where you do not wish to generate a surface (and don't care about
occlusion removal.)
Args:
texture_xy (texture): the texture to project
texture_z (np.array): the Z-values to use in the projection
angle (float): the angle to project at, in degrees (0 = overhead, 90 = side view)
Returns:
layer: A layer.
""" |
z_coef = np.sin(np.radians(angle))
y_coef = np.cos(np.radians(angle))
surface_x, surface_y = texture
return (surface_x, -surface_y * y_coef + surface_z * z_coef) |
<SYSTEM_TASK:>
Returns the height of the surface when projected at the given angle.
<END_TASK>
<USER_TASK:>
Description:
def project_surface(surface, angle=DEFAULT_ANGLE):
"""Returns the height of the surface when projected at the given angle.
Args:
surface (surface): the surface to project
angle (float): the angle at which to project the surface
Returns:
surface: A projected surface.
""" |
z_coef = np.sin(np.radians(angle))
y_coef = np.cos(np.radians(angle))
surface_height, surface_width = surface.shape
slope = np.tile(np.linspace(0., 1., surface_height), [surface_width, 1]).T
return slope * y_coef + surface * z_coef |
<SYSTEM_TASK:>
Maps a texture onto a surface, then projects to 2D and returns a layer.
<END_TASK>
<USER_TASK:>
Description:
def project_texture_on_surface(texture, surface, angle=DEFAULT_ANGLE):
"""Maps a texture onto a surface, then projects to 2D and returns a layer.
Args:
texture (texture): the texture to project
surface (surface): the surface to project onto
angle (float): the projection angle in degrees (0 = top-down, 90 = side view)
Returns:
layer: A layer.
""" |
projected_surface = project_surface(surface, angle)
texture_x, _ = texture
texture_y = map_texture_to_surface(texture, projected_surface)
return texture_x, texture_y |
<SYSTEM_TASK:>
Removes parts of a projected surface that are not visible.
<END_TASK>
<USER_TASK:>
Description:
def _remove_hidden_parts(projected_surface):
"""Removes parts of a projected surface that are not visible.
Args:
projected_surface (surface): the surface to use
Returns:
surface: A projected surface.
""" |
surface = np.copy(projected_surface)
surface[~_make_occlusion_mask(projected_surface)] = np.nan
return surface |
<SYSTEM_TASK:>
Projects a texture onto a surface with occluded areas removed.
<END_TASK>
<USER_TASK:>
Description:
def project_and_occlude_texture(texture, surface, angle=DEFAULT_ANGLE):
"""Projects a texture onto a surface with occluded areas removed.
Args:
texture (texture): the texture to map to the projected surface
surface (surface): the surface to project
angle (float): the angle to project at, in degrees (0 = overhead, 90 = side view)
Returns:
layer: A layer.
""" |
projected_surface = project_surface(surface, angle)
projected_surface = _remove_hidden_parts(projected_surface)
texture_y = map_texture_to_surface(texture, projected_surface)
texture_x, _ = texture
return texture_x, texture_y |
<SYSTEM_TASK:>
Makes a texture consisting of a given number of horizontal lines.
<END_TASK>
<USER_TASK:>
Description:
def make_lines_texture(num_lines=10, resolution=50):
"""Makes a texture consisting of a given number of horizontal lines.
Args:
num_lines (int): the number of lines to draw
resolution (int): the number of midpoints on each line
Returns:
A texture.
""" |
x, y = np.meshgrid(
np.hstack([np.linspace(0, 1, resolution), np.nan]),
np.linspace(0, 1, num_lines),
)
y[np.isnan(x)] = np.nan
return x.flatten(), y.flatten() |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.