body_hash stringlengths 64 64 | body stringlengths 23 109k | docstring stringlengths 1 57k | path stringlengths 4 198 | name stringlengths 1 115 | repository_name stringlengths 7 111 | repository_stars float64 0 191k | lang stringclasses 1 value | body_without_docstring stringlengths 14 108k | unified stringlengths 45 133k |
|---|---|---|---|---|---|---|---|---|---|
d12352aa0582fba887c07654b6f2596764a75ebb03fe54749535b76d019e4bcd | def dots_pause(soup, item):
'\n Rewrite three dots on thier own paragraph into a set of divs with\n class "fragment" applied. This is used in slideshows to create pauses\n '
pauses = soup.find_all('p', string=re.compile('\\. \\. \\.'))
for el in pauses:
next_els = list(el.next_siblings)
next_els.remove('\n')
if (len(next_els) > 0):
els = [i for i in itertools.takewhile((lambda x: ((x.name != 'hr') and (x not in pauses))), el.next_siblings)]
fragment = soup.new_tag('div', attrs={'class': 'fragment'})
el.wrap(fragment)
el.decompose()
for tag in els:
fragment.append(tag)
else:
el.parent.next_sibling['class'] = (el.parent.next_sibling['class'] + ['fragment'])
el.decompose() | Rewrite three dots on thier own paragraph into a set of divs with
class "fragment" applied. This is used in slideshows to create pauses | chirun/filter.py | dots_pause | sthagen/chirun-ncl-chirun | 5 | python | def dots_pause(soup, item):
'\n Rewrite three dots on thier own paragraph into a set of divs with\n class "fragment" applied. This is used in slideshows to create pauses\n '
pauses = soup.find_all('p', string=re.compile('\\. \\. \\.'))
for el in pauses:
next_els = list(el.next_siblings)
next_els.remove('\n')
if (len(next_els) > 0):
els = [i for i in itertools.takewhile((lambda x: ((x.name != 'hr') and (x not in pauses))), el.next_siblings)]
fragment = soup.new_tag('div', attrs={'class': 'fragment'})
el.wrap(fragment)
el.decompose()
for tag in els:
fragment.append(tag)
else:
el.parent.next_sibling['class'] = (el.parent.next_sibling['class'] + ['fragment'])
el.decompose() | def dots_pause(soup, item):
'\n Rewrite three dots on thier own paragraph into a set of divs with\n class "fragment" applied. This is used in slideshows to create pauses\n '
pauses = soup.find_all('p', string=re.compile('\\. \\. \\.'))
for el in pauses:
next_els = list(el.next_siblings)
next_els.remove('\n')
if (len(next_els) > 0):
els = [i for i in itertools.takewhile((lambda x: ((x.name != 'hr') and (x not in pauses))), el.next_siblings)]
fragment = soup.new_tag('div', attrs={'class': 'fragment'})
el.wrap(fragment)
el.decompose()
for tag in els:
fragment.append(tag)
else:
el.parent.next_sibling['class'] = (el.parent.next_sibling['class'] + ['fragment'])
el.decompose()<|docstring|>Rewrite three dots on thier own paragraph into a set of divs with
class "fragment" applied. This is used in slideshows to create pauses<|endoftext|> |
5e41eabdc27022b5c5a65c92e8e5499505cf2734758c432c5473f97da5bd91fc | def mathjax_script_dollar(soup, item):
'\n Rewrite MathJax math/tex scripts to use dollars instead.\n Useful for notebooks where we have less control over MathJax.\n '
for el in soup.find_all('script'):
if ('math/tex' in el.attrs['type']):
el.name = 'span'
del el.attrs['type']
el.string = '${}$'.format(el.string) | Rewrite MathJax math/tex scripts to use dollars instead.
Useful for notebooks where we have less control over MathJax. | chirun/filter.py | mathjax_script_dollar | sthagen/chirun-ncl-chirun | 5 | python | def mathjax_script_dollar(soup, item):
'\n Rewrite MathJax math/tex scripts to use dollars instead.\n Useful for notebooks where we have less control over MathJax.\n '
for el in soup.find_all('script'):
if ('math/tex' in el.attrs['type']):
el.name = 'span'
del el.attrs['type']
el.string = '${}$'.format(el.string) | def mathjax_script_dollar(soup, item):
'\n Rewrite MathJax math/tex scripts to use dollars instead.\n Useful for notebooks where we have less control over MathJax.\n '
for el in soup.find_all('script'):
if ('math/tex' in el.attrs['type']):
el.name = 'span'
del el.attrs['type']
el.string = '${}$'.format(el.string)<|docstring|>Rewrite MathJax math/tex scripts to use dollars instead.
Useful for notebooks where we have less control over MathJax.<|endoftext|> |
08b640138da9b2a6c0a0eeebd117f51774169225989335055f3a94572cd8e2cc | def links_to_data_uri(soup, item):
"\n Rewrite links into to embedded data-uri streams\n Useful for jupyter notebooks where we'd like things to be self contained\n "
tags = {'a': ['href'], 'img': ['src'], 'source': ['src']}
filetypes = {'.png': 'data/png', '.jpg': 'data/jpeg', '.jpeg': 'data/jpeg'}
for (tag, attrs) in tags.items():
for el in soup.find_all(tag):
for attr in attrs:
url = el.get(attr)
if (not url.startswith(('http://', 'https://', 'ftp://'))):
for ft in filetypes.keys():
if (ft in url):
src_path = ((item.course.get_build_dir() / item.out_path) / Path(url))
with open(str(src_path), 'rb') as f:
data = b64encode(f.read()).decode('ascii')
el[attr] = 'data:{};base64,{}'.format(filetypes[ft], data)
break | Rewrite links into to embedded data-uri streams
Useful for jupyter notebooks where we'd like things to be self contained | chirun/filter.py | links_to_data_uri | sthagen/chirun-ncl-chirun | 5 | python | def links_to_data_uri(soup, item):
"\n Rewrite links into to embedded data-uri streams\n Useful for jupyter notebooks where we'd like things to be self contained\n "
tags = {'a': ['href'], 'img': ['src'], 'source': ['src']}
filetypes = {'.png': 'data/png', '.jpg': 'data/jpeg', '.jpeg': 'data/jpeg'}
for (tag, attrs) in tags.items():
for el in soup.find_all(tag):
for attr in attrs:
url = el.get(attr)
if (not url.startswith(('http://', 'https://', 'ftp://'))):
for ft in filetypes.keys():
if (ft in url):
src_path = ((item.course.get_build_dir() / item.out_path) / Path(url))
with open(str(src_path), 'rb') as f:
data = b64encode(f.read()).decode('ascii')
el[attr] = 'data:{};base64,{}'.format(filetypes[ft], data)
break | def links_to_data_uri(soup, item):
"\n Rewrite links into to embedded data-uri streams\n Useful for jupyter notebooks where we'd like things to be self contained\n "
tags = {'a': ['href'], 'img': ['src'], 'source': ['src']}
filetypes = {'.png': 'data/png', '.jpg': 'data/jpeg', '.jpeg': 'data/jpeg'}
for (tag, attrs) in tags.items():
for el in soup.find_all(tag):
for attr in attrs:
url = el.get(attr)
if (not url.startswith(('http://', 'https://', 'ftp://'))):
for ft in filetypes.keys():
if (ft in url):
src_path = ((item.course.get_build_dir() / item.out_path) / Path(url))
with open(str(src_path), 'rb') as f:
data = b64encode(f.read()).decode('ascii')
el[attr] = 'data:{};base64,{}'.format(filetypes[ft], data)
break<|docstring|>Rewrite links into to embedded data-uri streams
Useful for jupyter notebooks where we'd like things to be self contained<|endoftext|> |
e66e2c91e78970b35a79090295216bab1588620508e9f661a47d33a3fa38b689 | def recent_statuses(self, page=1, startdate=None, enddate=None):
'Return a single page of the most recent statuses from this team.'
statuses = self.statuses().filter_by(reply_to=None).order_by(desc(Status.created))
return paginate(statuses, page, startdate, enddate) | Return a single page of the most recent statuses from this team. | standup/apps/users/models.py | recent_statuses | rlr/standup | 2 | python | def recent_statuses(self, page=1, startdate=None, enddate=None):
statuses = self.statuses().filter_by(reply_to=None).order_by(desc(Status.created))
return paginate(statuses, page, startdate, enddate) | def recent_statuses(self, page=1, startdate=None, enddate=None):
statuses = self.statuses().filter_by(reply_to=None).order_by(desc(Status.created))
return paginate(statuses, page, startdate, enddate)<|docstring|>Return a single page of the most recent statuses from this team.<|endoftext|> |
4304e3774feb7f184271823472f8178ffa4081a5f071a48cb1233685509023da | def statuses(self):
'Return all statuses from this team.'
db = get_session(current_app)
user_ids = [u.id for u in self.users]
if user_ids:
return db.query(Status).filter(Status.user_id.in_(user_ids))
else:
return db.query(Status).filter('0=1') | Return all statuses from this team. | standup/apps/users/models.py | statuses | rlr/standup | 2 | python | def statuses(self):
db = get_session(current_app)
user_ids = [u.id for u in self.users]
if user_ids:
return db.query(Status).filter(Status.user_id.in_(user_ids))
else:
return db.query(Status).filter('0=1') | def statuses(self):
db = get_session(current_app)
user_ids = [u.id for u in self.users]
if user_ids:
return db.query(Status).filter(Status.user_id.in_(user_ids))
else:
return db.query(Status).filter('0=1')<|docstring|>Return all statuses from this team.<|endoftext|> |
96041d3bd2d3006b2dd577d0862d597e7bf876ceab66eb0b0e9932f0fbcf8c28 | def recent_statuses(self, page=1, startdate=None, enddate=None):
'Return a single page of the most recent statuses from this user.'
statuses = self.statuses.filter_by(reply_to=None).order_by(desc(Status.created))
return paginate(statuses, page, startdate, enddate) | Return a single page of the most recent statuses from this user. | standup/apps/users/models.py | recent_statuses | rlr/standup | 2 | python | def recent_statuses(self, page=1, startdate=None, enddate=None):
statuses = self.statuses.filter_by(reply_to=None).order_by(desc(Status.created))
return paginate(statuses, page, startdate, enddate) | def recent_statuses(self, page=1, startdate=None, enddate=None):
statuses = self.statuses.filter_by(reply_to=None).order_by(desc(Status.created))
return paginate(statuses, page, startdate, enddate)<|docstring|>Return a single page of the most recent statuses from this user.<|endoftext|> |
183ecd6b3615084338614afcc0f33082e43c21ebc9fcef8f6297e20477dccf45 | def dictify(self):
'Returns an OrderedDict of model attributes'
data = OrderedDict()
data['id'] = self.id
data['username'] = self.username
data['name'] = self.name
data['slug'] = self.slug
data['email'] = self.email
data['github_handle'] = self.github_handle
data['is_admin'] = self.is_admin
return data | Returns an OrderedDict of model attributes | standup/apps/users/models.py | dictify | rlr/standup | 2 | python | def dictify(self):
data = OrderedDict()
data['id'] = self.id
data['username'] = self.username
data['name'] = self.name
data['slug'] = self.slug
data['email'] = self.email
data['github_handle'] = self.github_handle
data['is_admin'] = self.is_admin
return data | def dictify(self):
data = OrderedDict()
data['id'] = self.id
data['username'] = self.username
data['name'] = self.name
data['slug'] = self.slug
data['email'] = self.email
data['github_handle'] = self.github_handle
data['is_admin'] = self.is_admin
return data<|docstring|>Returns an OrderedDict of model attributes<|endoftext|> |
6feee78cb3c0301f8965e6593822a0ad9e68cfc762e32d949c37c18fc3749199 | def get_group_with_redirect(id_or_qualified_short_id, queryset=None):
'\n Retrieve a group by ID, checking the redirect table if the requested group\n does not exist. Returns a two-tuple of ``(object, redirected)``.\n '
if (queryset is None):
queryset = Group.objects.all()
getter = Group.objects.get_from_cache
else:
getter = queryset.get
if (not (isinstance(id_or_qualified_short_id, (long, int)) or id_or_qualified_short_id.isdigit())):
short_id = parse_short_id(id_or_qualified_short_id)
if (not short_id):
raise Group.DoesNotExist()
params = {'project__slug': short_id.project_slug, 'short_id': short_id.short_id}
else:
short_id = None
params = {'id': id_or_qualified_short_id}
try:
return (getter(**params), False)
except Group.DoesNotExist as error:
from sentry.models import GroupRedirect
if short_id:
params = {'id': GroupRedirect.objects.filter(previous_short_id=short_id.short_id, previous_project_slug=short_id.project_slug).values_list('group_id', flat=True)}
else:
params['id'] = GroupRedirect.objects.filter(previous_group_id=params['id']).values_list('group_id', flat=True)
try:
return (queryset.get(**params), True)
except Group.DoesNotExist:
raise error | Retrieve a group by ID, checking the redirect table if the requested group
does not exist. Returns a two-tuple of ``(object, redirected)``. | src/sentry/models/group.py | get_group_with_redirect | alexpeters0n/sentry | 1 | python | def get_group_with_redirect(id_or_qualified_short_id, queryset=None):
'\n Retrieve a group by ID, checking the redirect table if the requested group\n does not exist. Returns a two-tuple of ``(object, redirected)``.\n '
if (queryset is None):
queryset = Group.objects.all()
getter = Group.objects.get_from_cache
else:
getter = queryset.get
if (not (isinstance(id_or_qualified_short_id, (long, int)) or id_or_qualified_short_id.isdigit())):
short_id = parse_short_id(id_or_qualified_short_id)
if (not short_id):
raise Group.DoesNotExist()
params = {'project__slug': short_id.project_slug, 'short_id': short_id.short_id}
else:
short_id = None
params = {'id': id_or_qualified_short_id}
try:
return (getter(**params), False)
except Group.DoesNotExist as error:
from sentry.models import GroupRedirect
if short_id:
params = {'id': GroupRedirect.objects.filter(previous_short_id=short_id.short_id, previous_project_slug=short_id.project_slug).values_list('group_id', flat=True)}
else:
params['id'] = GroupRedirect.objects.filter(previous_group_id=params['id']).values_list('group_id', flat=True)
try:
return (queryset.get(**params), True)
except Group.DoesNotExist:
raise error | def get_group_with_redirect(id_or_qualified_short_id, queryset=None):
'\n Retrieve a group by ID, checking the redirect table if the requested group\n does not exist. Returns a two-tuple of ``(object, redirected)``.\n '
if (queryset is None):
queryset = Group.objects.all()
getter = Group.objects.get_from_cache
else:
getter = queryset.get
if (not (isinstance(id_or_qualified_short_id, (long, int)) or id_or_qualified_short_id.isdigit())):
short_id = parse_short_id(id_or_qualified_short_id)
if (not short_id):
raise Group.DoesNotExist()
params = {'project__slug': short_id.project_slug, 'short_id': short_id.short_id}
else:
short_id = None
params = {'id': id_or_qualified_short_id}
try:
return (getter(**params), False)
except Group.DoesNotExist as error:
from sentry.models import GroupRedirect
if short_id:
params = {'id': GroupRedirect.objects.filter(previous_short_id=short_id.short_id, previous_project_slug=short_id.project_slug).values_list('group_id', flat=True)}
else:
params['id'] = GroupRedirect.objects.filter(previous_group_id=params['id']).values_list('group_id', flat=True)
try:
return (queryset.get(**params), True)
except Group.DoesNotExist:
raise error<|docstring|>Retrieve a group by ID, checking the redirect table if the requested group
does not exist. Returns a two-tuple of ``(object, redirected)``.<|endoftext|> |
9c7a26cba994b7febe3ee4c1b2905f844fb721d21ef15a7b555d72777a7e526a | def from_event_id(self, project, event_id):
'\n Resolves the 32 character event_id string into\n a Group for which it is found.\n '
from sentry.models import SnubaEvent
group_id = None
event = SnubaEvent.objects.from_event_id(event_id, project.id)
if event:
group_id = event.group_id
if (group_id is None):
raise Group.DoesNotExist()
return Group.objects.get(id=group_id) | Resolves the 32 character event_id string into
a Group for which it is found. | src/sentry/models/group.py | from_event_id | alexpeters0n/sentry | 1 | python | def from_event_id(self, project, event_id):
'\n Resolves the 32 character event_id string into\n a Group for which it is found.\n '
from sentry.models import SnubaEvent
group_id = None
event = SnubaEvent.objects.from_event_id(event_id, project.id)
if event:
group_id = event.group_id
if (group_id is None):
raise Group.DoesNotExist()
return Group.objects.get(id=group_id) | def from_event_id(self, project, event_id):
'\n Resolves the 32 character event_id string into\n a Group for which it is found.\n '
from sentry.models import SnubaEvent
group_id = None
event = SnubaEvent.objects.from_event_id(event_id, project.id)
if event:
group_id = event.group_id
if (group_id is None):
raise Group.DoesNotExist()
return Group.objects.get(id=group_id)<|docstring|>Resolves the 32 character event_id string into
a Group for which it is found.<|endoftext|> |
a1f9939a3d3c4e2e9b8e85c50f5f6ba2dba361377b1c221ccc17de4874595ca7 | def get_event_type(self):
'\n Return the type of this issue.\n\n See ``sentry.eventtypes``.\n '
return self.data.get('type', 'default') | Return the type of this issue.
See ``sentry.eventtypes``. | src/sentry/models/group.py | get_event_type | alexpeters0n/sentry | 1 | python | def get_event_type(self):
'\n Return the type of this issue.\n\n See ``sentry.eventtypes``.\n '
return self.data.get('type', 'default') | def get_event_type(self):
'\n Return the type of this issue.\n\n See ``sentry.eventtypes``.\n '
return self.data.get('type', 'default')<|docstring|>Return the type of this issue.
See ``sentry.eventtypes``.<|endoftext|> |
4ec4883f7001cb960fe9d3eeb96aa4822f7d7f8ef6bb135502b2d6badf4cee03 | def get_event_metadata(self):
'\n Return the metadata of this issue.\n\n See ``sentry.eventtypes``.\n '
return self.data['metadata'] | Return the metadata of this issue.
See ``sentry.eventtypes``. | src/sentry/models/group.py | get_event_metadata | alexpeters0n/sentry | 1 | python | def get_event_metadata(self):
'\n Return the metadata of this issue.\n\n See ``sentry.eventtypes``.\n '
return self.data['metadata'] | def get_event_metadata(self):
'\n Return the metadata of this issue.\n\n See ``sentry.eventtypes``.\n '
return self.data['metadata']<|docstring|>Return the metadata of this issue.
See ``sentry.eventtypes``.<|endoftext|> |
12606555f9203128426b0abc829923570955bcd83da2a87fcdeebda022b22137 | def get_message_supplement(self, msg: types_gen.DeviceData) -> Optional[core.PyReachStatus]:
'Get additional message.'
if ((msg.device_type == 'client-annotation') and (not msg.device_name) and (msg.data_type == 'cmd-status')):
return utils.pyreach_status_from_message(msg)
return None | Get additional message. | pyreach/impl/client_annotation_impl.py | get_message_supplement | google-research/pyreach | 13 | python | def get_message_supplement(self, msg: types_gen.DeviceData) -> Optional[core.PyReachStatus]:
if ((msg.device_type == 'client-annotation') and (not msg.device_name) and (msg.data_type == 'cmd-status')):
return utils.pyreach_status_from_message(msg)
return None | def get_message_supplement(self, msg: types_gen.DeviceData) -> Optional[core.PyReachStatus]:
if ((msg.device_type == 'client-annotation') and (not msg.device_name) and (msg.data_type == 'cmd-status')):
return utils.pyreach_status_from_message(msg)
return None<|docstring|>Get additional message.<|endoftext|> |
2c70e4e0a5957a26ecfc8e2c1eaf90541f795390e2a9726c815f1dd01c1c6374 | def get_wrapper(self) -> Tuple[('ClientAnnotationDevice', 'client_annotation.ClientAnnotation')]:
'Get the wrapper for the device that should be shown to the user.'
return (self, ClientAnnotationImpl(self)) | Get the wrapper for the device that should be shown to the user. | pyreach/impl/client_annotation_impl.py | get_wrapper | google-research/pyreach | 13 | python | def get_wrapper(self) -> Tuple[('ClientAnnotationDevice', 'client_annotation.ClientAnnotation')]:
return (self, ClientAnnotationImpl(self)) | def get_wrapper(self) -> Tuple[('ClientAnnotationDevice', 'client_annotation.ClientAnnotation')]:
return (self, ClientAnnotationImpl(self))<|docstring|>Get the wrapper for the device that should be shown to the user.<|endoftext|> |
fc12aecb080d29cc667118cdc19d94b9ada2c54ba9662d823ff634562215a75f | def send_annotation(self, annotation: logs_pb2.ClientAnnotation) -> 'queue.Queue[Optional[Tuple[types_gen.DeviceData, Optional[core.PyReachStatus]]]]':
'Annotate the logs with the given client annotation.\n\n Args:\n annotation: The annotation to log.\n\n Raises:\n PyReachError: if an interval annotation is sent.\n\n Returns:\n A queue of response.\n '
data_annotation = types_gen.ClientAnnotation.from_proto(annotation)
assert data_annotation
if (data_annotation.interval_start or data_annotation.interval_end):
raise core.PyReachError('Interval annotations must be sent via the logger device')
return self.send_tagged_request(types_gen.CommandData(ts=utils.timestamp_now(), tag=utils.generate_tag(), device_type='client-annotation', data_type='client-annotation', client_annotation=data_annotation), timeout=30) | Annotate the logs with the given client annotation.
Args:
annotation: The annotation to log.
Raises:
PyReachError: if an interval annotation is sent.
Returns:
A queue of response. | pyreach/impl/client_annotation_impl.py | send_annotation | google-research/pyreach | 13 | python | def send_annotation(self, annotation: logs_pb2.ClientAnnotation) -> 'queue.Queue[Optional[Tuple[types_gen.DeviceData, Optional[core.PyReachStatus]]]]':
'Annotate the logs with the given client annotation.\n\n Args:\n annotation: The annotation to log.\n\n Raises:\n PyReachError: if an interval annotation is sent.\n\n Returns:\n A queue of response.\n '
data_annotation = types_gen.ClientAnnotation.from_proto(annotation)
assert data_annotation
if (data_annotation.interval_start or data_annotation.interval_end):
raise core.PyReachError('Interval annotations must be sent via the logger device')
return self.send_tagged_request(types_gen.CommandData(ts=utils.timestamp_now(), tag=utils.generate_tag(), device_type='client-annotation', data_type='client-annotation', client_annotation=data_annotation), timeout=30) | def send_annotation(self, annotation: logs_pb2.ClientAnnotation) -> 'queue.Queue[Optional[Tuple[types_gen.DeviceData, Optional[core.PyReachStatus]]]]':
'Annotate the logs with the given client annotation.\n\n Args:\n annotation: The annotation to log.\n\n Raises:\n PyReachError: if an interval annotation is sent.\n\n Returns:\n A queue of response.\n '
data_annotation = types_gen.ClientAnnotation.from_proto(annotation)
assert data_annotation
if (data_annotation.interval_start or data_annotation.interval_end):
raise core.PyReachError('Interval annotations must be sent via the logger device')
return self.send_tagged_request(types_gen.CommandData(ts=utils.timestamp_now(), tag=utils.generate_tag(), device_type='client-annotation', data_type='client-annotation', client_annotation=data_annotation), timeout=30)<|docstring|>Annotate the logs with the given client annotation.
Args:
annotation: The annotation to log.
Raises:
PyReachError: if an interval annotation is sent.
Returns:
A queue of response.<|endoftext|> |
514702111596c1cbd8754803682754cc70d0345e8edfc06528ef5b0a175852c4 | def __init__(self, device: ClientAnnotationDevice) -> None:
'Create the client annotation implementation.\n\n Args:\n device: The device implementation.\n '
self._device = device | Create the client annotation implementation.
Args:
device: The device implementation. | pyreach/impl/client_annotation_impl.py | __init__ | google-research/pyreach | 13 | python | def __init__(self, device: ClientAnnotationDevice) -> None:
'Create the client annotation implementation.\n\n Args:\n device: The device implementation.\n '
self._device = device | def __init__(self, device: ClientAnnotationDevice) -> None:
'Create the client annotation implementation.\n\n Args:\n device: The device implementation.\n '
self._device = device<|docstring|>Create the client annotation implementation.
Args:
device: The device implementation.<|endoftext|> |
a115431402f620236e62d994e575ebe491521428d73064f1ef825d8897e6f40c | def annotate(self, annotation: logs_pb2.ClientAnnotation) -> core.PyReachStatus:
'Annotate the logs with the given client annotation.\n\n Args:\n annotation: The annotation to log.\n\n Raises:\n PyReachError: if an interval annotation is sent.\n\n Returns:\n The annotation PyReachStatus.\n '
q = self._device.send_annotation(annotation)
msgs = thread_util.extract_all_from_queue(q)
if (not msgs):
return core.PyReachStatus(utils.timestamp_now(), status='rejected', error='timeout')
if (len(msgs) != 1):
logging.warning('expected single message, got %d', len(msgs))
result = msgs[(len(msgs) - 1)][1]
if (result is None):
return core.PyReachStatus(utils.timestamp_now(), status='rejected', error='timeout')
return result | Annotate the logs with the given client annotation.
Args:
annotation: The annotation to log.
Raises:
PyReachError: if an interval annotation is sent.
Returns:
The annotation PyReachStatus. | pyreach/impl/client_annotation_impl.py | annotate | google-research/pyreach | 13 | python | def annotate(self, annotation: logs_pb2.ClientAnnotation) -> core.PyReachStatus:
'Annotate the logs with the given client annotation.\n\n Args:\n annotation: The annotation to log.\n\n Raises:\n PyReachError: if an interval annotation is sent.\n\n Returns:\n The annotation PyReachStatus.\n '
q = self._device.send_annotation(annotation)
msgs = thread_util.extract_all_from_queue(q)
if (not msgs):
return core.PyReachStatus(utils.timestamp_now(), status='rejected', error='timeout')
if (len(msgs) != 1):
logging.warning('expected single message, got %d', len(msgs))
result = msgs[(len(msgs) - 1)][1]
if (result is None):
return core.PyReachStatus(utils.timestamp_now(), status='rejected', error='timeout')
return result | def annotate(self, annotation: logs_pb2.ClientAnnotation) -> core.PyReachStatus:
'Annotate the logs with the given client annotation.\n\n Args:\n annotation: The annotation to log.\n\n Raises:\n PyReachError: if an interval annotation is sent.\n\n Returns:\n The annotation PyReachStatus.\n '
q = self._device.send_annotation(annotation)
msgs = thread_util.extract_all_from_queue(q)
if (not msgs):
return core.PyReachStatus(utils.timestamp_now(), status='rejected', error='timeout')
if (len(msgs) != 1):
logging.warning('expected single message, got %d', len(msgs))
result = msgs[(len(msgs) - 1)][1]
if (result is None):
return core.PyReachStatus(utils.timestamp_now(), status='rejected', error='timeout')
return result<|docstring|>Annotate the logs with the given client annotation.
Args:
annotation: The annotation to log.
Raises:
PyReachError: if an interval annotation is sent.
Returns:
The annotation PyReachStatus.<|endoftext|> |
1cb089251d7ee5778533512ba1d58231174aa9061cc249dbc7c0ae98009be9ed | def async_annotate(self, annotation: logs_pb2.ClientAnnotation, callback: Optional[Callable[([core.PyReachStatus], None)]]=None) -> None:
'Annotate the logs with the given client annotation.\n\n Args:\n annotation: The annotation to log.\n callback: callback when status is received.\n\n Raises:\n PyReachError: if an interval annotation is sent.\n\n Returns:\n The annotation PyReachStatus.\n '
q = self._device.send_annotation(annotation)
self._device.queue_to_error_callback(q, callback, callback) | Annotate the logs with the given client annotation.
Args:
annotation: The annotation to log.
callback: callback when status is received.
Raises:
PyReachError: if an interval annotation is sent.
Returns:
The annotation PyReachStatus. | pyreach/impl/client_annotation_impl.py | async_annotate | google-research/pyreach | 13 | python | def async_annotate(self, annotation: logs_pb2.ClientAnnotation, callback: Optional[Callable[([core.PyReachStatus], None)]]=None) -> None:
'Annotate the logs with the given client annotation.\n\n Args:\n annotation: The annotation to log.\n callback: callback when status is received.\n\n Raises:\n PyReachError: if an interval annotation is sent.\n\n Returns:\n The annotation PyReachStatus.\n '
q = self._device.send_annotation(annotation)
self._device.queue_to_error_callback(q, callback, callback) | def async_annotate(self, annotation: logs_pb2.ClientAnnotation, callback: Optional[Callable[([core.PyReachStatus], None)]]=None) -> None:
'Annotate the logs with the given client annotation.\n\n Args:\n annotation: The annotation to log.\n callback: callback when status is received.\n\n Raises:\n PyReachError: if an interval annotation is sent.\n\n Returns:\n The annotation PyReachStatus.\n '
q = self._device.send_annotation(annotation)
self._device.queue_to_error_callback(q, callback, callback)<|docstring|>Annotate the logs with the given client annotation.
Args:
annotation: The annotation to log.
callback: callback when status is received.
Raises:
PyReachError: if an interval annotation is sent.
Returns:
The annotation PyReachStatus.<|endoftext|> |
fc8e9179c74b77bef8e57beb798c5b7af5127294e853916b0c66d656796881b5 | def test1(self):
'test createBarcodeDrawing'
from reportlab.graphics.barcode import createBarcodeDrawing
from reportlab.graphics.barcode import getCodeNames
for name in getCodeNames():
d = createBarcodeDrawing(name)
for t in getattr(d.__class__, '_tests', []):
createBarcodeDrawing(name, value=t) | test createBarcodeDrawing | dep/reportlab/tests/test_graphics_barcode.py | test1 | csterryliu/Legal-Attest-Letter-Generator | 52 | python | def test1(self):
from reportlab.graphics.barcode import createBarcodeDrawing
from reportlab.graphics.barcode import getCodeNames
for name in getCodeNames():
d = createBarcodeDrawing(name)
for t in getattr(d.__class__, '_tests', []):
createBarcodeDrawing(name, value=t) | def test1(self):
from reportlab.graphics.barcode import createBarcodeDrawing
from reportlab.graphics.barcode import getCodeNames
for name in getCodeNames():
d = createBarcodeDrawing(name)
for t in getattr(d.__class__, '_tests', []):
createBarcodeDrawing(name, value=t)<|docstring|>test createBarcodeDrawing<|endoftext|> |
212433ba53ef4f3206e532116ea6c57b218fd3c2c5342b76998515c2ba7d28f1 | def get_elem_data(elem_json):
' Returns the pertinent data of an element in the JSON file. '
elem_name = elem_json['name']
elem_type = determine_elem(elem_json['lib_fqn'])
subsys_id = elem_json['parent_comp_id']
prefix_subs = ''
while subsys_id:
for subsystem in subsys_list:
if (subsystem['id'] == subsys_id):
prefix_subs = ((subsystem['name'] + '.') + prefix_subs)
subsys_id = subsystem['parent_comp_id']
elem_name = (prefix_subs + elem_name)
elem_name = elem_name.replace(' ', '_')
elem_data = {}
def elem_get_nodes():
nonlocal elem_json
nodes_dict = {}
for term in elem_json['terminals']:
for n in node_data:
if (term['id'] in n['terminals']):
nodes_dict.update({term['name']: str(n['id'])})
return nodes_dict
if (elem_type == 'I_meas'):
meas_nodes = elem_get_nodes()
if (len(meas_nodes) == 3):
elem_type = 'I_meas_out'
name = elem_name
else:
name = ('_I_meas__' + elem_name)
elem_data = {'name': name, 'nodes': meas_nodes, 'init_data': {'voltage': '0', 'analysis_type': analysis_type}}
if (len(meas_nodes) == 2):
if (analysis_type == 'AC small-signal'):
meas_aliases.extend([f'mag({elem_name})', f'phase({elem_name})'])
else:
meas_aliases.append(elem_name)
elif (elem_type == 'V_meas'):
meas_nodes = elem_get_nodes()
if (len(meas_nodes) == 3):
elem_type = 'V_meas_out'
name = elem_name
else:
name = ('_V_meas__' + elem_name)
elem_data = {'name': name, 'nodes': meas_nodes, 'init_data': {'current': '0', 'analysis_type': analysis_type}}
if (len(meas_nodes) == 2):
if (analysis_type == 'AC small-signal'):
meas_aliases.extend([f'mag({elem_name})', f'phase({elem_name})'])
else:
meas_aliases.append(elem_name)
elif (elem_type in ['Probe', 'Vnode']):
elem_data = {'name': elem_name, 'nodes': elem_get_nodes(), 'init_data': {'analysis_type': analysis_type}}
elif (elem_json['masks'] and (not (elem_type in ['V_meas', 'I_meas']))):
prop_list = elem_json['masks'][0]['properties']
init_dict = {prop['name']: str(prop['value']) for prop in prop_list}
init_dict.update({'analysis_type': analysis_type})
elem_data = {'name': elem_name, 'nodes': elem_get_nodes(), 'init_data': init_dict}
return (elem_type, elem_data) | Returns the pertinent data of an element in the JSON file. | xyce_conv/schematic_converter/tse2xyce.py | get_elem_data | typhoon-hil/xyce-typhoon-hil-interface | 4 | python | def get_elem_data(elem_json):
' '
elem_name = elem_json['name']
elem_type = determine_elem(elem_json['lib_fqn'])
subsys_id = elem_json['parent_comp_id']
prefix_subs =
while subsys_id:
for subsystem in subsys_list:
if (subsystem['id'] == subsys_id):
prefix_subs = ((subsystem['name'] + '.') + prefix_subs)
subsys_id = subsystem['parent_comp_id']
elem_name = (prefix_subs + elem_name)
elem_name = elem_name.replace(' ', '_')
elem_data = {}
def elem_get_nodes():
nonlocal elem_json
nodes_dict = {}
for term in elem_json['terminals']:
for n in node_data:
if (term['id'] in n['terminals']):
nodes_dict.update({term['name']: str(n['id'])})
return nodes_dict
if (elem_type == 'I_meas'):
meas_nodes = elem_get_nodes()
if (len(meas_nodes) == 3):
elem_type = 'I_meas_out'
name = elem_name
else:
name = ('_I_meas__' + elem_name)
elem_data = {'name': name, 'nodes': meas_nodes, 'init_data': {'voltage': '0', 'analysis_type': analysis_type}}
if (len(meas_nodes) == 2):
if (analysis_type == 'AC small-signal'):
meas_aliases.extend([f'mag({elem_name})', f'phase({elem_name})'])
else:
meas_aliases.append(elem_name)
elif (elem_type == 'V_meas'):
meas_nodes = elem_get_nodes()
if (len(meas_nodes) == 3):
elem_type = 'V_meas_out'
name = elem_name
else:
name = ('_V_meas__' + elem_name)
elem_data = {'name': name, 'nodes': meas_nodes, 'init_data': {'current': '0', 'analysis_type': analysis_type}}
if (len(meas_nodes) == 2):
if (analysis_type == 'AC small-signal'):
meas_aliases.extend([f'mag({elem_name})', f'phase({elem_name})'])
else:
meas_aliases.append(elem_name)
elif (elem_type in ['Probe', 'Vnode']):
elem_data = {'name': elem_name, 'nodes': elem_get_nodes(), 'init_data': {'analysis_type': analysis_type}}
elif (elem_json['masks'] and (not (elem_type in ['V_meas', 'I_meas']))):
prop_list = elem_json['masks'][0]['properties']
init_dict = {prop['name']: str(prop['value']) for prop in prop_list}
init_dict.update({'analysis_type': analysis_type})
elem_data = {'name': elem_name, 'nodes': elem_get_nodes(), 'init_data': init_dict}
return (elem_type, elem_data) | def get_elem_data(elem_json):
' '
elem_name = elem_json['name']
elem_type = determine_elem(elem_json['lib_fqn'])
subsys_id = elem_json['parent_comp_id']
prefix_subs =
while subsys_id:
for subsystem in subsys_list:
if (subsystem['id'] == subsys_id):
prefix_subs = ((subsystem['name'] + '.') + prefix_subs)
subsys_id = subsystem['parent_comp_id']
elem_name = (prefix_subs + elem_name)
elem_name = elem_name.replace(' ', '_')
elem_data = {}
def elem_get_nodes():
nonlocal elem_json
nodes_dict = {}
for term in elem_json['terminals']:
for n in node_data:
if (term['id'] in n['terminals']):
nodes_dict.update({term['name']: str(n['id'])})
return nodes_dict
if (elem_type == 'I_meas'):
meas_nodes = elem_get_nodes()
if (len(meas_nodes) == 3):
elem_type = 'I_meas_out'
name = elem_name
else:
name = ('_I_meas__' + elem_name)
elem_data = {'name': name, 'nodes': meas_nodes, 'init_data': {'voltage': '0', 'analysis_type': analysis_type}}
if (len(meas_nodes) == 2):
if (analysis_type == 'AC small-signal'):
meas_aliases.extend([f'mag({elem_name})', f'phase({elem_name})'])
else:
meas_aliases.append(elem_name)
elif (elem_type == 'V_meas'):
meas_nodes = elem_get_nodes()
if (len(meas_nodes) == 3):
elem_type = 'V_meas_out'
name = elem_name
else:
name = ('_V_meas__' + elem_name)
elem_data = {'name': name, 'nodes': meas_nodes, 'init_data': {'current': '0', 'analysis_type': analysis_type}}
if (len(meas_nodes) == 2):
if (analysis_type == 'AC small-signal'):
meas_aliases.extend([f'mag({elem_name})', f'phase({elem_name})'])
else:
meas_aliases.append(elem_name)
elif (elem_type in ['Probe', 'Vnode']):
elem_data = {'name': elem_name, 'nodes': elem_get_nodes(), 'init_data': {'analysis_type': analysis_type}}
elif (elem_json['masks'] and (not (elem_type in ['V_meas', 'I_meas']))):
prop_list = elem_json['masks'][0]['properties']
init_dict = {prop['name']: str(prop['value']) for prop in prop_list}
init_dict.update({'analysis_type': analysis_type})
elem_data = {'name': elem_name, 'nodes': elem_get_nodes(), 'init_data': init_dict}
return (elem_type, elem_data)<|docstring|>Returns the pertinent data of an element in the JSON file.<|endoftext|> |
72eeaf06ee4c1a2a1b393a93efbe5cd920b6c3f1ce0a08c26b7c04c77c36a926 | def __init__(self, can_create_org_repo=None, description=None, includes_all_repositories=None, name=None, permission=None, units=None, units_map=None):
'CreateTeamOption - a model defined in Swagger'
self._can_create_org_repo = None
self._description = None
self._includes_all_repositories = None
self._name = None
self._permission = None
self._units = None
self._units_map = None
self.discriminator = None
if (can_create_org_repo is not None):
self.can_create_org_repo = can_create_org_repo
if (description is not None):
self.description = description
if (includes_all_repositories is not None):
self.includes_all_repositories = includes_all_repositories
self.name = name
if (permission is not None):
self.permission = permission
if (units is not None):
self.units = units
if (units_map is not None):
self.units_map = units_map | CreateTeamOption - a model defined in Swagger | gitea_api/models/create_team_option.py | __init__ | r7l/python-gitea-api | 1 | python | def __init__(self, can_create_org_repo=None, description=None, includes_all_repositories=None, name=None, permission=None, units=None, units_map=None):
self._can_create_org_repo = None
self._description = None
self._includes_all_repositories = None
self._name = None
self._permission = None
self._units = None
self._units_map = None
self.discriminator = None
if (can_create_org_repo is not None):
self.can_create_org_repo = can_create_org_repo
if (description is not None):
self.description = description
if (includes_all_repositories is not None):
self.includes_all_repositories = includes_all_repositories
self.name = name
if (permission is not None):
self.permission = permission
if (units is not None):
self.units = units
if (units_map is not None):
self.units_map = units_map | def __init__(self, can_create_org_repo=None, description=None, includes_all_repositories=None, name=None, permission=None, units=None, units_map=None):
self._can_create_org_repo = None
self._description = None
self._includes_all_repositories = None
self._name = None
self._permission = None
self._units = None
self._units_map = None
self.discriminator = None
if (can_create_org_repo is not None):
self.can_create_org_repo = can_create_org_repo
if (description is not None):
self.description = description
if (includes_all_repositories is not None):
self.includes_all_repositories = includes_all_repositories
self.name = name
if (permission is not None):
self.permission = permission
if (units is not None):
self.units = units
if (units_map is not None):
self.units_map = units_map<|docstring|>CreateTeamOption - a model defined in Swagger<|endoftext|> |
646cb477b1f77163d8b3d27da51437da18430a529fb1a8fd952e0a641c01c37c | @property
def can_create_org_repo(self):
'Gets the can_create_org_repo of this CreateTeamOption. # noqa: E501\n\n\n :return: The can_create_org_repo of this CreateTeamOption. # noqa: E501\n :rtype: bool\n '
return self._can_create_org_repo | Gets the can_create_org_repo of this CreateTeamOption. # noqa: E501
:return: The can_create_org_repo of this CreateTeamOption. # noqa: E501
:rtype: bool | gitea_api/models/create_team_option.py | can_create_org_repo | r7l/python-gitea-api | 1 | python | @property
def can_create_org_repo(self):
'Gets the can_create_org_repo of this CreateTeamOption. # noqa: E501\n\n\n :return: The can_create_org_repo of this CreateTeamOption. # noqa: E501\n :rtype: bool\n '
return self._can_create_org_repo | @property
def can_create_org_repo(self):
'Gets the can_create_org_repo of this CreateTeamOption. # noqa: E501\n\n\n :return: The can_create_org_repo of this CreateTeamOption. # noqa: E501\n :rtype: bool\n '
return self._can_create_org_repo<|docstring|>Gets the can_create_org_repo of this CreateTeamOption. # noqa: E501
:return: The can_create_org_repo of this CreateTeamOption. # noqa: E501
:rtype: bool<|endoftext|> |
707f45224e46dfca7ae408d949313edf052ceb16e108942031108d4f8ec6b407 | @can_create_org_repo.setter
def can_create_org_repo(self, can_create_org_repo):
'Sets the can_create_org_repo of this CreateTeamOption.\n\n\n :param can_create_org_repo: The can_create_org_repo of this CreateTeamOption. # noqa: E501\n :type: bool\n '
self._can_create_org_repo = can_create_org_repo | Sets the can_create_org_repo of this CreateTeamOption.
:param can_create_org_repo: The can_create_org_repo of this CreateTeamOption. # noqa: E501
:type: bool | gitea_api/models/create_team_option.py | can_create_org_repo | r7l/python-gitea-api | 1 | python | @can_create_org_repo.setter
def can_create_org_repo(self, can_create_org_repo):
'Sets the can_create_org_repo of this CreateTeamOption.\n\n\n :param can_create_org_repo: The can_create_org_repo of this CreateTeamOption. # noqa: E501\n :type: bool\n '
self._can_create_org_repo = can_create_org_repo | @can_create_org_repo.setter
def can_create_org_repo(self, can_create_org_repo):
'Sets the can_create_org_repo of this CreateTeamOption.\n\n\n :param can_create_org_repo: The can_create_org_repo of this CreateTeamOption. # noqa: E501\n :type: bool\n '
self._can_create_org_repo = can_create_org_repo<|docstring|>Sets the can_create_org_repo of this CreateTeamOption.
:param can_create_org_repo: The can_create_org_repo of this CreateTeamOption. # noqa: E501
:type: bool<|endoftext|> |
3f975bd4be1c334722cf078b7b1cd2a15878f959bea6438ae66716e69eceb0db | @property
def description(self):
'Gets the description of this CreateTeamOption. # noqa: E501\n\n\n :return: The description of this CreateTeamOption. # noqa: E501\n :rtype: str\n '
return self._description | Gets the description of this CreateTeamOption. # noqa: E501
:return: The description of this CreateTeamOption. # noqa: E501
:rtype: str | gitea_api/models/create_team_option.py | description | r7l/python-gitea-api | 1 | python | @property
def description(self):
'Gets the description of this CreateTeamOption. # noqa: E501\n\n\n :return: The description of this CreateTeamOption. # noqa: E501\n :rtype: str\n '
return self._description | @property
def description(self):
'Gets the description of this CreateTeamOption. # noqa: E501\n\n\n :return: The description of this CreateTeamOption. # noqa: E501\n :rtype: str\n '
return self._description<|docstring|>Gets the description of this CreateTeamOption. # noqa: E501
:return: The description of this CreateTeamOption. # noqa: E501
:rtype: str<|endoftext|> |
9b8a5958412c0dc1b8b9daff49c4e243b3a651f5bf85fae5420a7a15e43652fc | @description.setter
def description(self, description):
'Sets the description of this CreateTeamOption.\n\n\n :param description: The description of this CreateTeamOption. # noqa: E501\n :type: str\n '
self._description = description | Sets the description of this CreateTeamOption.
:param description: The description of this CreateTeamOption. # noqa: E501
:type: str | gitea_api/models/create_team_option.py | description | r7l/python-gitea-api | 1 | python | @description.setter
def description(self, description):
'Sets the description of this CreateTeamOption.\n\n\n :param description: The description of this CreateTeamOption. # noqa: E501\n :type: str\n '
self._description = description | @description.setter
def description(self, description):
'Sets the description of this CreateTeamOption.\n\n\n :param description: The description of this CreateTeamOption. # noqa: E501\n :type: str\n '
self._description = description<|docstring|>Sets the description of this CreateTeamOption.
:param description: The description of this CreateTeamOption. # noqa: E501
:type: str<|endoftext|> |
82d1523edc0b13080a91d10205a5bd3b903a4875393fee6361fbed95fecf494b | @property
def includes_all_repositories(self):
'Gets the includes_all_repositories of this CreateTeamOption. # noqa: E501\n\n\n :return: The includes_all_repositories of this CreateTeamOption. # noqa: E501\n :rtype: bool\n '
return self._includes_all_repositories | Gets the includes_all_repositories of this CreateTeamOption. # noqa: E501
:return: The includes_all_repositories of this CreateTeamOption. # noqa: E501
:rtype: bool | gitea_api/models/create_team_option.py | includes_all_repositories | r7l/python-gitea-api | 1 | python | @property
def includes_all_repositories(self):
'Gets the includes_all_repositories of this CreateTeamOption. # noqa: E501\n\n\n :return: The includes_all_repositories of this CreateTeamOption. # noqa: E501\n :rtype: bool\n '
return self._includes_all_repositories | @property
def includes_all_repositories(self):
'Gets the includes_all_repositories of this CreateTeamOption. # noqa: E501\n\n\n :return: The includes_all_repositories of this CreateTeamOption. # noqa: E501\n :rtype: bool\n '
return self._includes_all_repositories<|docstring|>Gets the includes_all_repositories of this CreateTeamOption. # noqa: E501
:return: The includes_all_repositories of this CreateTeamOption. # noqa: E501
:rtype: bool<|endoftext|> |
b6f443d99b3d9999d5730462a789939f6dfaf7700e97bb7e34379e8f105567a2 | @includes_all_repositories.setter
def includes_all_repositories(self, includes_all_repositories):
'Sets the includes_all_repositories of this CreateTeamOption.\n\n\n :param includes_all_repositories: The includes_all_repositories of this CreateTeamOption. # noqa: E501\n :type: bool\n '
self._includes_all_repositories = includes_all_repositories | Sets the includes_all_repositories of this CreateTeamOption.
:param includes_all_repositories: The includes_all_repositories of this CreateTeamOption. # noqa: E501
:type: bool | gitea_api/models/create_team_option.py | includes_all_repositories | r7l/python-gitea-api | 1 | python | @includes_all_repositories.setter
def includes_all_repositories(self, includes_all_repositories):
'Sets the includes_all_repositories of this CreateTeamOption.\n\n\n :param includes_all_repositories: The includes_all_repositories of this CreateTeamOption. # noqa: E501\n :type: bool\n '
self._includes_all_repositories = includes_all_repositories | @includes_all_repositories.setter
def includes_all_repositories(self, includes_all_repositories):
'Sets the includes_all_repositories of this CreateTeamOption.\n\n\n :param includes_all_repositories: The includes_all_repositories of this CreateTeamOption. # noqa: E501\n :type: bool\n '
self._includes_all_repositories = includes_all_repositories<|docstring|>Sets the includes_all_repositories of this CreateTeamOption.
:param includes_all_repositories: The includes_all_repositories of this CreateTeamOption. # noqa: E501
:type: bool<|endoftext|> |
defc9c7a66ab6c04c792205daaa27ff4b4ec5bcfb417dba1fac2b2771da43b04 | @property
def name(self):
'Gets the name of this CreateTeamOption. # noqa: E501\n\n\n :return: The name of this CreateTeamOption. # noqa: E501\n :rtype: str\n '
return self._name | Gets the name of this CreateTeamOption. # noqa: E501
:return: The name of this CreateTeamOption. # noqa: E501
:rtype: str | gitea_api/models/create_team_option.py | name | r7l/python-gitea-api | 1 | python | @property
def name(self):
'Gets the name of this CreateTeamOption. # noqa: E501\n\n\n :return: The name of this CreateTeamOption. # noqa: E501\n :rtype: str\n '
return self._name | @property
def name(self):
'Gets the name of this CreateTeamOption. # noqa: E501\n\n\n :return: The name of this CreateTeamOption. # noqa: E501\n :rtype: str\n '
return self._name<|docstring|>Gets the name of this CreateTeamOption. # noqa: E501
:return: The name of this CreateTeamOption. # noqa: E501
:rtype: str<|endoftext|> |
b35aba3c83df61e1fff254fbf5905144f78d42b1959359aed52bc42cc9b7bb97 | @name.setter
def name(self, name):
'Sets the name of this CreateTeamOption.\n\n\n :param name: The name of this CreateTeamOption. # noqa: E501\n :type: str\n '
if (name is None):
raise ValueError('Invalid value for `name`, must not be `None`')
self._name = name | Sets the name of this CreateTeamOption.
:param name: The name of this CreateTeamOption. # noqa: E501
:type: str | gitea_api/models/create_team_option.py | name | r7l/python-gitea-api | 1 | python | @name.setter
def name(self, name):
'Sets the name of this CreateTeamOption.\n\n\n :param name: The name of this CreateTeamOption. # noqa: E501\n :type: str\n '
if (name is None):
raise ValueError('Invalid value for `name`, must not be `None`')
self._name = name | @name.setter
def name(self, name):
'Sets the name of this CreateTeamOption.\n\n\n :param name: The name of this CreateTeamOption. # noqa: E501\n :type: str\n '
if (name is None):
raise ValueError('Invalid value for `name`, must not be `None`')
self._name = name<|docstring|>Sets the name of this CreateTeamOption.
:param name: The name of this CreateTeamOption. # noqa: E501
:type: str<|endoftext|> |
6a81ba9afcd3abb0189d7b8a9e09331e1a56703b52afed530c0f5f3735f9e7a1 | @property
def permission(self):
'Gets the permission of this CreateTeamOption. # noqa: E501\n\n\n :return: The permission of this CreateTeamOption. # noqa: E501\n :rtype: str\n '
return self._permission | Gets the permission of this CreateTeamOption. # noqa: E501
:return: The permission of this CreateTeamOption. # noqa: E501
:rtype: str | gitea_api/models/create_team_option.py | permission | r7l/python-gitea-api | 1 | python | @property
def permission(self):
'Gets the permission of this CreateTeamOption. # noqa: E501\n\n\n :return: The permission of this CreateTeamOption. # noqa: E501\n :rtype: str\n '
return self._permission | @property
def permission(self):
'Gets the permission of this CreateTeamOption. # noqa: E501\n\n\n :return: The permission of this CreateTeamOption. # noqa: E501\n :rtype: str\n '
return self._permission<|docstring|>Gets the permission of this CreateTeamOption. # noqa: E501
:return: The permission of this CreateTeamOption. # noqa: E501
:rtype: str<|endoftext|> |
3bc1853fef12088daff733b524650aa40f7dd251d8df07b46fb3478d411dd05e | @permission.setter
def permission(self, permission):
'Sets the permission of this CreateTeamOption.\n\n\n :param permission: The permission of this CreateTeamOption. # noqa: E501\n :type: str\n '
allowed_values = ['read', 'write', 'admin']
if (permission not in allowed_values):
raise ValueError('Invalid value for `permission` ({0}), must be one of {1}'.format(permission, allowed_values))
self._permission = permission | Sets the permission of this CreateTeamOption.
:param permission: The permission of this CreateTeamOption. # noqa: E501
:type: str | gitea_api/models/create_team_option.py | permission | r7l/python-gitea-api | 1 | python | @permission.setter
def permission(self, permission):
'Sets the permission of this CreateTeamOption.\n\n\n :param permission: The permission of this CreateTeamOption. # noqa: E501\n :type: str\n '
allowed_values = ['read', 'write', 'admin']
if (permission not in allowed_values):
raise ValueError('Invalid value for `permission` ({0}), must be one of {1}'.format(permission, allowed_values))
self._permission = permission | @permission.setter
def permission(self, permission):
'Sets the permission of this CreateTeamOption.\n\n\n :param permission: The permission of this CreateTeamOption. # noqa: E501\n :type: str\n '
allowed_values = ['read', 'write', 'admin']
if (permission not in allowed_values):
raise ValueError('Invalid value for `permission` ({0}), must be one of {1}'.format(permission, allowed_values))
self._permission = permission<|docstring|>Sets the permission of this CreateTeamOption.
:param permission: The permission of this CreateTeamOption. # noqa: E501
:type: str<|endoftext|> |
698d3a4c5f5ff23cc40a30bd5aedd4c856b9d8de3510b737212a50475cd89fa3 | @property
def units(self):
'Gets the units of this CreateTeamOption. # noqa: E501\n\n\n :return: The units of this CreateTeamOption. # noqa: E501\n :rtype: list[str]\n '
return self._units | Gets the units of this CreateTeamOption. # noqa: E501
:return: The units of this CreateTeamOption. # noqa: E501
:rtype: list[str] | gitea_api/models/create_team_option.py | units | r7l/python-gitea-api | 1 | python | @property
def units(self):
'Gets the units of this CreateTeamOption. # noqa: E501\n\n\n :return: The units of this CreateTeamOption. # noqa: E501\n :rtype: list[str]\n '
return self._units | @property
def units(self):
'Gets the units of this CreateTeamOption. # noqa: E501\n\n\n :return: The units of this CreateTeamOption. # noqa: E501\n :rtype: list[str]\n '
return self._units<|docstring|>Gets the units of this CreateTeamOption. # noqa: E501
:return: The units of this CreateTeamOption. # noqa: E501
:rtype: list[str]<|endoftext|> |
91685fa4456d06b47707f95f4dad796bcba5ccba5c9865374852f7155544e2c1 | @units.setter
def units(self, units):
'Sets the units of this CreateTeamOption.\n\n\n :param units: The units of this CreateTeamOption. # noqa: E501\n :type: list[str]\n '
self._units = units | Sets the units of this CreateTeamOption.
:param units: The units of this CreateTeamOption. # noqa: E501
:type: list[str] | gitea_api/models/create_team_option.py | units | r7l/python-gitea-api | 1 | python | @units.setter
def units(self, units):
'Sets the units of this CreateTeamOption.\n\n\n :param units: The units of this CreateTeamOption. # noqa: E501\n :type: list[str]\n '
self._units = units | @units.setter
def units(self, units):
'Sets the units of this CreateTeamOption.\n\n\n :param units: The units of this CreateTeamOption. # noqa: E501\n :type: list[str]\n '
self._units = units<|docstring|>Sets the units of this CreateTeamOption.
:param units: The units of this CreateTeamOption. # noqa: E501
:type: list[str]<|endoftext|> |
8ff038e25095e6b42f2535573b9fdf956b7a45d86a9871e9a7a83da5b35c33b5 | @property
def units_map(self):
'Gets the units_map of this CreateTeamOption. # noqa: E501\n\n\n :return: The units_map of this CreateTeamOption. # noqa: E501\n :rtype: dict(str, str)\n '
return self._units_map | Gets the units_map of this CreateTeamOption. # noqa: E501
:return: The units_map of this CreateTeamOption. # noqa: E501
:rtype: dict(str, str) | gitea_api/models/create_team_option.py | units_map | r7l/python-gitea-api | 1 | python | @property
def units_map(self):
'Gets the units_map of this CreateTeamOption. # noqa: E501\n\n\n :return: The units_map of this CreateTeamOption. # noqa: E501\n :rtype: dict(str, str)\n '
return self._units_map | @property
def units_map(self):
'Gets the units_map of this CreateTeamOption. # noqa: E501\n\n\n :return: The units_map of this CreateTeamOption. # noqa: E501\n :rtype: dict(str, str)\n '
return self._units_map<|docstring|>Gets the units_map of this CreateTeamOption. # noqa: E501
:return: The units_map of this CreateTeamOption. # noqa: E501
:rtype: dict(str, str)<|endoftext|> |
79f8ce374b270f55d3d7c9a1ae1a49da98f496d22e66238281ead5eacf4aaf92 | @units_map.setter
def units_map(self, units_map):
'Sets the units_map of this CreateTeamOption.\n\n\n :param units_map: The units_map of this CreateTeamOption. # noqa: E501\n :type: dict(str, str)\n '
self._units_map = units_map | Sets the units_map of this CreateTeamOption.
:param units_map: The units_map of this CreateTeamOption. # noqa: E501
:type: dict(str, str) | gitea_api/models/create_team_option.py | units_map | r7l/python-gitea-api | 1 | python | @units_map.setter
def units_map(self, units_map):
'Sets the units_map of this CreateTeamOption.\n\n\n :param units_map: The units_map of this CreateTeamOption. # noqa: E501\n :type: dict(str, str)\n '
self._units_map = units_map | @units_map.setter
def units_map(self, units_map):
'Sets the units_map of this CreateTeamOption.\n\n\n :param units_map: The units_map of this CreateTeamOption. # noqa: E501\n :type: dict(str, str)\n '
self._units_map = units_map<|docstring|>Sets the units_map of this CreateTeamOption.
:param units_map: The units_map of this CreateTeamOption. # noqa: E501
:type: dict(str, str)<|endoftext|> |
133d07253021e58dd0c751d7b560e1879a3a7aed5c6d05903fc91921508e6b9d | def to_dict(self):
'Returns the model properties as a dict'
result = {}
for (attr, _) in six.iteritems(self.swagger_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map((lambda x: (x.to_dict() if hasattr(x, 'to_dict') else x)), value))
elif hasattr(value, 'to_dict'):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map((lambda item: ((item[0], item[1].to_dict()) if hasattr(item[1], 'to_dict') else item)), value.items()))
else:
result[attr] = value
if issubclass(CreateTeamOption, dict):
for (key, value) in self.items():
result[key] = value
return result | Returns the model properties as a dict | gitea_api/models/create_team_option.py | to_dict | r7l/python-gitea-api | 1 | python | def to_dict(self):
result = {}
for (attr, _) in six.iteritems(self.swagger_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map((lambda x: (x.to_dict() if hasattr(x, 'to_dict') else x)), value))
elif hasattr(value, 'to_dict'):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map((lambda item: ((item[0], item[1].to_dict()) if hasattr(item[1], 'to_dict') else item)), value.items()))
else:
result[attr] = value
if issubclass(CreateTeamOption, dict):
for (key, value) in self.items():
result[key] = value
return result | def to_dict(self):
result = {}
for (attr, _) in six.iteritems(self.swagger_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map((lambda x: (x.to_dict() if hasattr(x, 'to_dict') else x)), value))
elif hasattr(value, 'to_dict'):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map((lambda item: ((item[0], item[1].to_dict()) if hasattr(item[1], 'to_dict') else item)), value.items()))
else:
result[attr] = value
if issubclass(CreateTeamOption, dict):
for (key, value) in self.items():
result[key] = value
return result<|docstring|>Returns the model properties as a dict<|endoftext|> |
cbb19eaa2fc8a113d9e32f924ef280a7e97563f8915f94f65dab438997af2e99 | def to_str(self):
'Returns the string representation of the model'
return pprint.pformat(self.to_dict()) | Returns the string representation of the model | gitea_api/models/create_team_option.py | to_str | r7l/python-gitea-api | 1 | python | def to_str(self):
return pprint.pformat(self.to_dict()) | def to_str(self):
return pprint.pformat(self.to_dict())<|docstring|>Returns the string representation of the model<|endoftext|> |
772243a2c2b3261a9b954d07aaf295e3c1242a579a495e2d6a5679c677861703 | def __repr__(self):
'For `print` and `pprint`'
return self.to_str() | For `print` and `pprint` | gitea_api/models/create_team_option.py | __repr__ | r7l/python-gitea-api | 1 | python | def __repr__(self):
return self.to_str() | def __repr__(self):
return self.to_str()<|docstring|>For `print` and `pprint`<|endoftext|> |
27dd825cf10318461eca4c81d361261d60d5bc597838d4ae0a20acac5602f7d5 | def __eq__(self, other):
'Returns true if both objects are equal'
if (not isinstance(other, CreateTeamOption)):
return False
return (self.__dict__ == other.__dict__) | Returns true if both objects are equal | gitea_api/models/create_team_option.py | __eq__ | r7l/python-gitea-api | 1 | python | def __eq__(self, other):
if (not isinstance(other, CreateTeamOption)):
return False
return (self.__dict__ == other.__dict__) | def __eq__(self, other):
if (not isinstance(other, CreateTeamOption)):
return False
return (self.__dict__ == other.__dict__)<|docstring|>Returns true if both objects are equal<|endoftext|> |
43dc6740163eb9fc1161d09cb2208a64c7ad0cc8d9c8637ac3264522d3ec7e42 | def __ne__(self, other):
'Returns true if both objects are not equal'
return (not (self == other)) | Returns true if both objects are not equal | gitea_api/models/create_team_option.py | __ne__ | r7l/python-gitea-api | 1 | python | def __ne__(self, other):
return (not (self == other)) | def __ne__(self, other):
return (not (self == other))<|docstring|>Returns true if both objects are not equal<|endoftext|> |
85a958edfae2244d7a0c5fb014e90393a546f8c52012cf2197730b63263a9a02 | def static_scan(fn, inputs, start, reverse=False):
'drop-in replacement for tf.scan.\n\n tf.scan has some issues with multiple devices.\n '
last = start
outputs = [[] for _ in tf.nest.flatten(start)]
indices = range(tf.nest.flatten(inputs)[0].shape[0])
if reverse:
indices = reversed(indices)
for index in indices:
inp = tf.nest.map_structure((lambda x: x[index]), inputs)
last = fn(last, inp)
[o.append(l) for (o, l) in zip(outputs, tf.nest.flatten(last))]
if reverse:
outputs = [list(reversed(x)) for x in outputs]
outputs = [tf.stack(x, 0) for x in outputs]
return tf.nest.pack_sequence_as(start, outputs) | drop-in replacement for tf.scan.
tf.scan has some issues with multiple devices. | planners/planners.py | static_scan | pacificlion/world_models | 106 | python | def static_scan(fn, inputs, start, reverse=False):
'drop-in replacement for tf.scan.\n\n tf.scan has some issues with multiple devices.\n '
last = start
outputs = [[] for _ in tf.nest.flatten(start)]
indices = range(tf.nest.flatten(inputs)[0].shape[0])
if reverse:
indices = reversed(indices)
for index in indices:
inp = tf.nest.map_structure((lambda x: x[index]), inputs)
last = fn(last, inp)
[o.append(l) for (o, l) in zip(outputs, tf.nest.flatten(last))]
if reverse:
outputs = [list(reversed(x)) for x in outputs]
outputs = [tf.stack(x, 0) for x in outputs]
return tf.nest.pack_sequence_as(start, outputs) | def static_scan(fn, inputs, start, reverse=False):
'drop-in replacement for tf.scan.\n\n tf.scan has some issues with multiple devices.\n '
last = start
outputs = [[] for _ in tf.nest.flatten(start)]
indices = range(tf.nest.flatten(inputs)[0].shape[0])
if reverse:
indices = reversed(indices)
for index in indices:
inp = tf.nest.map_structure((lambda x: x[index]), inputs)
last = fn(last, inp)
[o.append(l) for (o, l) in zip(outputs, tf.nest.flatten(last))]
if reverse:
outputs = [list(reversed(x)) for x in outputs]
outputs = [tf.stack(x, 0) for x in outputs]
return tf.nest.pack_sequence_as(start, outputs)<|docstring|>drop-in replacement for tf.scan.
tf.scan has some issues with multiple devices.<|endoftext|> |
d8326affeb5a1adfc3690a47f295fc4ed3a69b3c41ade98ba181dc0bf59fd5b9 | def __init__(self, predict_fn: Callable[([np.ndarray, Any], Dict[(Text, np.ndarray)])], observe_fn: Callable[([np.ndarray, np.ndarray, np.ndarray, Any], Any)], reset_fn: Callable[([Any, int], Any)], task: tasks.Task, objective_fn: Callable[([Dict[(Text, np.ndarray)]], np.ndarray)], horizon: int, iterations: int, proposals: int, fraction: float, weighted: bool=False):
'Initialize a CEM planner that queries a world model.\n\n Args:\n predict_fn: a callable with the following positional arguments:\n * planned_actions: a [batch, steps, action_dims] ndarray\n * state: the state object returned from observe_fn.\n This method is expected to return:\n * predictions: a dictionary with possibly the following entries:\n * "image": [batch, steps, height, width, channels] ndarray of the\n model predictions of the state of the world conditioned actions.\n * "reward": [batch, steps, 1] ndarray of the reward predictions.\n observe_fn: a callable with the following positional arguments:\n * last_images: a [batch, steps, height, width, channels] ndarray\n * last_actions: a [batch, steps, action_dims] ndarray\n * last_reward: a [batch, steps, 1] ndarray\n * state: the previously returned `state`.\n This method is expected to return:\n * state: Anything the model needs to continue predicting current\n episode.\n reset_fn: a callable with the following keyword arguments:\n * state: the state object\n * proposals: the number of proposals.\n This method is expected to return:\n * state: the new state with cleared history.\n task: The task of type `tasks.Task`.\n objective_fn: a callable with the following positional arguments:\n * predictions: a dictionary possibly containing "image" and "reward"\n that will come from the `predict_fn`\n This method is expected to return:\n * rewards: a [batch, steps, 1] ndarray of containing scalar rewards.\n horizon: the planning horizon to specify how many steps into the future to\n consider for choosing the right plan.\n iterations: How many iterations to estimate the final distribution.\n proposals: How many proposals to consider in each iteration.\n fraction: The percentage of proposals to select with the highest score to\n fit the distribution.\n weighted: fit distribution by weighting proposals with their predicted\n rewards.\n '
super(CEM, self).__init__()
self._action_space = task.create_env().action_space
self._objective_fn = objective_fn
self._predict_fn = predict_fn
self._observe_fn = observe_fn
self._reset_fn = reset_fn
self._horizon = horizon
self._iterations = iterations
self._proposals = proposals
self._fraction = fraction
self._weighted = weighted
self._state = {} | Initialize a CEM planner that queries a world model.
Args:
predict_fn: a callable with the following positional arguments:
* planned_actions: a [batch, steps, action_dims] ndarray
* state: the state object returned from observe_fn.
This method is expected to return:
* predictions: a dictionary with possibly the following entries:
* "image": [batch, steps, height, width, channels] ndarray of the
model predictions of the state of the world conditioned actions.
* "reward": [batch, steps, 1] ndarray of the reward predictions.
observe_fn: a callable with the following positional arguments:
* last_images: a [batch, steps, height, width, channels] ndarray
* last_actions: a [batch, steps, action_dims] ndarray
* last_reward: a [batch, steps, 1] ndarray
* state: the previously returned `state`.
This method is expected to return:
* state: Anything the model needs to continue predicting current
episode.
reset_fn: a callable with the following keyword arguments:
* state: the state object
* proposals: the number of proposals.
This method is expected to return:
* state: the new state with cleared history.
task: The task of type `tasks.Task`.
objective_fn: a callable with the following positional arguments:
* predictions: a dictionary possibly containing "image" and "reward"
that will come from the `predict_fn`
This method is expected to return:
* rewards: a [batch, steps, 1] ndarray of containing scalar rewards.
horizon: the planning horizon to specify how many steps into the future to
consider for choosing the right plan.
iterations: How many iterations to estimate the final distribution.
proposals: How many proposals to consider in each iteration.
fraction: The percentage of proposals to select with the highest score to
fit the distribution.
weighted: fit distribution by weighting proposals with their predicted
rewards. | planners/planners.py | __init__ | pacificlion/world_models | 106 | python | def __init__(self, predict_fn: Callable[([np.ndarray, Any], Dict[(Text, np.ndarray)])], observe_fn: Callable[([np.ndarray, np.ndarray, np.ndarray, Any], Any)], reset_fn: Callable[([Any, int], Any)], task: tasks.Task, objective_fn: Callable[([Dict[(Text, np.ndarray)]], np.ndarray)], horizon: int, iterations: int, proposals: int, fraction: float, weighted: bool=False):
'Initialize a CEM planner that queries a world model.\n\n Args:\n predict_fn: a callable with the following positional arguments:\n * planned_actions: a [batch, steps, action_dims] ndarray\n * state: the state object returned from observe_fn.\n This method is expected to return:\n * predictions: a dictionary with possibly the following entries:\n * "image": [batch, steps, height, width, channels] ndarray of the\n model predictions of the state of the world conditioned actions.\n * "reward": [batch, steps, 1] ndarray of the reward predictions.\n observe_fn: a callable with the following positional arguments:\n * last_images: a [batch, steps, height, width, channels] ndarray\n * last_actions: a [batch, steps, action_dims] ndarray\n * last_reward: a [batch, steps, 1] ndarray\n * state: the previously returned `state`.\n This method is expected to return:\n * state: Anything the model needs to continue predicting current\n episode.\n reset_fn: a callable with the following keyword arguments:\n * state: the state object\n * proposals: the number of proposals.\n This method is expected to return:\n * state: the new state with cleared history.\n task: The task of type `tasks.Task`.\n objective_fn: a callable with the following positional arguments:\n * predictions: a dictionary possibly containing "image" and "reward"\n that will come from the `predict_fn`\n This method is expected to return:\n * rewards: a [batch, steps, 1] ndarray of containing scalar rewards.\n horizon: the planning horizon to specify how many steps into the future to\n consider for choosing the right plan.\n iterations: How many iterations to estimate the final distribution.\n proposals: How many proposals to consider in each iteration.\n fraction: The percentage of proposals to select with the highest score to\n fit the distribution.\n weighted: fit distribution by weighting proposals with their predicted\n rewards.\n '
super(CEM, self).__init__()
self._action_space = task.create_env().action_space
self._objective_fn = objective_fn
self._predict_fn = predict_fn
self._observe_fn = observe_fn
self._reset_fn = reset_fn
self._horizon = horizon
self._iterations = iterations
self._proposals = proposals
self._fraction = fraction
self._weighted = weighted
self._state = {} | def __init__(self, predict_fn: Callable[([np.ndarray, Any], Dict[(Text, np.ndarray)])], observe_fn: Callable[([np.ndarray, np.ndarray, np.ndarray, Any], Any)], reset_fn: Callable[([Any, int], Any)], task: tasks.Task, objective_fn: Callable[([Dict[(Text, np.ndarray)]], np.ndarray)], horizon: int, iterations: int, proposals: int, fraction: float, weighted: bool=False):
'Initialize a CEM planner that queries a world model.\n\n Args:\n predict_fn: a callable with the following positional arguments:\n * planned_actions: a [batch, steps, action_dims] ndarray\n * state: the state object returned from observe_fn.\n This method is expected to return:\n * predictions: a dictionary with possibly the following entries:\n * "image": [batch, steps, height, width, channels] ndarray of the\n model predictions of the state of the world conditioned actions.\n * "reward": [batch, steps, 1] ndarray of the reward predictions.\n observe_fn: a callable with the following positional arguments:\n * last_images: a [batch, steps, height, width, channels] ndarray\n * last_actions: a [batch, steps, action_dims] ndarray\n * last_reward: a [batch, steps, 1] ndarray\n * state: the previously returned `state`.\n This method is expected to return:\n * state: Anything the model needs to continue predicting current\n episode.\n reset_fn: a callable with the following keyword arguments:\n * state: the state object\n * proposals: the number of proposals.\n This method is expected to return:\n * state: the new state with cleared history.\n task: The task of type `tasks.Task`.\n objective_fn: a callable with the following positional arguments:\n * predictions: a dictionary possibly containing "image" and "reward"\n that will come from the `predict_fn`\n This method is expected to return:\n * rewards: a [batch, steps, 1] ndarray of containing scalar rewards.\n horizon: the planning horizon to specify how many steps into the future to\n consider for choosing the right plan.\n iterations: How many iterations to estimate the final distribution.\n proposals: How many proposals to consider in each iteration.\n fraction: The percentage of proposals to select with the highest score to\n fit the distribution.\n weighted: fit distribution by weighting proposals with their predicted\n rewards.\n '
super(CEM, self).__init__()
self._action_space = task.create_env().action_space
self._objective_fn = objective_fn
self._predict_fn = predict_fn
self._observe_fn = observe_fn
self._reset_fn = reset_fn
self._horizon = horizon
self._iterations = iterations
self._proposals = proposals
self._fraction = fraction
self._weighted = weighted
self._state = {}<|docstring|>Initialize a CEM planner that queries a world model.
Args:
predict_fn: a callable with the following positional arguments:
* planned_actions: a [batch, steps, action_dims] ndarray
* state: the state object returned from observe_fn.
This method is expected to return:
* predictions: a dictionary with possibly the following entries:
* "image": [batch, steps, height, width, channels] ndarray of the
model predictions of the state of the world conditioned actions.
* "reward": [batch, steps, 1] ndarray of the reward predictions.
observe_fn: a callable with the following positional arguments:
* last_images: a [batch, steps, height, width, channels] ndarray
* last_actions: a [batch, steps, action_dims] ndarray
* last_reward: a [batch, steps, 1] ndarray
* state: the previously returned `state`.
This method is expected to return:
* state: Anything the model needs to continue predicting current
episode.
reset_fn: a callable with the following keyword arguments:
* state: the state object
* proposals: the number of proposals.
This method is expected to return:
* state: the new state with cleared history.
task: The task of type `tasks.Task`.
objective_fn: a callable with the following positional arguments:
* predictions: a dictionary possibly containing "image" and "reward"
that will come from the `predict_fn`
This method is expected to return:
* rewards: a [batch, steps, 1] ndarray of containing scalar rewards.
horizon: the planning horizon to specify how many steps into the future to
consider for choosing the right plan.
iterations: How many iterations to estimate the final distribution.
proposals: How many proposals to consider in each iteration.
fraction: The percentage of proposals to select with the highest score to
fit the distribution.
weighted: fit distribution by weighting proposals with their predicted
rewards.<|endoftext|> |
65915836d57a71f3853f075a79d6e2e8d87f2c477e3a6da720f09cb4061e7337 | def initialize_distribution(self):
'Returns initial distribution for action space.'
if self.is_discrete:
n = self._action_space.n
return ([([(1.0 / n)] * n)] * self._horizon)
else:
means = ([((self._action_space.high + self._action_space.low) / 2.0)] * self._horizon)
covs = ([np.diag(((self._action_space.high - self._action_space.low) / 2.0))] * self._horizon)
return (means, covs) | Returns initial distribution for action space. | planners/planners.py | initialize_distribution | pacificlion/world_models | 106 | python | def initialize_distribution(self):
if self.is_discrete:
n = self._action_space.n
return ([([(1.0 / n)] * n)] * self._horizon)
else:
means = ([((self._action_space.high + self._action_space.low) / 2.0)] * self._horizon)
covs = ([np.diag(((self._action_space.high - self._action_space.low) / 2.0))] * self._horizon)
return (means, covs) | def initialize_distribution(self):
if self.is_discrete:
n = self._action_space.n
return ([([(1.0 / n)] * n)] * self._horizon)
else:
means = ([((self._action_space.high + self._action_space.low) / 2.0)] * self._horizon)
covs = ([np.diag(((self._action_space.high - self._action_space.low) / 2.0))] * self._horizon)
return (means, covs)<|docstring|>Returns initial distribution for action space.<|endoftext|> |
194bd552dad6a4290069547a51431cc1394da6abd5b0e38b66389d0996a8e86f | def _sample_continuous_actions(self, means, covs):
'Samples actions from a multivariate Gaussian.'
all_actions = []
for (mean, cov) in zip(means, covs):
actions = np.random.multivariate_normal(mean, cov, (self._proposals,))
actions = np.clip(actions, self._action_space.low, self._action_space.high)
actions = actions.astype(np.float32)
all_actions.extend([actions])
all_actions = np.array(all_actions)
traj_proposals = np.transpose(all_actions, (1, 0, 2))
return traj_proposals | Samples actions from a multivariate Gaussian. | planners/planners.py | _sample_continuous_actions | pacificlion/world_models | 106 | python | def _sample_continuous_actions(self, means, covs):
all_actions = []
for (mean, cov) in zip(means, covs):
actions = np.random.multivariate_normal(mean, cov, (self._proposals,))
actions = np.clip(actions, self._action_space.low, self._action_space.high)
actions = actions.astype(np.float32)
all_actions.extend([actions])
all_actions = np.array(all_actions)
traj_proposals = np.transpose(all_actions, (1, 0, 2))
return traj_proposals | def _sample_continuous_actions(self, means, covs):
all_actions = []
for (mean, cov) in zip(means, covs):
actions = np.random.multivariate_normal(mean, cov, (self._proposals,))
actions = np.clip(actions, self._action_space.low, self._action_space.high)
actions = actions.astype(np.float32)
all_actions.extend([actions])
all_actions = np.array(all_actions)
traj_proposals = np.transpose(all_actions, (1, 0, 2))
return traj_proposals<|docstring|>Samples actions from a multivariate Gaussian.<|endoftext|> |
189596ab5855ab21640b48b4793e5f4fa28b2221552eb315a982e872bd23f432 | def _sample_discrete_actions(self, pvals):
'Samples actions from multinomial.'
all_actions = []
for pval in pvals:
actions = np.random.multinomial(n=1, pvals=pval, size=(self._proposals,))
actions = np.expand_dims(np.argmax(actions, axis=1), axis=(- 1))
actions = actions.astype(np.int32)
all_actions.append(actions)
all_actions = np.array(all_actions)
traj_proposals = np.transpose(all_actions, (1, 0, 2))
return traj_proposals | Samples actions from multinomial. | planners/planners.py | _sample_discrete_actions | pacificlion/world_models | 106 | python | def _sample_discrete_actions(self, pvals):
all_actions = []
for pval in pvals:
actions = np.random.multinomial(n=1, pvals=pval, size=(self._proposals,))
actions = np.expand_dims(np.argmax(actions, axis=1), axis=(- 1))
actions = actions.astype(np.int32)
all_actions.append(actions)
all_actions = np.array(all_actions)
traj_proposals = np.transpose(all_actions, (1, 0, 2))
return traj_proposals | def _sample_discrete_actions(self, pvals):
all_actions = []
for pval in pvals:
actions = np.random.multinomial(n=1, pvals=pval, size=(self._proposals,))
actions = np.expand_dims(np.argmax(actions, axis=1), axis=(- 1))
actions = actions.astype(np.int32)
all_actions.append(actions)
all_actions = np.array(all_actions)
traj_proposals = np.transpose(all_actions, (1, 0, 2))
return traj_proposals<|docstring|>Samples actions from multinomial.<|endoftext|> |
f30f331ea6e020b4d8e29dbcc517853bebf1c843c38dfcecdce193f2922131eb | def generate_rewards(self, traj_proposals):
'Given a set of actions, outputs the corresponding rewards.'
predictions = self._predict_fn(traj_proposals, self._state)
traj_rewards = self._objective_fn(predictions)
return (traj_rewards, predictions) | Given a set of actions, outputs the corresponding rewards. | planners/planners.py | generate_rewards | pacificlion/world_models | 106 | python | def generate_rewards(self, traj_proposals):
predictions = self._predict_fn(traj_proposals, self._state)
traj_rewards = self._objective_fn(predictions)
return (traj_rewards, predictions) | def generate_rewards(self, traj_proposals):
predictions = self._predict_fn(traj_proposals, self._state)
traj_rewards = self._objective_fn(predictions)
return (traj_rewards, predictions)<|docstring|>Given a set of actions, outputs the corresponding rewards.<|endoftext|> |
3f45f0a6d29e6a7fb0b205c7799309280a81548d526b4ee0bcaa2f8e3cf366ea | def _fit_gaussian(self, rewards, traj_proposals):
'Re-fits a Gaussian to the best actions.'
top_k = int((self._fraction * self._proposals))
indices = np.squeeze(np.argpartition(rewards, (- top_k), axis=0), axis=(- 1))[(- top_k):]
best_trajectories = traj_proposals[indices]
if self._weighted:
weights = rewards.numpy()[(indices, 0)]
else:
weights = np.ones_like(rewards[(indices, 0)])
actions_to_fit = np.transpose(best_trajectories[(0:top_k, 0:self._horizon)], (1, 0, 2))
means = []
covs = []
for i in range(self._horizon):
means.append(np.average(actions_to_fit[i], weights=weights, axis=0))
covs.append(np.cov(actions_to_fit[i].T, aweights=weights))
return (means, covs) | Re-fits a Gaussian to the best actions. | planners/planners.py | _fit_gaussian | pacificlion/world_models | 106 | python | def _fit_gaussian(self, rewards, traj_proposals):
top_k = int((self._fraction * self._proposals))
indices = np.squeeze(np.argpartition(rewards, (- top_k), axis=0), axis=(- 1))[(- top_k):]
best_trajectories = traj_proposals[indices]
if self._weighted:
weights = rewards.numpy()[(indices, 0)]
else:
weights = np.ones_like(rewards[(indices, 0)])
actions_to_fit = np.transpose(best_trajectories[(0:top_k, 0:self._horizon)], (1, 0, 2))
means = []
covs = []
for i in range(self._horizon):
means.append(np.average(actions_to_fit[i], weights=weights, axis=0))
covs.append(np.cov(actions_to_fit[i].T, aweights=weights))
return (means, covs) | def _fit_gaussian(self, rewards, traj_proposals):
top_k = int((self._fraction * self._proposals))
indices = np.squeeze(np.argpartition(rewards, (- top_k), axis=0), axis=(- 1))[(- top_k):]
best_trajectories = traj_proposals[indices]
if self._weighted:
weights = rewards.numpy()[(indices, 0)]
else:
weights = np.ones_like(rewards[(indices, 0)])
actions_to_fit = np.transpose(best_trajectories[(0:top_k, 0:self._horizon)], (1, 0, 2))
means = []
covs = []
for i in range(self._horizon):
means.append(np.average(actions_to_fit[i], weights=weights, axis=0))
covs.append(np.cov(actions_to_fit[i].T, aweights=weights))
return (means, covs)<|docstring|>Re-fits a Gaussian to the best actions.<|endoftext|> |
744828dbf6c6189c479e0767e6997a112920ea51162cc2783dcd31e7fd978453 | def _fit_multinomial(self, rewards, traj_proposals):
'Re-fits multinomials to the best actions.'
top_k = int((self._fraction * self._proposals))
indices = np.squeeze(np.argpartition(rewards, (- top_k), axis=0), axis=(- 1))[(- top_k):]
best_trajectories = traj_proposals[indices]
if self._weighted:
weights = rewards.numpy()[(indices, 0)]
else:
weights = np.ones_like(rewards[(indices, 0)])
actions_to_fit = np.transpose(best_trajectories[(0:top_k, 0:self._horizon)], (1, 0, 2))
pvals = []
for i in range(self._horizon):
action_onehot = np.bincount(actions_to_fit[(i, :, 0)], minlength=self._action_space.n)
pval = ((action_onehot * weights) / np.sum(weights))
pvals.append(pval.tolist())
return pvals | Re-fits multinomials to the best actions. | planners/planners.py | _fit_multinomial | pacificlion/world_models | 106 | python | def _fit_multinomial(self, rewards, traj_proposals):
top_k = int((self._fraction * self._proposals))
indices = np.squeeze(np.argpartition(rewards, (- top_k), axis=0), axis=(- 1))[(- top_k):]
best_trajectories = traj_proposals[indices]
if self._weighted:
weights = rewards.numpy()[(indices, 0)]
else:
weights = np.ones_like(rewards[(indices, 0)])
actions_to_fit = np.transpose(best_trajectories[(0:top_k, 0:self._horizon)], (1, 0, 2))
pvals = []
for i in range(self._horizon):
action_onehot = np.bincount(actions_to_fit[(i, :, 0)], minlength=self._action_space.n)
pval = ((action_onehot * weights) / np.sum(weights))
pvals.append(pval.tolist())
return pvals | def _fit_multinomial(self, rewards, traj_proposals):
top_k = int((self._fraction * self._proposals))
indices = np.squeeze(np.argpartition(rewards, (- top_k), axis=0), axis=(- 1))[(- top_k):]
best_trajectories = traj_proposals[indices]
if self._weighted:
weights = rewards.numpy()[(indices, 0)]
else:
weights = np.ones_like(rewards[(indices, 0)])
actions_to_fit = np.transpose(best_trajectories[(0:top_k, 0:self._horizon)], (1, 0, 2))
pvals = []
for i in range(self._horizon):
action_onehot = np.bincount(actions_to_fit[(i, :, 0)], minlength=self._action_space.n)
pval = ((action_onehot * weights) / np.sum(weights))
pvals.append(pval.tolist())
return pvals<|docstring|>Re-fits multinomials to the best actions.<|endoftext|> |
93a71a7ae228af3cb07eae515c138cc8605ca1465c8dccd0cdc0a9450cf641af | def __init__(self, predict_fn: Callable[([np.ndarray, Any], Dict[(Text, np.ndarray)])], observe_fn: Callable[([np.ndarray, np.ndarray, np.ndarray, Any], Any)], reset_fn: Callable[([Any, int], Any)], task: tasks.Task, objective_fn: Callable[([Dict[(Text, np.ndarray)]], np.ndarray)], horizon: int, iterations: int, proposals: int, fraction: float, beta: List[float], gamma: float):
'Initialize a MPPI planner that queries a world model.\n\n Args:\n predict_fn: a callable with the following positional arguments:\n * planned_actions: a [batch, steps, action_dims] ndarray\n * state: the state object returned from observe_fn.\n This method is expected to return:\n * predictions: a dictionary with possibly the following entries:\n * "image": [batch, steps, height, width, channels] ndarray of the\n model predictions of the state of the world conditioned actions.\n * "reward": [batch, steps, 1] ndarray of the reward predictions.\n observe_fn: a callable with the following positional arguments:\n * last_images: a [batch, steps, height, width, channels] ndarray\n * last_actions: a [batch, steps, action_dims] ndarray\n * last_reward: a [batch, steps, 1] ndarray\n * state: the previously returned `state` or {} for the start of\n episode\n This method is expected to return:\n * state: Anything the model needs to continue predicting current\n episode.\n reset_fn: a callable with the following positional arguments:\n * state: the state object\n * batch_size: the batch size.\n This method is expected to return:\n * state: the new state with cleared history.\n task: The task of type `tasks.Task`.\n objective_fn: a callable with the following positional arguments:\n * predictions: a dictionary possibly containing "image" and "reward"\n that will come from the `predict_fn`\n This method is expected to return:\n * rewards: a [batch, steps, 1] ndarray of containing scalar rewards.\n horizon: the planning horizon to specify how many steps into the future to\n consider for choosing the right plan.\n iterations: How many iterations to estimate the final distribution.\n proposals: How many proposals to consider in each iteration.\n fraction: The percentage of proposals to select with the highest score to\n fit the distribution.\n beta: Coefficients for correlated noise during sampling.\n gamma: Weight for top_k rewards when fitting the gaussian.\n '
super(MPPI, self).__init__(predict_fn, observe_fn, reset_fn, task, objective_fn, horizon, iterations, proposals, fraction, False)
self._beta = beta
self._gamma = gamma | Initialize a MPPI planner that queries a world model.
Args:
predict_fn: a callable with the following positional arguments:
* planned_actions: a [batch, steps, action_dims] ndarray
* state: the state object returned from observe_fn.
This method is expected to return:
* predictions: a dictionary with possibly the following entries:
* "image": [batch, steps, height, width, channels] ndarray of the
model predictions of the state of the world conditioned actions.
* "reward": [batch, steps, 1] ndarray of the reward predictions.
observe_fn: a callable with the following positional arguments:
* last_images: a [batch, steps, height, width, channels] ndarray
* last_actions: a [batch, steps, action_dims] ndarray
* last_reward: a [batch, steps, 1] ndarray
* state: the previously returned `state` or {} for the start of
episode
This method is expected to return:
* state: Anything the model needs to continue predicting current
episode.
reset_fn: a callable with the following positional arguments:
* state: the state object
* batch_size: the batch size.
This method is expected to return:
* state: the new state with cleared history.
task: The task of type `tasks.Task`.
objective_fn: a callable with the following positional arguments:
* predictions: a dictionary possibly containing "image" and "reward"
that will come from the `predict_fn`
This method is expected to return:
* rewards: a [batch, steps, 1] ndarray of containing scalar rewards.
horizon: the planning horizon to specify how many steps into the future to
consider for choosing the right plan.
iterations: How many iterations to estimate the final distribution.
proposals: How many proposals to consider in each iteration.
fraction: The percentage of proposals to select with the highest score to
fit the distribution.
beta: Coefficients for correlated noise during sampling.
gamma: Weight for top_k rewards when fitting the gaussian. | planners/planners.py | __init__ | pacificlion/world_models | 106 | python | def __init__(self, predict_fn: Callable[([np.ndarray, Any], Dict[(Text, np.ndarray)])], observe_fn: Callable[([np.ndarray, np.ndarray, np.ndarray, Any], Any)], reset_fn: Callable[([Any, int], Any)], task: tasks.Task, objective_fn: Callable[([Dict[(Text, np.ndarray)]], np.ndarray)], horizon: int, iterations: int, proposals: int, fraction: float, beta: List[float], gamma: float):
'Initialize a MPPI planner that queries a world model.\n\n Args:\n predict_fn: a callable with the following positional arguments:\n * planned_actions: a [batch, steps, action_dims] ndarray\n * state: the state object returned from observe_fn.\n This method is expected to return:\n * predictions: a dictionary with possibly the following entries:\n * "image": [batch, steps, height, width, channels] ndarray of the\n model predictions of the state of the world conditioned actions.\n * "reward": [batch, steps, 1] ndarray of the reward predictions.\n observe_fn: a callable with the following positional arguments:\n * last_images: a [batch, steps, height, width, channels] ndarray\n * last_actions: a [batch, steps, action_dims] ndarray\n * last_reward: a [batch, steps, 1] ndarray\n * state: the previously returned `state` or {} for the start of\n episode\n This method is expected to return:\n * state: Anything the model needs to continue predicting current\n episode.\n reset_fn: a callable with the following positional arguments:\n * state: the state object\n * batch_size: the batch size.\n This method is expected to return:\n * state: the new state with cleared history.\n task: The task of type `tasks.Task`.\n objective_fn: a callable with the following positional arguments:\n * predictions: a dictionary possibly containing "image" and "reward"\n that will come from the `predict_fn`\n This method is expected to return:\n * rewards: a [batch, steps, 1] ndarray of containing scalar rewards.\n horizon: the planning horizon to specify how many steps into the future to\n consider for choosing the right plan.\n iterations: How many iterations to estimate the final distribution.\n proposals: How many proposals to consider in each iteration.\n fraction: The percentage of proposals to select with the highest score to\n fit the distribution.\n beta: Coefficients for correlated noise during sampling.\n gamma: Weight for top_k rewards when fitting the gaussian.\n '
super(MPPI, self).__init__(predict_fn, observe_fn, reset_fn, task, objective_fn, horizon, iterations, proposals, fraction, False)
self._beta = beta
self._gamma = gamma | def __init__(self, predict_fn: Callable[([np.ndarray, Any], Dict[(Text, np.ndarray)])], observe_fn: Callable[([np.ndarray, np.ndarray, np.ndarray, Any], Any)], reset_fn: Callable[([Any, int], Any)], task: tasks.Task, objective_fn: Callable[([Dict[(Text, np.ndarray)]], np.ndarray)], horizon: int, iterations: int, proposals: int, fraction: float, beta: List[float], gamma: float):
'Initialize a MPPI planner that queries a world model.\n\n Args:\n predict_fn: a callable with the following positional arguments:\n * planned_actions: a [batch, steps, action_dims] ndarray\n * state: the state object returned from observe_fn.\n This method is expected to return:\n * predictions: a dictionary with possibly the following entries:\n * "image": [batch, steps, height, width, channels] ndarray of the\n model predictions of the state of the world conditioned actions.\n * "reward": [batch, steps, 1] ndarray of the reward predictions.\n observe_fn: a callable with the following positional arguments:\n * last_images: a [batch, steps, height, width, channels] ndarray\n * last_actions: a [batch, steps, action_dims] ndarray\n * last_reward: a [batch, steps, 1] ndarray\n * state: the previously returned `state` or {} for the start of\n episode\n This method is expected to return:\n * state: Anything the model needs to continue predicting current\n episode.\n reset_fn: a callable with the following positional arguments:\n * state: the state object\n * batch_size: the batch size.\n This method is expected to return:\n * state: the new state with cleared history.\n task: The task of type `tasks.Task`.\n objective_fn: a callable with the following positional arguments:\n * predictions: a dictionary possibly containing "image" and "reward"\n that will come from the `predict_fn`\n This method is expected to return:\n * rewards: a [batch, steps, 1] ndarray of containing scalar rewards.\n horizon: the planning horizon to specify how many steps into the future to\n consider for choosing the right plan.\n iterations: How many iterations to estimate the final distribution.\n proposals: How many proposals to consider in each iteration.\n fraction: The percentage of proposals to select with the highest score to\n fit the distribution.\n beta: Coefficients for correlated noise during sampling.\n gamma: Weight for top_k rewards when fitting the gaussian.\n '
super(MPPI, self).__init__(predict_fn, observe_fn, reset_fn, task, objective_fn, horizon, iterations, proposals, fraction, False)
self._beta = beta
self._gamma = gamma<|docstring|>Initialize a MPPI planner that queries a world model.
Args:
predict_fn: a callable with the following positional arguments:
* planned_actions: a [batch, steps, action_dims] ndarray
* state: the state object returned from observe_fn.
This method is expected to return:
* predictions: a dictionary with possibly the following entries:
* "image": [batch, steps, height, width, channels] ndarray of the
model predictions of the state of the world conditioned actions.
* "reward": [batch, steps, 1] ndarray of the reward predictions.
observe_fn: a callable with the following positional arguments:
* last_images: a [batch, steps, height, width, channels] ndarray
* last_actions: a [batch, steps, action_dims] ndarray
* last_reward: a [batch, steps, 1] ndarray
* state: the previously returned `state` or {} for the start of
episode
This method is expected to return:
* state: Anything the model needs to continue predicting current
episode.
reset_fn: a callable with the following positional arguments:
* state: the state object
* batch_size: the batch size.
This method is expected to return:
* state: the new state with cleared history.
task: The task of type `tasks.Task`.
objective_fn: a callable with the following positional arguments:
* predictions: a dictionary possibly containing "image" and "reward"
that will come from the `predict_fn`
This method is expected to return:
* rewards: a [batch, steps, 1] ndarray of containing scalar rewards.
horizon: the planning horizon to specify how many steps into the future to
consider for choosing the right plan.
iterations: How many iterations to estimate the final distribution.
proposals: How many proposals to consider in each iteration.
fraction: The percentage of proposals to select with the highest score to
fit the distribution.
beta: Coefficients for correlated noise during sampling.
gamma: Weight for top_k rewards when fitting the gaussian.<|endoftext|> |
a5b0b9a57fb0167f0cbb965ab8095e79a6fef9879cc34ad054d54718249c2a8a | def _sample_continuous_actions(self, means, covs):
'Samples actions with correlated noise using MPPI.'
all_actions = []
u = []
n = []
for (mean, cov) in zip(means, covs):
u.append(np.random.multivariate_normal(np.zeros_like(mean), cov, (self._proposals,)))
n.append((self._beta[0] * u[0]))
n.append(((self._beta[0] * u[1]) + (self._beta[1] * n[0])))
for i in range(2, len(u)):
n.append((((self._beta[0] * u[i]) + (self._beta[1] * n[(- 1)])) + (self._beta[2] * n[(- 2)])))
for i in range(len(means)):
actions = (n[i] + means[i])
actions = np.clip(actions, self._action_space.low, self._action_space.high)
all_actions.extend([actions])
all_actions = np.array(all_actions)
traj_proposals = np.transpose(all_actions, (1, 0, 2))
traj_proposals = traj_proposals.astype(np.float32)
return traj_proposals | Samples actions with correlated noise using MPPI. | planners/planners.py | _sample_continuous_actions | pacificlion/world_models | 106 | python | def _sample_continuous_actions(self, means, covs):
all_actions = []
u = []
n = []
for (mean, cov) in zip(means, covs):
u.append(np.random.multivariate_normal(np.zeros_like(mean), cov, (self._proposals,)))
n.append((self._beta[0] * u[0]))
n.append(((self._beta[0] * u[1]) + (self._beta[1] * n[0])))
for i in range(2, len(u)):
n.append((((self._beta[0] * u[i]) + (self._beta[1] * n[(- 1)])) + (self._beta[2] * n[(- 2)])))
for i in range(len(means)):
actions = (n[i] + means[i])
actions = np.clip(actions, self._action_space.low, self._action_space.high)
all_actions.extend([actions])
all_actions = np.array(all_actions)
traj_proposals = np.transpose(all_actions, (1, 0, 2))
traj_proposals = traj_proposals.astype(np.float32)
return traj_proposals | def _sample_continuous_actions(self, means, covs):
all_actions = []
u = []
n = []
for (mean, cov) in zip(means, covs):
u.append(np.random.multivariate_normal(np.zeros_like(mean), cov, (self._proposals,)))
n.append((self._beta[0] * u[0]))
n.append(((self._beta[0] * u[1]) + (self._beta[1] * n[0])))
for i in range(2, len(u)):
n.append((((self._beta[0] * u[i]) + (self._beta[1] * n[(- 1)])) + (self._beta[2] * n[(- 2)])))
for i in range(len(means)):
actions = (n[i] + means[i])
actions = np.clip(actions, self._action_space.low, self._action_space.high)
all_actions.extend([actions])
all_actions = np.array(all_actions)
traj_proposals = np.transpose(all_actions, (1, 0, 2))
traj_proposals = traj_proposals.astype(np.float32)
return traj_proposals<|docstring|>Samples actions with correlated noise using MPPI.<|endoftext|> |
25b44f1ddef348805c9ede8d1792fcad4497b33770ad91ced68b9b85cadb3843 | def _fit_gaussian(self, rewards, traj_proposals):
'Re-fits a Gaussian to the best actions.'
top_k = int((self._fraction * self._proposals))
indices = np.squeeze(np.argpartition(rewards, (- top_k), axis=0), axis=(- 1))[(- top_k):]
best_trajectories = traj_proposals[indices]
best_rewards = np.array(rewards)[indices]
actions_to_fit = np.transpose(best_trajectories[(0:top_k, 0:self._horizon)], (1, 0, 2))
means = []
covs = []
weights = np.exp((self._gamma * best_rewards))
weights = (weights / np.sum(weights))
for i in range(self._horizon):
weighted_actions = (weights.T * actions_to_fit[i].T).T
means.append(np.mean(weighted_actions, axis=0))
covs.append(np.cov(actions_to_fit[i].T))
return (means, covs) | Re-fits a Gaussian to the best actions. | planners/planners.py | _fit_gaussian | pacificlion/world_models | 106 | python | def _fit_gaussian(self, rewards, traj_proposals):
top_k = int((self._fraction * self._proposals))
indices = np.squeeze(np.argpartition(rewards, (- top_k), axis=0), axis=(- 1))[(- top_k):]
best_trajectories = traj_proposals[indices]
best_rewards = np.array(rewards)[indices]
actions_to_fit = np.transpose(best_trajectories[(0:top_k, 0:self._horizon)], (1, 0, 2))
means = []
covs = []
weights = np.exp((self._gamma * best_rewards))
weights = (weights / np.sum(weights))
for i in range(self._horizon):
weighted_actions = (weights.T * actions_to_fit[i].T).T
means.append(np.mean(weighted_actions, axis=0))
covs.append(np.cov(actions_to_fit[i].T))
return (means, covs) | def _fit_gaussian(self, rewards, traj_proposals):
top_k = int((self._fraction * self._proposals))
indices = np.squeeze(np.argpartition(rewards, (- top_k), axis=0), axis=(- 1))[(- top_k):]
best_trajectories = traj_proposals[indices]
best_rewards = np.array(rewards)[indices]
actions_to_fit = np.transpose(best_trajectories[(0:top_k, 0:self._horizon)], (1, 0, 2))
means = []
covs = []
weights = np.exp((self._gamma * best_rewards))
weights = (weights / np.sum(weights))
for i in range(self._horizon):
weighted_actions = (weights.T * actions_to_fit[i].T).T
means.append(np.mean(weighted_actions, axis=0))
covs.append(np.cov(actions_to_fit[i].T))
return (means, covs)<|docstring|>Re-fits a Gaussian to the best actions.<|endoftext|> |
f40f7aab2ef17c47db0e55238a57c004525b3dbb2e8e60abe4a8447b6ace8e88 | @tf.function
def initialize_distribution(self):
'Returns initial mean and covariance.'
means = tf.stack(([((self._action_space.high + self._action_space.low) / 2.0)] * self._horizon), axis=0)
stdevs = tf.stack(([((self._action_space.high - self._action_space.low) / 2.0)] * self._horizon), axis=0)
return (means, stdevs) | Returns initial mean and covariance. | planners/planners.py | initialize_distribution | pacificlion/world_models | 106 | python | @tf.function
def initialize_distribution(self):
means = tf.stack(([((self._action_space.high + self._action_space.low) / 2.0)] * self._horizon), axis=0)
stdevs = tf.stack(([((self._action_space.high - self._action_space.low) / 2.0)] * self._horizon), axis=0)
return (means, stdevs) | @tf.function
def initialize_distribution(self):
means = tf.stack(([((self._action_space.high + self._action_space.low) / 2.0)] * self._horizon), axis=0)
stdevs = tf.stack(([((self._action_space.high - self._action_space.low) / 2.0)] * self._horizon), axis=0)
return (means, stdevs)<|docstring|>Returns initial mean and covariance.<|endoftext|> |
d268ddec98e953c1fc00838dfdbeb2a7e7662203da81d9615116a22cafff19dd | @tf.function
def sample_continuous_actions(self, means, stdevs):
'Samples actions from a multivariate Gaussian.'
actions = tfp.distributions.MultivariateNormalDiag(loc=means, scale_diag=stdevs).sample([self._proposals])
actions = tf.clip_by_value(actions, self._action_space.low, self._action_space.high)
return actions | Samples actions from a multivariate Gaussian. | planners/planners.py | sample_continuous_actions | pacificlion/world_models | 106 | python | @tf.function
def sample_continuous_actions(self, means, stdevs):
actions = tfp.distributions.MultivariateNormalDiag(loc=means, scale_diag=stdevs).sample([self._proposals])
actions = tf.clip_by_value(actions, self._action_space.low, self._action_space.high)
return actions | @tf.function
def sample_continuous_actions(self, means, stdevs):
actions = tfp.distributions.MultivariateNormalDiag(loc=means, scale_diag=stdevs).sample([self._proposals])
actions = tf.clip_by_value(actions, self._action_space.low, self._action_space.high)
return actions<|docstring|>Samples actions from a multivariate Gaussian.<|endoftext|> |
5cb12d29c6976de983ea6cdffc56f7400c53df5a71b857207347f209a2989db3 | @tf.function
def generate_rewards(self, traj_proposals, state):
'Given a set of actions, outputs the corresponding rewards.'
predictions = self._predict_fn(traj_proposals, state)
traj_rewards = self._objective_fn(predictions)
return (traj_rewards, predictions) | Given a set of actions, outputs the corresponding rewards. | planners/planners.py | generate_rewards | pacificlion/world_models | 106 | python | @tf.function
def generate_rewards(self, traj_proposals, state):
predictions = self._predict_fn(traj_proposals, state)
traj_rewards = self._objective_fn(predictions)
return (traj_rewards, predictions) | @tf.function
def generate_rewards(self, traj_proposals, state):
predictions = self._predict_fn(traj_proposals, state)
traj_rewards = self._objective_fn(predictions)
return (traj_rewards, predictions)<|docstring|>Given a set of actions, outputs the corresponding rewards.<|endoftext|> |
4e449e476698c794759409f972a63a3b0dfcc4f2432c1df39c7ad861489fa438 | @tf.function
def fit_gaussian(self, rewards, traj_proposals):
'Re-fits a Gaussian to the best actions.'
top_k = int((self._fraction * self._proposals))
rewards = tf.squeeze(rewards, axis=(- 1))
(_, indices) = tf.nn.top_k(rewards, top_k, sorted=False)
best_actions = tf.gather(traj_proposals, indices)
if self._weighted:
weights = tf.gather(rewards, indices)
(means, variance) = tf.nn.weighted_moments(best_actions, axes=0, frequency_weights=weights[(..., None, None)])
else:
(means, variance) = tf.nn.moments(best_actions, axes=0)
stdevs = tf.sqrt((variance + 1e-06))
return (means, stdevs) | Re-fits a Gaussian to the best actions. | planners/planners.py | fit_gaussian | pacificlion/world_models | 106 | python | @tf.function
def fit_gaussian(self, rewards, traj_proposals):
top_k = int((self._fraction * self._proposals))
rewards = tf.squeeze(rewards, axis=(- 1))
(_, indices) = tf.nn.top_k(rewards, top_k, sorted=False)
best_actions = tf.gather(traj_proposals, indices)
if self._weighted:
weights = tf.gather(rewards, indices)
(means, variance) = tf.nn.weighted_moments(best_actions, axes=0, frequency_weights=weights[(..., None, None)])
else:
(means, variance) = tf.nn.moments(best_actions, axes=0)
stdevs = tf.sqrt((variance + 1e-06))
return (means, stdevs) | @tf.function
def fit_gaussian(self, rewards, traj_proposals):
top_k = int((self._fraction * self._proposals))
rewards = tf.squeeze(rewards, axis=(- 1))
(_, indices) = tf.nn.top_k(rewards, top_k, sorted=False)
best_actions = tf.gather(traj_proposals, indices)
if self._weighted:
weights = tf.gather(rewards, indices)
(means, variance) = tf.nn.weighted_moments(best_actions, axes=0, frequency_weights=weights[(..., None, None)])
else:
(means, variance) = tf.nn.moments(best_actions, axes=0)
stdevs = tf.sqrt((variance + 1e-06))
return (means, stdevs)<|docstring|>Re-fits a Gaussian to the best actions.<|endoftext|> |
e5827322c8d5aa26ab5cd00a8bd2b00cbe52e3e2c00032d7c574276927d9ccf9 | def addParticipant(self, address, amount):
'\n Add participants of the airdrop into self.recipients\n '
self.recipients[address] = amount | Add participants of the airdrop into self.recipients | utils/rpc_module.py | addParticipant | Nadro-J/tipbot-v2 | 3 | python | def addParticipant(self, address, amount):
'\n \n '
self.recipients[address] = amount | def addParticipant(self, address, amount):
'\n \n '
self.recipients[address] = amount<|docstring|>Add participants of the airdrop into self.recipients<|endoftext|> |
036ba05f4aecfc59ecbd0734c7eb74553c40684d41d4f3338e62eff83052993e | def clearRecipients(self):
'\n clear participants of the airdrop from self.recipients. Only call once payment has been made\n '
self.recipients.clear() | clear participants of the airdrop from self.recipients. Only call once payment has been made | utils/rpc_module.py | clearRecipients | Nadro-J/tipbot-v2 | 3 | python | def clearRecipients(self):
'\n \n '
self.recipients.clear() | def clearRecipients(self):
'\n \n '
self.recipients.clear()<|docstring|>clear participants of the airdrop from self.recipients. Only call once payment has been made<|endoftext|> |
a1bb9e629cd9ba865028e36fb8a9a70cd37dbbfdaa571ee9f223ac4485551859 | def sendmany(self):
'\n Send from airdrop wallet specified in config.json\n '
payload = json.dumps({'method': 'sendmany', 'params': ['', self.recipients, 16], 'jsonrpc': '2.0'})
response = requests.post(self.serverURL, headers=self.headers, data=payload, auth=(self.rpc_user, self.rpc_pass))
return response.json()['result'] | Send from airdrop wallet specified in config.json | utils/rpc_module.py | sendmany | Nadro-J/tipbot-v2 | 3 | python | def sendmany(self):
'\n \n '
payload = json.dumps({'method': 'sendmany', 'params': [, self.recipients, 16], 'jsonrpc': '2.0'})
response = requests.post(self.serverURL, headers=self.headers, data=payload, auth=(self.rpc_user, self.rpc_pass))
return response.json()['result'] | def sendmany(self):
'\n \n '
payload = json.dumps({'method': 'sendmany', 'params': [, self.recipients, 16], 'jsonrpc': '2.0'})
response = requests.post(self.serverURL, headers=self.headers, data=payload, auth=(self.rpc_user, self.rpc_pass))
return response.json()['result']<|docstring|>Send from airdrop wallet specified in config.json<|endoftext|> |
4406bc8c9f5d2089341d383d2a975e9862bd50e2816171f50328141ff305aa82 | def store(self, obj: Any, key: str=None, overwrite: bool=False) -> str:
'\n 存储一个对象, 返回其 key\n\n :param obj: 待存储的对象\n :param key: 若不指定, 随机生成一个运行期间不会重复的 key\n :param overwrite: 存在相同的 key 时是否覆盖\n :return: 对象的 key\n '
if (not key):
hash_str = str(id(obj))
key = md5(hash_str.encode('utf-8')).hexdigest()
exist = (key in self._db)
if ((not exist) or (exist and overwrite)):
logger.debug(f'Store {obj} -> <Key {key}>')
self._db[key] = obj
return key | 存储一个对象, 返回其 key
:param obj: 待存储的对象
:param key: 若不指定, 随机生成一个运行期间不会重复的 key
:param overwrite: 存在相同的 key 时是否覆盖
:return: 对象的 key | api/core/cache.py | store | StoneMoe/Anime-API | 543 | python | def store(self, obj: Any, key: str=None, overwrite: bool=False) -> str:
'\n 存储一个对象, 返回其 key\n\n :param obj: 待存储的对象\n :param key: 若不指定, 随机生成一个运行期间不会重复的 key\n :param overwrite: 存在相同的 key 时是否覆盖\n :return: 对象的 key\n '
if (not key):
hash_str = str(id(obj))
key = md5(hash_str.encode('utf-8')).hexdigest()
exist = (key in self._db)
if ((not exist) or (exist and overwrite)):
logger.debug(f'Store {obj} -> <Key {key}>')
self._db[key] = obj
return key | def store(self, obj: Any, key: str=None, overwrite: bool=False) -> str:
'\n 存储一个对象, 返回其 key\n\n :param obj: 待存储的对象\n :param key: 若不指定, 随机生成一个运行期间不会重复的 key\n :param overwrite: 存在相同的 key 时是否覆盖\n :return: 对象的 key\n '
if (not key):
hash_str = str(id(obj))
key = md5(hash_str.encode('utf-8')).hexdigest()
exist = (key in self._db)
if ((not exist) or (exist and overwrite)):
logger.debug(f'Store {obj} -> <Key {key}>')
self._db[key] = obj
return key<|docstring|>存储一个对象, 返回其 key
:param obj: 待存储的对象
:param key: 若不指定, 随机生成一个运行期间不会重复的 key
:param overwrite: 存在相同的 key 时是否覆盖
:return: 对象的 key<|endoftext|> |
c82379185a406c1fa8aec5fbd35f9bca5703329e006b32305d7f3ddc70a1c657 | def fetch(self, key: str) -> Any:
'从数据库读取一个对象'
ret = self._db.get(key)
logger.debug(f"Fetch <Key {key}> -> {(ret if ret else 'Nothing Found')}")
return ret | 从数据库读取一个对象 | api/core/cache.py | fetch | StoneMoe/Anime-API | 543 | python | def fetch(self, key: str) -> Any:
ret = self._db.get(key)
logger.debug(f"Fetch <Key {key}> -> {(ret if ret else 'Nothing Found')}")
return ret | def fetch(self, key: str) -> Any:
ret = self._db.get(key)
logger.debug(f"Fetch <Key {key}> -> {(ret if ret else 'Nothing Found')}")
return ret<|docstring|>从数据库读取一个对象<|endoftext|> |
8944f8d8c75b168058153e0148359f410d0a074b3432049f001bbcac80c9d1bf | def update(self, key: str, value: Any) -> str:
'更新 key 绑定的对象'
if (key in self._db):
logger.debug(f'Update <Key {key}> -> {value}')
self._db[key] = value
return key | 更新 key 绑定的对象 | api/core/cache.py | update | StoneMoe/Anime-API | 543 | python | def update(self, key: str, value: Any) -> str:
if (key in self._db):
logger.debug(f'Update <Key {key}> -> {value}')
self._db[key] = value
return key | def update(self, key: str, value: Any) -> str:
if (key in self._db):
logger.debug(f'Update <Key {key}> -> {value}')
self._db[key] = value
return key<|docstring|>更新 key 绑定的对象<|endoftext|> |
b2d23e7ea98880acdf407f22521488007f26c6b50662db7f5a6646481593093a | def size(self) -> float:
'获取缓存对象的大小(KB)'
return (asizeof.asizeof(self._db) / 1024) | 获取缓存对象的大小(KB) | api/core/cache.py | size | StoneMoe/Anime-API | 543 | python | def size(self) -> float:
return (asizeof.asizeof(self._db) / 1024) | def size(self) -> float:
return (asizeof.asizeof(self._db) / 1024)<|docstring|>获取缓存对象的大小(KB)<|endoftext|> |
865480a46a587374a14328389b5f20f1313ef192af8c5c00d64fa52850eb285a | def clear(self) -> float:
'清空数据, 返回清理的内存大小(KB)'
logger.warning(f'CacheDB has been cleared, object in total: {len(self._db)}')
size = self.size()
self._db.clear()
return size | 清空数据, 返回清理的内存大小(KB) | api/core/cache.py | clear | StoneMoe/Anime-API | 543 | python | def clear(self) -> float:
logger.warning(f'CacheDB has been cleared, object in total: {len(self._db)}')
size = self.size()
self._db.clear()
return size | def clear(self) -> float:
logger.warning(f'CacheDB has been cleared, object in total: {len(self._db)}')
size = self.size()
self._db.clear()
return size<|docstring|>清空数据, 返回清理的内存大小(KB)<|endoftext|> |
3a27860bc3dc8d28f852ea39b4b71443b7395973370a8f05f2201c66625b6f76 | def expval(op):
'Expectation value of the supplied observable.\n\n **Example:**\n\n .. code-block:: python3\n\n dev = qml.device("default.qubit", wires=2)\n\n @qml.qnode(dev)\n def circuit(x):\n qml.RX(x, wires=0)\n qml.Hadamard(wires=1)\n qml.CNOT(wires=[0, 1])\n return qml.expval(qml.PauliY(0))\n\n Executing this QNode:\n\n >>> circuit(0.5)\n -0.4794255386042029\n\n Args:\n op (Observable): a quantum observable object\n\n Raises:\n QuantumFunctionError: `op` is not an instance of :class:`~.Observable`\n '
if (not isinstance(op, Observable)):
raise QuantumFunctionError('{} is not an observable: cannot be used with expval'.format(op.name))
meas_op = MeasurementProcess(Expectation)
qml.QueuingContext.update_info(op, owner=meas_op)
qml.QueuingContext.append(meas_op, owns=op)
return op | Expectation value of the supplied observable.
**Example:**
.. code-block:: python3
dev = qml.device("default.qubit", wires=2)
@qml.qnode(dev)
def circuit(x):
qml.RX(x, wires=0)
qml.Hadamard(wires=1)
qml.CNOT(wires=[0, 1])
return qml.expval(qml.PauliY(0))
Executing this QNode:
>>> circuit(0.5)
-0.4794255386042029
Args:
op (Observable): a quantum observable object
Raises:
QuantumFunctionError: `op` is not an instance of :class:`~.Observable` | pennylane/beta/queuing/measure.py | expval | gvvynplaine/pennylane | 0 | python | def expval(op):
'Expectation value of the supplied observable.\n\n **Example:**\n\n .. code-block:: python3\n\n dev = qml.device("default.qubit", wires=2)\n\n @qml.qnode(dev)\n def circuit(x):\n qml.RX(x, wires=0)\n qml.Hadamard(wires=1)\n qml.CNOT(wires=[0, 1])\n return qml.expval(qml.PauliY(0))\n\n Executing this QNode:\n\n >>> circuit(0.5)\n -0.4794255386042029\n\n Args:\n op (Observable): a quantum observable object\n\n Raises:\n QuantumFunctionError: `op` is not an instance of :class:`~.Observable`\n '
if (not isinstance(op, Observable)):
raise QuantumFunctionError('{} is not an observable: cannot be used with expval'.format(op.name))
meas_op = MeasurementProcess(Expectation)
qml.QueuingContext.update_info(op, owner=meas_op)
qml.QueuingContext.append(meas_op, owns=op)
return op | def expval(op):
'Expectation value of the supplied observable.\n\n **Example:**\n\n .. code-block:: python3\n\n dev = qml.device("default.qubit", wires=2)\n\n @qml.qnode(dev)\n def circuit(x):\n qml.RX(x, wires=0)\n qml.Hadamard(wires=1)\n qml.CNOT(wires=[0, 1])\n return qml.expval(qml.PauliY(0))\n\n Executing this QNode:\n\n >>> circuit(0.5)\n -0.4794255386042029\n\n Args:\n op (Observable): a quantum observable object\n\n Raises:\n QuantumFunctionError: `op` is not an instance of :class:`~.Observable`\n '
if (not isinstance(op, Observable)):
raise QuantumFunctionError('{} is not an observable: cannot be used with expval'.format(op.name))
meas_op = MeasurementProcess(Expectation)
qml.QueuingContext.update_info(op, owner=meas_op)
qml.QueuingContext.append(meas_op, owns=op)
return op<|docstring|>Expectation value of the supplied observable.
**Example:**
.. code-block:: python3
dev = qml.device("default.qubit", wires=2)
@qml.qnode(dev)
def circuit(x):
qml.RX(x, wires=0)
qml.Hadamard(wires=1)
qml.CNOT(wires=[0, 1])
return qml.expval(qml.PauliY(0))
Executing this QNode:
>>> circuit(0.5)
-0.4794255386042029
Args:
op (Observable): a quantum observable object
Raises:
QuantumFunctionError: `op` is not an instance of :class:`~.Observable`<|endoftext|> |
bc78ace6cb654cd6a7efa195c5cdc60ae27505090137470f7792e3ecc7084fa9 | def var(op):
'Variance of the supplied observable.\n\n **Example:**\n\n .. code-block:: python3\n\n dev = qml.device("default.qubit", wires=2)\n\n @qml.qnode(dev)\n def circuit(x):\n qml.RX(x, wires=0)\n qml.Hadamard(wires=1)\n qml.CNOT(wires=[0, 1])\n return qml.var(qml.PauliY(0))\n\n Executing this QNode:\n\n >>> circuit(0.5)\n 0.7701511529340698\n\n Args:\n op (Observable): a quantum observable object\n\n Raises:\n QuantumFunctionError: `op` is not an instance of :class:`~.Observable`\n '
if (not isinstance(op, Observable)):
raise QuantumFunctionError('{} is not an observable: cannot be used with var'.format(op.name))
meas_op = MeasurementProcess(Variance)
qml.QueuingContext.update_info(op, owner=meas_op)
qml.QueuingContext.append(meas_op, owns=op)
return op | Variance of the supplied observable.
**Example:**
.. code-block:: python3
dev = qml.device("default.qubit", wires=2)
@qml.qnode(dev)
def circuit(x):
qml.RX(x, wires=0)
qml.Hadamard(wires=1)
qml.CNOT(wires=[0, 1])
return qml.var(qml.PauliY(0))
Executing this QNode:
>>> circuit(0.5)
0.7701511529340698
Args:
op (Observable): a quantum observable object
Raises:
QuantumFunctionError: `op` is not an instance of :class:`~.Observable` | pennylane/beta/queuing/measure.py | var | gvvynplaine/pennylane | 0 | python | def var(op):
'Variance of the supplied observable.\n\n **Example:**\n\n .. code-block:: python3\n\n dev = qml.device("default.qubit", wires=2)\n\n @qml.qnode(dev)\n def circuit(x):\n qml.RX(x, wires=0)\n qml.Hadamard(wires=1)\n qml.CNOT(wires=[0, 1])\n return qml.var(qml.PauliY(0))\n\n Executing this QNode:\n\n >>> circuit(0.5)\n 0.7701511529340698\n\n Args:\n op (Observable): a quantum observable object\n\n Raises:\n QuantumFunctionError: `op` is not an instance of :class:`~.Observable`\n '
if (not isinstance(op, Observable)):
raise QuantumFunctionError('{} is not an observable: cannot be used with var'.format(op.name))
meas_op = MeasurementProcess(Variance)
qml.QueuingContext.update_info(op, owner=meas_op)
qml.QueuingContext.append(meas_op, owns=op)
return op | def var(op):
'Variance of the supplied observable.\n\n **Example:**\n\n .. code-block:: python3\n\n dev = qml.device("default.qubit", wires=2)\n\n @qml.qnode(dev)\n def circuit(x):\n qml.RX(x, wires=0)\n qml.Hadamard(wires=1)\n qml.CNOT(wires=[0, 1])\n return qml.var(qml.PauliY(0))\n\n Executing this QNode:\n\n >>> circuit(0.5)\n 0.7701511529340698\n\n Args:\n op (Observable): a quantum observable object\n\n Raises:\n QuantumFunctionError: `op` is not an instance of :class:`~.Observable`\n '
if (not isinstance(op, Observable)):
raise QuantumFunctionError('{} is not an observable: cannot be used with var'.format(op.name))
meas_op = MeasurementProcess(Variance)
qml.QueuingContext.update_info(op, owner=meas_op)
qml.QueuingContext.append(meas_op, owns=op)
return op<|docstring|>Variance of the supplied observable.
**Example:**
.. code-block:: python3
dev = qml.device("default.qubit", wires=2)
@qml.qnode(dev)
def circuit(x):
qml.RX(x, wires=0)
qml.Hadamard(wires=1)
qml.CNOT(wires=[0, 1])
return qml.var(qml.PauliY(0))
Executing this QNode:
>>> circuit(0.5)
0.7701511529340698
Args:
op (Observable): a quantum observable object
Raises:
QuantumFunctionError: `op` is not an instance of :class:`~.Observable`<|endoftext|> |
bbd6ed5f572912759e71d21f2e4c84b152bd608812c9f1fc0f69e57584fe54c3 | def sample(op):
'Sample from the supplied observable, with the number of shots\n determined from the ``dev.shots`` attribute of the corresponding device.\n\n **Example:**\n\n .. code-block:: python3\n\n dev = qml.device("default.qubit", wires=2, shots=4)\n\n @qml.qnode(dev)\n def circuit(x):\n qml.RX(x, wires=0)\n qml.Hadamard(wires=1)\n qml.CNOT(wires=[0, 1])\n return qml.sample(qml.PauliY(0))\n\n Executing this QNode:\n\n >>> circuit(0.5)\n array([ 1., 1., 1., -1.])\n\n Args:\n op (Observable): a quantum observable object\n\n Raises:\n QuantumFunctionError: `op` is not an instance of :class:`~.Observable`\n '
if (not isinstance(op, Observable)):
raise QuantumFunctionError('{} is not an observable: cannot be used with sample'.format(op.name))
meas_op = MeasurementProcess(Sample)
qml.QueuingContext.update_info(op, owner=meas_op)
qml.QueuingContext.append(meas_op, owns=op)
return op | Sample from the supplied observable, with the number of shots
determined from the ``dev.shots`` attribute of the corresponding device.
**Example:**
.. code-block:: python3
dev = qml.device("default.qubit", wires=2, shots=4)
@qml.qnode(dev)
def circuit(x):
qml.RX(x, wires=0)
qml.Hadamard(wires=1)
qml.CNOT(wires=[0, 1])
return qml.sample(qml.PauliY(0))
Executing this QNode:
>>> circuit(0.5)
array([ 1., 1., 1., -1.])
Args:
op (Observable): a quantum observable object
Raises:
QuantumFunctionError: `op` is not an instance of :class:`~.Observable` | pennylane/beta/queuing/measure.py | sample | gvvynplaine/pennylane | 0 | python | def sample(op):
'Sample from the supplied observable, with the number of shots\n determined from the ``dev.shots`` attribute of the corresponding device.\n\n **Example:**\n\n .. code-block:: python3\n\n dev = qml.device("default.qubit", wires=2, shots=4)\n\n @qml.qnode(dev)\n def circuit(x):\n qml.RX(x, wires=0)\n qml.Hadamard(wires=1)\n qml.CNOT(wires=[0, 1])\n return qml.sample(qml.PauliY(0))\n\n Executing this QNode:\n\n >>> circuit(0.5)\n array([ 1., 1., 1., -1.])\n\n Args:\n op (Observable): a quantum observable object\n\n Raises:\n QuantumFunctionError: `op` is not an instance of :class:`~.Observable`\n '
if (not isinstance(op, Observable)):
raise QuantumFunctionError('{} is not an observable: cannot be used with sample'.format(op.name))
meas_op = MeasurementProcess(Sample)
qml.QueuingContext.update_info(op, owner=meas_op)
qml.QueuingContext.append(meas_op, owns=op)
return op | def sample(op):
'Sample from the supplied observable, with the number of shots\n determined from the ``dev.shots`` attribute of the corresponding device.\n\n **Example:**\n\n .. code-block:: python3\n\n dev = qml.device("default.qubit", wires=2, shots=4)\n\n @qml.qnode(dev)\n def circuit(x):\n qml.RX(x, wires=0)\n qml.Hadamard(wires=1)\n qml.CNOT(wires=[0, 1])\n return qml.sample(qml.PauliY(0))\n\n Executing this QNode:\n\n >>> circuit(0.5)\n array([ 1., 1., 1., -1.])\n\n Args:\n op (Observable): a quantum observable object\n\n Raises:\n QuantumFunctionError: `op` is not an instance of :class:`~.Observable`\n '
if (not isinstance(op, Observable)):
raise QuantumFunctionError('{} is not an observable: cannot be used with sample'.format(op.name))
meas_op = MeasurementProcess(Sample)
qml.QueuingContext.update_info(op, owner=meas_op)
qml.QueuingContext.append(meas_op, owns=op)
return op<|docstring|>Sample from the supplied observable, with the number of shots
determined from the ``dev.shots`` attribute of the corresponding device.
**Example:**
.. code-block:: python3
dev = qml.device("default.qubit", wires=2, shots=4)
@qml.qnode(dev)
def circuit(x):
qml.RX(x, wires=0)
qml.Hadamard(wires=1)
qml.CNOT(wires=[0, 1])
return qml.sample(qml.PauliY(0))
Executing this QNode:
>>> circuit(0.5)
array([ 1., 1., 1., -1.])
Args:
op (Observable): a quantum observable object
Raises:
QuantumFunctionError: `op` is not an instance of :class:`~.Observable`<|endoftext|> |
7b4672b614d5e66b8c926e7511b36cca7ae92a440c273c9b7391dccfd011a749 | def probs(wires):
'Probability of each computational basis state.\n\n This measurement function accepts no observables, and instead\n instructs the QNode to return a flat array containing the\n probabilities of each quantum state.\n\n Marginal probabilities may also be requested by restricting\n the wires to a subset of the full system; the size of the\n returned array will be ``[2**len(wires)]``.\n\n **Example:**\n\n .. code-block:: python3\n\n dev = qml.device("default.qubit", wires=2)\n\n @qml.qnode(dev)\n def circuit():\n qml.Hadamard(wires=1)\n return qml.probs(wires=[0, 1])\n\n Executing this QNode:\n\n >>> circuit()\n array([0.5, 0.5, 0. , 0. ])\n\n The returned array is in lexicographic order, so corresponds\n to a :math:`50\\%` chance of measuring either :math:`|00\\rangle`\n or :math:`|01\\rangle`.\n\n Args:\n wires (Sequence[int] or int): the wire the operation acts on\n '
op = Identity(wires=wires, do_queue=False)
meas_op = MeasurementProcess(Probability)
qml.QueuingContext.append(op)
qml.QueuingContext.update_info(op, owner=meas_op)
qml.QueuingContext.append(meas_op, owns=op)
return op | Probability of each computational basis state.
This measurement function accepts no observables, and instead
instructs the QNode to return a flat array containing the
probabilities of each quantum state.
Marginal probabilities may also be requested by restricting
the wires to a subset of the full system; the size of the
returned array will be ``[2**len(wires)]``.
**Example:**
.. code-block:: python3
dev = qml.device("default.qubit", wires=2)
@qml.qnode(dev)
def circuit():
qml.Hadamard(wires=1)
return qml.probs(wires=[0, 1])
Executing this QNode:
>>> circuit()
array([0.5, 0.5, 0. , 0. ])
The returned array is in lexicographic order, so corresponds
to a :math:`50\%` chance of measuring either :math:`|00\rangle`
or :math:`|01\rangle`.
Args:
wires (Sequence[int] or int): the wire the operation acts on | pennylane/beta/queuing/measure.py | probs | gvvynplaine/pennylane | 0 | python | def probs(wires):
'Probability of each computational basis state.\n\n This measurement function accepts no observables, and instead\n instructs the QNode to return a flat array containing the\n probabilities of each quantum state.\n\n Marginal probabilities may also be requested by restricting\n the wires to a subset of the full system; the size of the\n returned array will be ``[2**len(wires)]``.\n\n **Example:**\n\n .. code-block:: python3\n\n dev = qml.device("default.qubit", wires=2)\n\n @qml.qnode(dev)\n def circuit():\n qml.Hadamard(wires=1)\n return qml.probs(wires=[0, 1])\n\n Executing this QNode:\n\n >>> circuit()\n array([0.5, 0.5, 0. , 0. ])\n\n The returned array is in lexicographic order, so corresponds\n to a :math:`50\\%` chance of measuring either :math:`|00\\rangle`\n or :math:`|01\\rangle`.\n\n Args:\n wires (Sequence[int] or int): the wire the operation acts on\n '
op = Identity(wires=wires, do_queue=False)
meas_op = MeasurementProcess(Probability)
qml.QueuingContext.append(op)
qml.QueuingContext.update_info(op, owner=meas_op)
qml.QueuingContext.append(meas_op, owns=op)
return op | def probs(wires):
'Probability of each computational basis state.\n\n This measurement function accepts no observables, and instead\n instructs the QNode to return a flat array containing the\n probabilities of each quantum state.\n\n Marginal probabilities may also be requested by restricting\n the wires to a subset of the full system; the size of the\n returned array will be ``[2**len(wires)]``.\n\n **Example:**\n\n .. code-block:: python3\n\n dev = qml.device("default.qubit", wires=2)\n\n @qml.qnode(dev)\n def circuit():\n qml.Hadamard(wires=1)\n return qml.probs(wires=[0, 1])\n\n Executing this QNode:\n\n >>> circuit()\n array([0.5, 0.5, 0. , 0. ])\n\n The returned array is in lexicographic order, so corresponds\n to a :math:`50\\%` chance of measuring either :math:`|00\\rangle`\n or :math:`|01\\rangle`.\n\n Args:\n wires (Sequence[int] or int): the wire the operation acts on\n '
op = Identity(wires=wires, do_queue=False)
meas_op = MeasurementProcess(Probability)
qml.QueuingContext.append(op)
qml.QueuingContext.update_info(op, owner=meas_op)
qml.QueuingContext.append(meas_op, owns=op)
return op<|docstring|>Probability of each computational basis state.
This measurement function accepts no observables, and instead
instructs the QNode to return a flat array containing the
probabilities of each quantum state.
Marginal probabilities may also be requested by restricting
the wires to a subset of the full system; the size of the
returned array will be ``[2**len(wires)]``.
**Example:**
.. code-block:: python3
dev = qml.device("default.qubit", wires=2)
@qml.qnode(dev)
def circuit():
qml.Hadamard(wires=1)
return qml.probs(wires=[0, 1])
Executing this QNode:
>>> circuit()
array([0.5, 0.5, 0. , 0. ])
The returned array is in lexicographic order, so corresponds
to a :math:`50\%` chance of measuring either :math:`|00\rangle`
or :math:`|01\rangle`.
Args:
wires (Sequence[int] or int): the wire the operation acts on<|endoftext|> |
c6ec45ca38605aa0bedd268714cc8ad99a8abd3bfb740ecad2d0da2d824e69ec | def select(self):
' select based on n_constant value\n\n :return: GaussianHMM object\n '
best_num_components = self.n_constant
return self.base_model(best_num_components) | select based on n_constant value
:return: GaussianHMM object | my_model_selectors.py | select | fcfabio/AIND-Recognizer | 0 | python | def select(self):
' select based on n_constant value\n\n :return: GaussianHMM object\n '
best_num_components = self.n_constant
return self.base_model(best_num_components) | def select(self):
' select based on n_constant value\n\n :return: GaussianHMM object\n '
best_num_components = self.n_constant
return self.base_model(best_num_components)<|docstring|>select based on n_constant value
:return: GaussianHMM object<|endoftext|> |
d1518cad76dc0280a924f06c727e1758b982706fdd2fcb826b21a1b5a3a8c72a | def select(self):
' select the best model for self.this_word based on\n BIC score for n between self.min_n_components and self.max_n_components\n\n :return: GaussianHMM object\n '
warnings.filterwarnings('ignore', category=DeprecationWarning)
bic_value = float('inf')
best_model = None
for n in range(self.min_n_components, (self.max_n_components + 1)):
try:
model = self.base_model(n)
logL = model.score(self.X, self.lengths)
logN = np.log(len(self.sequences))
p = (((n ** 2) + ((2 * n) * model.n_features)) - 1)
currentBIC = (((- 2) * logL) + (p * logN))
if (bic_value > currentBIC):
bic_value = currentBIC
best_model = model
except:
pass
return best_model | select the best model for self.this_word based on
BIC score for n between self.min_n_components and self.max_n_components
:return: GaussianHMM object | my_model_selectors.py | select | fcfabio/AIND-Recognizer | 0 | python | def select(self):
' select the best model for self.this_word based on\n BIC score for n between self.min_n_components and self.max_n_components\n\n :return: GaussianHMM object\n '
warnings.filterwarnings('ignore', category=DeprecationWarning)
bic_value = float('inf')
best_model = None
for n in range(self.min_n_components, (self.max_n_components + 1)):
try:
model = self.base_model(n)
logL = model.score(self.X, self.lengths)
logN = np.log(len(self.sequences))
p = (((n ** 2) + ((2 * n) * model.n_features)) - 1)
currentBIC = (((- 2) * logL) + (p * logN))
if (bic_value > currentBIC):
bic_value = currentBIC
best_model = model
except:
pass
return best_model | def select(self):
' select the best model for self.this_word based on\n BIC score for n between self.min_n_components and self.max_n_components\n\n :return: GaussianHMM object\n '
warnings.filterwarnings('ignore', category=DeprecationWarning)
bic_value = float('inf')
best_model = None
for n in range(self.min_n_components, (self.max_n_components + 1)):
try:
model = self.base_model(n)
logL = model.score(self.X, self.lengths)
logN = np.log(len(self.sequences))
p = (((n ** 2) + ((2 * n) * model.n_features)) - 1)
currentBIC = (((- 2) * logL) + (p * logN))
if (bic_value > currentBIC):
bic_value = currentBIC
best_model = model
except:
pass
return best_model<|docstring|>select the best model for self.this_word based on
BIC score for n between self.min_n_components and self.max_n_components
:return: GaussianHMM object<|endoftext|> |
76742e4612820b7f9bcbc86e21b6dbec67170bd0a846a84c04730205ebf2addf | def permute(self, nums):
'\n :type nums: List[int]\n :rtype: List[List[int]]\n '
from itertools import permutations
return [list(t) for t in permutations(nums, len(nums))] | :type nums: List[int]
:rtype: List[List[int]] | 46.permutations.py | permute | elfgzp/leetCode | 3 | python | def permute(self, nums):
'\n :type nums: List[int]\n :rtype: List[List[int]]\n '
from itertools import permutations
return [list(t) for t in permutations(nums, len(nums))] | def permute(self, nums):
'\n :type nums: List[int]\n :rtype: List[List[int]]\n '
from itertools import permutations
return [list(t) for t in permutations(nums, len(nums))]<|docstring|>:type nums: List[int]
:rtype: List[List[int]]<|endoftext|> |
203f22e29e7669c8d6bfe59b9b83909052c5a9056a677e3ccc97b65da13dec33 | def create(self, validated_data):
'Creates and return new user'
user = models.UserProfile.objects.create_user(email=validated_data['email'], name=validated_data['name'], password=validated_data['password'])
return user | Creates and return new user | profiles_api/serializers.py | create | Basel-h-ashour/Django-Rest-API-Udemy | 0 | python | def create(self, validated_data):
user = models.UserProfile.objects.create_user(email=validated_data['email'], name=validated_data['name'], password=validated_data['password'])
return user | def create(self, validated_data):
user = models.UserProfile.objects.create_user(email=validated_data['email'], name=validated_data['name'], password=validated_data['password'])
return user<|docstring|>Creates and return new user<|endoftext|> |
152bff5f0d6b608d2d798b943c4a104740e88071dc687790cdc452f83998a2be | def get_pool(account_name: Optional[str]=None, pool_name: Optional[str]=None, resource_group_name: Optional[str]=None, opts: Optional[pulumi.InvokeOptions]=None) -> AwaitableGetPoolResult:
'\n Capacity pool resource\n API Version: 2020-11-01.\n\n\n :param str account_name: The name of the NetApp account\n :param str pool_name: The name of the capacity pool\n :param str resource_group_name: The name of the resource group.\n '
__args__ = dict()
__args__['accountName'] = account_name
__args__['poolName'] = pool_name
__args__['resourceGroupName'] = resource_group_name
if (opts is None):
opts = pulumi.InvokeOptions()
if (opts.version is None):
opts.version = _utilities.get_version()
__ret__ = pulumi.runtime.invoke('azure-nextgen:netapp:getPool', __args__, opts=opts, typ=GetPoolResult).value
return AwaitableGetPoolResult(id=__ret__.id, location=__ret__.location, name=__ret__.name, pool_id=__ret__.pool_id, provisioning_state=__ret__.provisioning_state, qos_type=__ret__.qos_type, service_level=__ret__.service_level, size=__ret__.size, tags=__ret__.tags, total_throughput_mibps=__ret__.total_throughput_mibps, type=__ret__.type, utilized_throughput_mibps=__ret__.utilized_throughput_mibps) | Capacity pool resource
API Version: 2020-11-01.
:param str account_name: The name of the NetApp account
:param str pool_name: The name of the capacity pool
:param str resource_group_name: The name of the resource group. | sdk/python/pulumi_azure_nextgen/netapp/get_pool.py | get_pool | pulumi/pulumi-azure-nextgen | 31 | python | def get_pool(account_name: Optional[str]=None, pool_name: Optional[str]=None, resource_group_name: Optional[str]=None, opts: Optional[pulumi.InvokeOptions]=None) -> AwaitableGetPoolResult:
'\n Capacity pool resource\n API Version: 2020-11-01.\n\n\n :param str account_name: The name of the NetApp account\n :param str pool_name: The name of the capacity pool\n :param str resource_group_name: The name of the resource group.\n '
__args__ = dict()
__args__['accountName'] = account_name
__args__['poolName'] = pool_name
__args__['resourceGroupName'] = resource_group_name
if (opts is None):
opts = pulumi.InvokeOptions()
if (opts.version is None):
opts.version = _utilities.get_version()
__ret__ = pulumi.runtime.invoke('azure-nextgen:netapp:getPool', __args__, opts=opts, typ=GetPoolResult).value
return AwaitableGetPoolResult(id=__ret__.id, location=__ret__.location, name=__ret__.name, pool_id=__ret__.pool_id, provisioning_state=__ret__.provisioning_state, qos_type=__ret__.qos_type, service_level=__ret__.service_level, size=__ret__.size, tags=__ret__.tags, total_throughput_mibps=__ret__.total_throughput_mibps, type=__ret__.type, utilized_throughput_mibps=__ret__.utilized_throughput_mibps) | def get_pool(account_name: Optional[str]=None, pool_name: Optional[str]=None, resource_group_name: Optional[str]=None, opts: Optional[pulumi.InvokeOptions]=None) -> AwaitableGetPoolResult:
'\n Capacity pool resource\n API Version: 2020-11-01.\n\n\n :param str account_name: The name of the NetApp account\n :param str pool_name: The name of the capacity pool\n :param str resource_group_name: The name of the resource group.\n '
__args__ = dict()
__args__['accountName'] = account_name
__args__['poolName'] = pool_name
__args__['resourceGroupName'] = resource_group_name
if (opts is None):
opts = pulumi.InvokeOptions()
if (opts.version is None):
opts.version = _utilities.get_version()
__ret__ = pulumi.runtime.invoke('azure-nextgen:netapp:getPool', __args__, opts=opts, typ=GetPoolResult).value
return AwaitableGetPoolResult(id=__ret__.id, location=__ret__.location, name=__ret__.name, pool_id=__ret__.pool_id, provisioning_state=__ret__.provisioning_state, qos_type=__ret__.qos_type, service_level=__ret__.service_level, size=__ret__.size, tags=__ret__.tags, total_throughput_mibps=__ret__.total_throughput_mibps, type=__ret__.type, utilized_throughput_mibps=__ret__.utilized_throughput_mibps)<|docstring|>Capacity pool resource
API Version: 2020-11-01.
:param str account_name: The name of the NetApp account
:param str pool_name: The name of the capacity pool
:param str resource_group_name: The name of the resource group.<|endoftext|> |
c7555b76c32cbace89e835b1a8840f8632ce2e800e091d40a70154c313d15c0c | @property
@pulumi.getter
def id(self) -> str:
'\n Resource Id\n '
return pulumi.get(self, 'id') | Resource Id | sdk/python/pulumi_azure_nextgen/netapp/get_pool.py | id | pulumi/pulumi-azure-nextgen | 31 | python | @property
@pulumi.getter
def id(self) -> str:
'\n \n '
return pulumi.get(self, 'id') | @property
@pulumi.getter
def id(self) -> str:
'\n \n '
return pulumi.get(self, 'id')<|docstring|>Resource Id<|endoftext|> |
f54d78656eb9a7301e74c6419336268cdea0e5d183b5e1bd9aaf4e350382f72a | @property
@pulumi.getter
def location(self) -> str:
'\n Resource location\n '
return pulumi.get(self, 'location') | Resource location | sdk/python/pulumi_azure_nextgen/netapp/get_pool.py | location | pulumi/pulumi-azure-nextgen | 31 | python | @property
@pulumi.getter
def location(self) -> str:
'\n \n '
return pulumi.get(self, 'location') | @property
@pulumi.getter
def location(self) -> str:
'\n \n '
return pulumi.get(self, 'location')<|docstring|>Resource location<|endoftext|> |
c6d0445b1d962fbadc55868ad51474fa56f777490fcbc6fb8cf6d91fa4e5487d | @property
@pulumi.getter
def name(self) -> str:
'\n Resource name\n '
return pulumi.get(self, 'name') | Resource name | sdk/python/pulumi_azure_nextgen/netapp/get_pool.py | name | pulumi/pulumi-azure-nextgen | 31 | python | @property
@pulumi.getter
def name(self) -> str:
'\n \n '
return pulumi.get(self, 'name') | @property
@pulumi.getter
def name(self) -> str:
'\n \n '
return pulumi.get(self, 'name')<|docstring|>Resource name<|endoftext|> |
48102c6d09ee740942c79f2fc99bb4236419dc339e16b6499cb732f28e11a0cf | @property
@pulumi.getter(name='poolId')
def pool_id(self) -> str:
'\n UUID v4 used to identify the Pool\n '
return pulumi.get(self, 'pool_id') | UUID v4 used to identify the Pool | sdk/python/pulumi_azure_nextgen/netapp/get_pool.py | pool_id | pulumi/pulumi-azure-nextgen | 31 | python | @property
@pulumi.getter(name='poolId')
def pool_id(self) -> str:
'\n \n '
return pulumi.get(self, 'pool_id') | @property
@pulumi.getter(name='poolId')
def pool_id(self) -> str:
'\n \n '
return pulumi.get(self, 'pool_id')<|docstring|>UUID v4 used to identify the Pool<|endoftext|> |
941f707f5af948c0cad278d520904eacf4511c5156d39ee69dc678edf9b80079 | @property
@pulumi.getter(name='provisioningState')
def provisioning_state(self) -> str:
'\n Azure lifecycle management\n '
return pulumi.get(self, 'provisioning_state') | Azure lifecycle management | sdk/python/pulumi_azure_nextgen/netapp/get_pool.py | provisioning_state | pulumi/pulumi-azure-nextgen | 31 | python | @property
@pulumi.getter(name='provisioningState')
def provisioning_state(self) -> str:
'\n \n '
return pulumi.get(self, 'provisioning_state') | @property
@pulumi.getter(name='provisioningState')
def provisioning_state(self) -> str:
'\n \n '
return pulumi.get(self, 'provisioning_state')<|docstring|>Azure lifecycle management<|endoftext|> |
61f8b4c083bef4f34404028ca4d64e4813f6189e197a7b2dd3da04e7aa1caab4 | @property
@pulumi.getter(name='qosType')
def qos_type(self) -> Optional[str]:
'\n The qos type of the pool\n '
return pulumi.get(self, 'qos_type') | The qos type of the pool | sdk/python/pulumi_azure_nextgen/netapp/get_pool.py | qos_type | pulumi/pulumi-azure-nextgen | 31 | python | @property
@pulumi.getter(name='qosType')
def qos_type(self) -> Optional[str]:
'\n \n '
return pulumi.get(self, 'qos_type') | @property
@pulumi.getter(name='qosType')
def qos_type(self) -> Optional[str]:
'\n \n '
return pulumi.get(self, 'qos_type')<|docstring|>The qos type of the pool<|endoftext|> |
0c691ef0147de3544eac983ca0428e238d568735542a8b28265a2684d174ace5 | @property
@pulumi.getter(name='serviceLevel')
def service_level(self) -> str:
'\n The service level of the file system\n '
return pulumi.get(self, 'service_level') | The service level of the file system | sdk/python/pulumi_azure_nextgen/netapp/get_pool.py | service_level | pulumi/pulumi-azure-nextgen | 31 | python | @property
@pulumi.getter(name='serviceLevel')
def service_level(self) -> str:
'\n \n '
return pulumi.get(self, 'service_level') | @property
@pulumi.getter(name='serviceLevel')
def service_level(self) -> str:
'\n \n '
return pulumi.get(self, 'service_level')<|docstring|>The service level of the file system<|endoftext|> |
a6166c278ff58b0087703074d95801f7c57288e3afc0f384cb44e50aebe7c01d | @property
@pulumi.getter
def size(self) -> float:
'\n Provisioned size of the pool (in bytes). Allowed values are in 4TiB chunks (value must be multiply of 4398046511104).\n '
return pulumi.get(self, 'size') | Provisioned size of the pool (in bytes). Allowed values are in 4TiB chunks (value must be multiply of 4398046511104). | sdk/python/pulumi_azure_nextgen/netapp/get_pool.py | size | pulumi/pulumi-azure-nextgen | 31 | python | @property
@pulumi.getter
def size(self) -> float:
'\n \n '
return pulumi.get(self, 'size') | @property
@pulumi.getter
def size(self) -> float:
'\n \n '
return pulumi.get(self, 'size')<|docstring|>Provisioned size of the pool (in bytes). Allowed values are in 4TiB chunks (value must be multiply of 4398046511104).<|endoftext|> |
b846b8a8a70927a057c9deabb76b366cbea7ca5499f613c44e07027510c6026e | @property
@pulumi.getter
def tags(self) -> Optional[Mapping[(str, str)]]:
'\n Resource tags\n '
return pulumi.get(self, 'tags') | Resource tags | sdk/python/pulumi_azure_nextgen/netapp/get_pool.py | tags | pulumi/pulumi-azure-nextgen | 31 | python | @property
@pulumi.getter
def tags(self) -> Optional[Mapping[(str, str)]]:
'\n \n '
return pulumi.get(self, 'tags') | @property
@pulumi.getter
def tags(self) -> Optional[Mapping[(str, str)]]:
'\n \n '
return pulumi.get(self, 'tags')<|docstring|>Resource tags<|endoftext|> |
aa4e66fee47feed64eee12c00ebfc093b223dcce0a3897c9323024851a4507a0 | @property
@pulumi.getter(name='totalThroughputMibps')
def total_throughput_mibps(self) -> float:
'\n Total throughput of pool in Mibps\n '
return pulumi.get(self, 'total_throughput_mibps') | Total throughput of pool in Mibps | sdk/python/pulumi_azure_nextgen/netapp/get_pool.py | total_throughput_mibps | pulumi/pulumi-azure-nextgen | 31 | python | @property
@pulumi.getter(name='totalThroughputMibps')
def total_throughput_mibps(self) -> float:
'\n \n '
return pulumi.get(self, 'total_throughput_mibps') | @property
@pulumi.getter(name='totalThroughputMibps')
def total_throughput_mibps(self) -> float:
'\n \n '
return pulumi.get(self, 'total_throughput_mibps')<|docstring|>Total throughput of pool in Mibps<|endoftext|> |
1de5f490c55441e0d371ba61ec23c38c343ce26787fc47ed7b67dd96422f16f0 | @property
@pulumi.getter
def type(self) -> str:
'\n Resource type\n '
return pulumi.get(self, 'type') | Resource type | sdk/python/pulumi_azure_nextgen/netapp/get_pool.py | type | pulumi/pulumi-azure-nextgen | 31 | python | @property
@pulumi.getter
def type(self) -> str:
'\n \n '
return pulumi.get(self, 'type') | @property
@pulumi.getter
def type(self) -> str:
'\n \n '
return pulumi.get(self, 'type')<|docstring|>Resource type<|endoftext|> |
abf74c71d2cf17ed4aef943f613cbce1c6b579b6f5eefa3b7a24234e937aa8cd | @property
@pulumi.getter(name='utilizedThroughputMibps')
def utilized_throughput_mibps(self) -> float:
'\n Utilized throughput of pool in Mibps\n '
return pulumi.get(self, 'utilized_throughput_mibps') | Utilized throughput of pool in Mibps | sdk/python/pulumi_azure_nextgen/netapp/get_pool.py | utilized_throughput_mibps | pulumi/pulumi-azure-nextgen | 31 | python | @property
@pulumi.getter(name='utilizedThroughputMibps')
def utilized_throughput_mibps(self) -> float:
'\n \n '
return pulumi.get(self, 'utilized_throughput_mibps') | @property
@pulumi.getter(name='utilizedThroughputMibps')
def utilized_throughput_mibps(self) -> float:
'\n \n '
return pulumi.get(self, 'utilized_throughput_mibps')<|docstring|>Utilized throughput of pool in Mibps<|endoftext|> |
78ae0c5ee1448cf3982cc9241741e80312b949479692abdfe919c5ec0b1f62ad | def config_logger(name, format='%(message)s', datefmt=None, stream=sys.stdout, level=logging.INFO, filename=None, filemode='w', filelevel=None, propagate=False):
'Do basic configuration for the logging system. Similar to\n logging.basicConfig but the logger ``name`` is configurable and both a file\n output and a stream output can be created. Returns a logger object.\n \n The default behaviour is to create a StreamHandler which writes to\n sys.stdout, set a formatter using the "%(message)s" format string, and\n add the handler to the ``name`` logger.\n \n A number of optional keyword arguments may be specified, which can alter\n the default behaviour.\n\n Parameters\n ----------\n name :\n Logger name\n format :\n handler format string (Default value = \'%(message)s\')\n datefmt :\n handler date/time format specifier (Default value = None)\n stream :\n initialize the StreamHandler using ``stream``\n (None disables the stream, default=sys.stdout)\n level :\n logger level (default=INFO).\n filename :\n create FileHandler using ``filename`` (default=None)\n filemode :\n open ``filename`` with specified filemode (\'w\' or \'a\') (Default value = \'w\')\n filelevel :\n logger level for file logger (default=``level``)\n propagate :\n propagate message to parent (default=False)\n\n Returns\n -------\n type\n logging.Logger object\n\n '
logger = logging.getLogger(name)
logger.setLevel(level)
fmt = logging.Formatter(format, datefmt)
logger.propagate = propagate
for hdlr in logger.handlers:
logger.removeHandler(hdlr)
if (not (filename or stream)):
logger.addHandler(NullHandler())
if filename:
hdlr = logging.FileHandler(filename, filemode)
if (filelevel is None):
filelevel = level
hdlr.setLevel(filelevel)
hdlr.setFormatter(fmt)
logger.addHandler(hdlr)
if stream:
hdlr = logging.StreamHandler(stream)
hdlr.setLevel(level)
hdlr.setFormatter(fmt)
logger.addHandler(hdlr)
return logger | Do basic configuration for the logging system. Similar to
logging.basicConfig but the logger ``name`` is configurable and both a file
output and a stream output can be created. Returns a logger object.
The default behaviour is to create a StreamHandler which writes to
sys.stdout, set a formatter using the "%(message)s" format string, and
add the handler to the ``name`` logger.
A number of optional keyword arguments may be specified, which can alter
the default behaviour.
Parameters
----------
name :
Logger name
format :
handler format string (Default value = '%(message)s')
datefmt :
handler date/time format specifier (Default value = None)
stream :
initialize the StreamHandler using ``stream``
(None disables the stream, default=sys.stdout)
level :
logger level (default=INFO).
filename :
create FileHandler using ``filename`` (default=None)
filemode :
open ``filename`` with specified filemode ('w' or 'a') (Default value = 'w')
filelevel :
logger level for file logger (default=``level``)
propagate :
propagate message to parent (default=False)
Returns
-------
type
logging.Logger object | xija/clogging.py | config_logger | jzuhone/xija | 2 | python | def config_logger(name, format='%(message)s', datefmt=None, stream=sys.stdout, level=logging.INFO, filename=None, filemode='w', filelevel=None, propagate=False):
'Do basic configuration for the logging system. Similar to\n logging.basicConfig but the logger ``name`` is configurable and both a file\n output and a stream output can be created. Returns a logger object.\n \n The default behaviour is to create a StreamHandler which writes to\n sys.stdout, set a formatter using the "%(message)s" format string, and\n add the handler to the ``name`` logger.\n \n A number of optional keyword arguments may be specified, which can alter\n the default behaviour.\n\n Parameters\n ----------\n name :\n Logger name\n format :\n handler format string (Default value = \'%(message)s\')\n datefmt :\n handler date/time format specifier (Default value = None)\n stream :\n initialize the StreamHandler using ``stream``\n (None disables the stream, default=sys.stdout)\n level :\n logger level (default=INFO).\n filename :\n create FileHandler using ``filename`` (default=None)\n filemode :\n open ``filename`` with specified filemode (\'w\' or \'a\') (Default value = \'w\')\n filelevel :\n logger level for file logger (default=``level``)\n propagate :\n propagate message to parent (default=False)\n\n Returns\n -------\n type\n logging.Logger object\n\n '
logger = logging.getLogger(name)
logger.setLevel(level)
fmt = logging.Formatter(format, datefmt)
logger.propagate = propagate
for hdlr in logger.handlers:
logger.removeHandler(hdlr)
if (not (filename or stream)):
logger.addHandler(NullHandler())
if filename:
hdlr = logging.FileHandler(filename, filemode)
if (filelevel is None):
filelevel = level
hdlr.setLevel(filelevel)
hdlr.setFormatter(fmt)
logger.addHandler(hdlr)
if stream:
hdlr = logging.StreamHandler(stream)
hdlr.setLevel(level)
hdlr.setFormatter(fmt)
logger.addHandler(hdlr)
return logger | def config_logger(name, format='%(message)s', datefmt=None, stream=sys.stdout, level=logging.INFO, filename=None, filemode='w', filelevel=None, propagate=False):
'Do basic configuration for the logging system. Similar to\n logging.basicConfig but the logger ``name`` is configurable and both a file\n output and a stream output can be created. Returns a logger object.\n \n The default behaviour is to create a StreamHandler which writes to\n sys.stdout, set a formatter using the "%(message)s" format string, and\n add the handler to the ``name`` logger.\n \n A number of optional keyword arguments may be specified, which can alter\n the default behaviour.\n\n Parameters\n ----------\n name :\n Logger name\n format :\n handler format string (Default value = \'%(message)s\')\n datefmt :\n handler date/time format specifier (Default value = None)\n stream :\n initialize the StreamHandler using ``stream``\n (None disables the stream, default=sys.stdout)\n level :\n logger level (default=INFO).\n filename :\n create FileHandler using ``filename`` (default=None)\n filemode :\n open ``filename`` with specified filemode (\'w\' or \'a\') (Default value = \'w\')\n filelevel :\n logger level for file logger (default=``level``)\n propagate :\n propagate message to parent (default=False)\n\n Returns\n -------\n type\n logging.Logger object\n\n '
logger = logging.getLogger(name)
logger.setLevel(level)
fmt = logging.Formatter(format, datefmt)
logger.propagate = propagate
for hdlr in logger.handlers:
logger.removeHandler(hdlr)
if (not (filename or stream)):
logger.addHandler(NullHandler())
if filename:
hdlr = logging.FileHandler(filename, filemode)
if (filelevel is None):
filelevel = level
hdlr.setLevel(filelevel)
hdlr.setFormatter(fmt)
logger.addHandler(hdlr)
if stream:
hdlr = logging.StreamHandler(stream)
hdlr.setLevel(level)
hdlr.setFormatter(fmt)
logger.addHandler(hdlr)
return logger<|docstring|>Do basic configuration for the logging system. Similar to
logging.basicConfig but the logger ``name`` is configurable and both a file
output and a stream output can be created. Returns a logger object.
The default behaviour is to create a StreamHandler which writes to
sys.stdout, set a formatter using the "%(message)s" format string, and
add the handler to the ``name`` logger.
A number of optional keyword arguments may be specified, which can alter
the default behaviour.
Parameters
----------
name :
Logger name
format :
handler format string (Default value = '%(message)s')
datefmt :
handler date/time format specifier (Default value = None)
stream :
initialize the StreamHandler using ``stream``
(None disables the stream, default=sys.stdout)
level :
logger level (default=INFO).
filename :
create FileHandler using ``filename`` (default=None)
filemode :
open ``filename`` with specified filemode ('w' or 'a') (Default value = 'w')
filelevel :
logger level for file logger (default=``level``)
propagate :
propagate message to parent (default=False)
Returns
-------
type
logging.Logger object<|endoftext|> |
57d2d0e62ba5c9b3218821092176cacb1c0d6c74342fc7903fc4f2a749bf3ff0 | def __init__(self, env=None, env_from=None, selector=None, volume_mounts=None, volumes=None):
'V1alpha1PodPresetSpec - a model defined in OpenAPI'
self._env = None
self._env_from = None
self._selector = None
self._volume_mounts = None
self._volumes = None
self.discriminator = None
if (env is not None):
self.env = env
if (env_from is not None):
self.env_from = env_from
if (selector is not None):
self.selector = selector
if (volume_mounts is not None):
self.volume_mounts = volume_mounts
if (volumes is not None):
self.volumes = volumes | V1alpha1PodPresetSpec - a model defined in OpenAPI | kubernetes/client/models/v1alpha1_pod_preset_spec.py | __init__ | MoShitrit/python | 2 | python | def __init__(self, env=None, env_from=None, selector=None, volume_mounts=None, volumes=None):
self._env = None
self._env_from = None
self._selector = None
self._volume_mounts = None
self._volumes = None
self.discriminator = None
if (env is not None):
self.env = env
if (env_from is not None):
self.env_from = env_from
if (selector is not None):
self.selector = selector
if (volume_mounts is not None):
self.volume_mounts = volume_mounts
if (volumes is not None):
self.volumes = volumes | def __init__(self, env=None, env_from=None, selector=None, volume_mounts=None, volumes=None):
self._env = None
self._env_from = None
self._selector = None
self._volume_mounts = None
self._volumes = None
self.discriminator = None
if (env is not None):
self.env = env
if (env_from is not None):
self.env_from = env_from
if (selector is not None):
self.selector = selector
if (volume_mounts is not None):
self.volume_mounts = volume_mounts
if (volumes is not None):
self.volumes = volumes<|docstring|>V1alpha1PodPresetSpec - a model defined in OpenAPI<|endoftext|> |
af3f30f4fafd59952a8e745b6cbfc782ed542c0f73242832f977c28410fda66b | @property
def env(self):
'Gets the env of this V1alpha1PodPresetSpec. # noqa: E501\n\n Env defines the collection of EnvVar to inject into containers. # noqa: E501\n\n :return: The env of this V1alpha1PodPresetSpec. # noqa: E501\n :rtype: list[V1EnvVar]\n '
return self._env | Gets the env of this V1alpha1PodPresetSpec. # noqa: E501
Env defines the collection of EnvVar to inject into containers. # noqa: E501
:return: The env of this V1alpha1PodPresetSpec. # noqa: E501
:rtype: list[V1EnvVar] | kubernetes/client/models/v1alpha1_pod_preset_spec.py | env | MoShitrit/python | 2 | python | @property
def env(self):
'Gets the env of this V1alpha1PodPresetSpec. # noqa: E501\n\n Env defines the collection of EnvVar to inject into containers. # noqa: E501\n\n :return: The env of this V1alpha1PodPresetSpec. # noqa: E501\n :rtype: list[V1EnvVar]\n '
return self._env | @property
def env(self):
'Gets the env of this V1alpha1PodPresetSpec. # noqa: E501\n\n Env defines the collection of EnvVar to inject into containers. # noqa: E501\n\n :return: The env of this V1alpha1PodPresetSpec. # noqa: E501\n :rtype: list[V1EnvVar]\n '
return self._env<|docstring|>Gets the env of this V1alpha1PodPresetSpec. # noqa: E501
Env defines the collection of EnvVar to inject into containers. # noqa: E501
:return: The env of this V1alpha1PodPresetSpec. # noqa: E501
:rtype: list[V1EnvVar]<|endoftext|> |
bd9dcb412acee839598a1711580c355237a010731fb1001d34edec01a4d0519e | @env.setter
def env(self, env):
'Sets the env of this V1alpha1PodPresetSpec.\n\n Env defines the collection of EnvVar to inject into containers. # noqa: E501\n\n :param env: The env of this V1alpha1PodPresetSpec. # noqa: E501\n :type: list[V1EnvVar]\n '
self._env = env | Sets the env of this V1alpha1PodPresetSpec.
Env defines the collection of EnvVar to inject into containers. # noqa: E501
:param env: The env of this V1alpha1PodPresetSpec. # noqa: E501
:type: list[V1EnvVar] | kubernetes/client/models/v1alpha1_pod_preset_spec.py | env | MoShitrit/python | 2 | python | @env.setter
def env(self, env):
'Sets the env of this V1alpha1PodPresetSpec.\n\n Env defines the collection of EnvVar to inject into containers. # noqa: E501\n\n :param env: The env of this V1alpha1PodPresetSpec. # noqa: E501\n :type: list[V1EnvVar]\n '
self._env = env | @env.setter
def env(self, env):
'Sets the env of this V1alpha1PodPresetSpec.\n\n Env defines the collection of EnvVar to inject into containers. # noqa: E501\n\n :param env: The env of this V1alpha1PodPresetSpec. # noqa: E501\n :type: list[V1EnvVar]\n '
self._env = env<|docstring|>Sets the env of this V1alpha1PodPresetSpec.
Env defines the collection of EnvVar to inject into containers. # noqa: E501
:param env: The env of this V1alpha1PodPresetSpec. # noqa: E501
:type: list[V1EnvVar]<|endoftext|> |
50b0abf0eee05cfb648e5d4fb60dc3f724bbb10d6b1e4a768d15f521f9b1aaf0 | @property
def env_from(self):
'Gets the env_from of this V1alpha1PodPresetSpec. # noqa: E501\n\n EnvFrom defines the collection of EnvFromSource to inject into containers. # noqa: E501\n\n :return: The env_from of this V1alpha1PodPresetSpec. # noqa: E501\n :rtype: list[V1EnvFromSource]\n '
return self._env_from | Gets the env_from of this V1alpha1PodPresetSpec. # noqa: E501
EnvFrom defines the collection of EnvFromSource to inject into containers. # noqa: E501
:return: The env_from of this V1alpha1PodPresetSpec. # noqa: E501
:rtype: list[V1EnvFromSource] | kubernetes/client/models/v1alpha1_pod_preset_spec.py | env_from | MoShitrit/python | 2 | python | @property
def env_from(self):
'Gets the env_from of this V1alpha1PodPresetSpec. # noqa: E501\n\n EnvFrom defines the collection of EnvFromSource to inject into containers. # noqa: E501\n\n :return: The env_from of this V1alpha1PodPresetSpec. # noqa: E501\n :rtype: list[V1EnvFromSource]\n '
return self._env_from | @property
def env_from(self):
'Gets the env_from of this V1alpha1PodPresetSpec. # noqa: E501\n\n EnvFrom defines the collection of EnvFromSource to inject into containers. # noqa: E501\n\n :return: The env_from of this V1alpha1PodPresetSpec. # noqa: E501\n :rtype: list[V1EnvFromSource]\n '
return self._env_from<|docstring|>Gets the env_from of this V1alpha1PodPresetSpec. # noqa: E501
EnvFrom defines the collection of EnvFromSource to inject into containers. # noqa: E501
:return: The env_from of this V1alpha1PodPresetSpec. # noqa: E501
:rtype: list[V1EnvFromSource]<|endoftext|> |
79e3302cf41d291776f47c854d5330c9cc8310ee68f01d222bfc1942eb0cecfd | @env_from.setter
def env_from(self, env_from):
'Sets the env_from of this V1alpha1PodPresetSpec.\n\n EnvFrom defines the collection of EnvFromSource to inject into containers. # noqa: E501\n\n :param env_from: The env_from of this V1alpha1PodPresetSpec. # noqa: E501\n :type: list[V1EnvFromSource]\n '
self._env_from = env_from | Sets the env_from of this V1alpha1PodPresetSpec.
EnvFrom defines the collection of EnvFromSource to inject into containers. # noqa: E501
:param env_from: The env_from of this V1alpha1PodPresetSpec. # noqa: E501
:type: list[V1EnvFromSource] | kubernetes/client/models/v1alpha1_pod_preset_spec.py | env_from | MoShitrit/python | 2 | python | @env_from.setter
def env_from(self, env_from):
'Sets the env_from of this V1alpha1PodPresetSpec.\n\n EnvFrom defines the collection of EnvFromSource to inject into containers. # noqa: E501\n\n :param env_from: The env_from of this V1alpha1PodPresetSpec. # noqa: E501\n :type: list[V1EnvFromSource]\n '
self._env_from = env_from | @env_from.setter
def env_from(self, env_from):
'Sets the env_from of this V1alpha1PodPresetSpec.\n\n EnvFrom defines the collection of EnvFromSource to inject into containers. # noqa: E501\n\n :param env_from: The env_from of this V1alpha1PodPresetSpec. # noqa: E501\n :type: list[V1EnvFromSource]\n '
self._env_from = env_from<|docstring|>Sets the env_from of this V1alpha1PodPresetSpec.
EnvFrom defines the collection of EnvFromSource to inject into containers. # noqa: E501
:param env_from: The env_from of this V1alpha1PodPresetSpec. # noqa: E501
:type: list[V1EnvFromSource]<|endoftext|> |
fcf61f5cac5876b73fad30b839967b67a1dd16811ae67ee1e94c0ed905e3aed5 | @property
def selector(self):
'Gets the selector of this V1alpha1PodPresetSpec. # noqa: E501\n\n\n :return: The selector of this V1alpha1PodPresetSpec. # noqa: E501\n :rtype: V1LabelSelector\n '
return self._selector | Gets the selector of this V1alpha1PodPresetSpec. # noqa: E501
:return: The selector of this V1alpha1PodPresetSpec. # noqa: E501
:rtype: V1LabelSelector | kubernetes/client/models/v1alpha1_pod_preset_spec.py | selector | MoShitrit/python | 2 | python | @property
def selector(self):
'Gets the selector of this V1alpha1PodPresetSpec. # noqa: E501\n\n\n :return: The selector of this V1alpha1PodPresetSpec. # noqa: E501\n :rtype: V1LabelSelector\n '
return self._selector | @property
def selector(self):
'Gets the selector of this V1alpha1PodPresetSpec. # noqa: E501\n\n\n :return: The selector of this V1alpha1PodPresetSpec. # noqa: E501\n :rtype: V1LabelSelector\n '
return self._selector<|docstring|>Gets the selector of this V1alpha1PodPresetSpec. # noqa: E501
:return: The selector of this V1alpha1PodPresetSpec. # noqa: E501
:rtype: V1LabelSelector<|endoftext|> |
22aef2a9fee63bf354cca5ba6103041738623e1a8321c628ef0b8e3c9feec0ac | @selector.setter
def selector(self, selector):
'Sets the selector of this V1alpha1PodPresetSpec.\n\n\n :param selector: The selector of this V1alpha1PodPresetSpec. # noqa: E501\n :type: V1LabelSelector\n '
self._selector = selector | Sets the selector of this V1alpha1PodPresetSpec.
:param selector: The selector of this V1alpha1PodPresetSpec. # noqa: E501
:type: V1LabelSelector | kubernetes/client/models/v1alpha1_pod_preset_spec.py | selector | MoShitrit/python | 2 | python | @selector.setter
def selector(self, selector):
'Sets the selector of this V1alpha1PodPresetSpec.\n\n\n :param selector: The selector of this V1alpha1PodPresetSpec. # noqa: E501\n :type: V1LabelSelector\n '
self._selector = selector | @selector.setter
def selector(self, selector):
'Sets the selector of this V1alpha1PodPresetSpec.\n\n\n :param selector: The selector of this V1alpha1PodPresetSpec. # noqa: E501\n :type: V1LabelSelector\n '
self._selector = selector<|docstring|>Sets the selector of this V1alpha1PodPresetSpec.
:param selector: The selector of this V1alpha1PodPresetSpec. # noqa: E501
:type: V1LabelSelector<|endoftext|> |
b1f673c8070b326adcbae47933869aebf8aff4646fc2c8a68e273ff0c44b647c | @property
def volume_mounts(self):
'Gets the volume_mounts of this V1alpha1PodPresetSpec. # noqa: E501\n\n VolumeMounts defines the collection of VolumeMount to inject into containers. # noqa: E501\n\n :return: The volume_mounts of this V1alpha1PodPresetSpec. # noqa: E501\n :rtype: list[V1VolumeMount]\n '
return self._volume_mounts | Gets the volume_mounts of this V1alpha1PodPresetSpec. # noqa: E501
VolumeMounts defines the collection of VolumeMount to inject into containers. # noqa: E501
:return: The volume_mounts of this V1alpha1PodPresetSpec. # noqa: E501
:rtype: list[V1VolumeMount] | kubernetes/client/models/v1alpha1_pod_preset_spec.py | volume_mounts | MoShitrit/python | 2 | python | @property
def volume_mounts(self):
'Gets the volume_mounts of this V1alpha1PodPresetSpec. # noqa: E501\n\n VolumeMounts defines the collection of VolumeMount to inject into containers. # noqa: E501\n\n :return: The volume_mounts of this V1alpha1PodPresetSpec. # noqa: E501\n :rtype: list[V1VolumeMount]\n '
return self._volume_mounts | @property
def volume_mounts(self):
'Gets the volume_mounts of this V1alpha1PodPresetSpec. # noqa: E501\n\n VolumeMounts defines the collection of VolumeMount to inject into containers. # noqa: E501\n\n :return: The volume_mounts of this V1alpha1PodPresetSpec. # noqa: E501\n :rtype: list[V1VolumeMount]\n '
return self._volume_mounts<|docstring|>Gets the volume_mounts of this V1alpha1PodPresetSpec. # noqa: E501
VolumeMounts defines the collection of VolumeMount to inject into containers. # noqa: E501
:return: The volume_mounts of this V1alpha1PodPresetSpec. # noqa: E501
:rtype: list[V1VolumeMount]<|endoftext|> |
a5c64357846452b7e5dbf7b74b41c9d99375f90ff42b67baaa0d99308adbcb99 | @volume_mounts.setter
def volume_mounts(self, volume_mounts):
'Sets the volume_mounts of this V1alpha1PodPresetSpec.\n\n VolumeMounts defines the collection of VolumeMount to inject into containers. # noqa: E501\n\n :param volume_mounts: The volume_mounts of this V1alpha1PodPresetSpec. # noqa: E501\n :type: list[V1VolumeMount]\n '
self._volume_mounts = volume_mounts | Sets the volume_mounts of this V1alpha1PodPresetSpec.
VolumeMounts defines the collection of VolumeMount to inject into containers. # noqa: E501
:param volume_mounts: The volume_mounts of this V1alpha1PodPresetSpec. # noqa: E501
:type: list[V1VolumeMount] | kubernetes/client/models/v1alpha1_pod_preset_spec.py | volume_mounts | MoShitrit/python | 2 | python | @volume_mounts.setter
def volume_mounts(self, volume_mounts):
'Sets the volume_mounts of this V1alpha1PodPresetSpec.\n\n VolumeMounts defines the collection of VolumeMount to inject into containers. # noqa: E501\n\n :param volume_mounts: The volume_mounts of this V1alpha1PodPresetSpec. # noqa: E501\n :type: list[V1VolumeMount]\n '
self._volume_mounts = volume_mounts | @volume_mounts.setter
def volume_mounts(self, volume_mounts):
'Sets the volume_mounts of this V1alpha1PodPresetSpec.\n\n VolumeMounts defines the collection of VolumeMount to inject into containers. # noqa: E501\n\n :param volume_mounts: The volume_mounts of this V1alpha1PodPresetSpec. # noqa: E501\n :type: list[V1VolumeMount]\n '
self._volume_mounts = volume_mounts<|docstring|>Sets the volume_mounts of this V1alpha1PodPresetSpec.
VolumeMounts defines the collection of VolumeMount to inject into containers. # noqa: E501
:param volume_mounts: The volume_mounts of this V1alpha1PodPresetSpec. # noqa: E501
:type: list[V1VolumeMount]<|endoftext|> |
47c536ccdfabdb9e176849c8b58b53e6cf40872b76d0d0bd14cba0278396532c | @property
def volumes(self):
'Gets the volumes of this V1alpha1PodPresetSpec. # noqa: E501\n\n Volumes defines the collection of Volume to inject into the pod. # noqa: E501\n\n :return: The volumes of this V1alpha1PodPresetSpec. # noqa: E501\n :rtype: list[V1Volume]\n '
return self._volumes | Gets the volumes of this V1alpha1PodPresetSpec. # noqa: E501
Volumes defines the collection of Volume to inject into the pod. # noqa: E501
:return: The volumes of this V1alpha1PodPresetSpec. # noqa: E501
:rtype: list[V1Volume] | kubernetes/client/models/v1alpha1_pod_preset_spec.py | volumes | MoShitrit/python | 2 | python | @property
def volumes(self):
'Gets the volumes of this V1alpha1PodPresetSpec. # noqa: E501\n\n Volumes defines the collection of Volume to inject into the pod. # noqa: E501\n\n :return: The volumes of this V1alpha1PodPresetSpec. # noqa: E501\n :rtype: list[V1Volume]\n '
return self._volumes | @property
def volumes(self):
'Gets the volumes of this V1alpha1PodPresetSpec. # noqa: E501\n\n Volumes defines the collection of Volume to inject into the pod. # noqa: E501\n\n :return: The volumes of this V1alpha1PodPresetSpec. # noqa: E501\n :rtype: list[V1Volume]\n '
return self._volumes<|docstring|>Gets the volumes of this V1alpha1PodPresetSpec. # noqa: E501
Volumes defines the collection of Volume to inject into the pod. # noqa: E501
:return: The volumes of this V1alpha1PodPresetSpec. # noqa: E501
:rtype: list[V1Volume]<|endoftext|> |
cd79e6e41134f756714ada68b22cd42d2492c175f97bca50797dc4d2deaa9378 | @volumes.setter
def volumes(self, volumes):
'Sets the volumes of this V1alpha1PodPresetSpec.\n\n Volumes defines the collection of Volume to inject into the pod. # noqa: E501\n\n :param volumes: The volumes of this V1alpha1PodPresetSpec. # noqa: E501\n :type: list[V1Volume]\n '
self._volumes = volumes | Sets the volumes of this V1alpha1PodPresetSpec.
Volumes defines the collection of Volume to inject into the pod. # noqa: E501
:param volumes: The volumes of this V1alpha1PodPresetSpec. # noqa: E501
:type: list[V1Volume] | kubernetes/client/models/v1alpha1_pod_preset_spec.py | volumes | MoShitrit/python | 2 | python | @volumes.setter
def volumes(self, volumes):
'Sets the volumes of this V1alpha1PodPresetSpec.\n\n Volumes defines the collection of Volume to inject into the pod. # noqa: E501\n\n :param volumes: The volumes of this V1alpha1PodPresetSpec. # noqa: E501\n :type: list[V1Volume]\n '
self._volumes = volumes | @volumes.setter
def volumes(self, volumes):
'Sets the volumes of this V1alpha1PodPresetSpec.\n\n Volumes defines the collection of Volume to inject into the pod. # noqa: E501\n\n :param volumes: The volumes of this V1alpha1PodPresetSpec. # noqa: E501\n :type: list[V1Volume]\n '
self._volumes = volumes<|docstring|>Sets the volumes of this V1alpha1PodPresetSpec.
Volumes defines the collection of Volume to inject into the pod. # noqa: E501
:param volumes: The volumes of this V1alpha1PodPresetSpec. # noqa: E501
:type: list[V1Volume]<|endoftext|> |
5a4e41bb6a0def746593298cb605df98f1366e957c4ca89b12010ea7db707963 | def to_dict(self):
'Returns the model properties as a dict'
result = {}
for (attr, _) in six.iteritems(self.openapi_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map((lambda x: (x.to_dict() if hasattr(x, 'to_dict') else x)), value))
elif hasattr(value, 'to_dict'):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map((lambda item: ((item[0], item[1].to_dict()) if hasattr(item[1], 'to_dict') else item)), value.items()))
else:
result[attr] = value
return result | Returns the model properties as a dict | kubernetes/client/models/v1alpha1_pod_preset_spec.py | to_dict | MoShitrit/python | 2 | python | def to_dict(self):
result = {}
for (attr, _) in six.iteritems(self.openapi_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map((lambda x: (x.to_dict() if hasattr(x, 'to_dict') else x)), value))
elif hasattr(value, 'to_dict'):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map((lambda item: ((item[0], item[1].to_dict()) if hasattr(item[1], 'to_dict') else item)), value.items()))
else:
result[attr] = value
return result | def to_dict(self):
result = {}
for (attr, _) in six.iteritems(self.openapi_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map((lambda x: (x.to_dict() if hasattr(x, 'to_dict') else x)), value))
elif hasattr(value, 'to_dict'):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map((lambda item: ((item[0], item[1].to_dict()) if hasattr(item[1], 'to_dict') else item)), value.items()))
else:
result[attr] = value
return result<|docstring|>Returns the model properties as a dict<|endoftext|> |
cbb19eaa2fc8a113d9e32f924ef280a7e97563f8915f94f65dab438997af2e99 | def to_str(self):
'Returns the string representation of the model'
return pprint.pformat(self.to_dict()) | Returns the string representation of the model | kubernetes/client/models/v1alpha1_pod_preset_spec.py | to_str | MoShitrit/python | 2 | python | def to_str(self):
return pprint.pformat(self.to_dict()) | def to_str(self):
return pprint.pformat(self.to_dict())<|docstring|>Returns the string representation of the model<|endoftext|> |
772243a2c2b3261a9b954d07aaf295e3c1242a579a495e2d6a5679c677861703 | def __repr__(self):
'For `print` and `pprint`'
return self.to_str() | For `print` and `pprint` | kubernetes/client/models/v1alpha1_pod_preset_spec.py | __repr__ | MoShitrit/python | 2 | python | def __repr__(self):
return self.to_str() | def __repr__(self):
return self.to_str()<|docstring|>For `print` and `pprint`<|endoftext|> |
7b118065b30acee7fd9d000b39d8926d9121807519ef37bc5d565bdadb08b525 | def __eq__(self, other):
'Returns true if both objects are equal'
if (not isinstance(other, V1alpha1PodPresetSpec)):
return False
return (self.__dict__ == other.__dict__) | Returns true if both objects are equal | kubernetes/client/models/v1alpha1_pod_preset_spec.py | __eq__ | MoShitrit/python | 2 | python | def __eq__(self, other):
if (not isinstance(other, V1alpha1PodPresetSpec)):
return False
return (self.__dict__ == other.__dict__) | def __eq__(self, other):
if (not isinstance(other, V1alpha1PodPresetSpec)):
return False
return (self.__dict__ == other.__dict__)<|docstring|>Returns true if both objects are equal<|endoftext|> |
43dc6740163eb9fc1161d09cb2208a64c7ad0cc8d9c8637ac3264522d3ec7e42 | def __ne__(self, other):
'Returns true if both objects are not equal'
return (not (self == other)) | Returns true if both objects are not equal | kubernetes/client/models/v1alpha1_pod_preset_spec.py | __ne__ | MoShitrit/python | 2 | python | def __ne__(self, other):
return (not (self == other)) | def __ne__(self, other):
return (not (self == other))<|docstring|>Returns true if both objects are not equal<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.