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 |
|---|---|---|---|---|---|---|---|---|---|
729ced47d4e2c406a3cad6c25a1d67d4393472de76d8205600eb81af8f9368ec | @convert_to_seconds(['t_start', 't_end'])
@apply_to_mask
@apply_to_audio
def subclip(self, t_start=0, t_end=None):
"\n Returns a clip playing the content of the current clip\n between times ``t_start`` and ``t_end``, which can be expressed\n in seconds (15.35), in (min, sec), in (hour, min, sec), or as a\n string: '01:03:05.35'.\n If ``t_end`` is not provided, it is assumed to be the duration\n of the clip (potentially infinite).\n If ``t_end`` is a negative value, it is reset to\n ``clip.duration + t_end. ``. For instance: ::\n\n >>> # cut the last two seconds of the clip:\n >>> newclip = clip.subclip(0,-2)\n\n If ``t_end`` is provided or if the clip has a duration attribute,\n the duration of the returned clip is set automatically.\n\n The ``mask`` and ``audio`` of the resulting subclip will be\n subclips of ``mask`` and ``audio`` the original clip, if\n they exist.\n "
if (t_start < 0):
t_start = (self.duration + t_start)
if ((self.duration is not None) and (t_start > self.duration)):
raise ValueError(((('t_start (%.02f) ' % t_start) + "should be smaller than the clip's ") + ('duration (%.02f).' % self.duration)))
newclip = self.fl_time((lambda t: (t + t_start)), apply_to=[])
if ((t_end is None) and (self.duration is not None)):
t_end = self.duration
elif ((t_end is not None) and (t_end < 0)):
if (self.duration is None):
print((('Error: subclip with negative times (here %s)' % str((t_start, t_end))) + ' can only be extracted from clips with a ``duration``'))
else:
t_end = (self.duration + t_end)
if (t_end is not None):
newclip.duration = (t_end - t_start)
newclip.end = (newclip.start + newclip.duration)
return newclip | Returns a clip playing the content of the current clip
between times ``t_start`` and ``t_end``, which can be expressed
in seconds (15.35), in (min, sec), in (hour, min, sec), or as a
string: '01:03:05.35'.
If ``t_end`` is not provided, it is assumed to be the duration
of the clip (potentially infinite).
If ``t_end`` is a negative value, it is reset to
``clip.duration + t_end. ``. For instance: ::
>>> # cut the last two seconds of the clip:
>>> newclip = clip.subclip(0,-2)
If ``t_end`` is provided or if the clip has a duration attribute,
the duration of the returned clip is set automatically.
The ``mask`` and ``audio`` of the resulting subclip will be
subclips of ``mask`` and ``audio`` the original clip, if
they exist. | moviepy/Clip.py | subclip | Baronsindo/moviepy | 3 | python | @convert_to_seconds(['t_start', 't_end'])
@apply_to_mask
@apply_to_audio
def subclip(self, t_start=0, t_end=None):
"\n Returns a clip playing the content of the current clip\n between times ``t_start`` and ``t_end``, which can be expressed\n in seconds (15.35), in (min, sec), in (hour, min, sec), or as a\n string: '01:03:05.35'.\n If ``t_end`` is not provided, it is assumed to be the duration\n of the clip (potentially infinite).\n If ``t_end`` is a negative value, it is reset to\n ``clip.duration + t_end. ``. For instance: ::\n\n >>> # cut the last two seconds of the clip:\n >>> newclip = clip.subclip(0,-2)\n\n If ``t_end`` is provided or if the clip has a duration attribute,\n the duration of the returned clip is set automatically.\n\n The ``mask`` and ``audio`` of the resulting subclip will be\n subclips of ``mask`` and ``audio`` the original clip, if\n they exist.\n "
if (t_start < 0):
t_start = (self.duration + t_start)
if ((self.duration is not None) and (t_start > self.duration)):
raise ValueError(((('t_start (%.02f) ' % t_start) + "should be smaller than the clip's ") + ('duration (%.02f).' % self.duration)))
newclip = self.fl_time((lambda t: (t + t_start)), apply_to=[])
if ((t_end is None) and (self.duration is not None)):
t_end = self.duration
elif ((t_end is not None) and (t_end < 0)):
if (self.duration is None):
print((('Error: subclip with negative times (here %s)' % str((t_start, t_end))) + ' can only be extracted from clips with a ``duration``'))
else:
t_end = (self.duration + t_end)
if (t_end is not None):
newclip.duration = (t_end - t_start)
newclip.end = (newclip.start + newclip.duration)
return newclip | @convert_to_seconds(['t_start', 't_end'])
@apply_to_mask
@apply_to_audio
def subclip(self, t_start=0, t_end=None):
"\n Returns a clip playing the content of the current clip\n between times ``t_start`` and ``t_end``, which can be expressed\n in seconds (15.35), in (min, sec), in (hour, min, sec), or as a\n string: '01:03:05.35'.\n If ``t_end`` is not provided, it is assumed to be the duration\n of the clip (potentially infinite).\n If ``t_end`` is a negative value, it is reset to\n ``clip.duration + t_end. ``. For instance: ::\n\n >>> # cut the last two seconds of the clip:\n >>> newclip = clip.subclip(0,-2)\n\n If ``t_end`` is provided or if the clip has a duration attribute,\n the duration of the returned clip is set automatically.\n\n The ``mask`` and ``audio`` of the resulting subclip will be\n subclips of ``mask`` and ``audio`` the original clip, if\n they exist.\n "
if (t_start < 0):
t_start = (self.duration + t_start)
if ((self.duration is not None) and (t_start > self.duration)):
raise ValueError(((('t_start (%.02f) ' % t_start) + "should be smaller than the clip's ") + ('duration (%.02f).' % self.duration)))
newclip = self.fl_time((lambda t: (t + t_start)), apply_to=[])
if ((t_end is None) and (self.duration is not None)):
t_end = self.duration
elif ((t_end is not None) and (t_end < 0)):
if (self.duration is None):
print((('Error: subclip with negative times (here %s)' % str((t_start, t_end))) + ' can only be extracted from clips with a ``duration``'))
else:
t_end = (self.duration + t_end)
if (t_end is not None):
newclip.duration = (t_end - t_start)
newclip.end = (newclip.start + newclip.duration)
return newclip<|docstring|>Returns a clip playing the content of the current clip
between times ``t_start`` and ``t_end``, which can be expressed
in seconds (15.35), in (min, sec), in (hour, min, sec), or as a
string: '01:03:05.35'.
If ``t_end`` is not provided, it is assumed to be the duration
of the clip (potentially infinite).
If ``t_end`` is a negative value, it is reset to
``clip.duration + t_end. ``. For instance: ::
>>> # cut the last two seconds of the clip:
>>> newclip = clip.subclip(0,-2)
If ``t_end`` is provided or if the clip has a duration attribute,
the duration of the returned clip is set automatically.
The ``mask`` and ``audio`` of the resulting subclip will be
subclips of ``mask`` and ``audio`` the original clip, if
they exist.<|endoftext|> |
7dbdd10ae39c9ab41ba2c647701b8b67f1b55d6e1dac47f0f0af18e076f163df | @apply_to_mask
@apply_to_audio
@convert_to_seconds(['ta', 'tb'])
def cutout(self, ta, tb):
"\n Returns a clip playing the content of the current clip but\n skips the extract between ``ta`` and ``tb``, which can be\n expressed in seconds (15.35), in (min, sec), in (hour, min, sec),\n or as a string: '01:03:05.35'.\n If the original clip has a ``duration`` attribute set,\n the duration of the returned clip is automatically computed as\n `` duration - (tb - ta)``.\n\n The resulting clip's ``audio`` and ``mask`` will also be cutout\n if they exist.\n "
fl = (lambda t: (t + ((t >= ta) * (tb - ta))))
newclip = self.fl_time(fl)
if (self.duration is not None):
return newclip.set_duration((self.duration - (tb - ta)))
else:
return newclip | Returns a clip playing the content of the current clip but
skips the extract between ``ta`` and ``tb``, which can be
expressed in seconds (15.35), in (min, sec), in (hour, min, sec),
or as a string: '01:03:05.35'.
If the original clip has a ``duration`` attribute set,
the duration of the returned clip is automatically computed as
`` duration - (tb - ta)``.
The resulting clip's ``audio`` and ``mask`` will also be cutout
if they exist. | moviepy/Clip.py | cutout | Baronsindo/moviepy | 3 | python | @apply_to_mask
@apply_to_audio
@convert_to_seconds(['ta', 'tb'])
def cutout(self, ta, tb):
"\n Returns a clip playing the content of the current clip but\n skips the extract between ``ta`` and ``tb``, which can be\n expressed in seconds (15.35), in (min, sec), in (hour, min, sec),\n or as a string: '01:03:05.35'.\n If the original clip has a ``duration`` attribute set,\n the duration of the returned clip is automatically computed as\n `` duration - (tb - ta)``.\n\n The resulting clip's ``audio`` and ``mask`` will also be cutout\n if they exist.\n "
fl = (lambda t: (t + ((t >= ta) * (tb - ta))))
newclip = self.fl_time(fl)
if (self.duration is not None):
return newclip.set_duration((self.duration - (tb - ta)))
else:
return newclip | @apply_to_mask
@apply_to_audio
@convert_to_seconds(['ta', 'tb'])
def cutout(self, ta, tb):
"\n Returns a clip playing the content of the current clip but\n skips the extract between ``ta`` and ``tb``, which can be\n expressed in seconds (15.35), in (min, sec), in (hour, min, sec),\n or as a string: '01:03:05.35'.\n If the original clip has a ``duration`` attribute set,\n the duration of the returned clip is automatically computed as\n `` duration - (tb - ta)``.\n\n The resulting clip's ``audio`` and ``mask`` will also be cutout\n if they exist.\n "
fl = (lambda t: (t + ((t >= ta) * (tb - ta))))
newclip = self.fl_time(fl)
if (self.duration is not None):
return newclip.set_duration((self.duration - (tb - ta)))
else:
return newclip<|docstring|>Returns a clip playing the content of the current clip but
skips the extract between ``ta`` and ``tb``, which can be
expressed in seconds (15.35), in (min, sec), in (hour, min, sec),
or as a string: '01:03:05.35'.
If the original clip has a ``duration`` attribute set,
the duration of the returned clip is automatically computed as
`` duration - (tb - ta)``.
The resulting clip's ``audio`` and ``mask`` will also be cutout
if they exist.<|endoftext|> |
50590b300810a2407586240ebe3596deec32228089cb04ed2f00b0a8c80248a9 | @requires_duration
@use_clip_fps_by_default
def iter_frames(self, fps=None, with_times=False, logger=None, dtype=None):
' Iterates over all the frames of the clip.\n\n Returns each frame of the clip as a HxWxN np.array,\n where N=1 for mask clips and N=3 for RGB clips.\n\n This function is not really meant for video editing.\n It provides an easy way to do frame-by-frame treatment of\n a video, for fields like science, computer vision...\n\n The ``fps`` (frames per second) parameter is optional if the\n clip already has a ``fps`` attribute.\n\n Use dtype="uint8" when using the pictures to write video, images...\n\n Examples\n ---------\n\n >>> # prints the maximum of red that is contained\n >>> # on the first line of each frame of the clip.\n >>> from moviepy.editor import VideoFileClip\n >>> myclip = VideoFileClip(\'myvideo.mp4\')\n >>> print ( [frame[0,:,0].max()\n for frame in myclip.iter_frames()])\n '
logger = proglog.default_bar_logger(logger)
for t in logger.iter_bar(t=np.arange(0, self.duration, (1.0 / fps))):
frame = self.get_frame(t)
if ((dtype is not None) and (frame.dtype != dtype)):
frame = frame.astype(dtype)
if with_times:
(yield (t, frame))
else:
(yield frame) | Iterates over all the frames of the clip.
Returns each frame of the clip as a HxWxN np.array,
where N=1 for mask clips and N=3 for RGB clips.
This function is not really meant for video editing.
It provides an easy way to do frame-by-frame treatment of
a video, for fields like science, computer vision...
The ``fps`` (frames per second) parameter is optional if the
clip already has a ``fps`` attribute.
Use dtype="uint8" when using the pictures to write video, images...
Examples
---------
>>> # prints the maximum of red that is contained
>>> # on the first line of each frame of the clip.
>>> from moviepy.editor import VideoFileClip
>>> myclip = VideoFileClip('myvideo.mp4')
>>> print ( [frame[0,:,0].max()
for frame in myclip.iter_frames()]) | moviepy/Clip.py | iter_frames | Baronsindo/moviepy | 3 | python | @requires_duration
@use_clip_fps_by_default
def iter_frames(self, fps=None, with_times=False, logger=None, dtype=None):
' Iterates over all the frames of the clip.\n\n Returns each frame of the clip as a HxWxN np.array,\n where N=1 for mask clips and N=3 for RGB clips.\n\n This function is not really meant for video editing.\n It provides an easy way to do frame-by-frame treatment of\n a video, for fields like science, computer vision...\n\n The ``fps`` (frames per second) parameter is optional if the\n clip already has a ``fps`` attribute.\n\n Use dtype="uint8" when using the pictures to write video, images...\n\n Examples\n ---------\n\n >>> # prints the maximum of red that is contained\n >>> # on the first line of each frame of the clip.\n >>> from moviepy.editor import VideoFileClip\n >>> myclip = VideoFileClip(\'myvideo.mp4\')\n >>> print ( [frame[0,:,0].max()\n for frame in myclip.iter_frames()])\n '
logger = proglog.default_bar_logger(logger)
for t in logger.iter_bar(t=np.arange(0, self.duration, (1.0 / fps))):
frame = self.get_frame(t)
if ((dtype is not None) and (frame.dtype != dtype)):
frame = frame.astype(dtype)
if with_times:
(yield (t, frame))
else:
(yield frame) | @requires_duration
@use_clip_fps_by_default
def iter_frames(self, fps=None, with_times=False, logger=None, dtype=None):
' Iterates over all the frames of the clip.\n\n Returns each frame of the clip as a HxWxN np.array,\n where N=1 for mask clips and N=3 for RGB clips.\n\n This function is not really meant for video editing.\n It provides an easy way to do frame-by-frame treatment of\n a video, for fields like science, computer vision...\n\n The ``fps`` (frames per second) parameter is optional if the\n clip already has a ``fps`` attribute.\n\n Use dtype="uint8" when using the pictures to write video, images...\n\n Examples\n ---------\n\n >>> # prints the maximum of red that is contained\n >>> # on the first line of each frame of the clip.\n >>> from moviepy.editor import VideoFileClip\n >>> myclip = VideoFileClip(\'myvideo.mp4\')\n >>> print ( [frame[0,:,0].max()\n for frame in myclip.iter_frames()])\n '
logger = proglog.default_bar_logger(logger)
for t in logger.iter_bar(t=np.arange(0, self.duration, (1.0 / fps))):
frame = self.get_frame(t)
if ((dtype is not None) and (frame.dtype != dtype)):
frame = frame.astype(dtype)
if with_times:
(yield (t, frame))
else:
(yield frame)<|docstring|>Iterates over all the frames of the clip.
Returns each frame of the clip as a HxWxN np.array,
where N=1 for mask clips and N=3 for RGB clips.
This function is not really meant for video editing.
It provides an easy way to do frame-by-frame treatment of
a video, for fields like science, computer vision...
The ``fps`` (frames per second) parameter is optional if the
clip already has a ``fps`` attribute.
Use dtype="uint8" when using the pictures to write video, images...
Examples
---------
>>> # prints the maximum of red that is contained
>>> # on the first line of each frame of the clip.
>>> from moviepy.editor import VideoFileClip
>>> myclip = VideoFileClip('myvideo.mp4')
>>> print ( [frame[0,:,0].max()
for frame in myclip.iter_frames()])<|endoftext|> |
d81536a2cf2fcb261d4a5d16566ce3e4c77fb5539b4ba2f9d143aee5b0182bcc | def close(self):
' \n Release any resources that are in use.\n '
pass | Release any resources that are in use. | moviepy/Clip.py | close | Baronsindo/moviepy | 3 | python | def close(self):
' \n \n '
pass | def close(self):
' \n \n '
pass<|docstring|>Release any resources that are in use.<|endoftext|> |
bfc49b56f155f3feb73279868e0159d4fcb1d8b6184d4c790ebd65c9b5242e43 | def delete_all_requests(conn):
'\n Delete all rows in the tasks table\n :param conn: Connection to the SQLite database\n :return:\n '
sql = 'DELETE FROM projects'
cur = conn.cursor()
cur.execute(sql)
conn.commit() | Delete all rows in the tasks table
:param conn: Connection to the SQLite database
:return: | sqlite.py | delete_all_requests | TheBroMoe/Authenticate.Me | 0 | python | def delete_all_requests(conn):
'\n Delete all rows in the tasks table\n :param conn: Connection to the SQLite database\n :return:\n '
sql = 'DELETE FROM projects'
cur = conn.cursor()
cur.execute(sql)
conn.commit() | def delete_all_requests(conn):
'\n Delete all rows in the tasks table\n :param conn: Connection to the SQLite database\n :return:\n '
sql = 'DELETE FROM projects'
cur = conn.cursor()
cur.execute(sql)
conn.commit()<|docstring|>Delete all rows in the tasks table
:param conn: Connection to the SQLite database
:return:<|endoftext|> |
9a7f6e8a9645cbaa77dd0434dc1940f75cf7ed44b393b3be5d13d855c1e798af | def structure_to_form_actions(structure):
'Convert a list of python objects to a list of form actions. If the python\n object is a tuple, a CallMethod is constructed with this tuple as arguments. If\n the python object is an instance of as Action, it is kept as is.\n '
from .list_action import CallMethod
def object_to_action(o):
if isinstance(o, Action):
return o
return CallMethod(o[0], o[1])
return [object_to_action(o) for o in structure] | Convert a list of python objects to a list of form actions. If the python
object is a tuple, a CallMethod is constructed with this tuple as arguments. If
the python object is an instance of as Action, it is kept as is. | camelot/admin/action/form_action.py | structure_to_form_actions | Kristof-Welslau/camelot | 12 | python | def structure_to_form_actions(structure):
'Convert a list of python objects to a list of form actions. If the python\n object is a tuple, a CallMethod is constructed with this tuple as arguments. If\n the python object is an instance of as Action, it is kept as is.\n '
from .list_action import CallMethod
def object_to_action(o):
if isinstance(o, Action):
return o
return CallMethod(o[0], o[1])
return [object_to_action(o) for o in structure] | def structure_to_form_actions(structure):
'Convert a list of python objects to a list of form actions. If the python\n object is a tuple, a CallMethod is constructed with this tuple as arguments. If\n the python object is an instance of as Action, it is kept as is.\n '
from .list_action import CallMethod
def object_to_action(o):
if isinstance(o, Action):
return o
return CallMethod(o[0], o[1])
return [object_to_action(o) for o in structure]<|docstring|>Convert a list of python objects to a list of form actions. If the python
object is a tuple, a CallMethod is constructed with this tuple as arguments. If
the python object is an instance of as Action, it is kept as is.<|endoftext|> |
0791cb807f34918cf02a7d64bb7722679d189a92efb4e3db35ccb4dbc9d72515 | def get_object(self):
'\n :return: the object currently displayed in the form, None if no object\n is displayed yet\n '
if (self.current_row != None):
return self._model._get_object(self.current_row) | :return: the object currently displayed in the form, None if no object
is displayed yet | camelot/admin/action/form_action.py | get_object | Kristof-Welslau/camelot | 12 | python | def get_object(self):
'\n :return: the object currently displayed in the form, None if no object\n is displayed yet\n '
if (self.current_row != None):
return self._model._get_object(self.current_row) | def get_object(self):
'\n :return: the object currently displayed in the form, None if no object\n is displayed yet\n '
if (self.current_row != None):
return self._model._get_object(self.current_row)<|docstring|>:return: the object currently displayed in the form, None if no object
is displayed yet<|endoftext|> |
c1909dfd3800055bf017db99d01f8e68a270cfa5ba2eadb95a5b02f26b5fdf70 | def get_collection(self, yield_per=None):
'\n :param yield_per: an integer number giving a hint on how many objects\n should fetched from the database at the same time.\n :return: a generator over the objects in the list\n '
for obj in self._model.get_collection():
(yield obj) | :param yield_per: an integer number giving a hint on how many objects
should fetched from the database at the same time.
:return: a generator over the objects in the list | camelot/admin/action/form_action.py | get_collection | Kristof-Welslau/camelot | 12 | python | def get_collection(self, yield_per=None):
'\n :param yield_per: an integer number giving a hint on how many objects\n should fetched from the database at the same time.\n :return: a generator over the objects in the list\n '
for obj in self._model.get_collection():
(yield obj) | def get_collection(self, yield_per=None):
'\n :param yield_per: an integer number giving a hint on how many objects\n should fetched from the database at the same time.\n :return: a generator over the objects in the list\n '
for obj in self._model.get_collection():
(yield obj)<|docstring|>:param yield_per: an integer number giving a hint on how many objects
should fetched from the database at the same time.
:return: a generator over the objects in the list<|endoftext|> |
2f51f7708db065e354d9d7b7bfa4a3ef5995f73d726a545313b8ddf8c6e78943 | def get_selection(self, yield_per=None):
"\n Method to be compatible with a \n :class:`camelot.admin.action.list_action.ListActionModelContext`, this\n allows creating a single Action to be used on a form and on list.\n \n :param yield_per: this parameter has no effect, it's here only for\n compatibility with :meth:`camelot.admin.action.list_action.ListActionModelContext.get_selection`\n :return: a generator that yields the current object displayed in the \n form and does not yield anything if no object is displayed yet\n in the form.\n "
if (self.current_row != None):
(yield self._model._get_object(self.current_row)) | Method to be compatible with a
:class:`camelot.admin.action.list_action.ListActionModelContext`, this
allows creating a single Action to be used on a form and on list.
:param yield_per: this parameter has no effect, it's here only for
compatibility with :meth:`camelot.admin.action.list_action.ListActionModelContext.get_selection`
:return: a generator that yields the current object displayed in the
form and does not yield anything if no object is displayed yet
in the form. | camelot/admin/action/form_action.py | get_selection | Kristof-Welslau/camelot | 12 | python | def get_selection(self, yield_per=None):
"\n Method to be compatible with a \n :class:`camelot.admin.action.list_action.ListActionModelContext`, this\n allows creating a single Action to be used on a form and on list.\n \n :param yield_per: this parameter has no effect, it's here only for\n compatibility with :meth:`camelot.admin.action.list_action.ListActionModelContext.get_selection`\n :return: a generator that yields the current object displayed in the \n form and does not yield anything if no object is displayed yet\n in the form.\n "
if (self.current_row != None):
(yield self._model._get_object(self.current_row)) | def get_selection(self, yield_per=None):
"\n Method to be compatible with a \n :class:`camelot.admin.action.list_action.ListActionModelContext`, this\n allows creating a single Action to be used on a form and on list.\n \n :param yield_per: this parameter has no effect, it's here only for\n compatibility with :meth:`camelot.admin.action.list_action.ListActionModelContext.get_selection`\n :return: a generator that yields the current object displayed in the \n form and does not yield anything if no object is displayed yet\n in the form.\n "
if (self.current_row != None):
(yield self._model._get_object(self.current_row))<|docstring|>Method to be compatible with a
:class:`camelot.admin.action.list_action.ListActionModelContext`, this
allows creating a single Action to be used on a form and on list.
:param yield_per: this parameter has no effect, it's here only for
compatibility with :meth:`camelot.admin.action.list_action.ListActionModelContext.get_selection`
:return: a generator that yields the current object displayed in the
form and does not yield anything if no object is displayed yet
in the form.<|endoftext|> |
39b0245aabb8966733e7745695b2ea9a9894cb31ae53f5e66dbfd2d9ce0aa305 | def step_when_valid(self):
'\n :return: the `ActionStep` to take when the current object is valid\n '
from camelot.view import action_steps
return action_steps.CloseView() | :return: the `ActionStep` to take when the current object is valid | camelot/admin/action/form_action.py | step_when_valid | Kristof-Welslau/camelot | 12 | python | def step_when_valid(self):
'\n \n '
from camelot.view import action_steps
return action_steps.CloseView() | def step_when_valid(self):
'\n \n '
from camelot.view import action_steps
return action_steps.CloseView()<|docstring|>:return: the `ActionStep` to take when the current object is valid<|endoftext|> |
54870847beab764b26dad94a28056400419723b771331d1d9ff627576323354e | async def get_locale(bot, ctx: commands.Context):
'|coro|\n\n Retrieves the locale of a user to respond with.\n\n Parameters\n -----------\n ctx: :class:`commands.Context`\n The context to get the prefix of.\n\n Returns\n -------\n str:\n Locale to use in responses.\n '
cog = bot.get_cog('LocaleStore')
if cog:
try:
ret = cog.get(ctx)
if asyncio.iscoroutine(ret):
ret = (await ret)
return ret
except Exception as e:
traceback.print_exc() | |coro|
Retrieves the locale of a user to respond with.
Parameters
-----------
ctx: :class:`commands.Context`
The context to get the prefix of.
Returns
-------
str:
Locale to use in responses. | nest/client.py | get_locale | Oxylibrium/Nest | 10 | python | async def get_locale(bot, ctx: commands.Context):
'|coro|\n\n Retrieves the locale of a user to respond with.\n\n Parameters\n -----------\n ctx: :class:`commands.Context`\n The context to get the prefix of.\n\n Returns\n -------\n str:\n Locale to use in responses.\n '
cog = bot.get_cog('LocaleStore')
if cog:
try:
ret = cog.get(ctx)
if asyncio.iscoroutine(ret):
ret = (await ret)
return ret
except Exception as e:
traceback.print_exc() | async def get_locale(bot, ctx: commands.Context):
'|coro|\n\n Retrieves the locale of a user to respond with.\n\n Parameters\n -----------\n ctx: :class:`commands.Context`\n The context to get the prefix of.\n\n Returns\n -------\n str:\n Locale to use in responses.\n '
cog = bot.get_cog('LocaleStore')
if cog:
try:
ret = cog.get(ctx)
if asyncio.iscoroutine(ret):
ret = (await ret)
return ret
except Exception as e:
traceback.print_exc()<|docstring|>|coro|
Retrieves the locale of a user to respond with.
Parameters
-----------
ctx: :class:`commands.Context`
The context to get the prefix of.
Returns
-------
str:
Locale to use in responses.<|endoftext|> |
7ce6e60bb0c804539631d8f4185e5d0a479d6b781a26c665d105d3825439c994 | async def __call__(self, bot, message: discord.Message):
'|coro|\n\n Retrieves the prefix the bot is listening to\n with the message as a context.\n\n Parameters\n -----------\n ctx: :class:`commands.Context`\n The context to get the prefix of.\n\n Returns\n --------\n Dict[str, str]\n A prefix the bot is listening for in each category.\n '
cog = bot.get_cog('PrefixStore')
if cog:
try:
prefix = cog.get(message)
if asyncio.iscoroutine(prefix):
prefix = (await prefix)
except Exception as e:
traceback.print_exc()
prefix = None
if (not isinstance(prefix, str)):
prefix = self._default
else:
prefix = self._default
return commands.when_mentioned_or(prefix)(bot, message) | |coro|
Retrieves the prefix the bot is listening to
with the message as a context.
Parameters
-----------
ctx: :class:`commands.Context`
The context to get the prefix of.
Returns
--------
Dict[str, str]
A prefix the bot is listening for in each category. | nest/client.py | __call__ | Oxylibrium/Nest | 10 | python | async def __call__(self, bot, message: discord.Message):
'|coro|\n\n Retrieves the prefix the bot is listening to\n with the message as a context.\n\n Parameters\n -----------\n ctx: :class:`commands.Context`\n The context to get the prefix of.\n\n Returns\n --------\n Dict[str, str]\n A prefix the bot is listening for in each category.\n '
cog = bot.get_cog('PrefixStore')
if cog:
try:
prefix = cog.get(message)
if asyncio.iscoroutine(prefix):
prefix = (await prefix)
except Exception as e:
traceback.print_exc()
prefix = None
if (not isinstance(prefix, str)):
prefix = self._default
else:
prefix = self._default
return commands.when_mentioned_or(prefix)(bot, message) | async def __call__(self, bot, message: discord.Message):
'|coro|\n\n Retrieves the prefix the bot is listening to\n with the message as a context.\n\n Parameters\n -----------\n ctx: :class:`commands.Context`\n The context to get the prefix of.\n\n Returns\n --------\n Dict[str, str]\n A prefix the bot is listening for in each category.\n '
cog = bot.get_cog('PrefixStore')
if cog:
try:
prefix = cog.get(message)
if asyncio.iscoroutine(prefix):
prefix = (await prefix)
except Exception as e:
traceback.print_exc()
prefix = None
if (not isinstance(prefix, str)):
prefix = self._default
else:
prefix = self._default
return commands.when_mentioned_or(prefix)(bot, message)<|docstring|>|coro|
Retrieves the prefix the bot is listening to
with the message as a context.
Parameters
-----------
ctx: :class:`commands.Context`
The context to get the prefix of.
Returns
--------
Dict[str, str]
A prefix the bot is listening for in each category.<|endoftext|> |
86b1c32753c2df6c9c90aef3a29c63c60023c22b5dfaff3faf093f9519adcc3b | async def on_ready(self):
'Log successful login event'
self._logger.info(f'Logged in as {self.user.name}. ID: {str(self.user.id)}')
(await self.change_presence(activity=discord.Activity(name='with code'))) | Log successful login event | nest/client.py | on_ready | Oxylibrium/Nest | 10 | python | async def on_ready(self):
self._logger.info(f'Logged in as {self.user.name}. ID: {str(self.user.id)}')
(await self.change_presence(activity=discord.Activity(name='with code'))) | async def on_ready(self):
self._logger.info(f'Logged in as {self.user.name}. ID: {str(self.user.id)}')
(await self.change_presence(activity=discord.Activity(name='with code')))<|docstring|>Log successful login event<|endoftext|> |
3e3c2617df1799765750969bd4d320077044a43cc0d58df201efbe8f731af747 | async def get_context(self, message: discord.Message, *, cls=commands.Context) -> commands.Context:
"|coro|\n\n Returns the invocation context from the message.\n\n The returned context is not guaranteed to be a valid invocation\n context, :attr:`.Context.valid` must be checked to make sure it is.\n If the context is not valid then it is not a valid candidate to be\n invoked under :meth:`~.Bot.invoke`.\n\n Parameters\n -----------\n message: :class:`discord.Message`\n The message to get the invocation context from.\n cls\n The factory class that will be used to create the context.\n By default, this is :class:`.Context`. Should a custom\n class be provided, it must be similar enough to :class:`.Context`'s\n interface.\n\n Returns\n --------\n :class:`.Context`\n The invocation context. The type of this can change via the\n ``cls`` parameter.\n "
ctx = (await super().get_context(message, cls=cls))
if ctx.command:
user_locale = (await get_locale(self, ctx))
ctx.locale = (user_locale if user_locale else self.i18n.locale)
ctx._ = functools.partial(self.i18n.getstr, locale=ctx.locale, cog=ctx.command.cog_name)
return ctx | |coro|
Returns the invocation context from the message.
The returned context is not guaranteed to be a valid invocation
context, :attr:`.Context.valid` must be checked to make sure it is.
If the context is not valid then it is not a valid candidate to be
invoked under :meth:`~.Bot.invoke`.
Parameters
-----------
message: :class:`discord.Message`
The message to get the invocation context from.
cls
The factory class that will be used to create the context.
By default, this is :class:`.Context`. Should a custom
class be provided, it must be similar enough to :class:`.Context`'s
interface.
Returns
--------
:class:`.Context`
The invocation context. The type of this can change via the
``cls`` parameter. | nest/client.py | get_context | Oxylibrium/Nest | 10 | python | async def get_context(self, message: discord.Message, *, cls=commands.Context) -> commands.Context:
"|coro|\n\n Returns the invocation context from the message.\n\n The returned context is not guaranteed to be a valid invocation\n context, :attr:`.Context.valid` must be checked to make sure it is.\n If the context is not valid then it is not a valid candidate to be\n invoked under :meth:`~.Bot.invoke`.\n\n Parameters\n -----------\n message: :class:`discord.Message`\n The message to get the invocation context from.\n cls\n The factory class that will be used to create the context.\n By default, this is :class:`.Context`. Should a custom\n class be provided, it must be similar enough to :class:`.Context`'s\n interface.\n\n Returns\n --------\n :class:`.Context`\n The invocation context. The type of this can change via the\n ``cls`` parameter.\n "
ctx = (await super().get_context(message, cls=cls))
if ctx.command:
user_locale = (await get_locale(self, ctx))
ctx.locale = (user_locale if user_locale else self.i18n.locale)
ctx._ = functools.partial(self.i18n.getstr, locale=ctx.locale, cog=ctx.command.cog_name)
return ctx | async def get_context(self, message: discord.Message, *, cls=commands.Context) -> commands.Context:
"|coro|\n\n Returns the invocation context from the message.\n\n The returned context is not guaranteed to be a valid invocation\n context, :attr:`.Context.valid` must be checked to make sure it is.\n If the context is not valid then it is not a valid candidate to be\n invoked under :meth:`~.Bot.invoke`.\n\n Parameters\n -----------\n message: :class:`discord.Message`\n The message to get the invocation context from.\n cls\n The factory class that will be used to create the context.\n By default, this is :class:`.Context`. Should a custom\n class be provided, it must be similar enough to :class:`.Context`'s\n interface.\n\n Returns\n --------\n :class:`.Context`\n The invocation context. The type of this can change via the\n ``cls`` parameter.\n "
ctx = (await super().get_context(message, cls=cls))
if ctx.command:
user_locale = (await get_locale(self, ctx))
ctx.locale = (user_locale if user_locale else self.i18n.locale)
ctx._ = functools.partial(self.i18n.getstr, locale=ctx.locale, cog=ctx.command.cog_name)
return ctx<|docstring|>|coro|
Returns the invocation context from the message.
The returned context is not guaranteed to be a valid invocation
context, :attr:`.Context.valid` must be checked to make sure it is.
If the context is not valid then it is not a valid candidate to be
invoked under :meth:`~.Bot.invoke`.
Parameters
-----------
message: :class:`discord.Message`
The message to get the invocation context from.
cls
The factory class that will be used to create the context.
By default, this is :class:`.Context`. Should a custom
class be provided, it must be similar enough to :class:`.Context`'s
interface.
Returns
--------
:class:`.Context`
The invocation context. The type of this can change via the
``cls`` parameter.<|endoftext|> |
f7328957fb4b23c296634a68133ebfb5bd7f7dd4f91dde3d7f159e2d9d59cce6 | def load_module(self, name: str):
'Loads a module from the modules directory.\n\n A module is a d.py extension that contains commands, cogs, or\n listeners and i18n data.\n\n Parameters\n ----------\n name: str\n The extension name to load. It must be a valid name of a folder\n within the modules directory.\n\n Raises\n ------\n ClientException\n The extension does not have a setup function.\n ImportError\n The extension could not be imported.\n '
if (name in self.extensions):
return
self.load_extension(f'modules.{name}')
self.i18n.load_module(name) | Loads a module from the modules directory.
A module is a d.py extension that contains commands, cogs, or
listeners and i18n data.
Parameters
----------
name: str
The extension name to load. It must be a valid name of a folder
within the modules directory.
Raises
------
ClientException
The extension does not have a setup function.
ImportError
The extension could not be imported. | nest/client.py | load_module | Oxylibrium/Nest | 10 | python | def load_module(self, name: str):
'Loads a module from the modules directory.\n\n A module is a d.py extension that contains commands, cogs, or\n listeners and i18n data.\n\n Parameters\n ----------\n name: str\n The extension name to load. It must be a valid name of a folder\n within the modules directory.\n\n Raises\n ------\n ClientException\n The extension does not have a setup function.\n ImportError\n The extension could not be imported.\n '
if (name in self.extensions):
return
self.load_extension(f'modules.{name}')
self.i18n.load_module(name) | def load_module(self, name: str):
'Loads a module from the modules directory.\n\n A module is a d.py extension that contains commands, cogs, or\n listeners and i18n data.\n\n Parameters\n ----------\n name: str\n The extension name to load. It must be a valid name of a folder\n within the modules directory.\n\n Raises\n ------\n ClientException\n The extension does not have a setup function.\n ImportError\n The extension could not be imported.\n '
if (name in self.extensions):
return
self.load_extension(f'modules.{name}')
self.i18n.load_module(name)<|docstring|>Loads a module from the modules directory.
A module is a d.py extension that contains commands, cogs, or
listeners and i18n data.
Parameters
----------
name: str
The extension name to load. It must be a valid name of a folder
within the modules directory.
Raises
------
ClientException
The extension does not have a setup function.
ImportError
The extension could not be imported.<|endoftext|> |
85f0d5c624e4fa5495f475752099881e4a228d93961c5d768e0d84721fe19501 | def reload_module(self, name: str):
'Loads a module from the modules directory.\n\n A module is a d.py extension that contains commands, cogs, or\n listeners and i18n data.\n\n Parameters\n ----------\n name: str\n The extension name to load. It must be a valid name of a folder\n within the modules directory.\n\n Raises\n ------\n ClientException\n The extension does not have a setup function.\n ImportError\n The extension could not be imported.\n '
self.reload_extension(f'modules.{name}')
self.i18n.load_module(name) | Loads a module from the modules directory.
A module is a d.py extension that contains commands, cogs, or
listeners and i18n data.
Parameters
----------
name: str
The extension name to load. It must be a valid name of a folder
within the modules directory.
Raises
------
ClientException
The extension does not have a setup function.
ImportError
The extension could not be imported. | nest/client.py | reload_module | Oxylibrium/Nest | 10 | python | def reload_module(self, name: str):
'Loads a module from the modules directory.\n\n A module is a d.py extension that contains commands, cogs, or\n listeners and i18n data.\n\n Parameters\n ----------\n name: str\n The extension name to load. It must be a valid name of a folder\n within the modules directory.\n\n Raises\n ------\n ClientException\n The extension does not have a setup function.\n ImportError\n The extension could not be imported.\n '
self.reload_extension(f'modules.{name}')
self.i18n.load_module(name) | def reload_module(self, name: str):
'Loads a module from the modules directory.\n\n A module is a d.py extension that contains commands, cogs, or\n listeners and i18n data.\n\n Parameters\n ----------\n name: str\n The extension name to load. It must be a valid name of a folder\n within the modules directory.\n\n Raises\n ------\n ClientException\n The extension does not have a setup function.\n ImportError\n The extension could not be imported.\n '
self.reload_extension(f'modules.{name}')
self.i18n.load_module(name)<|docstring|>Loads a module from the modules directory.
A module is a d.py extension that contains commands, cogs, or
listeners and i18n data.
Parameters
----------
name: str
The extension name to load. It must be a valid name of a folder
within the modules directory.
Raises
------
ClientException
The extension does not have a setup function.
ImportError
The extension could not be imported.<|endoftext|> |
1b124ac14054b610d9fd78cfab93fe071021a588e941220a52d8a298fbe706f1 | def run(self, bot: bool=True):
'\n Start running the bot.\n\n Parameters\n ----------\n bot: bool\n If bot is a bot account or a selfbot.\n '
super().run(self.tokens['discord'], bot=bot) | Start running the bot.
Parameters
----------
bot: bool
If bot is a bot account or a selfbot. | nest/client.py | run | Oxylibrium/Nest | 10 | python | def run(self, bot: bool=True):
'\n Start running the bot.\n\n Parameters\n ----------\n bot: bool\n If bot is a bot account or a selfbot.\n '
super().run(self.tokens['discord'], bot=bot) | def run(self, bot: bool=True):
'\n Start running the bot.\n\n Parameters\n ----------\n bot: bool\n If bot is a bot account or a selfbot.\n '
super().run(self.tokens['discord'], bot=bot)<|docstring|>Start running the bot.
Parameters
----------
bot: bool
If bot is a bot account or a selfbot.<|endoftext|> |
73254e59196243dfe522b21ad3bb6c989637e568d313f672ad4f8d0fc9436edc | def __init__(self, world, ego_vehicles, config, randomize=False, debug_mode=True, criteria_enable=True, timeout=60):
'\n Initialize all parameters required for NewScenario\n '
self.timeout = timeout
self._map = CarlaDataProvider.get_map()
self._weather_presets = find_weather_presets()
self._weather_index = 0
preset = self._weather_presets[self._weather_index]
world.set_weather(preset[0])
super(SetLevelIntersection3A, self).__init__('TestScenario', ego_vehicles, config, world, debug_mode, criteria_enable=criteria_enable) | Initialize all parameters required for NewScenario | srunner/custom_scenarios/setlevel_intersection_3cars.py | __init__ | goRichard/scenario_runner_fzi | 0 | python | def __init__(self, world, ego_vehicles, config, randomize=False, debug_mode=True, criteria_enable=True, timeout=60):
'\n \n '
self.timeout = timeout
self._map = CarlaDataProvider.get_map()
self._weather_presets = find_weather_presets()
self._weather_index = 0
preset = self._weather_presets[self._weather_index]
world.set_weather(preset[0])
super(SetLevelIntersection3A, self).__init__('TestScenario', ego_vehicles, config, world, debug_mode, criteria_enable=criteria_enable) | def __init__(self, world, ego_vehicles, config, randomize=False, debug_mode=True, criteria_enable=True, timeout=60):
'\n \n '
self.timeout = timeout
self._map = CarlaDataProvider.get_map()
self._weather_presets = find_weather_presets()
self._weather_index = 0
preset = self._weather_presets[self._weather_index]
world.set_weather(preset[0])
super(SetLevelIntersection3A, self).__init__('TestScenario', ego_vehicles, config, world, debug_mode, criteria_enable=criteria_enable)<|docstring|>Initialize all parameters required for NewScenario<|endoftext|> |
71c44d267efff1118c0ef6a51271506d1bedbdbb33cd6c20e0ae92ca8248d998 | def _create_behavior(self):
'\n 3 agents enter intersection and start at scenario start time\n '
root = py_trees.composites.Parallel(policy=py_trees.common.ParallelPolicy.SUCCESS_ON_ONE)
agent1 = py_trees.composites.Sequence()
agent2 = py_trees.composites.Sequence()
leaf1 = AccelerateToVelocity(self.other_actors[0], 6.0, 28.0)
leaf2 = KeepVelocity(self.other_actors[0], 28.0)
agent1.add_child(leaf1)
agent1.add_child(leaf2)
leaf3 = AccelerateToVelocity(self.other_actors[1], 6.0, 40.0)
leaf4 = KeepVelocity(self.other_actors[1], 40.0)
agent2.add_child(leaf3)
agent2.add_child(leaf4)
root.add_child(agent1)
root.add_child(agent2)
return root | 3 agents enter intersection and start at scenario start time | srunner/custom_scenarios/setlevel_intersection_3cars.py | _create_behavior | goRichard/scenario_runner_fzi | 0 | python | def _create_behavior(self):
'\n \n '
root = py_trees.composites.Parallel(policy=py_trees.common.ParallelPolicy.SUCCESS_ON_ONE)
agent1 = py_trees.composites.Sequence()
agent2 = py_trees.composites.Sequence()
leaf1 = AccelerateToVelocity(self.other_actors[0], 6.0, 28.0)
leaf2 = KeepVelocity(self.other_actors[0], 28.0)
agent1.add_child(leaf1)
agent1.add_child(leaf2)
leaf3 = AccelerateToVelocity(self.other_actors[1], 6.0, 40.0)
leaf4 = KeepVelocity(self.other_actors[1], 40.0)
agent2.add_child(leaf3)
agent2.add_child(leaf4)
root.add_child(agent1)
root.add_child(agent2)
return root | def _create_behavior(self):
'\n \n '
root = py_trees.composites.Parallel(policy=py_trees.common.ParallelPolicy.SUCCESS_ON_ONE)
agent1 = py_trees.composites.Sequence()
agent2 = py_trees.composites.Sequence()
leaf1 = AccelerateToVelocity(self.other_actors[0], 6.0, 28.0)
leaf2 = KeepVelocity(self.other_actors[0], 28.0)
agent1.add_child(leaf1)
agent1.add_child(leaf2)
leaf3 = AccelerateToVelocity(self.other_actors[1], 6.0, 40.0)
leaf4 = KeepVelocity(self.other_actors[1], 40.0)
agent2.add_child(leaf3)
agent2.add_child(leaf4)
root.add_child(agent1)
root.add_child(agent2)
return root<|docstring|>3 agents enter intersection and start at scenario start time<|endoftext|> |
4a5587e97f8d313fe50031858f0f39a0904f62fb9ed81c566a682cc76f472901 | def _create_test_criteria(self):
'\n different test criteria\n '
parallel_criteria = py_trees.composites.Parallel('group_criteria', policy=py_trees.common.ParallelPolicy.SUCCESS_ON_ONE)
collision_criterion = CollisionTest(self.ego_vehicles[0], terminate_on_failure=True)
parallel_criteria.add_child(collision_criterion)
in_region_criterion = InRadiusRegionTest(self.ego_vehicles[0], 258.26, (- 270.1), 2.0)
parallel_criteria.add_child(in_region_criterion)
return parallel_criteria | different test criteria | srunner/custom_scenarios/setlevel_intersection_3cars.py | _create_test_criteria | goRichard/scenario_runner_fzi | 0 | python | def _create_test_criteria(self):
'\n \n '
parallel_criteria = py_trees.composites.Parallel('group_criteria', policy=py_trees.common.ParallelPolicy.SUCCESS_ON_ONE)
collision_criterion = CollisionTest(self.ego_vehicles[0], terminate_on_failure=True)
parallel_criteria.add_child(collision_criterion)
in_region_criterion = InRadiusRegionTest(self.ego_vehicles[0], 258.26, (- 270.1), 2.0)
parallel_criteria.add_child(in_region_criterion)
return parallel_criteria | def _create_test_criteria(self):
'\n \n '
parallel_criteria = py_trees.composites.Parallel('group_criteria', policy=py_trees.common.ParallelPolicy.SUCCESS_ON_ONE)
collision_criterion = CollisionTest(self.ego_vehicles[0], terminate_on_failure=True)
parallel_criteria.add_child(collision_criterion)
in_region_criterion = InRadiusRegionTest(self.ego_vehicles[0], 258.26, (- 270.1), 2.0)
parallel_criteria.add_child(in_region_criterion)
return parallel_criteria<|docstring|>different test criteria<|endoftext|> |
fd8dd333b4ac49886acc118a8387f3fa086d75f878d8ef94a4eb920e0772b11e | def SemVer(compatible_at: Tuple[(int, int)]=None) -> Callable[([str], Tuple[(int, int, int)])]:
' Validates that a string is formatted as semantic version: major.minor.patch.\n Additionally ensures that this semantic version is compatible with the provided\n compatible_at.\n\n Arguments:\n - compatible_at: Semantic version which program is compatible with, the \n validator checks the parsed semantic version for compatibility if this is \n not None.\n\n Returns: Validation function.\n '
def validate(value: str) -> Tuple[(int, int, int)]:
' Validates based on the requirements defined in SemVer().\n Arugments:\n - value: To validate.\n\n Returns: Value if valid.\n\n Raises:\n - v.Invalid: If invalid.\n '
parts = value.split('.')
if (len(parts) != 3):
raise v.Invalid(('should be 3 integers seperated by dots in the ' + 'format: major.minor.patch'))
try:
major = int(parts[0])
except ValueError as e:
raise v.Invalid(f'failed to parse major component as an integer: {e}')
try:
minor = int(parts[1])
except ValueError as e:
raise v.Invalid(f'failed to parse minor component as an integer: {e}')
try:
patch = int(parts[2])
except ValueError as e:
raise v.Invalid(f'failed to parse patch component as an integer: {e}')
if (compatible_at is not None):
if ((major != compatible_at[0]) or (minor < compatible_at[1])):
raise v.Invalid(((((f'semantic versions are not compatible, was: ' + f'major={major} minor={minor} patch={patch}, ') + f'compatible version(s): ') + f'major={compatible_at[0]} ') + f'minor>={compatible_at[1]} patch=*'))
return (major, minor, patch)
return validate | Validates that a string is formatted as semantic version: major.minor.patch.
Additionally ensures that this semantic version is compatible with the provided
compatible_at.
Arguments:
- compatible_at: Semantic version which program is compatible with, the
validator checks the parsed semantic version for compatibility if this is
not None.
Returns: Validation function. | py-sdk/wallet_sdk/__init__.py | SemVer | Noah-Huppert/wallet-service | 0 | python | def SemVer(compatible_at: Tuple[(int, int)]=None) -> Callable[([str], Tuple[(int, int, int)])]:
' Validates that a string is formatted as semantic version: major.minor.patch.\n Additionally ensures that this semantic version is compatible with the provided\n compatible_at.\n\n Arguments:\n - compatible_at: Semantic version which program is compatible with, the \n validator checks the parsed semantic version for compatibility if this is \n not None.\n\n Returns: Validation function.\n '
def validate(value: str) -> Tuple[(int, int, int)]:
' Validates based on the requirements defined in SemVer().\n Arugments:\n - value: To validate.\n\n Returns: Value if valid.\n\n Raises:\n - v.Invalid: If invalid.\n '
parts = value.split('.')
if (len(parts) != 3):
raise v.Invalid(('should be 3 integers seperated by dots in the ' + 'format: major.minor.patch'))
try:
major = int(parts[0])
except ValueError as e:
raise v.Invalid(f'failed to parse major component as an integer: {e}')
try:
minor = int(parts[1])
except ValueError as e:
raise v.Invalid(f'failed to parse minor component as an integer: {e}')
try:
patch = int(parts[2])
except ValueError as e:
raise v.Invalid(f'failed to parse patch component as an integer: {e}')
if (compatible_at is not None):
if ((major != compatible_at[0]) or (minor < compatible_at[1])):
raise v.Invalid(((((f'semantic versions are not compatible, was: ' + f'major={major} minor={minor} patch={patch}, ') + f'compatible version(s): ') + f'major={compatible_at[0]} ') + f'minor>={compatible_at[1]} patch=*'))
return (major, minor, patch)
return validate | def SemVer(compatible_at: Tuple[(int, int)]=None) -> Callable[([str], Tuple[(int, int, int)])]:
' Validates that a string is formatted as semantic version: major.minor.patch.\n Additionally ensures that this semantic version is compatible with the provided\n compatible_at.\n\n Arguments:\n - compatible_at: Semantic version which program is compatible with, the \n validator checks the parsed semantic version for compatibility if this is \n not None.\n\n Returns: Validation function.\n '
def validate(value: str) -> Tuple[(int, int, int)]:
' Validates based on the requirements defined in SemVer().\n Arugments:\n - value: To validate.\n\n Returns: Value if valid.\n\n Raises:\n - v.Invalid: If invalid.\n '
parts = value.split('.')
if (len(parts) != 3):
raise v.Invalid(('should be 3 integers seperated by dots in the ' + 'format: major.minor.patch'))
try:
major = int(parts[0])
except ValueError as e:
raise v.Invalid(f'failed to parse major component as an integer: {e}')
try:
minor = int(parts[1])
except ValueError as e:
raise v.Invalid(f'failed to parse minor component as an integer: {e}')
try:
patch = int(parts[2])
except ValueError as e:
raise v.Invalid(f'failed to parse patch component as an integer: {e}')
if (compatible_at is not None):
if ((major != compatible_at[0]) or (minor < compatible_at[1])):
raise v.Invalid(((((f'semantic versions are not compatible, was: ' + f'major={major} minor={minor} patch={patch}, ') + f'compatible version(s): ') + f'major={compatible_at[0]} ') + f'minor>={compatible_at[1]} patch=*'))
return (major, minor, patch)
return validate<|docstring|>Validates that a string is formatted as semantic version: major.minor.patch.
Additionally ensures that this semantic version is compatible with the provided
compatible_at.
Arguments:
- compatible_at: Semantic version which program is compatible with, the
validator checks the parsed semantic version for compatibility if this is
not None.
Returns: Validation function.<|endoftext|> |
ad7b6ef0f32129728a67161cc7ebd468e1ed965c6b41f2541120d4eabb4030d4 | def dotget(root, path: str, default=None) -> object:
" Access an item in the root field via a dot path.\n Arguments:\n - root: Object to access via dot path.\n - path: Every dot path should be relative to the state property.\n - default: Default value if path doesn't exist.\n\n Returns: Value. If path does not exist default is returned.\n "
parts = path.split('.')
for part in parts:
try:
if (type(root) is list):
root = root[int(part)]
else:
root = root[part]
except KeyError:
return default
return root | Access an item in the root field via a dot path.
Arguments:
- root: Object to access via dot path.
- path: Every dot path should be relative to the state property.
- default: Default value if path doesn't exist.
Returns: Value. If path does not exist default is returned. | py-sdk/wallet_sdk/__init__.py | dotget | Noah-Huppert/wallet-service | 0 | python | def dotget(root, path: str, default=None) -> object:
" Access an item in the root field via a dot path.\n Arguments:\n - root: Object to access via dot path.\n - path: Every dot path should be relative to the state property.\n - default: Default value if path doesn't exist.\n\n Returns: Value. If path does not exist default is returned.\n "
parts = path.split('.')
for part in parts:
try:
if (type(root) is list):
root = root[int(part)]
else:
root = root[part]
except KeyError:
return default
return root | def dotget(root, path: str, default=None) -> object:
" Access an item in the root field via a dot path.\n Arguments:\n - root: Object to access via dot path.\n - path: Every dot path should be relative to the state property.\n - default: Default value if path doesn't exist.\n\n Returns: Value. If path does not exist default is returned.\n "
parts = path.split('.')
for part in parts:
try:
if (type(root) is list):
root = root[int(part)]
else:
root = root[part]
except KeyError:
return default
return root<|docstring|>Access an item in the root field via a dot path.
Arguments:
- root: Object to access via dot path.
- path: Every dot path should be relative to the state property.
- default: Default value if path doesn't exist.
Returns: Value. If path does not exist default is returned.<|endoftext|> |
1ab3a528f1d1830560a94bbc451456003f96c9c36b4c2020a7bf6670a4562d45 | def validate(value: str) -> Tuple[(int, int, int)]:
' Validates based on the requirements defined in SemVer().\n Arugments:\n - value: To validate.\n\n Returns: Value if valid.\n\n Raises:\n - v.Invalid: If invalid.\n '
parts = value.split('.')
if (len(parts) != 3):
raise v.Invalid(('should be 3 integers seperated by dots in the ' + 'format: major.minor.patch'))
try:
major = int(parts[0])
except ValueError as e:
raise v.Invalid(f'failed to parse major component as an integer: {e}')
try:
minor = int(parts[1])
except ValueError as e:
raise v.Invalid(f'failed to parse minor component as an integer: {e}')
try:
patch = int(parts[2])
except ValueError as e:
raise v.Invalid(f'failed to parse patch component as an integer: {e}')
if (compatible_at is not None):
if ((major != compatible_at[0]) or (minor < compatible_at[1])):
raise v.Invalid(((((f'semantic versions are not compatible, was: ' + f'major={major} minor={minor} patch={patch}, ') + f'compatible version(s): ') + f'major={compatible_at[0]} ') + f'minor>={compatible_at[1]} patch=*'))
return (major, minor, patch) | Validates based on the requirements defined in SemVer().
Arugments:
- value: To validate.
Returns: Value if valid.
Raises:
- v.Invalid: If invalid. | py-sdk/wallet_sdk/__init__.py | validate | Noah-Huppert/wallet-service | 0 | python | def validate(value: str) -> Tuple[(int, int, int)]:
' Validates based on the requirements defined in SemVer().\n Arugments:\n - value: To validate.\n\n Returns: Value if valid.\n\n Raises:\n - v.Invalid: If invalid.\n '
parts = value.split('.')
if (len(parts) != 3):
raise v.Invalid(('should be 3 integers seperated by dots in the ' + 'format: major.minor.patch'))
try:
major = int(parts[0])
except ValueError as e:
raise v.Invalid(f'failed to parse major component as an integer: {e}')
try:
minor = int(parts[1])
except ValueError as e:
raise v.Invalid(f'failed to parse minor component as an integer: {e}')
try:
patch = int(parts[2])
except ValueError as e:
raise v.Invalid(f'failed to parse patch component as an integer: {e}')
if (compatible_at is not None):
if ((major != compatible_at[0]) or (minor < compatible_at[1])):
raise v.Invalid(((((f'semantic versions are not compatible, was: ' + f'major={major} minor={minor} patch={patch}, ') + f'compatible version(s): ') + f'major={compatible_at[0]} ') + f'minor>={compatible_at[1]} patch=*'))
return (major, minor, patch) | def validate(value: str) -> Tuple[(int, int, int)]:
' Validates based on the requirements defined in SemVer().\n Arugments:\n - value: To validate.\n\n Returns: Value if valid.\n\n Raises:\n - v.Invalid: If invalid.\n '
parts = value.split('.')
if (len(parts) != 3):
raise v.Invalid(('should be 3 integers seperated by dots in the ' + 'format: major.minor.patch'))
try:
major = int(parts[0])
except ValueError as e:
raise v.Invalid(f'failed to parse major component as an integer: {e}')
try:
minor = int(parts[1])
except ValueError as e:
raise v.Invalid(f'failed to parse minor component as an integer: {e}')
try:
patch = int(parts[2])
except ValueError as e:
raise v.Invalid(f'failed to parse patch component as an integer: {e}')
if (compatible_at is not None):
if ((major != compatible_at[0]) or (minor < compatible_at[1])):
raise v.Invalid(((((f'semantic versions are not compatible, was: ' + f'major={major} minor={minor} patch={patch}, ') + f'compatible version(s): ') + f'major={compatible_at[0]} ') + f'minor>={compatible_at[1]} patch=*'))
return (major, minor, patch)<|docstring|>Validates based on the requirements defined in SemVer().
Arugments:
- value: To validate.
Returns: Value if valid.
Raises:
- v.Invalid: If invalid.<|endoftext|> |
87d9eec16706b25d6da469a59f1061929ddacc9b8cf952b91370b6fa92069e95 | def __init__(self, url: str, method: str, status_code: int, error: str):
' Initializes.\n Arguments:\n - url: Request URL of API call.\n - method: HTTP method of API call.\n - status_code: HTTP status code of API response. Is -1 if not response from the server was received.\n - error: Issue which occurred.\n '
super().__init__('Failed to call {method} {url}: {status_code} {error}'.format(method=method, url=url, status_code=status_code, error=error))
self.url = url
self.method = method
self.status_code = status_code
self.error = error | Initializes.
Arguments:
- url: Request URL of API call.
- method: HTTP method of API call.
- status_code: HTTP status code of API response. Is -1 if not response from the server was received.
- error: Issue which occurred. | py-sdk/wallet_sdk/__init__.py | __init__ | Noah-Huppert/wallet-service | 0 | python | def __init__(self, url: str, method: str, status_code: int, error: str):
' Initializes.\n Arguments:\n - url: Request URL of API call.\n - method: HTTP method of API call.\n - status_code: HTTP status code of API response. Is -1 if not response from the server was received.\n - error: Issue which occurred.\n '
super().__init__('Failed to call {method} {url}: {status_code} {error}'.format(method=method, url=url, status_code=status_code, error=error))
self.url = url
self.method = method
self.status_code = status_code
self.error = error | def __init__(self, url: str, method: str, status_code: int, error: str):
' Initializes.\n Arguments:\n - url: Request URL of API call.\n - method: HTTP method of API call.\n - status_code: HTTP status code of API response. Is -1 if not response from the server was received.\n - error: Issue which occurred.\n '
super().__init__('Failed to call {method} {url}: {status_code} {error}'.format(method=method, url=url, status_code=status_code, error=error))
self.url = url
self.method = method
self.status_code = status_code
self.error = error<|docstring|>Initializes.
Arguments:
- url: Request URL of API call.
- method: HTTP method of API call.
- status_code: HTTP status code of API response. Is -1 if not response from the server was received.
- error: Issue which occurred.<|endoftext|> |
bbfbc23f540227b4b717b8792f54ef4e418aa18f53df5a4ab9e4a672fee48791 | @staticmethod
def CheckResp(resp: requests.Response, resp_schema: v.Schema=None):
' Determine if a response was successful, if not raise a WalletAPIError.\n Arguments:\n - resp: Response to check.\n - resp_schema: If provided ensures that the response has JSON data which\n matches this schema.\n\n Raises:\n - WalletAPIError: If the response indicates failure.\n '
if (not resp.ok):
resp_error_val = 'Unknown'
try:
data = resp.json()
if ('error' in data):
resp_error_val = data['error']
except ValueError:
pass
raise WalletAPIError(url=resp.request.url, method=resp.request.method, status_code=resp.status_code, error=('Error response ({status_code} {status_msg}): {error_msg} ' + '{raw_body}').format(status_code=resp.status_code, status_msg=resp.reason, error_msg=resp_error_val, raw_body=resp.text))
if (resp_schema is not None):
data = None
try:
data = resp.json()
except ValueError:
raise WalletAPIError(url=resp.request.url, method=resp.request.method, status_code=resp.status_code, error='Response did not have JSON body: actual body={}'.format(resp.text))
try:
resp_schema(data)
except v.MultipleInvalid as e:
field_path = '.'.join(map(str, e.path))
raise WalletAPIError(url=resp.request.url, method=resp.request.method, status_code=resp.status_code, error=('Response JSON not in the correct format: ' + '"{field_path}" was "{actual}" but: {error}'.format(field_path=field_path, actual=dotget(data, field_path), error=e.msg))) | Determine if a response was successful, if not raise a WalletAPIError.
Arguments:
- resp: Response to check.
- resp_schema: If provided ensures that the response has JSON data which
matches this schema.
Raises:
- WalletAPIError: If the response indicates failure. | py-sdk/wallet_sdk/__init__.py | CheckResp | Noah-Huppert/wallet-service | 0 | python | @staticmethod
def CheckResp(resp: requests.Response, resp_schema: v.Schema=None):
' Determine if a response was successful, if not raise a WalletAPIError.\n Arguments:\n - resp: Response to check.\n - resp_schema: If provided ensures that the response has JSON data which\n matches this schema.\n\n Raises:\n - WalletAPIError: If the response indicates failure.\n '
if (not resp.ok):
resp_error_val = 'Unknown'
try:
data = resp.json()
if ('error' in data):
resp_error_val = data['error']
except ValueError:
pass
raise WalletAPIError(url=resp.request.url, method=resp.request.method, status_code=resp.status_code, error=('Error response ({status_code} {status_msg}): {error_msg} ' + '{raw_body}').format(status_code=resp.status_code, status_msg=resp.reason, error_msg=resp_error_val, raw_body=resp.text))
if (resp_schema is not None):
data = None
try:
data = resp.json()
except ValueError:
raise WalletAPIError(url=resp.request.url, method=resp.request.method, status_code=resp.status_code, error='Response did not have JSON body: actual body={}'.format(resp.text))
try:
resp_schema(data)
except v.MultipleInvalid as e:
field_path = '.'.join(map(str, e.path))
raise WalletAPIError(url=resp.request.url, method=resp.request.method, status_code=resp.status_code, error=('Response JSON not in the correct format: ' + '"{field_path}" was "{actual}" but: {error}'.format(field_path=field_path, actual=dotget(data, field_path), error=e.msg))) | @staticmethod
def CheckResp(resp: requests.Response, resp_schema: v.Schema=None):
' Determine if a response was successful, if not raise a WalletAPIError.\n Arguments:\n - resp: Response to check.\n - resp_schema: If provided ensures that the response has JSON data which\n matches this schema.\n\n Raises:\n - WalletAPIError: If the response indicates failure.\n '
if (not resp.ok):
resp_error_val = 'Unknown'
try:
data = resp.json()
if ('error' in data):
resp_error_val = data['error']
except ValueError:
pass
raise WalletAPIError(url=resp.request.url, method=resp.request.method, status_code=resp.status_code, error=('Error response ({status_code} {status_msg}): {error_msg} ' + '{raw_body}').format(status_code=resp.status_code, status_msg=resp.reason, error_msg=resp_error_val, raw_body=resp.text))
if (resp_schema is not None):
data = None
try:
data = resp.json()
except ValueError:
raise WalletAPIError(url=resp.request.url, method=resp.request.method, status_code=resp.status_code, error='Response did not have JSON body: actual body={}'.format(resp.text))
try:
resp_schema(data)
except v.MultipleInvalid as e:
field_path = '.'.join(map(str, e.path))
raise WalletAPIError(url=resp.request.url, method=resp.request.method, status_code=resp.status_code, error=('Response JSON not in the correct format: ' + '"{field_path}" was "{actual}" but: {error}'.format(field_path=field_path, actual=dotget(data, field_path), error=e.msg)))<|docstring|>Determine if a response was successful, if not raise a WalletAPIError.
Arguments:
- resp: Response to check.
- resp_schema: If provided ensures that the response has JSON data which
matches this schema.
Raises:
- WalletAPIError: If the response indicates failure.<|endoftext|> |
d10cf52644cd8e94a1f53d113eb614859fb3511714b500d6c85d4c438f65b5ef | def __init__(self):
' Initializes.\n '
super().__init__('user does not have funds to back the transaction') | Initializes. | py-sdk/wallet_sdk/__init__.py | __init__ | Noah-Huppert/wallet-service | 0 | python | def __init__(self):
' \n '
super().__init__('user does not have funds to back the transaction') | def __init__(self):
' \n '
super().__init__('user does not have funds to back the transaction')<|docstring|>Initializes.<|endoftext|> |
00252119e204433d23189e3405acdd8aa76084dca39687aeb27350cd53997193 | def __init__(self, msg: str):
' Initializes.\n Arguments:\n - msg: Description of issue.\n '
super().__init__(msg) | Initializes.
Arguments:
- msg: Description of issue. | py-sdk/wallet_sdk/__init__.py | __init__ | Noah-Huppert/wallet-service | 0 | python | def __init__(self, msg: str):
' Initializes.\n Arguments:\n - msg: Description of issue.\n '
super().__init__(msg) | def __init__(self, msg: str):
' Initializes.\n Arguments:\n - msg: Description of issue.\n '
super().__init__(msg)<|docstring|>Initializes.
Arguments:
- msg: Description of issue.<|endoftext|> |
b1331bcaab55cd383d4be2ca36d6b582af8bd5c35c32fe630a3349eef372b074 | def __init__(self, api_url: str, authority_id: str, private_key: str):
' Initializes the API client.\n Arguments:\n - api_url: HTTP URL of wallet service API.\n - authority_id: Unique identifier of authority to act as.\n - private_key: PEM encoded ECDSA P-256 private key used to authenticate as\n an authority with the wallet service API.\n '
self.api_url = api_url
self.authority_id = authority_id
self.private_key = private_key
self.auth_token = jwt.encode({'sub': authority_id}, self.private_key, algorithm='ES256')
with open(os.path.join(os.path.dirname(os.path.realpath(__file__)), './VERSION'), 'r') as f:
self.__version__ = f.read().replace('\n', '')
self.service_health_good = None | Initializes the API client.
Arguments:
- api_url: HTTP URL of wallet service API.
- authority_id: Unique identifier of authority to act as.
- private_key: PEM encoded ECDSA P-256 private key used to authenticate as
an authority with the wallet service API. | py-sdk/wallet_sdk/__init__.py | __init__ | Noah-Huppert/wallet-service | 0 | python | def __init__(self, api_url: str, authority_id: str, private_key: str):
' Initializes the API client.\n Arguments:\n - api_url: HTTP URL of wallet service API.\n - authority_id: Unique identifier of authority to act as.\n - private_key: PEM encoded ECDSA P-256 private key used to authenticate as\n an authority with the wallet service API.\n '
self.api_url = api_url
self.authority_id = authority_id
self.private_key = private_key
self.auth_token = jwt.encode({'sub': authority_id}, self.private_key, algorithm='ES256')
with open(os.path.join(os.path.dirname(os.path.realpath(__file__)), './VERSION'), 'r') as f:
self.__version__ = f.read().replace('\n', )
self.service_health_good = None | def __init__(self, api_url: str, authority_id: str, private_key: str):
' Initializes the API client.\n Arguments:\n - api_url: HTTP URL of wallet service API.\n - authority_id: Unique identifier of authority to act as.\n - private_key: PEM encoded ECDSA P-256 private key used to authenticate as\n an authority with the wallet service API.\n '
self.api_url = api_url
self.authority_id = authority_id
self.private_key = private_key
self.auth_token = jwt.encode({'sub': authority_id}, self.private_key, algorithm='ES256')
with open(os.path.join(os.path.dirname(os.path.realpath(__file__)), './VERSION'), 'r') as f:
self.__version__ = f.read().replace('\n', )
self.service_health_good = None<|docstring|>Initializes the API client.
Arguments:
- api_url: HTTP URL of wallet service API.
- authority_id: Unique identifier of authority to act as.
- private_key: PEM encoded ECDSA P-256 private key used to authenticate as
an authority with the wallet service API.<|endoftext|> |
afc7cd2dbedb9be1a4a3d2b5163457bd8be2e0be7c3cf2e744dc01fb3eb4c184 | def LoadFromConfig(config_file_path: str) -> 'WalletClient':
' Loads Wallet API client configuration from a config file.\n Arguments:\n - config_file_path: Path to wallet service configuration file.\n \n Returns: WalletClient.\n\n Raises:\n - WalletConfigError: If an error occurrs loading the configuration file.\n '
dat = None
try:
with open(config_file_path, 'r') as f:
dat = json.load(f)
except IOError as e:
raise WalletConfigError((f'Error reading configuration file ' + f'"{config_file_path}": {e}'))
except json.JSONDecodeError as e:
raise WalletConfigError((f'Error decoding configuration file as JSON ' + f'"{config_file_path}": {e}'))
config = None
try:
config = WalletClient.CONFIG_FILE_SCHEMA(dat)
except v.MultipleInvalid as e:
raise WalletConfigError((f'Error validating configuration file ' + f'"{config_file_path}": {e}'))
return WalletClient(api_url='{}/api/v{}'.format(config['api_base_url'], COMPATIBLE_API_VERSION[0]), authority_id=config['authority_id'], private_key=config['private_key']) | Loads Wallet API client configuration from a config file.
Arguments:
- config_file_path: Path to wallet service configuration file.
Returns: WalletClient.
Raises:
- WalletConfigError: If an error occurrs loading the configuration file. | py-sdk/wallet_sdk/__init__.py | LoadFromConfig | Noah-Huppert/wallet-service | 0 | python | def LoadFromConfig(config_file_path: str) -> 'WalletClient':
' Loads Wallet API client configuration from a config file.\n Arguments:\n - config_file_path: Path to wallet service configuration file.\n \n Returns: WalletClient.\n\n Raises:\n - WalletConfigError: If an error occurrs loading the configuration file.\n '
dat = None
try:
with open(config_file_path, 'r') as f:
dat = json.load(f)
except IOError as e:
raise WalletConfigError((f'Error reading configuration file ' + f'"{config_file_path}": {e}'))
except json.JSONDecodeError as e:
raise WalletConfigError((f'Error decoding configuration file as JSON ' + f'"{config_file_path}": {e}'))
config = None
try:
config = WalletClient.CONFIG_FILE_SCHEMA(dat)
except v.MultipleInvalid as e:
raise WalletConfigError((f'Error validating configuration file ' + f'"{config_file_path}": {e}'))
return WalletClient(api_url='{}/api/v{}'.format(config['api_base_url'], COMPATIBLE_API_VERSION[0]), authority_id=config['authority_id'], private_key=config['private_key']) | def LoadFromConfig(config_file_path: str) -> 'WalletClient':
' Loads Wallet API client configuration from a config file.\n Arguments:\n - config_file_path: Path to wallet service configuration file.\n \n Returns: WalletClient.\n\n Raises:\n - WalletConfigError: If an error occurrs loading the configuration file.\n '
dat = None
try:
with open(config_file_path, 'r') as f:
dat = json.load(f)
except IOError as e:
raise WalletConfigError((f'Error reading configuration file ' + f'"{config_file_path}": {e}'))
except json.JSONDecodeError as e:
raise WalletConfigError((f'Error decoding configuration file as JSON ' + f'"{config_file_path}": {e}'))
config = None
try:
config = WalletClient.CONFIG_FILE_SCHEMA(dat)
except v.MultipleInvalid as e:
raise WalletConfigError((f'Error validating configuration file ' + f'"{config_file_path}": {e}'))
return WalletClient(api_url='{}/api/v{}'.format(config['api_base_url'], COMPATIBLE_API_VERSION[0]), authority_id=config['authority_id'], private_key=config['private_key'])<|docstring|>Loads Wallet API client configuration from a config file.
Arguments:
- config_file_path: Path to wallet service configuration file.
Returns: WalletClient.
Raises:
- WalletConfigError: If an error occurrs loading the configuration file.<|endoftext|> |
203318c4b424c69fb58b3803b6e420dd6c42a905662119d8da9d53d8a29011d2 | def __do_request__(self, method: str, path: str, resp_schema: v.Schema=None, __is_health_check_req__=False, **kwargs) -> requests.Response:
" Performs an HTTP request to the API. Handles error checking, response\n parsing and validation, user agent, and authorization.\n Arguments:\n - method: HTTP method, all caps.\n - path: Path to request, appended to self.api_url.\n - resp_schema: Schema which if not None will be used to validate \n the response.\n - __is_health_check_req__: If true the method won't automatically check\n the wallet service's health if self.service_health_good is None. This\n prevents infinite loops when __do_request__ is used internally to perform\n check_service_health().\n - kwargs: Any additional args which are accepted by requests.request (https://requests.readthedocs.io/en/master/api/#requests.request)\n\n Returns: The response.\n "
if ((self.service_health_good != True) and (not __is_health_check_req__)):
try:
self.check_service_health()
except WalletAPIError as e:
raise WalletAPIError((self.api_url + path), method, e.status_code, (("The wallet service's health " + "had not been checked yet, upon checking the service's ") + 'health was found to be bad: {}'.format(str(e))))
if ('headers' not in kwargs):
kwargs['headers'] = {}
if ('Authorization' not in kwargs['headers']):
kwargs['headers']['Authorization'] = self.auth_token
if ('User-Agent' not in kwargs['headers']):
kwargs['headers']['User-Agent'] = 'wallet-service-py-sdk {}'.format(self.__version__)
try:
resp = requests.request(url=(self.api_url + path), method=method, **kwargs)
WalletAPIError.CheckResp(resp, resp_schema)
return resp
except WalletAPIError as e:
if (e.status_code == 402):
raise NotEnoughFundsError()
else:
raise e
except requests.RequestException as e:
raise WalletAPIError((self.api_url + path), method, (- 1), str(e)) | Performs an HTTP request to the API. Handles error checking, response
parsing and validation, user agent, and authorization.
Arguments:
- method: HTTP method, all caps.
- path: Path to request, appended to self.api_url.
- resp_schema: Schema which if not None will be used to validate
the response.
- __is_health_check_req__: If true the method won't automatically check
the wallet service's health if self.service_health_good is None. This
prevents infinite loops when __do_request__ is used internally to perform
check_service_health().
- kwargs: Any additional args which are accepted by requests.request (https://requests.readthedocs.io/en/master/api/#requests.request)
Returns: The response. | py-sdk/wallet_sdk/__init__.py | __do_request__ | Noah-Huppert/wallet-service | 0 | python | def __do_request__(self, method: str, path: str, resp_schema: v.Schema=None, __is_health_check_req__=False, **kwargs) -> requests.Response:
" Performs an HTTP request to the API. Handles error checking, response\n parsing and validation, user agent, and authorization.\n Arguments:\n - method: HTTP method, all caps.\n - path: Path to request, appended to self.api_url.\n - resp_schema: Schema which if not None will be used to validate \n the response.\n - __is_health_check_req__: If true the method won't automatically check\n the wallet service's health if self.service_health_good is None. This\n prevents infinite loops when __do_request__ is used internally to perform\n check_service_health().\n - kwargs: Any additional args which are accepted by requests.request (https://requests.readthedocs.io/en/master/api/#requests.request)\n\n Returns: The response.\n "
if ((self.service_health_good != True) and (not __is_health_check_req__)):
try:
self.check_service_health()
except WalletAPIError as e:
raise WalletAPIError((self.api_url + path), method, e.status_code, (("The wallet service's health " + "had not been checked yet, upon checking the service's ") + 'health was found to be bad: {}'.format(str(e))))
if ('headers' not in kwargs):
kwargs['headers'] = {}
if ('Authorization' not in kwargs['headers']):
kwargs['headers']['Authorization'] = self.auth_token
if ('User-Agent' not in kwargs['headers']):
kwargs['headers']['User-Agent'] = 'wallet-service-py-sdk {}'.format(self.__version__)
try:
resp = requests.request(url=(self.api_url + path), method=method, **kwargs)
WalletAPIError.CheckResp(resp, resp_schema)
return resp
except WalletAPIError as e:
if (e.status_code == 402):
raise NotEnoughFundsError()
else:
raise e
except requests.RequestException as e:
raise WalletAPIError((self.api_url + path), method, (- 1), str(e)) | def __do_request__(self, method: str, path: str, resp_schema: v.Schema=None, __is_health_check_req__=False, **kwargs) -> requests.Response:
" Performs an HTTP request to the API. Handles error checking, response\n parsing and validation, user agent, and authorization.\n Arguments:\n - method: HTTP method, all caps.\n - path: Path to request, appended to self.api_url.\n - resp_schema: Schema which if not None will be used to validate \n the response.\n - __is_health_check_req__: If true the method won't automatically check\n the wallet service's health if self.service_health_good is None. This\n prevents infinite loops when __do_request__ is used internally to perform\n check_service_health().\n - kwargs: Any additional args which are accepted by requests.request (https://requests.readthedocs.io/en/master/api/#requests.request)\n\n Returns: The response.\n "
if ((self.service_health_good != True) and (not __is_health_check_req__)):
try:
self.check_service_health()
except WalletAPIError as e:
raise WalletAPIError((self.api_url + path), method, e.status_code, (("The wallet service's health " + "had not been checked yet, upon checking the service's ") + 'health was found to be bad: {}'.format(str(e))))
if ('headers' not in kwargs):
kwargs['headers'] = {}
if ('Authorization' not in kwargs['headers']):
kwargs['headers']['Authorization'] = self.auth_token
if ('User-Agent' not in kwargs['headers']):
kwargs['headers']['User-Agent'] = 'wallet-service-py-sdk {}'.format(self.__version__)
try:
resp = requests.request(url=(self.api_url + path), method=method, **kwargs)
WalletAPIError.CheckResp(resp, resp_schema)
return resp
except WalletAPIError as e:
if (e.status_code == 402):
raise NotEnoughFundsError()
else:
raise e
except requests.RequestException as e:
raise WalletAPIError((self.api_url + path), method, (- 1), str(e))<|docstring|>Performs an HTTP request to the API. Handles error checking, response
parsing and validation, user agent, and authorization.
Arguments:
- method: HTTP method, all caps.
- path: Path to request, appended to self.api_url.
- resp_schema: Schema which if not None will be used to validate
the response.
- __is_health_check_req__: If true the method won't automatically check
the wallet service's health if self.service_health_good is None. This
prevents infinite loops when __do_request__ is used internally to perform
check_service_health().
- kwargs: Any additional args which are accepted by requests.request (https://requests.readthedocs.io/en/master/api/#requests.request)
Returns: The response.<|endoftext|> |
87f122ce215b4b6765d7483417e6148eee56b6712a9860dc3c8b692b2d5fc63a | def check_service_health(self):
' Ensures that the wallet service is operating.\n Stores the result in self.wallet_service_good.\n Returns: True if service halth is good. False is never returned, instead\n the WalletAPIError exception is used to indicate failure.\n\n Raises:\n - WalletAPIError: If the service is not operating correctly.\n '
try:
self.__do_request__('GET', '/health', WalletClient.HEALTH_RESP_SCHEMA, __is_health_check_req__=True)
except WalletAPIError as e:
self.wallet_service_good = False
raise e
self.wallet_service_good = True
return True | Ensures that the wallet service is operating.
Stores the result in self.wallet_service_good.
Returns: True if service halth is good. False is never returned, instead
the WalletAPIError exception is used to indicate failure.
Raises:
- WalletAPIError: If the service is not operating correctly. | py-sdk/wallet_sdk/__init__.py | check_service_health | Noah-Huppert/wallet-service | 0 | python | def check_service_health(self):
' Ensures that the wallet service is operating.\n Stores the result in self.wallet_service_good.\n Returns: True if service halth is good. False is never returned, instead\n the WalletAPIError exception is used to indicate failure.\n\n Raises:\n - WalletAPIError: If the service is not operating correctly.\n '
try:
self.__do_request__('GET', '/health', WalletClient.HEALTH_RESP_SCHEMA, __is_health_check_req__=True)
except WalletAPIError as e:
self.wallet_service_good = False
raise e
self.wallet_service_good = True
return True | def check_service_health(self):
' Ensures that the wallet service is operating.\n Stores the result in self.wallet_service_good.\n Returns: True if service halth is good. False is never returned, instead\n the WalletAPIError exception is used to indicate failure.\n\n Raises:\n - WalletAPIError: If the service is not operating correctly.\n '
try:
self.__do_request__('GET', '/health', WalletClient.HEALTH_RESP_SCHEMA, __is_health_check_req__=True)
except WalletAPIError as e:
self.wallet_service_good = False
raise e
self.wallet_service_good = True
return True<|docstring|>Ensures that the wallet service is operating.
Stores the result in self.wallet_service_good.
Returns: True if service halth is good. False is never returned, instead
the WalletAPIError exception is used to indicate failure.
Raises:
- WalletAPIError: If the service is not operating correctly.<|endoftext|> |
9c650a3dedf2b3bc450be446924650f0fec1e15361f6100dd0bf68e159aec339 | def get_wallets(self, user_ids: List[str]=[], authority_ids: List[str]=[]) -> List[Dict[(str, object)]]:
" Get wallets. Filterable by user and authority.\n Arguments:\n - user_ids: If provided only returns these user's wallets.\n - authority_ids: If provided only returns the value of wallets' transactions\n with authorities.\n\n Returns: Wallets.\n\n Raises:\n - WalletAPIError\n "
resp = self.__do_request__('GET', '/wallet', resp_schema=WalletClient.GET_WALLETS_RESP_SCHEMA, params={'user_ids': ','.join(user_ids), 'authority_ids': ','.join(authority_ids)})
return resp.json()['wallets'] | Get wallets. Filterable by user and authority.
Arguments:
- user_ids: If provided only returns these user's wallets.
- authority_ids: If provided only returns the value of wallets' transactions
with authorities.
Returns: Wallets.
Raises:
- WalletAPIError | py-sdk/wallet_sdk/__init__.py | get_wallets | Noah-Huppert/wallet-service | 0 | python | def get_wallets(self, user_ids: List[str]=[], authority_ids: List[str]=[]) -> List[Dict[(str, object)]]:
" Get wallets. Filterable by user and authority.\n Arguments:\n - user_ids: If provided only returns these user's wallets.\n - authority_ids: If provided only returns the value of wallets' transactions\n with authorities.\n\n Returns: Wallets.\n\n Raises:\n - WalletAPIError\n "
resp = self.__do_request__('GET', '/wallet', resp_schema=WalletClient.GET_WALLETS_RESP_SCHEMA, params={'user_ids': ','.join(user_ids), 'authority_ids': ','.join(authority_ids)})
return resp.json()['wallets'] | def get_wallets(self, user_ids: List[str]=[], authority_ids: List[str]=[]) -> List[Dict[(str, object)]]:
" Get wallets. Filterable by user and authority.\n Arguments:\n - user_ids: If provided only returns these user's wallets.\n - authority_ids: If provided only returns the value of wallets' transactions\n with authorities.\n\n Returns: Wallets.\n\n Raises:\n - WalletAPIError\n "
resp = self.__do_request__('GET', '/wallet', resp_schema=WalletClient.GET_WALLETS_RESP_SCHEMA, params={'user_ids': ','.join(user_ids), 'authority_ids': ','.join(authority_ids)})
return resp.json()['wallets']<|docstring|>Get wallets. Filterable by user and authority.
Arguments:
- user_ids: If provided only returns these user's wallets.
- authority_ids: If provided only returns the value of wallets' transactions
with authorities.
Returns: Wallets.
Raises:
- WalletAPIError<|endoftext|> |
0b4c53b8b047636daf24351209a98fd1ad39092325b7401b20fc142886e20eee | def create_entry(self, user_id: str, amount: int, reason: str, item: Optional[EntryItemT]=None) -> Dict[(str, object)]:
' Creates an entry in the wallet service.\n Argments:\n - user_id: ID of user involved in entry.\n - amount: Positive amount to add, or negative amount to remove.\n - reason: Purpose for adding or removing value to / from a user.\n - item: Item which is being exchanged in this entry, optional.\n\n Returns: Created entry\n\n Raises:\n - WalletAPIError\n - NotEnoughFundsError: If the user does not have enough funds to back the new entry.\n '
resp = self.__do_request__('POST', '/entry', resp_schema=WalletClient.CREATE_ENTRY_RESP_SCHEMA, json={'user_id': user_id, 'amount': amount, 'reason': reason, 'item': item})
return resp.json()['entry'] | Creates an entry in the wallet service.
Argments:
- user_id: ID of user involved in entry.
- amount: Positive amount to add, or negative amount to remove.
- reason: Purpose for adding or removing value to / from a user.
- item: Item which is being exchanged in this entry, optional.
Returns: Created entry
Raises:
- WalletAPIError
- NotEnoughFundsError: If the user does not have enough funds to back the new entry. | py-sdk/wallet_sdk/__init__.py | create_entry | Noah-Huppert/wallet-service | 0 | python | def create_entry(self, user_id: str, amount: int, reason: str, item: Optional[EntryItemT]=None) -> Dict[(str, object)]:
' Creates an entry in the wallet service.\n Argments:\n - user_id: ID of user involved in entry.\n - amount: Positive amount to add, or negative amount to remove.\n - reason: Purpose for adding or removing value to / from a user.\n - item: Item which is being exchanged in this entry, optional.\n\n Returns: Created entry\n\n Raises:\n - WalletAPIError\n - NotEnoughFundsError: If the user does not have enough funds to back the new entry.\n '
resp = self.__do_request__('POST', '/entry', resp_schema=WalletClient.CREATE_ENTRY_RESP_SCHEMA, json={'user_id': user_id, 'amount': amount, 'reason': reason, 'item': item})
return resp.json()['entry'] | def create_entry(self, user_id: str, amount: int, reason: str, item: Optional[EntryItemT]=None) -> Dict[(str, object)]:
' Creates an entry in the wallet service.\n Argments:\n - user_id: ID of user involved in entry.\n - amount: Positive amount to add, or negative amount to remove.\n - reason: Purpose for adding or removing value to / from a user.\n - item: Item which is being exchanged in this entry, optional.\n\n Returns: Created entry\n\n Raises:\n - WalletAPIError\n - NotEnoughFundsError: If the user does not have enough funds to back the new entry.\n '
resp = self.__do_request__('POST', '/entry', resp_schema=WalletClient.CREATE_ENTRY_RESP_SCHEMA, json={'user_id': user_id, 'amount': amount, 'reason': reason, 'item': item})
return resp.json()['entry']<|docstring|>Creates an entry in the wallet service.
Argments:
- user_id: ID of user involved in entry.
- amount: Positive amount to add, or negative amount to remove.
- reason: Purpose for adding or removing value to / from a user.
- item: Item which is being exchanged in this entry, optional.
Returns: Created entry
Raises:
- WalletAPIError
- NotEnoughFundsError: If the user does not have enough funds to back the new entry.<|endoftext|> |
d2f234b6e76c1910683e41c525ed5ede9a04f5e0ed1d5cfb46811877299e27dd | def get_inventory(self, entry_ids: List[str]=[], user_ids: List[str]=[], authority_ids: List[str]=[], used: Optional[bool]=False) -> List[Dict[(str, object)]]:
' Get user inventories. Filterable by user, authority, and item URI.\n Arguments:\n - entry_ids: Filter inventories to specified entries, optional.\n - user_ids: Filter inventories to specified users, optional.\n - authority_ids: Filter inventories to items from specified authorities, optional.\n - used: Filter inventories to used or unused items, optional. Defaults to un-used items.\n\n Returns: Wallets.\n\n Raises:\n - WalletAPIError\n '
usedStr = None
if (used is not None):
if used:
usedStr = 'true'
else:
usedStr = 'false'
resp = self.__do_request__('GET', '/entry/inventory', resp_schema=WalletClient.GET_INVENTORY_RESP_SCHEMA, params={'entry_ids': ','.join(entry_ids), 'user_ids': ','.join(user_ids), 'authority_ids': ','.join(authority_ids), 'used': usedStr})
return resp.json()['inventory'] | Get user inventories. Filterable by user, authority, and item URI.
Arguments:
- entry_ids: Filter inventories to specified entries, optional.
- user_ids: Filter inventories to specified users, optional.
- authority_ids: Filter inventories to items from specified authorities, optional.
- used: Filter inventories to used or unused items, optional. Defaults to un-used items.
Returns: Wallets.
Raises:
- WalletAPIError | py-sdk/wallet_sdk/__init__.py | get_inventory | Noah-Huppert/wallet-service | 0 | python | def get_inventory(self, entry_ids: List[str]=[], user_ids: List[str]=[], authority_ids: List[str]=[], used: Optional[bool]=False) -> List[Dict[(str, object)]]:
' Get user inventories. Filterable by user, authority, and item URI.\n Arguments:\n - entry_ids: Filter inventories to specified entries, optional.\n - user_ids: Filter inventories to specified users, optional.\n - authority_ids: Filter inventories to items from specified authorities, optional.\n - used: Filter inventories to used or unused items, optional. Defaults to un-used items.\n\n Returns: Wallets.\n\n Raises:\n - WalletAPIError\n '
usedStr = None
if (used is not None):
if used:
usedStr = 'true'
else:
usedStr = 'false'
resp = self.__do_request__('GET', '/entry/inventory', resp_schema=WalletClient.GET_INVENTORY_RESP_SCHEMA, params={'entry_ids': ','.join(entry_ids), 'user_ids': ','.join(user_ids), 'authority_ids': ','.join(authority_ids), 'used': usedStr})
return resp.json()['inventory'] | def get_inventory(self, entry_ids: List[str]=[], user_ids: List[str]=[], authority_ids: List[str]=[], used: Optional[bool]=False) -> List[Dict[(str, object)]]:
' Get user inventories. Filterable by user, authority, and item URI.\n Arguments:\n - entry_ids: Filter inventories to specified entries, optional.\n - user_ids: Filter inventories to specified users, optional.\n - authority_ids: Filter inventories to items from specified authorities, optional.\n - used: Filter inventories to used or unused items, optional. Defaults to un-used items.\n\n Returns: Wallets.\n\n Raises:\n - WalletAPIError\n '
usedStr = None
if (used is not None):
if used:
usedStr = 'true'
else:
usedStr = 'false'
resp = self.__do_request__('GET', '/entry/inventory', resp_schema=WalletClient.GET_INVENTORY_RESP_SCHEMA, params={'entry_ids': ','.join(entry_ids), 'user_ids': ','.join(user_ids), 'authority_ids': ','.join(authority_ids), 'used': usedStr})
return resp.json()['inventory']<|docstring|>Get user inventories. Filterable by user, authority, and item URI.
Arguments:
- entry_ids: Filter inventories to specified entries, optional.
- user_ids: Filter inventories to specified users, optional.
- authority_ids: Filter inventories to items from specified authorities, optional.
- used: Filter inventories to used or unused items, optional. Defaults to un-used items.
Returns: Wallets.
Raises:
- WalletAPIError<|endoftext|> |
dc030155ad25806e31d5df14f64b8d586289cf33ddc0b6074bc8a8ed4d40e7ab | def use_item(self, entry_id: str) -> Dict[(str, object)]:
' Mark an item as used.\n Argments:\n - entry_id: ID of entry in which item was noted.\n\n Returns: Entry with modified item.\n\n Raises:\n - WalletAPIError\n '
resp = self.__do_request__('POST', f'/entry/{entry_id}/inventory/use', resp_schema=WalletClient.MARK_USED_RESP_SCHEMA)
return resp.json()['entry'] | Mark an item as used.
Argments:
- entry_id: ID of entry in which item was noted.
Returns: Entry with modified item.
Raises:
- WalletAPIError | py-sdk/wallet_sdk/__init__.py | use_item | Noah-Huppert/wallet-service | 0 | python | def use_item(self, entry_id: str) -> Dict[(str, object)]:
' Mark an item as used.\n Argments:\n - entry_id: ID of entry in which item was noted.\n\n Returns: Entry with modified item.\n\n Raises:\n - WalletAPIError\n '
resp = self.__do_request__('POST', f'/entry/{entry_id}/inventory/use', resp_schema=WalletClient.MARK_USED_RESP_SCHEMA)
return resp.json()['entry'] | def use_item(self, entry_id: str) -> Dict[(str, object)]:
' Mark an item as used.\n Argments:\n - entry_id: ID of entry in which item was noted.\n\n Returns: Entry with modified item.\n\n Raises:\n - WalletAPIError\n '
resp = self.__do_request__('POST', f'/entry/{entry_id}/inventory/use', resp_schema=WalletClient.MARK_USED_RESP_SCHEMA)
return resp.json()['entry']<|docstring|>Mark an item as used.
Argments:
- entry_id: ID of entry in which item was noted.
Returns: Entry with modified item.
Raises:
- WalletAPIError<|endoftext|> |
893e7b27b42ac676d943d601ef58864a7aa076418234f6700388b689ede0f657 | def main():
'Entry point for creating a Spinnaker application.'
parser = argparse.ArgumentParser()
add_debug(parser)
add_app(parser)
parser.add_argument('--email', help='Email address to associate with application', default='example@example.com')
parser.add_argument('--project', help='Git project to associate with application', default='None')
parser.add_argument('--repo', help='Git repo to associate with application', default='None')
parser.add_argument('--git', help='Git URI', default=None)
args = parser.parse_args()
logging.basicConfig(format=LOGGING_FORMAT)
logging.getLogger(__package__.split('.')[0]).setLevel(args.debug)
if (args.git and (args.git != 'None')):
parsed = gogoutils.Parser(args.git).parse_url()
generated = gogoutils.Generator(*parsed, formats=APP_FORMATS)
project = generated.project
repo = generated.repo
else:
project = args.project
repo = args.repo
spinnakerapps = SpinnakerApp(app=args.app, email=args.email, project=project, repo=repo)
spinnakerapps.create_app() | Entry point for creating a Spinnaker application. | src/foremast/app/__main__.py | main | gitter-badger/foremast | 0 | python | def main():
parser = argparse.ArgumentParser()
add_debug(parser)
add_app(parser)
parser.add_argument('--email', help='Email address to associate with application', default='example@example.com')
parser.add_argument('--project', help='Git project to associate with application', default='None')
parser.add_argument('--repo', help='Git repo to associate with application', default='None')
parser.add_argument('--git', help='Git URI', default=None)
args = parser.parse_args()
logging.basicConfig(format=LOGGING_FORMAT)
logging.getLogger(__package__.split('.')[0]).setLevel(args.debug)
if (args.git and (args.git != 'None')):
parsed = gogoutils.Parser(args.git).parse_url()
generated = gogoutils.Generator(*parsed, formats=APP_FORMATS)
project = generated.project
repo = generated.repo
else:
project = args.project
repo = args.repo
spinnakerapps = SpinnakerApp(app=args.app, email=args.email, project=project, repo=repo)
spinnakerapps.create_app() | def main():
parser = argparse.ArgumentParser()
add_debug(parser)
add_app(parser)
parser.add_argument('--email', help='Email address to associate with application', default='example@example.com')
parser.add_argument('--project', help='Git project to associate with application', default='None')
parser.add_argument('--repo', help='Git repo to associate with application', default='None')
parser.add_argument('--git', help='Git URI', default=None)
args = parser.parse_args()
logging.basicConfig(format=LOGGING_FORMAT)
logging.getLogger(__package__.split('.')[0]).setLevel(args.debug)
if (args.git and (args.git != 'None')):
parsed = gogoutils.Parser(args.git).parse_url()
generated = gogoutils.Generator(*parsed, formats=APP_FORMATS)
project = generated.project
repo = generated.repo
else:
project = args.project
repo = args.repo
spinnakerapps = SpinnakerApp(app=args.app, email=args.email, project=project, repo=repo)
spinnakerapps.create_app()<|docstring|>Entry point for creating a Spinnaker application.<|endoftext|> |
2ddfbfe1ee7fc4336bf8330737f7b30c9e8185da16e33bce6485643dbab52397 | def check_request(request, need_login=None, is_post=None):
'\n 检测登录及http请求方式是否满足设定的条件。\n :param request: http请求\n :param need_login: 是否需要登录。True表示必须登录;False表示不能登录;None表示无需检测。\n :param is_post: 是否需要为post请求。True表示必须是;False表示不可是;None表示无需检测。\n :return:\n '
if (need_login is not None):
if not_login(request):
if need_login:
return CheckResult(False, ErrorInfo.User.not_login)
elif (need_login is False):
return CheckResult(False, ErrorInfo.User.has_login)
if (is_post is not None):
if (request_is_post(request) != is_post):
return CheckResult(False, ErrorInfo.Request.wrong_request_method)
return CheckResult(True, SuccessInfo.success) | 检测登录及http请求方式是否满足设定的条件。
:param request: http请求
:param need_login: 是否需要登录。True表示必须登录;False表示不能登录;None表示无需检测。
:param is_post: 是否需要为post请求。True表示必须是;False表示不可是;None表示无需检测。
:return: | api/views/util.py | check_request | kuwii/sdust-acmer | 2 | python | def check_request(request, need_login=None, is_post=None):
'\n 检测登录及http请求方式是否满足设定的条件。\n :param request: http请求\n :param need_login: 是否需要登录。True表示必须登录;False表示不能登录;None表示无需检测。\n :param is_post: 是否需要为post请求。True表示必须是;False表示不可是;None表示无需检测。\n :return:\n '
if (need_login is not None):
if not_login(request):
if need_login:
return CheckResult(False, ErrorInfo.User.not_login)
elif (need_login is False):
return CheckResult(False, ErrorInfo.User.has_login)
if (is_post is not None):
if (request_is_post(request) != is_post):
return CheckResult(False, ErrorInfo.Request.wrong_request_method)
return CheckResult(True, SuccessInfo.success) | def check_request(request, need_login=None, is_post=None):
'\n 检测登录及http请求方式是否满足设定的条件。\n :param request: http请求\n :param need_login: 是否需要登录。True表示必须登录;False表示不能登录;None表示无需检测。\n :param is_post: 是否需要为post请求。True表示必须是;False表示不可是;None表示无需检测。\n :return:\n '
if (need_login is not None):
if not_login(request):
if need_login:
return CheckResult(False, ErrorInfo.User.not_login)
elif (need_login is False):
return CheckResult(False, ErrorInfo.User.has_login)
if (is_post is not None):
if (request_is_post(request) != is_post):
return CheckResult(False, ErrorInfo.Request.wrong_request_method)
return CheckResult(True, SuccessInfo.success)<|docstring|>检测登录及http请求方式是否满足设定的条件。
:param request: http请求
:param need_login: 是否需要登录。True表示必须登录;False表示不能登录;None表示无需检测。
:param is_post: 是否需要为post请求。True表示必须是;False表示不可是;None表示无需检测。
:return:<|endoftext|> |
bb0365ced1e579e39840dcfbf657ae72c67bf0b6984f1bc8f897111ecf0260b8 | def check_can_manage(request, target_user, function_name=''):
'\n 检测当前用户能否对指定用户进行对应操作。要求必须登录且检测的两个用户不是同一个用户。\n :param request: http请求\n :param target_user: 被管理者\n :param function_name: 动作名称\n :return:\n '
can_manage = database_permitted_to_manage(request.user.username, target_user, function_name)
if (can_manage is None):
return CheckResult(False, ErrorInfo.User.user_not_exists)
if (not can_manage):
return CheckResult(False, ErrorInfo.Permission.no_permission)
return CheckResult(True, SuccessInfo.success) | 检测当前用户能否对指定用户进行对应操作。要求必须登录且检测的两个用户不是同一个用户。
:param request: http请求
:param target_user: 被管理者
:param function_name: 动作名称
:return: | api/views/util.py | check_can_manage | kuwii/sdust-acmer | 2 | python | def check_can_manage(request, target_user, function_name=):
'\n 检测当前用户能否对指定用户进行对应操作。要求必须登录且检测的两个用户不是同一个用户。\n :param request: http请求\n :param target_user: 被管理者\n :param function_name: 动作名称\n :return:\n '
can_manage = database_permitted_to_manage(request.user.username, target_user, function_name)
if (can_manage is None):
return CheckResult(False, ErrorInfo.User.user_not_exists)
if (not can_manage):
return CheckResult(False, ErrorInfo.Permission.no_permission)
return CheckResult(True, SuccessInfo.success) | def check_can_manage(request, target_user, function_name=):
'\n 检测当前用户能否对指定用户进行对应操作。要求必须登录且检测的两个用户不是同一个用户。\n :param request: http请求\n :param target_user: 被管理者\n :param function_name: 动作名称\n :return:\n '
can_manage = database_permitted_to_manage(request.user.username, target_user, function_name)
if (can_manage is None):
return CheckResult(False, ErrorInfo.User.user_not_exists)
if (not can_manage):
return CheckResult(False, ErrorInfo.Permission.no_permission)
return CheckResult(True, SuccessInfo.success)<|docstring|>检测当前用户能否对指定用户进行对应操作。要求必须登录且检测的两个用户不是同一个用户。
:param request: http请求
:param target_user: 被管理者
:param function_name: 动作名称
:return:<|endoftext|> |
288394e80fb39b681f222d465cad2240bab0986462a4f1c1292dba05ecc72cde | def get_data_source(self, name, master_data_source_name, slave_data_source_names):
'\n get data source for execute sql\n :param name:\n :param master_data_source_name:\n :param slave_data_source_names:\n :return: data source name\n '
raise NotImplementedError | get data source for execute sql
:param name:
:param master_data_source_name:
:param slave_data_source_names:
:return: data source name | shardingpy/api/algorithm/masterslave/base.py | get_data_source | hongfuli/sharding-py | 1 | python | def get_data_source(self, name, master_data_source_name, slave_data_source_names):
'\n get data source for execute sql\n :param name:\n :param master_data_source_name:\n :param slave_data_source_names:\n :return: data source name\n '
raise NotImplementedError | def get_data_source(self, name, master_data_source_name, slave_data_source_names):
'\n get data source for execute sql\n :param name:\n :param master_data_source_name:\n :param slave_data_source_names:\n :return: data source name\n '
raise NotImplementedError<|docstring|>get data source for execute sql
:param name:
:param master_data_source_name:
:param slave_data_source_names:
:return: data source name<|endoftext|> |
ed6386a4755d9cd58120982403e2a26811a7094797d4676702dd7677e005b427 | def serialize(self, root):
'Encodes a tree to a single string.\n\n :type root: TreeNode\n :rtype: str\n '
result = ''
def dfs(node):
nonlocal result
if (not node):
result += ('|' + ';')
return
result += (str(node.val) + ';')
dfs(node.left)
dfs(node.right)
dfs(root)
return result | Encodes a tree to a single string.
:type root: TreeNode
:rtype: str | leetcode/trees/serialize-deserialize.py | serialize | vtemian/interviews-prep | 8 | python | def serialize(self, root):
'Encodes a tree to a single string.\n\n :type root: TreeNode\n :rtype: str\n '
result =
def dfs(node):
nonlocal result
if (not node):
result += ('|' + ';')
return
result += (str(node.val) + ';')
dfs(node.left)
dfs(node.right)
dfs(root)
return result | def serialize(self, root):
'Encodes a tree to a single string.\n\n :type root: TreeNode\n :rtype: str\n '
result =
def dfs(node):
nonlocal result
if (not node):
result += ('|' + ';')
return
result += (str(node.val) + ';')
dfs(node.left)
dfs(node.right)
dfs(root)
return result<|docstring|>Encodes a tree to a single string.
:type root: TreeNode
:rtype: str<|endoftext|> |
e23f6c14ee1dbe3d91f340d59ed0f016b7812bd131c6dc9e054002607b095fe3 | def deserialize(self, data):
'Decodes your encoded data to tree.\n\n :type data: str\n :rtype: TreeNode\n '
nodes = data.split(';')[:(- 1)]
def build(idx):
if (idx >= len(nodes)):
return (None, idx)
if (nodes[idx] == '|'):
return (None, idx)
root = TreeNode(nodes[idx])
(root.left, idx) = build((idx + 1))
(root.right, idx) = build((idx + 1))
return (root, idx)
return build(0)[0] | Decodes your encoded data to tree.
:type data: str
:rtype: TreeNode | leetcode/trees/serialize-deserialize.py | deserialize | vtemian/interviews-prep | 8 | python | def deserialize(self, data):
'Decodes your encoded data to tree.\n\n :type data: str\n :rtype: TreeNode\n '
nodes = data.split(';')[:(- 1)]
def build(idx):
if (idx >= len(nodes)):
return (None, idx)
if (nodes[idx] == '|'):
return (None, idx)
root = TreeNode(nodes[idx])
(root.left, idx) = build((idx + 1))
(root.right, idx) = build((idx + 1))
return (root, idx)
return build(0)[0] | def deserialize(self, data):
'Decodes your encoded data to tree.\n\n :type data: str\n :rtype: TreeNode\n '
nodes = data.split(';')[:(- 1)]
def build(idx):
if (idx >= len(nodes)):
return (None, idx)
if (nodes[idx] == '|'):
return (None, idx)
root = TreeNode(nodes[idx])
(root.left, idx) = build((idx + 1))
(root.right, idx) = build((idx + 1))
return (root, idx)
return build(0)[0]<|docstring|>Decodes your encoded data to tree.
:type data: str
:rtype: TreeNode<|endoftext|> |
99a5e2a8e80364d7d861b0fa3aca47863c65e511444b228874f4cc888c262b9f | def test_same_version():
' Test the the version in setup.py matches the version in __init__.py '
res = subprocess.run([sys.executable, '-m', 'pip', 'show', 'cptk'], stdout=subprocess.PIPE, check=True, encoding='utf8')
fields = {line.partition(':')[0]: line.partition(':')[(- 1)].strip() for line in res.stdout.split('\n')}
from cptk import __version__
assert (__version__ == fields['Version']) | Test the the version in setup.py matches the version in __init__.py | tests/test_build.py | test_same_version | RealA10N/cptk | 5 | python | def test_same_version():
' '
res = subprocess.run([sys.executable, '-m', 'pip', 'show', 'cptk'], stdout=subprocess.PIPE, check=True, encoding='utf8')
fields = {line.partition(':')[0]: line.partition(':')[(- 1)].strip() for line in res.stdout.split('\n')}
from cptk import __version__
assert (__version__ == fields['Version']) | def test_same_version():
' '
res = subprocess.run([sys.executable, '-m', 'pip', 'show', 'cptk'], stdout=subprocess.PIPE, check=True, encoding='utf8')
fields = {line.partition(':')[0]: line.partition(':')[(- 1)].strip() for line in res.stdout.split('\n')}
from cptk import __version__
assert (__version__ == fields['Version'])<|docstring|>Test the the version in setup.py matches the version in __init__.py<|endoftext|> |
4335e3d738c6a9001770766e4deee87ef76e0686d62fa5218f196744fbfd2201 | def sampling(n):
'\n Pandas dataframe can return sample of a subset.\n But this function can create extra duplications, so subset could be extracted\n :param n: subset size\n :return: sampling function\n '
def _sample(x):
if (n > x.shape[0]):
count = ((n // x.shape[0]) + 1)
x = pd.concat(([x] * count))
return x.sample(n=n)
else:
return x.sample(n=n)
return _sample | Pandas dataframe can return sample of a subset.
But this function can create extra duplications, so subset could be extracted
:param n: subset size
:return: sampling function | sound_separation/data.py | sampling | blan4/sound_separation | 1 | python | def sampling(n):
'\n Pandas dataframe can return sample of a subset.\n But this function can create extra duplications, so subset could be extracted\n :param n: subset size\n :return: sampling function\n '
def _sample(x):
if (n > x.shape[0]):
count = ((n // x.shape[0]) + 1)
x = pd.concat(([x] * count))
return x.sample(n=n)
else:
return x.sample(n=n)
return _sample | def sampling(n):
'\n Pandas dataframe can return sample of a subset.\n But this function can create extra duplications, so subset could be extracted\n :param n: subset size\n :return: sampling function\n '
def _sample(x):
if (n > x.shape[0]):
count = ((n // x.shape[0]) + 1)
x = pd.concat(([x] * count))
return x.sample(n=n)
else:
return x.sample(n=n)
return _sample<|docstring|>Pandas dataframe can return sample of a subset.
But this function can create extra duplications, so subset could be extracted
:param n: subset size
:return: sampling function<|endoftext|> |
e7204e35234f43dcaa5333fbde395762beda4724c3bfabac4166abeb848945f2 | @curry
def correlation_feature_selection(train_set: pd.DataFrame, features: List[str], threshold: float=1.0) -> LogType:
"\n Feature selection based on correlation\n\n Parameters\n ----------\n train_set : pd.DataFrame\n A Pandas' DataFrame with the training data\n\n features : list of str\n The list of features to consider when dropping with correlation\n\n threshold : float\n The correlation threshold. Will drop features with correlation equal or\n above this threshold\n\n Returns\n ----------\n log with feature correlation, features to drop and final features\n "
correlogram = train_set[features].corr()
correlogram_diag = pd.DataFrame(tril(correlogram.values), columns=correlogram.columns, index=correlogram.index)
features_to_drop = pd.melt(correlogram_diag.reset_index(), id_vars='index').query('index!=variable').query('abs(value)>0.0').query(('abs(value)>=%f' % threshold))['variable'].tolist()
final_features = list((set(features) - set(features_to_drop)))
return {'feature_corr': correlogram.to_dict(), 'features_to_drop': features_to_drop, 'final_features': final_features} | Feature selection based on correlation
Parameters
----------
train_set : pd.DataFrame
A Pandas' DataFrame with the training data
features : list of str
The list of features to consider when dropping with correlation
threshold : float
The correlation threshold. Will drop features with correlation equal or
above this threshold
Returns
----------
log with feature correlation, features to drop and final features | src/fklearn/tuning/model_agnostic_fc.py | correlation_feature_selection | erickisos/fklearn | 1,505 | python | @curry
def correlation_feature_selection(train_set: pd.DataFrame, features: List[str], threshold: float=1.0) -> LogType:
"\n Feature selection based on correlation\n\n Parameters\n ----------\n train_set : pd.DataFrame\n A Pandas' DataFrame with the training data\n\n features : list of str\n The list of features to consider when dropping with correlation\n\n threshold : float\n The correlation threshold. Will drop features with correlation equal or\n above this threshold\n\n Returns\n ----------\n log with feature correlation, features to drop and final features\n "
correlogram = train_set[features].corr()
correlogram_diag = pd.DataFrame(tril(correlogram.values), columns=correlogram.columns, index=correlogram.index)
features_to_drop = pd.melt(correlogram_diag.reset_index(), id_vars='index').query('index!=variable').query('abs(value)>0.0').query(('abs(value)>=%f' % threshold))['variable'].tolist()
final_features = list((set(features) - set(features_to_drop)))
return {'feature_corr': correlogram.to_dict(), 'features_to_drop': features_to_drop, 'final_features': final_features} | @curry
def correlation_feature_selection(train_set: pd.DataFrame, features: List[str], threshold: float=1.0) -> LogType:
"\n Feature selection based on correlation\n\n Parameters\n ----------\n train_set : pd.DataFrame\n A Pandas' DataFrame with the training data\n\n features : list of str\n The list of features to consider when dropping with correlation\n\n threshold : float\n The correlation threshold. Will drop features with correlation equal or\n above this threshold\n\n Returns\n ----------\n log with feature correlation, features to drop and final features\n "
correlogram = train_set[features].corr()
correlogram_diag = pd.DataFrame(tril(correlogram.values), columns=correlogram.columns, index=correlogram.index)
features_to_drop = pd.melt(correlogram_diag.reset_index(), id_vars='index').query('index!=variable').query('abs(value)>0.0').query(('abs(value)>=%f' % threshold))['variable'].tolist()
final_features = list((set(features) - set(features_to_drop)))
return {'feature_corr': correlogram.to_dict(), 'features_to_drop': features_to_drop, 'final_features': final_features}<|docstring|>Feature selection based on correlation
Parameters
----------
train_set : pd.DataFrame
A Pandas' DataFrame with the training data
features : list of str
The list of features to consider when dropping with correlation
threshold : float
The correlation threshold. Will drop features with correlation equal or
above this threshold
Returns
----------
log with feature correlation, features to drop and final features<|endoftext|> |
92336839d9330031373dc95a3d6c2d4a425d606ea6696b7c318b13fdb007065a | @curry
def variance_feature_selection(train_set: pd.DataFrame, features: List[str], threshold: float=0.0) -> LogType:
"\n Feature selection based on variance\n\n Parameters\n ----------\n train_set : pd.DataFrame\n A Pandas' DataFrame with the training data\n\n features : list of str\n The list of features to consider when dropping with variance\n\n threshold : float\n The variance threshold. Will drop features with variance equal or\n bellow this threshold\n\n Returns\n ----------\n log with feature variance, features to drop and final features\n "
feature_var = train_set[features].var()
features_to_drop = feature_var[(feature_var <= threshold)].index.tolist()
final_features = list((set(features) - set(features_to_drop)))
return {'feature_var': feature_var.to_dict(), 'features_to_drop': features_to_drop, 'final_features': final_features} | Feature selection based on variance
Parameters
----------
train_set : pd.DataFrame
A Pandas' DataFrame with the training data
features : list of str
The list of features to consider when dropping with variance
threshold : float
The variance threshold. Will drop features with variance equal or
bellow this threshold
Returns
----------
log with feature variance, features to drop and final features | src/fklearn/tuning/model_agnostic_fc.py | variance_feature_selection | erickisos/fklearn | 1,505 | python | @curry
def variance_feature_selection(train_set: pd.DataFrame, features: List[str], threshold: float=0.0) -> LogType:
"\n Feature selection based on variance\n\n Parameters\n ----------\n train_set : pd.DataFrame\n A Pandas' DataFrame with the training data\n\n features : list of str\n The list of features to consider when dropping with variance\n\n threshold : float\n The variance threshold. Will drop features with variance equal or\n bellow this threshold\n\n Returns\n ----------\n log with feature variance, features to drop and final features\n "
feature_var = train_set[features].var()
features_to_drop = feature_var[(feature_var <= threshold)].index.tolist()
final_features = list((set(features) - set(features_to_drop)))
return {'feature_var': feature_var.to_dict(), 'features_to_drop': features_to_drop, 'final_features': final_features} | @curry
def variance_feature_selection(train_set: pd.DataFrame, features: List[str], threshold: float=0.0) -> LogType:
"\n Feature selection based on variance\n\n Parameters\n ----------\n train_set : pd.DataFrame\n A Pandas' DataFrame with the training data\n\n features : list of str\n The list of features to consider when dropping with variance\n\n threshold : float\n The variance threshold. Will drop features with variance equal or\n bellow this threshold\n\n Returns\n ----------\n log with feature variance, features to drop and final features\n "
feature_var = train_set[features].var()
features_to_drop = feature_var[(feature_var <= threshold)].index.tolist()
final_features = list((set(features) - set(features_to_drop)))
return {'feature_var': feature_var.to_dict(), 'features_to_drop': features_to_drop, 'final_features': final_features}<|docstring|>Feature selection based on variance
Parameters
----------
train_set : pd.DataFrame
A Pandas' DataFrame with the training data
features : list of str
The list of features to consider when dropping with variance
threshold : float
The variance threshold. Will drop features with variance equal or
bellow this threshold
Returns
----------
log with feature variance, features to drop and final features<|endoftext|> |
76c858689a1357ac5b45ce6e3783b41fb948a2a06e41bf685fa870887129ab65 | def cuda_visible_devices(i, visible=None):
" Cycling values for CUDA_VISIBLE_DEVICES environment variable\n\n Examples\n --------\n >>> cuda_visible_devices(0, range(4))\n '0,1,2,3'\n >>> cuda_visible_devices(3, range(8))\n '3,4,5,6,7,0,1,2'\n "
if (visible is None):
try:
visible = map(int, os.environ['CUDA_VISIBLE_DEVICES'].split(','))
except KeyError:
visible = range(get_n_gpus())
visible = list(visible)
L = (visible[i:] + visible[:i])
return ','.join(map(str, L)) | Cycling values for CUDA_VISIBLE_DEVICES environment variable
Examples
--------
>>> cuda_visible_devices(0, range(4))
'0,1,2,3'
>>> cuda_visible_devices(3, range(8))
'3,4,5,6,7,0,1,2' | dask_cuda/local_cuda_cluster.py | cuda_visible_devices | jacobtomlinson/dask-cuda | 0 | python | def cuda_visible_devices(i, visible=None):
" Cycling values for CUDA_VISIBLE_DEVICES environment variable\n\n Examples\n --------\n >>> cuda_visible_devices(0, range(4))\n '0,1,2,3'\n >>> cuda_visible_devices(3, range(8))\n '3,4,5,6,7,0,1,2'\n "
if (visible is None):
try:
visible = map(int, os.environ['CUDA_VISIBLE_DEVICES'].split(','))
except KeyError:
visible = range(get_n_gpus())
visible = list(visible)
L = (visible[i:] + visible[:i])
return ','.join(map(str, L)) | def cuda_visible_devices(i, visible=None):
" Cycling values for CUDA_VISIBLE_DEVICES environment variable\n\n Examples\n --------\n >>> cuda_visible_devices(0, range(4))\n '0,1,2,3'\n >>> cuda_visible_devices(3, range(8))\n '3,4,5,6,7,0,1,2'\n "
if (visible is None):
try:
visible = map(int, os.environ['CUDA_VISIBLE_DEVICES'].split(','))
except KeyError:
visible = range(get_n_gpus())
visible = list(visible)
L = (visible[i:] + visible[:i])
return ','.join(map(str, L))<|docstring|>Cycling values for CUDA_VISIBLE_DEVICES environment variable
Examples
--------
>>> cuda_visible_devices(0, range(4))
'0,1,2,3'
>>> cuda_visible_devices(3, range(8))
'3,4,5,6,7,0,1,2'<|endoftext|> |
1c301809dc9f5376664e24d7c02006e75fba840ee3d278dab98780f89fdee63f | def test_assert_truth(self):
'\n We shall contemplate truth by testing reality, via asserts.\n '
self.assertTrue(True) | We shall contemplate truth by testing reality, via asserts. | koans/about_asserts.py | test_assert_truth | Monto365/python_koans | 0 | python | def test_assert_truth(self):
'\n \n '
self.assertTrue(True) | def test_assert_truth(self):
'\n \n '
self.assertTrue(True)<|docstring|>We shall contemplate truth by testing reality, via asserts.<|endoftext|> |
d571d8dcef60de679498cfd07a1da2904dec00156dd88a6a23bb9456e7487ed0 | def test_assert_with_message(self):
'\n Enlightenment may be more easily achieved with appropriate messages.\n '
self.assertTrue(True, 'This should be True -- Please fix this') | Enlightenment may be more easily achieved with appropriate messages. | koans/about_asserts.py | test_assert_with_message | Monto365/python_koans | 0 | python | def test_assert_with_message(self):
'\n \n '
self.assertTrue(True, 'This should be True -- Please fix this') | def test_assert_with_message(self):
'\n \n '
self.assertTrue(True, 'This should be True -- Please fix this')<|docstring|>Enlightenment may be more easily achieved with appropriate messages.<|endoftext|> |
0f66e7baa800bc6e4a7b5c1a29f7083d295bd3d3354786c4b2e61697f06c9854 | def test_fill_in_values(self):
'\n Sometimes we will ask you to fill in the values\n '
self.assertEqual(2, (1 + 1)) | Sometimes we will ask you to fill in the values | koans/about_asserts.py | test_fill_in_values | Monto365/python_koans | 0 | python | def test_fill_in_values(self):
'\n \n '
self.assertEqual(2, (1 + 1)) | def test_fill_in_values(self):
'\n \n '
self.assertEqual(2, (1 + 1))<|docstring|>Sometimes we will ask you to fill in the values<|endoftext|> |
0b1cf7aaf9a581ea7b2636cd1e4f8d0b02ed2e3a60a6a62e9bbd5bc7c0918b99 | def test_assert_equality(self):
'\n To understand reality, we must compare our expectations against reality.\n '
expected_value = 2
actual_value = (1 + 1)
self.assertTrue((expected_value == actual_value)) | To understand reality, we must compare our expectations against reality. | koans/about_asserts.py | test_assert_equality | Monto365/python_koans | 0 | python | def test_assert_equality(self):
'\n \n '
expected_value = 2
actual_value = (1 + 1)
self.assertTrue((expected_value == actual_value)) | def test_assert_equality(self):
'\n \n '
expected_value = 2
actual_value = (1 + 1)
self.assertTrue((expected_value == actual_value))<|docstring|>To understand reality, we must compare our expectations against reality.<|endoftext|> |
4e34a9cbba9ea48ff1f987ef385812d0b1238941b13a8ea9ec59333b83a1aa57 | def test_a_better_way_of_asserting_equality(self):
'\n Some ways of asserting equality are better than others.\n '
expected_value = 2
actual_value = (1 + 1)
self.assertEqual(expected_value, actual_value) | Some ways of asserting equality are better than others. | koans/about_asserts.py | test_a_better_way_of_asserting_equality | Monto365/python_koans | 0 | python | def test_a_better_way_of_asserting_equality(self):
'\n \n '
expected_value = 2
actual_value = (1 + 1)
self.assertEqual(expected_value, actual_value) | def test_a_better_way_of_asserting_equality(self):
'\n \n '
expected_value = 2
actual_value = (1 + 1)
self.assertEqual(expected_value, actual_value)<|docstring|>Some ways of asserting equality are better than others.<|endoftext|> |
94ec2ffdca2a1d08eb1d8d91981a8492c8f7fbadde23d40eba1e045d63bd2d99 | def test_that_unittest_asserts_work_the_same_way_as_python_asserts(self):
'\n Understand what lies within.\n '
assert True | Understand what lies within. | koans/about_asserts.py | test_that_unittest_asserts_work_the_same_way_as_python_asserts | Monto365/python_koans | 0 | python | def test_that_unittest_asserts_work_the_same_way_as_python_asserts(self):
'\n \n '
assert True | def test_that_unittest_asserts_work_the_same_way_as_python_asserts(self):
'\n \n '
assert True<|docstring|>Understand what lies within.<|endoftext|> |
cc168e4b6dbb199d715bdcf88b493747afd9b17289aaf41964eb405b5e67c3fe | def test_that_sometimes_we_need_to_know_the_class_type(self):
'\n What is in a class name?\n '
self.assertEqual(str, 'navel'.__class__) | What is in a class name? | koans/about_asserts.py | test_that_sometimes_we_need_to_know_the_class_type | Monto365/python_koans | 0 | python | def test_that_sometimes_we_need_to_know_the_class_type(self):
'\n \n '
self.assertEqual(str, 'navel'.__class__) | def test_that_sometimes_we_need_to_know_the_class_type(self):
'\n \n '
self.assertEqual(str, 'navel'.__class__)<|docstring|>What is in a class name?<|endoftext|> |
ba27d5f503202a862189c7f2194a7ad5949a03d0acdb3b9f381f81ee48f83d2e | def __init__(self):
'Display a form to enter the size of the grid of the go game\n and start it\n\n Arguments:\n -\n\n Attributes updated by this function:\n self.grid_size\n '
starting_screen = Tk()
Label(starting_screen, text='Grid Size').grid(row=0)
sv_grid_size = StringVar()
sv_grid_size.trace('w', (lambda name, index, mode, sv=sv_grid_size: self.callback_grid_size()))
self.grid_size = Entry(starting_screen, textvariable=sv_grid_size)
self.grid_size.grid(row=0, column=1)
Label(starting_screen, text='Name Player 1 (Black)').grid(row=1)
sv_player_1 = StringVar()
sv_player_1.trace('w', (lambda name, index, mode, sv=sv_player_1: self.callback_player_1()))
self.player_1_name = Entry(starting_screen, textvariable=sv_player_1)
self.player_1_name.grid(row=1, column=1)
Label(starting_screen, text='Name Player 2 (White)').grid(row=3)
sv_player_2 = StringVar()
sv_player_2.trace('w', (lambda name, index, mode, sv=sv_player_2: self.callback_player_1()))
self.player_2_name = Entry(starting_screen, textvariable=sv_player_2)
self.player_2_name.grid(row=3, column=1)
Button(starting_screen, text='Start', command=self.start_game).grid(row=4, column=1, sticky=W, pady=4)
self.info_label = Label(starting_screen, text='')
self.info_label.grid(row=5, columnspan=2)
mainloop() | Display a form to enter the size of the grid of the go game
and start it
Arguments:
-
Attributes updated by this function:
self.grid_size | go.py | __init__ | nikzaugg/Go-Game | 6 | python | def __init__(self):
'Display a form to enter the size of the grid of the go game\n and start it\n\n Arguments:\n -\n\n Attributes updated by this function:\n self.grid_size\n '
starting_screen = Tk()
Label(starting_screen, text='Grid Size').grid(row=0)
sv_grid_size = StringVar()
sv_grid_size.trace('w', (lambda name, index, mode, sv=sv_grid_size: self.callback_grid_size()))
self.grid_size = Entry(starting_screen, textvariable=sv_grid_size)
self.grid_size.grid(row=0, column=1)
Label(starting_screen, text='Name Player 1 (Black)').grid(row=1)
sv_player_1 = StringVar()
sv_player_1.trace('w', (lambda name, index, mode, sv=sv_player_1: self.callback_player_1()))
self.player_1_name = Entry(starting_screen, textvariable=sv_player_1)
self.player_1_name.grid(row=1, column=1)
Label(starting_screen, text='Name Player 2 (White)').grid(row=3)
sv_player_2 = StringVar()
sv_player_2.trace('w', (lambda name, index, mode, sv=sv_player_2: self.callback_player_1()))
self.player_2_name = Entry(starting_screen, textvariable=sv_player_2)
self.player_2_name.grid(row=3, column=1)
Button(starting_screen, text='Start', command=self.start_game).grid(row=4, column=1, sticky=W, pady=4)
self.info_label = Label(starting_screen, text=)
self.info_label.grid(row=5, columnspan=2)
mainloop() | def __init__(self):
'Display a form to enter the size of the grid of the go game\n and start it\n\n Arguments:\n -\n\n Attributes updated by this function:\n self.grid_size\n '
starting_screen = Tk()
Label(starting_screen, text='Grid Size').grid(row=0)
sv_grid_size = StringVar()
sv_grid_size.trace('w', (lambda name, index, mode, sv=sv_grid_size: self.callback_grid_size()))
self.grid_size = Entry(starting_screen, textvariable=sv_grid_size)
self.grid_size.grid(row=0, column=1)
Label(starting_screen, text='Name Player 1 (Black)').grid(row=1)
sv_player_1 = StringVar()
sv_player_1.trace('w', (lambda name, index, mode, sv=sv_player_1: self.callback_player_1()))
self.player_1_name = Entry(starting_screen, textvariable=sv_player_1)
self.player_1_name.grid(row=1, column=1)
Label(starting_screen, text='Name Player 2 (White)').grid(row=3)
sv_player_2 = StringVar()
sv_player_2.trace('w', (lambda name, index, mode, sv=sv_player_2: self.callback_player_1()))
self.player_2_name = Entry(starting_screen, textvariable=sv_player_2)
self.player_2_name.grid(row=3, column=1)
Button(starting_screen, text='Start', command=self.start_game).grid(row=4, column=1, sticky=W, pady=4)
self.info_label = Label(starting_screen, text=)
self.info_label.grid(row=5, columnspan=2)
mainloop()<|docstring|>Display a form to enter the size of the grid of the go game
and start it
Arguments:
-
Attributes updated by this function:
self.grid_size<|endoftext|> |
1e41d89ce3fdaa452dd650927ddde309514dde710785ab3d8f3ad36ea8f41b90 | def callback_grid_size(self):
'Empty the info label\n '
self.info_label.config(text='') | Empty the info label | go.py | callback_grid_size | nikzaugg/Go-Game | 6 | python | def callback_grid_size(self):
'\n '
self.info_label.config(text=) | def callback_grid_size(self):
'\n '
self.info_label.config(text=)<|docstring|>Empty the info label<|endoftext|> |
88e4dc7049336c153fda5fc523be61e7ce873c5ed920bb569bb9ba5311d4f4ba | def callback_player_1(self):
'Empty the info label\n '
self.info_label.config(text='') | Empty the info label | go.py | callback_player_1 | nikzaugg/Go-Game | 6 | python | def callback_player_1(self):
'\n '
self.info_label.config(text=) | def callback_player_1(self):
'\n '
self.info_label.config(text=)<|docstring|>Empty the info label<|endoftext|> |
f82a56fb6a9eb046ec4cd8d4b9087da8c5e45af3255960a1dfb5880386c26337 | def callback_player_2(self):
'Empty the info label\n '
self.info_label.config(text='') | Empty the info label | go.py | callback_player_2 | nikzaugg/Go-Game | 6 | python | def callback_player_2(self):
'\n '
self.info_label.config(text=) | def callback_player_2(self):
'\n '
self.info_label.config(text=)<|docstring|>Empty the info label<|endoftext|> |
f895b2e99bd5b8b18317d5736a3cd58ab9675cc83541c791733c266c828f8354 | def start_game(self):
'Start a new go game with a given grid size.'
n = self.grid_size.get()
if ((not n.isdigit()) or (not (int(n) > 1))):
self.info_label.config(text='Please enter a grid size larger than 1!')
return None
player_1 = self.player_1_name.get()
player_2 = self.player_2_name.get()
if ((not player_1) or (not player_2)):
self.info_label.config(text='Please enter your names!')
return None
if (__name__ == '__main__'):
Controller(n, player_1, player_2) | Start a new go game with a given grid size. | go.py | start_game | nikzaugg/Go-Game | 6 | python | def start_game(self):
n = self.grid_size.get()
if ((not n.isdigit()) or (not (int(n) > 1))):
self.info_label.config(text='Please enter a grid size larger than 1!')
return None
player_1 = self.player_1_name.get()
player_2 = self.player_2_name.get()
if ((not player_1) or (not player_2)):
self.info_label.config(text='Please enter your names!')
return None
if (__name__ == '__main__'):
Controller(n, player_1, player_2) | def start_game(self):
n = self.grid_size.get()
if ((not n.isdigit()) or (not (int(n) > 1))):
self.info_label.config(text='Please enter a grid size larger than 1!')
return None
player_1 = self.player_1_name.get()
player_2 = self.player_2_name.get()
if ((not player_1) or (not player_2)):
self.info_label.config(text='Please enter your names!')
return None
if (__name__ == '__main__'):
Controller(n, player_1, player_2)<|docstring|>Start a new go game with a given grid size.<|endoftext|> |
3bcd326c219c25700103f27f656209a2ab3358e7633c99e0580f495cfaf86d43 | def kill_process(proc):
'\n Kill the process `proc` created with `subprocess`.\n '
p1_group = psutil.Process(proc.pid)
child_pids = p1_group.children(recursive=True)
for child_pid in child_pids:
os.kill(child_pid.pid, signal.SIGKILL) | Kill the process `proc` created with `subprocess`. | Part-03-Understanding-Software-Crafting-Your-Own-Tools/models/edx-platform/pavelib/utils/process.py | kill_process | osoco/better-ways-of-thinking-about-software | 3 | python | def kill_process(proc):
'\n \n '
p1_group = psutil.Process(proc.pid)
child_pids = p1_group.children(recursive=True)
for child_pid in child_pids:
os.kill(child_pid.pid, signal.SIGKILL) | def kill_process(proc):
'\n \n '
p1_group = psutil.Process(proc.pid)
child_pids = p1_group.children(recursive=True)
for child_pid in child_pids:
os.kill(child_pid.pid, signal.SIGKILL)<|docstring|>Kill the process `proc` created with `subprocess`.<|endoftext|> |
6d2fa9db95762067268aec93c3150262915c5d7bc7bc0406a154aa1f9cd08d6e | def run_multi_processes(cmd_list, out_log=None, err_log=None):
'\n Run each shell command in `cmd_list` in a separate process,\n piping stdout to `out_log` (a path) and stderr to `err_log` (also a path).\n\n Terminates the processes on CTRL-C and ensures the processes are killed\n if an error occurs.\n '
kwargs = {'shell': True, 'cwd': None}
pids = []
if out_log:
out_log_file = open(out_log, 'w')
kwargs['stdout'] = out_log_file
if err_log:
err_log_file = open(err_log, 'w')
kwargs['stderr'] = err_log_file
if tasks.environment.dry_run:
for cmd in cmd_list:
tasks.environment.info(cmd)
return
try:
for cmd in cmd_list:
pids.extend([subprocess.Popen(cmd, **kwargs)])
def _signal_handler(*args):
'\n What to do when process is ended\n '
print('\nEnding...')
signal.signal(signal.SIGINT, _signal_handler)
print('Enter CTL-C to end')
signal.pause()
print('Processes ending')
except Exception as err:
print(f'Error running process {err}', file=sys.stderr)
finally:
for pid in pids:
kill_process(pid) | Run each shell command in `cmd_list` in a separate process,
piping stdout to `out_log` (a path) and stderr to `err_log` (also a path).
Terminates the processes on CTRL-C and ensures the processes are killed
if an error occurs. | Part-03-Understanding-Software-Crafting-Your-Own-Tools/models/edx-platform/pavelib/utils/process.py | run_multi_processes | osoco/better-ways-of-thinking-about-software | 3 | python | def run_multi_processes(cmd_list, out_log=None, err_log=None):
'\n Run each shell command in `cmd_list` in a separate process,\n piping stdout to `out_log` (a path) and stderr to `err_log` (also a path).\n\n Terminates the processes on CTRL-C and ensures the processes are killed\n if an error occurs.\n '
kwargs = {'shell': True, 'cwd': None}
pids = []
if out_log:
out_log_file = open(out_log, 'w')
kwargs['stdout'] = out_log_file
if err_log:
err_log_file = open(err_log, 'w')
kwargs['stderr'] = err_log_file
if tasks.environment.dry_run:
for cmd in cmd_list:
tasks.environment.info(cmd)
return
try:
for cmd in cmd_list:
pids.extend([subprocess.Popen(cmd, **kwargs)])
def _signal_handler(*args):
'\n What to do when process is ended\n '
print('\nEnding...')
signal.signal(signal.SIGINT, _signal_handler)
print('Enter CTL-C to end')
signal.pause()
print('Processes ending')
except Exception as err:
print(f'Error running process {err}', file=sys.stderr)
finally:
for pid in pids:
kill_process(pid) | def run_multi_processes(cmd_list, out_log=None, err_log=None):
'\n Run each shell command in `cmd_list` in a separate process,\n piping stdout to `out_log` (a path) and stderr to `err_log` (also a path).\n\n Terminates the processes on CTRL-C and ensures the processes are killed\n if an error occurs.\n '
kwargs = {'shell': True, 'cwd': None}
pids = []
if out_log:
out_log_file = open(out_log, 'w')
kwargs['stdout'] = out_log_file
if err_log:
err_log_file = open(err_log, 'w')
kwargs['stderr'] = err_log_file
if tasks.environment.dry_run:
for cmd in cmd_list:
tasks.environment.info(cmd)
return
try:
for cmd in cmd_list:
pids.extend([subprocess.Popen(cmd, **kwargs)])
def _signal_handler(*args):
'\n What to do when process is ended\n '
print('\nEnding...')
signal.signal(signal.SIGINT, _signal_handler)
print('Enter CTL-C to end')
signal.pause()
print('Processes ending')
except Exception as err:
print(f'Error running process {err}', file=sys.stderr)
finally:
for pid in pids:
kill_process(pid)<|docstring|>Run each shell command in `cmd_list` in a separate process,
piping stdout to `out_log` (a path) and stderr to `err_log` (also a path).
Terminates the processes on CTRL-C and ensures the processes are killed
if an error occurs.<|endoftext|> |
b2b58f678794345013fa648e59f8f6279793b0a1473aabc8d679f3496d23c498 | def run_process(cmd, out_log=None, err_log=None):
'\n Run the shell command `cmd` in a separate process,\n piping stdout to `out_log` (a path) and stderr to `err_log` (also a path).\n\n Terminates the process on CTRL-C or if an error occurs.\n '
return run_multi_processes([cmd], out_log=out_log, err_log=err_log) | Run the shell command `cmd` in a separate process,
piping stdout to `out_log` (a path) and stderr to `err_log` (also a path).
Terminates the process on CTRL-C or if an error occurs. | Part-03-Understanding-Software-Crafting-Your-Own-Tools/models/edx-platform/pavelib/utils/process.py | run_process | osoco/better-ways-of-thinking-about-software | 3 | python | def run_process(cmd, out_log=None, err_log=None):
'\n Run the shell command `cmd` in a separate process,\n piping stdout to `out_log` (a path) and stderr to `err_log` (also a path).\n\n Terminates the process on CTRL-C or if an error occurs.\n '
return run_multi_processes([cmd], out_log=out_log, err_log=err_log) | def run_process(cmd, out_log=None, err_log=None):
'\n Run the shell command `cmd` in a separate process,\n piping stdout to `out_log` (a path) and stderr to `err_log` (also a path).\n\n Terminates the process on CTRL-C or if an error occurs.\n '
return run_multi_processes([cmd], out_log=out_log, err_log=err_log)<|docstring|>Run the shell command `cmd` in a separate process,
piping stdout to `out_log` (a path) and stderr to `err_log` (also a path).
Terminates the process on CTRL-C or if an error occurs.<|endoftext|> |
930ec2dfd15a810476b53ef50fd1dd1b3d4dc2473158c6ec9e22f56482256051 | def run_background_process(cmd, out_log=None, err_log=None, cwd=None):
'\n Runs a command as a background process. Sends SIGINT at exit.\n '
kwargs = {'shell': True, 'cwd': cwd}
if out_log:
out_log_file = open(out_log, 'w')
kwargs['stdout'] = out_log_file
if err_log:
err_log_file = open(err_log, 'w')
kwargs['stderr'] = err_log_file
proc = subprocess.Popen(cmd, **kwargs)
def exit_handler():
"\n Send SIGINT to the process's children. This is important\n for running commands under coverage, as coverage will not\n produce the correct artifacts if the child process isn't\n killed properly.\n "
p1_group = psutil.Process(proc.pid)
child_pids = p1_group.children(recursive=True)
for child_pid in child_pids:
os.kill(child_pid.pid, signal.SIGINT)
proc.wait()
atexit.register(exit_handler) | Runs a command as a background process. Sends SIGINT at exit. | Part-03-Understanding-Software-Crafting-Your-Own-Tools/models/edx-platform/pavelib/utils/process.py | run_background_process | osoco/better-ways-of-thinking-about-software | 3 | python | def run_background_process(cmd, out_log=None, err_log=None, cwd=None):
'\n \n '
kwargs = {'shell': True, 'cwd': cwd}
if out_log:
out_log_file = open(out_log, 'w')
kwargs['stdout'] = out_log_file
if err_log:
err_log_file = open(err_log, 'w')
kwargs['stderr'] = err_log_file
proc = subprocess.Popen(cmd, **kwargs)
def exit_handler():
"\n Send SIGINT to the process's children. This is important\n for running commands under coverage, as coverage will not\n produce the correct artifacts if the child process isn't\n killed properly.\n "
p1_group = psutil.Process(proc.pid)
child_pids = p1_group.children(recursive=True)
for child_pid in child_pids:
os.kill(child_pid.pid, signal.SIGINT)
proc.wait()
atexit.register(exit_handler) | def run_background_process(cmd, out_log=None, err_log=None, cwd=None):
'\n \n '
kwargs = {'shell': True, 'cwd': cwd}
if out_log:
out_log_file = open(out_log, 'w')
kwargs['stdout'] = out_log_file
if err_log:
err_log_file = open(err_log, 'w')
kwargs['stderr'] = err_log_file
proc = subprocess.Popen(cmd, **kwargs)
def exit_handler():
"\n Send SIGINT to the process's children. This is important\n for running commands under coverage, as coverage will not\n produce the correct artifacts if the child process isn't\n killed properly.\n "
p1_group = psutil.Process(proc.pid)
child_pids = p1_group.children(recursive=True)
for child_pid in child_pids:
os.kill(child_pid.pid, signal.SIGINT)
proc.wait()
atexit.register(exit_handler)<|docstring|>Runs a command as a background process. Sends SIGINT at exit.<|endoftext|> |
cd121a11816465b9aedddd4b786c8390bb254c239b9fc8d7534f9a5ef1679ac6 | def exit_handler():
"\n Send SIGINT to the process's children. This is important\n for running commands under coverage, as coverage will not\n produce the correct artifacts if the child process isn't\n killed properly.\n "
p1_group = psutil.Process(proc.pid)
child_pids = p1_group.children(recursive=True)
for child_pid in child_pids:
os.kill(child_pid.pid, signal.SIGINT)
proc.wait() | Send SIGINT to the process's children. This is important
for running commands under coverage, as coverage will not
produce the correct artifacts if the child process isn't
killed properly. | Part-03-Understanding-Software-Crafting-Your-Own-Tools/models/edx-platform/pavelib/utils/process.py | exit_handler | osoco/better-ways-of-thinking-about-software | 3 | python | def exit_handler():
"\n Send SIGINT to the process's children. This is important\n for running commands under coverage, as coverage will not\n produce the correct artifacts if the child process isn't\n killed properly.\n "
p1_group = psutil.Process(proc.pid)
child_pids = p1_group.children(recursive=True)
for child_pid in child_pids:
os.kill(child_pid.pid, signal.SIGINT)
proc.wait() | def exit_handler():
"\n Send SIGINT to the process's children. This is important\n for running commands under coverage, as coverage will not\n produce the correct artifacts if the child process isn't\n killed properly.\n "
p1_group = psutil.Process(proc.pid)
child_pids = p1_group.children(recursive=True)
for child_pid in child_pids:
os.kill(child_pid.pid, signal.SIGINT)
proc.wait()<|docstring|>Send SIGINT to the process's children. This is important
for running commands under coverage, as coverage will not
produce the correct artifacts if the child process isn't
killed properly.<|endoftext|> |
a5c3a6da608683f3182b3c88ccee00eacfd0ce3bc1ec8581202be049b719cc86 | def _signal_handler(*args):
'\n What to do when process is ended\n '
print('\nEnding...') | What to do when process is ended | Part-03-Understanding-Software-Crafting-Your-Own-Tools/models/edx-platform/pavelib/utils/process.py | _signal_handler | osoco/better-ways-of-thinking-about-software | 3 | python | def _signal_handler(*args):
'\n \n '
print('\nEnding...') | def _signal_handler(*args):
'\n \n '
print('\nEnding...')<|docstring|>What to do when process is ended<|endoftext|> |
4d14ab2e216be8ad4278d528acf08aaba945e44f0cd04c6724cd9754507ee74a | def _get_predefined_class(arg):
"\n Return the signature of the predefined class given by the string ``arg``.\n\n The signature is given by a tuple following the syntax\n (base field, class type, name, LaTeX name, function).\n\n Modify this method to add new predefined characteristic classes.\n\n TESTS::\n\n sage: from sage.manifolds.differentiable.characteristic_class import _get_predefined_class\n sage: _get_predefined_class('Chern')\n ('complex', 'multiplicative', 'c', 'c', x + 1)\n sage: _get_predefined_class('Pontryagin')\n ('real', 'multiplicative', 'p', 'p', x + 1)\n sage: _get_predefined_class('Euler')\n ('real', 'Pfaffian', 'e', 'e', x)\n\n "
if (not isinstance(arg, str)):
raise TypeError("argument 'arg' must be string")
x = SR.symbol('x')
if (arg == 'ChernChar'):
return ('complex', 'additive', 'ch', '\\mathrm{ch}', x.exp())
elif (arg == 'Todd'):
return ('complex', 'additive', 'Td', '\\mathrm{Td}', (x / (1 - (- x).exp())))
elif (arg == 'Chern'):
return ('complex', 'multiplicative', 'c', 'c', (1 + x))
elif (arg == 'Pontryagin'):
return ('real', 'multiplicative', 'p', 'p', (1 + x))
elif (arg == 'AHat'):
return ('real', 'multiplicative', 'A^', '\\hat{A}', (x.sqrt() / (2 * (x.sqrt() / 2).sinh())))
elif (arg == 'Hirzebruch'):
return ('real', 'multiplicative', 'L', 'L', (x.sqrt() / x.sqrt().tanh()))
elif (arg == 'Euler'):
return ('real', 'Pfaffian', 'e', 'e', x)
else:
raise ValueError(("the characteristic class '{}' is ".format(arg) + 'not predefined yet.')) | Return the signature of the predefined class given by the string ``arg``.
The signature is given by a tuple following the syntax
(base field, class type, name, LaTeX name, function).
Modify this method to add new predefined characteristic classes.
TESTS::
sage: from sage.manifolds.differentiable.characteristic_class import _get_predefined_class
sage: _get_predefined_class('Chern')
('complex', 'multiplicative', 'c', 'c', x + 1)
sage: _get_predefined_class('Pontryagin')
('real', 'multiplicative', 'p', 'p', x + 1)
sage: _get_predefined_class('Euler')
('real', 'Pfaffian', 'e', 'e', x) | src/sage/manifolds/differentiable/characteristic_class.py | _get_predefined_class | tashakim/sage | 4 | python | def _get_predefined_class(arg):
"\n Return the signature of the predefined class given by the string ``arg``.\n\n The signature is given by a tuple following the syntax\n (base field, class type, name, LaTeX name, function).\n\n Modify this method to add new predefined characteristic classes.\n\n TESTS::\n\n sage: from sage.manifolds.differentiable.characteristic_class import _get_predefined_class\n sage: _get_predefined_class('Chern')\n ('complex', 'multiplicative', 'c', 'c', x + 1)\n sage: _get_predefined_class('Pontryagin')\n ('real', 'multiplicative', 'p', 'p', x + 1)\n sage: _get_predefined_class('Euler')\n ('real', 'Pfaffian', 'e', 'e', x)\n\n "
if (not isinstance(arg, str)):
raise TypeError("argument 'arg' must be string")
x = SR.symbol('x')
if (arg == 'ChernChar'):
return ('complex', 'additive', 'ch', '\\mathrm{ch}', x.exp())
elif (arg == 'Todd'):
return ('complex', 'additive', 'Td', '\\mathrm{Td}', (x / (1 - (- x).exp())))
elif (arg == 'Chern'):
return ('complex', 'multiplicative', 'c', 'c', (1 + x))
elif (arg == 'Pontryagin'):
return ('real', 'multiplicative', 'p', 'p', (1 + x))
elif (arg == 'AHat'):
return ('real', 'multiplicative', 'A^', '\\hat{A}', (x.sqrt() / (2 * (x.sqrt() / 2).sinh())))
elif (arg == 'Hirzebruch'):
return ('real', 'multiplicative', 'L', 'L', (x.sqrt() / x.sqrt().tanh()))
elif (arg == 'Euler'):
return ('real', 'Pfaffian', 'e', 'e', x)
else:
raise ValueError(("the characteristic class '{}' is ".format(arg) + 'not predefined yet.')) | def _get_predefined_class(arg):
"\n Return the signature of the predefined class given by the string ``arg``.\n\n The signature is given by a tuple following the syntax\n (base field, class type, name, LaTeX name, function).\n\n Modify this method to add new predefined characteristic classes.\n\n TESTS::\n\n sage: from sage.manifolds.differentiable.characteristic_class import _get_predefined_class\n sage: _get_predefined_class('Chern')\n ('complex', 'multiplicative', 'c', 'c', x + 1)\n sage: _get_predefined_class('Pontryagin')\n ('real', 'multiplicative', 'p', 'p', x + 1)\n sage: _get_predefined_class('Euler')\n ('real', 'Pfaffian', 'e', 'e', x)\n\n "
if (not isinstance(arg, str)):
raise TypeError("argument 'arg' must be string")
x = SR.symbol('x')
if (arg == 'ChernChar'):
return ('complex', 'additive', 'ch', '\\mathrm{ch}', x.exp())
elif (arg == 'Todd'):
return ('complex', 'additive', 'Td', '\\mathrm{Td}', (x / (1 - (- x).exp())))
elif (arg == 'Chern'):
return ('complex', 'multiplicative', 'c', 'c', (1 + x))
elif (arg == 'Pontryagin'):
return ('real', 'multiplicative', 'p', 'p', (1 + x))
elif (arg == 'AHat'):
return ('real', 'multiplicative', 'A^', '\\hat{A}', (x.sqrt() / (2 * (x.sqrt() / 2).sinh())))
elif (arg == 'Hirzebruch'):
return ('real', 'multiplicative', 'L', 'L', (x.sqrt() / x.sqrt().tanh()))
elif (arg == 'Euler'):
return ('real', 'Pfaffian', 'e', 'e', x)
else:
raise ValueError(("the characteristic class '{}' is ".format(arg) + 'not predefined yet.'))<|docstring|>Return the signature of the predefined class given by the string ``arg``.
The signature is given by a tuple following the syntax
(base field, class type, name, LaTeX name, function).
Modify this method to add new predefined characteristic classes.
TESTS::
sage: from sage.manifolds.differentiable.characteristic_class import _get_predefined_class
sage: _get_predefined_class('Chern')
('complex', 'multiplicative', 'c', 'c', x + 1)
sage: _get_predefined_class('Pontryagin')
('real', 'multiplicative', 'p', 'p', x + 1)
sage: _get_predefined_class('Euler')
('real', 'Pfaffian', 'e', 'e', x)<|endoftext|> |
e27b9c0b3da767db81df7b7a37af243ef54753a400db32728490f674640c697c | def __init__(self, vbundle, func, class_type='multiplicative', name=None, latex_name=None):
"\n Construct a characteristic class.\n\n TESTS::\n\n sage: M = Manifold(3, 'M')\n sage: TM = M.tangent_bundle()\n sage: from sage.manifolds.differentiable.characteristic_class import CharacteristicClass\n sage: c = CharacteristicClass(TM, 1+x, name='c'); c\n Characteristic class c of multiplicative type associated to x + 1 on\n the Tangent bundle TM over the 3-dimensional differentiable\n manifold M\n sage: TestSuite(c).run()\n\n "
if (vbundle._field_type == 'neither_real_nor_complex'):
raise ValueError('the vector bundle must either be real or complex')
if (class_type not in ['additive', 'multiplicative', 'Pfaffian']):
raise ValueError("the argument 'class_type' must either be 'additive', 'multiplicative' or 'Pfaffian'")
if (class_type == 'Pfaffian'):
if ((vbundle._field_type != 'real') or ((vbundle._rank % 2) != 0)):
raise ValueError('Pfaffian classes can only be defined for real vector bundles of even rank')
self._name = name
if (latex_name is None):
self._latex_name = name
else:
self._latex_name = latex_name
self._func = func
self._class_type = class_type
self._vbundle = vbundle
self._base_space = vbundle._base_space
self._rank = vbundle._rank
self._coeff_list = self._get_coeff_list()
self._init_derived() | Construct a characteristic class.
TESTS::
sage: M = Manifold(3, 'M')
sage: TM = M.tangent_bundle()
sage: from sage.manifolds.differentiable.characteristic_class import CharacteristicClass
sage: c = CharacteristicClass(TM, 1+x, name='c'); c
Characteristic class c of multiplicative type associated to x + 1 on
the Tangent bundle TM over the 3-dimensional differentiable
manifold M
sage: TestSuite(c).run() | src/sage/manifolds/differentiable/characteristic_class.py | __init__ | tashakim/sage | 4 | python | def __init__(self, vbundle, func, class_type='multiplicative', name=None, latex_name=None):
"\n Construct a characteristic class.\n\n TESTS::\n\n sage: M = Manifold(3, 'M')\n sage: TM = M.tangent_bundle()\n sage: from sage.manifolds.differentiable.characteristic_class import CharacteristicClass\n sage: c = CharacteristicClass(TM, 1+x, name='c'); c\n Characteristic class c of multiplicative type associated to x + 1 on\n the Tangent bundle TM over the 3-dimensional differentiable\n manifold M\n sage: TestSuite(c).run()\n\n "
if (vbundle._field_type == 'neither_real_nor_complex'):
raise ValueError('the vector bundle must either be real or complex')
if (class_type not in ['additive', 'multiplicative', 'Pfaffian']):
raise ValueError("the argument 'class_type' must either be 'additive', 'multiplicative' or 'Pfaffian'")
if (class_type == 'Pfaffian'):
if ((vbundle._field_type != 'real') or ((vbundle._rank % 2) != 0)):
raise ValueError('Pfaffian classes can only be defined for real vector bundles of even rank')
self._name = name
if (latex_name is None):
self._latex_name = name
else:
self._latex_name = latex_name
self._func = func
self._class_type = class_type
self._vbundle = vbundle
self._base_space = vbundle._base_space
self._rank = vbundle._rank
self._coeff_list = self._get_coeff_list()
self._init_derived() | def __init__(self, vbundle, func, class_type='multiplicative', name=None, latex_name=None):
"\n Construct a characteristic class.\n\n TESTS::\n\n sage: M = Manifold(3, 'M')\n sage: TM = M.tangent_bundle()\n sage: from sage.manifolds.differentiable.characteristic_class import CharacteristicClass\n sage: c = CharacteristicClass(TM, 1+x, name='c'); c\n Characteristic class c of multiplicative type associated to x + 1 on\n the Tangent bundle TM over the 3-dimensional differentiable\n manifold M\n sage: TestSuite(c).run()\n\n "
if (vbundle._field_type == 'neither_real_nor_complex'):
raise ValueError('the vector bundle must either be real or complex')
if (class_type not in ['additive', 'multiplicative', 'Pfaffian']):
raise ValueError("the argument 'class_type' must either be 'additive', 'multiplicative' or 'Pfaffian'")
if (class_type == 'Pfaffian'):
if ((vbundle._field_type != 'real') or ((vbundle._rank % 2) != 0)):
raise ValueError('Pfaffian classes can only be defined for real vector bundles of even rank')
self._name = name
if (latex_name is None):
self._latex_name = name
else:
self._latex_name = latex_name
self._func = func
self._class_type = class_type
self._vbundle = vbundle
self._base_space = vbundle._base_space
self._rank = vbundle._rank
self._coeff_list = self._get_coeff_list()
self._init_derived()<|docstring|>Construct a characteristic class.
TESTS::
sage: M = Manifold(3, 'M')
sage: TM = M.tangent_bundle()
sage: from sage.manifolds.differentiable.characteristic_class import CharacteristicClass
sage: c = CharacteristicClass(TM, 1+x, name='c'); c
Characteristic class c of multiplicative type associated to x + 1 on
the Tangent bundle TM over the 3-dimensional differentiable
manifold M
sage: TestSuite(c).run()<|endoftext|> |
3c407c5bcd7679f2bfb7071e8293919ce72e1b3cdad6f4ae4649a6bf56f11d31 | def _get_coeff_list(self):
"\n Return the list of coefficients of the Taylor expansion at zero of the\n function.\n\n TESTS::\n\n sage: M = Manifold(2, 'M')\n sage: E = M.vector_bundle(1, 'E', field='complex')\n sage: c = E.characteristic_class(1+x)\n sage: c._get_coeff_list()\n [1, 1]\n\n "
pow_range = (self._base_space._dim // 2)
def_var = self._func.default_variable()
new_var = SR.symbol('x_char_class_', domain='complex')
if (self._vbundle._field_type == 'real'):
if (self._class_type == 'additive'):
func = (self._func.subs({def_var: (new_var ** 2)}) / 2)
elif (self._class_type == 'multiplicative'):
func = self._func.subs({def_var: (new_var ** 2)}).sqrt()
elif (self._class_type == 'Pfaffian'):
func = ((self._func.subs({def_var: new_var}) - self._func.subs({def_var: (- new_var)})) / 2)
else:
func = self._func.subs({def_var: new_var})
return func.taylor(new_var, 0, pow_range).coefficients(sparse=False) | Return the list of coefficients of the Taylor expansion at zero of the
function.
TESTS::
sage: M = Manifold(2, 'M')
sage: E = M.vector_bundle(1, 'E', field='complex')
sage: c = E.characteristic_class(1+x)
sage: c._get_coeff_list()
[1, 1] | src/sage/manifolds/differentiable/characteristic_class.py | _get_coeff_list | tashakim/sage | 4 | python | def _get_coeff_list(self):
"\n Return the list of coefficients of the Taylor expansion at zero of the\n function.\n\n TESTS::\n\n sage: M = Manifold(2, 'M')\n sage: E = M.vector_bundle(1, 'E', field='complex')\n sage: c = E.characteristic_class(1+x)\n sage: c._get_coeff_list()\n [1, 1]\n\n "
pow_range = (self._base_space._dim // 2)
def_var = self._func.default_variable()
new_var = SR.symbol('x_char_class_', domain='complex')
if (self._vbundle._field_type == 'real'):
if (self._class_type == 'additive'):
func = (self._func.subs({def_var: (new_var ** 2)}) / 2)
elif (self._class_type == 'multiplicative'):
func = self._func.subs({def_var: (new_var ** 2)}).sqrt()
elif (self._class_type == 'Pfaffian'):
func = ((self._func.subs({def_var: new_var}) - self._func.subs({def_var: (- new_var)})) / 2)
else:
func = self._func.subs({def_var: new_var})
return func.taylor(new_var, 0, pow_range).coefficients(sparse=False) | def _get_coeff_list(self):
"\n Return the list of coefficients of the Taylor expansion at zero of the\n function.\n\n TESTS::\n\n sage: M = Manifold(2, 'M')\n sage: E = M.vector_bundle(1, 'E', field='complex')\n sage: c = E.characteristic_class(1+x)\n sage: c._get_coeff_list()\n [1, 1]\n\n "
pow_range = (self._base_space._dim // 2)
def_var = self._func.default_variable()
new_var = SR.symbol('x_char_class_', domain='complex')
if (self._vbundle._field_type == 'real'):
if (self._class_type == 'additive'):
func = (self._func.subs({def_var: (new_var ** 2)}) / 2)
elif (self._class_type == 'multiplicative'):
func = self._func.subs({def_var: (new_var ** 2)}).sqrt()
elif (self._class_type == 'Pfaffian'):
func = ((self._func.subs({def_var: new_var}) - self._func.subs({def_var: (- new_var)})) / 2)
else:
func = self._func.subs({def_var: new_var})
return func.taylor(new_var, 0, pow_range).coefficients(sparse=False)<|docstring|>Return the list of coefficients of the Taylor expansion at zero of the
function.
TESTS::
sage: M = Manifold(2, 'M')
sage: E = M.vector_bundle(1, 'E', field='complex')
sage: c = E.characteristic_class(1+x)
sage: c._get_coeff_list()
[1, 1]<|endoftext|> |
c0649647b812414a4d309ef55278a136bfebae832603daadbffc63e2d8d167bf | def _init_derived(self):
"\n Initialize the derived quantities.\n\n TESTS::\n\n sage: M = Manifold(2, 'M')\n sage: TM = M.tangent_bundle()\n sage: c = TM.characteristic_class(1+x)\n sage: c._init_derived()\n\n "
self._mixed_forms = {} | Initialize the derived quantities.
TESTS::
sage: M = Manifold(2, 'M')
sage: TM = M.tangent_bundle()
sage: c = TM.characteristic_class(1+x)
sage: c._init_derived() | src/sage/manifolds/differentiable/characteristic_class.py | _init_derived | tashakim/sage | 4 | python | def _init_derived(self):
"\n Initialize the derived quantities.\n\n TESTS::\n\n sage: M = Manifold(2, 'M')\n sage: TM = M.tangent_bundle()\n sage: c = TM.characteristic_class(1+x)\n sage: c._init_derived()\n\n "
self._mixed_forms = {} | def _init_derived(self):
"\n Initialize the derived quantities.\n\n TESTS::\n\n sage: M = Manifold(2, 'M')\n sage: TM = M.tangent_bundle()\n sage: c = TM.characteristic_class(1+x)\n sage: c._init_derived()\n\n "
self._mixed_forms = {}<|docstring|>Initialize the derived quantities.
TESTS::
sage: M = Manifold(2, 'M')
sage: TM = M.tangent_bundle()
sage: c = TM.characteristic_class(1+x)
sage: c._init_derived()<|endoftext|> |
63d23ac97bfad5bf752a1f3e4fe963b25ab804281c73f9ec808c25fc9a217d37 | def _del_derived(self):
"\n Delete the derived quantities.\n\n TESTS::\n\n sage: M = Manifold(2, 'M')\n sage: TM = M.tangent_bundle()\n sage: c = TM.characteristic_class(1+x)\n sage: c._del_derived()\n\n "
self._mixed_forms.clear() | Delete the derived quantities.
TESTS::
sage: M = Manifold(2, 'M')
sage: TM = M.tangent_bundle()
sage: c = TM.characteristic_class(1+x)
sage: c._del_derived() | src/sage/manifolds/differentiable/characteristic_class.py | _del_derived | tashakim/sage | 4 | python | def _del_derived(self):
"\n Delete the derived quantities.\n\n TESTS::\n\n sage: M = Manifold(2, 'M')\n sage: TM = M.tangent_bundle()\n sage: c = TM.characteristic_class(1+x)\n sage: c._del_derived()\n\n "
self._mixed_forms.clear() | def _del_derived(self):
"\n Delete the derived quantities.\n\n TESTS::\n\n sage: M = Manifold(2, 'M')\n sage: TM = M.tangent_bundle()\n sage: c = TM.characteristic_class(1+x)\n sage: c._del_derived()\n\n "
self._mixed_forms.clear()<|docstring|>Delete the derived quantities.
TESTS::
sage: M = Manifold(2, 'M')
sage: TM = M.tangent_bundle()
sage: c = TM.characteristic_class(1+x)
sage: c._del_derived()<|endoftext|> |
8e46ac2738f576842eae7792d55ff12935016fa7849eebf1fbdcedae2a6e4b8a | def _repr_(self):
"\n String representation of the object.\n\n TESTS::\n\n sage: M = Manifold(2, 'M')\n sage: TM = M.tangent_bundle()\n sage: c = TM.characteristic_class(1+x, name='c')\n sage: c # indirect doctest\n Characteristic class c of multiplicative type associated to x + 1 on\n the Tangent bundle TM over the 2-dimensional differentiable\n manifold M\n sage: repr(c) # indirect doctest\n 'Characteristic class c of multiplicative type associated to x + 1\n on the Tangent bundle TM over the 2-dimensional differentiable\n manifold M'\n sage: c._repr_()\n 'Characteristic class c of multiplicative type associated to x + 1\n on the Tangent bundle TM over the 2-dimensional differentiable\n manifold M'\n\n "
desc = 'Characteristic class '
if (self._name is not None):
desc += (self._name + ' ')
desc += 'of {} type '.format(self._class_type)
desc += 'associated to {} on the {}'.format(self._func, self._vbundle)
return desc | String representation of the object.
TESTS::
sage: M = Manifold(2, 'M')
sage: TM = M.tangent_bundle()
sage: c = TM.characteristic_class(1+x, name='c')
sage: c # indirect doctest
Characteristic class c of multiplicative type associated to x + 1 on
the Tangent bundle TM over the 2-dimensional differentiable
manifold M
sage: repr(c) # indirect doctest
'Characteristic class c of multiplicative type associated to x + 1
on the Tangent bundle TM over the 2-dimensional differentiable
manifold M'
sage: c._repr_()
'Characteristic class c of multiplicative type associated to x + 1
on the Tangent bundle TM over the 2-dimensional differentiable
manifold M' | src/sage/manifolds/differentiable/characteristic_class.py | _repr_ | tashakim/sage | 4 | python | def _repr_(self):
"\n String representation of the object.\n\n TESTS::\n\n sage: M = Manifold(2, 'M')\n sage: TM = M.tangent_bundle()\n sage: c = TM.characteristic_class(1+x, name='c')\n sage: c # indirect doctest\n Characteristic class c of multiplicative type associated to x + 1 on\n the Tangent bundle TM over the 2-dimensional differentiable\n manifold M\n sage: repr(c) # indirect doctest\n 'Characteristic class c of multiplicative type associated to x + 1\n on the Tangent bundle TM over the 2-dimensional differentiable\n manifold M'\n sage: c._repr_()\n 'Characteristic class c of multiplicative type associated to x + 1\n on the Tangent bundle TM over the 2-dimensional differentiable\n manifold M'\n\n "
desc = 'Characteristic class '
if (self._name is not None):
desc += (self._name + ' ')
desc += 'of {} type '.format(self._class_type)
desc += 'associated to {} on the {}'.format(self._func, self._vbundle)
return desc | def _repr_(self):
"\n String representation of the object.\n\n TESTS::\n\n sage: M = Manifold(2, 'M')\n sage: TM = M.tangent_bundle()\n sage: c = TM.characteristic_class(1+x, name='c')\n sage: c # indirect doctest\n Characteristic class c of multiplicative type associated to x + 1 on\n the Tangent bundle TM over the 2-dimensional differentiable\n manifold M\n sage: repr(c) # indirect doctest\n 'Characteristic class c of multiplicative type associated to x + 1\n on the Tangent bundle TM over the 2-dimensional differentiable\n manifold M'\n sage: c._repr_()\n 'Characteristic class c of multiplicative type associated to x + 1\n on the Tangent bundle TM over the 2-dimensional differentiable\n manifold M'\n\n "
desc = 'Characteristic class '
if (self._name is not None):
desc += (self._name + ' ')
desc += 'of {} type '.format(self._class_type)
desc += 'associated to {} on the {}'.format(self._func, self._vbundle)
return desc<|docstring|>String representation of the object.
TESTS::
sage: M = Manifold(2, 'M')
sage: TM = M.tangent_bundle()
sage: c = TM.characteristic_class(1+x, name='c')
sage: c # indirect doctest
Characteristic class c of multiplicative type associated to x + 1 on
the Tangent bundle TM over the 2-dimensional differentiable
manifold M
sage: repr(c) # indirect doctest
'Characteristic class c of multiplicative type associated to x + 1
on the Tangent bundle TM over the 2-dimensional differentiable
manifold M'
sage: c._repr_()
'Characteristic class c of multiplicative type associated to x + 1
on the Tangent bundle TM over the 2-dimensional differentiable
manifold M'<|endoftext|> |
c59129e1a3e16d7bc11dfee4f8cf37ba0e65f44b73f0fb303c7d7c81cc8b1003 | def _latex_(self):
"\n LaTeX representation of the object.\n\n TESTS::\n\n sage: M = Manifold(2, 'M')\n sage: TM = M.tangent_bundle()\n sage: ch = TM.characteristic_class(exp(x), class_type='additive',\n ....: name='ch', latex_name=r'\\mathrm{ch}')\n sage: ch._latex_()\n '\\\\mathrm{ch}(TM)'\n\n "
return (((self._latex_name + '(') + self._vbundle._latex_name) + ')') | LaTeX representation of the object.
TESTS::
sage: M = Manifold(2, 'M')
sage: TM = M.tangent_bundle()
sage: ch = TM.characteristic_class(exp(x), class_type='additive',
....: name='ch', latex_name=r'\mathrm{ch}')
sage: ch._latex_()
'\\mathrm{ch}(TM)' | src/sage/manifolds/differentiable/characteristic_class.py | _latex_ | tashakim/sage | 4 | python | def _latex_(self):
"\n LaTeX representation of the object.\n\n TESTS::\n\n sage: M = Manifold(2, 'M')\n sage: TM = M.tangent_bundle()\n sage: ch = TM.characteristic_class(exp(x), class_type='additive',\n ....: name='ch', latex_name=r'\\mathrm{ch}')\n sage: ch._latex_()\n '\\\\mathrm{ch}(TM)'\n\n "
return (((self._latex_name + '(') + self._vbundle._latex_name) + ')') | def _latex_(self):
"\n LaTeX representation of the object.\n\n TESTS::\n\n sage: M = Manifold(2, 'M')\n sage: TM = M.tangent_bundle()\n sage: ch = TM.characteristic_class(exp(x), class_type='additive',\n ....: name='ch', latex_name=r'\\mathrm{ch}')\n sage: ch._latex_()\n '\\\\mathrm{ch}(TM)'\n\n "
return (((self._latex_name + '(') + self._vbundle._latex_name) + ')')<|docstring|>LaTeX representation of the object.
TESTS::
sage: M = Manifold(2, 'M')
sage: TM = M.tangent_bundle()
sage: ch = TM.characteristic_class(exp(x), class_type='additive',
....: name='ch', latex_name=r'\mathrm{ch}')
sage: ch._latex_()
'\\mathrm{ch}(TM)'<|endoftext|> |
a528922a1b802e337a6c8403dc244d8ca739a72b749a73247113fdbec699c41d | def class_type(self):
"\n Return the class type of ``self``.\n\n EXAMPLES::\n\n sage: M = Manifold(2, 'M')\n sage: TM = M.tangent_bundle()\n sage: ch = TM.characteristic_class(exp(x), class_type='additive',\n ....: name='ch', latex_name=r'\\mathrm{ch}')\n sage: ch.class_type()\n 'additive'\n\n "
return self._class_type | Return the class type of ``self``.
EXAMPLES::
sage: M = Manifold(2, 'M')
sage: TM = M.tangent_bundle()
sage: ch = TM.characteristic_class(exp(x), class_type='additive',
....: name='ch', latex_name=r'\mathrm{ch}')
sage: ch.class_type()
'additive' | src/sage/manifolds/differentiable/characteristic_class.py | class_type | tashakim/sage | 4 | python | def class_type(self):
"\n Return the class type of ``self``.\n\n EXAMPLES::\n\n sage: M = Manifold(2, 'M')\n sage: TM = M.tangent_bundle()\n sage: ch = TM.characteristic_class(exp(x), class_type='additive',\n ....: name='ch', latex_name=r'\\mathrm{ch}')\n sage: ch.class_type()\n 'additive'\n\n "
return self._class_type | def class_type(self):
"\n Return the class type of ``self``.\n\n EXAMPLES::\n\n sage: M = Manifold(2, 'M')\n sage: TM = M.tangent_bundle()\n sage: ch = TM.characteristic_class(exp(x), class_type='additive',\n ....: name='ch', latex_name=r'\\mathrm{ch}')\n sage: ch.class_type()\n 'additive'\n\n "
return self._class_type<|docstring|>Return the class type of ``self``.
EXAMPLES::
sage: M = Manifold(2, 'M')
sage: TM = M.tangent_bundle()
sage: ch = TM.characteristic_class(exp(x), class_type='additive',
....: name='ch', latex_name=r'\mathrm{ch}')
sage: ch.class_type()
'additive'<|endoftext|> |
cb4cc9b5512d6be0848409fd4265621f1cecc27a19340bc92dee04fdc599640b | def function(self):
"\n Return the function corresponding to this characteristic class.\n\n EXAMPLES::\n\n sage: M = Manifold(2, 'M')\n sage: TM = M.tangent_bundle()\n sage: e_class = TM.characteristic_class('Euler')\n sage: e_class.function()\n x\n sage: AHat = TM.characteristic_class('AHat')\n sage: AHat.function()\n 1/2*sqrt(x)/sinh(1/2*sqrt(x))\n sage: c = TM.characteristic_class(1+x, name='c')\n sage: c.function()\n x + 1\n\n "
return self._func | Return the function corresponding to this characteristic class.
EXAMPLES::
sage: M = Manifold(2, 'M')
sage: TM = M.tangent_bundle()
sage: e_class = TM.characteristic_class('Euler')
sage: e_class.function()
x
sage: AHat = TM.characteristic_class('AHat')
sage: AHat.function()
1/2*sqrt(x)/sinh(1/2*sqrt(x))
sage: c = TM.characteristic_class(1+x, name='c')
sage: c.function()
x + 1 | src/sage/manifolds/differentiable/characteristic_class.py | function | tashakim/sage | 4 | python | def function(self):
"\n Return the function corresponding to this characteristic class.\n\n EXAMPLES::\n\n sage: M = Manifold(2, 'M')\n sage: TM = M.tangent_bundle()\n sage: e_class = TM.characteristic_class('Euler')\n sage: e_class.function()\n x\n sage: AHat = TM.characteristic_class('AHat')\n sage: AHat.function()\n 1/2*sqrt(x)/sinh(1/2*sqrt(x))\n sage: c = TM.characteristic_class(1+x, name='c')\n sage: c.function()\n x + 1\n\n "
return self._func | def function(self):
"\n Return the function corresponding to this characteristic class.\n\n EXAMPLES::\n\n sage: M = Manifold(2, 'M')\n sage: TM = M.tangent_bundle()\n sage: e_class = TM.characteristic_class('Euler')\n sage: e_class.function()\n x\n sage: AHat = TM.characteristic_class('AHat')\n sage: AHat.function()\n 1/2*sqrt(x)/sinh(1/2*sqrt(x))\n sage: c = TM.characteristic_class(1+x, name='c')\n sage: c.function()\n x + 1\n\n "
return self._func<|docstring|>Return the function corresponding to this characteristic class.
EXAMPLES::
sage: M = Manifold(2, 'M')
sage: TM = M.tangent_bundle()
sage: e_class = TM.characteristic_class('Euler')
sage: e_class.function()
x
sage: AHat = TM.characteristic_class('AHat')
sage: AHat.function()
1/2*sqrt(x)/sinh(1/2*sqrt(x))
sage: c = TM.characteristic_class(1+x, name='c')
sage: c.function()
x + 1<|endoftext|> |
75b701b3f01320555d8e4a647f025e00aeec46aeb44b1abe702ea19e6efde2be | def get_form(self, connection, cmatrices=None):
"\n Return the form representing ``self`` with respect to the given\n connection ``connection``.\n\n INPUT:\n\n - ``connection`` -- connection to which the form should be associated to;\n this can be either a bundle connection as an instance of\n :class:`~sage.manifolds.differentiable.bundle_connection.BundleConnection`\n or, in case of the tensor bundle, an affine connection as an instance\n of :class:`~sage.manifolds.differentiable.affine_connection.AffineConnection`\n - ``cmatrices`` -- (default: ``None``) a dictionary of curvature\n matrices with local frames as keys and curvature matrices as items; if\n ``None``, Sage tries to get the curvature matrices from the connection\n\n OUTPUT:\n\n - mixed form as an instance of\n :class:`~sage.manifolds.differentiable.mixed_form.MixedForm`\n representing the total characteristic class\n\n .. NOTE::\n\n Be aware that depending on the characteristic class and complexity\n of the manifold, computation times may vary a lot. In addition, if\n not done before, the curvature form is computed from the connection,\n here. If this behaviour is not wanted and the curvature form is\n already known, please use the argument ``cmatrices``.\n\n EXAMPLES:\n\n Again, consider the Chern character on some 2-dimensional spacetime::\n\n sage: M = Manifold(2, 'M', structure='Lorentzian')\n sage: X.<t,x> = M.chart()\n sage: E = M.vector_bundle(1, 'E', field='complex'); E\n Differentiable complex vector bundle E -> M of rank 1 over the base\n space 2-dimensional Lorentzian manifold M\n sage: e = E.local_frame('e')\n\n And again, we define the connection `\\nabla^E` in terms of an\n electro-magnetic potential `A(t)`::\n\n sage: nab = E.bundle_connection('nabla^E', latex_name=r'\\nabla^E')\n sage: omega = M.one_form(name='omega')\n sage: A = function('A')\n sage: omega[1] = I*A(t)\n sage: omega.display()\n omega = I*A(t) dx\n sage: nab.set_connection_form(0, 0, omega)\n\n The Chern character is then given by::\n\n sage: ch = E.characteristic_class('ChernChar'); ch\n Characteristic class ch of additive type associated to e^x on the\n Differentiable complex vector bundle E -> M of rank 1 over the base\n space 2-dimensional Lorentzian manifold M\n\n Inserting the connection, the result is a mixed differential form with\n a priori non-zero components in even degrees::\n\n sage: ch_form = ch.get_form(nab); ch_form\n Mixed differential form ch(E, nabla^E) on the 2-dimensional\n Lorentzian manifold M\n sage: ch_form.display()\n ch(E, nabla^E) = ch_0(E, nabla^E) + zero + ch_1(E, nabla^E)\n sage: ch_form.display_expansion()\n ch(E, nabla^E) = [1] + [0] + [1/2*d(A)/dt/pi dt/\\dx]\n\n Due to long computation times, the form is saved::\n\n sage: ch_form is ch.get_form(nab)\n True\n\n "
from .bundle_connection import BundleConnection
from .affine_connection import AffineConnection
if (not isinstance(connection, (AffineConnection, BundleConnection))):
raise TypeError('argument must be an affine connection on the manifold or bundle connection on the vector bundle')
if (connection not in self._mixed_forms):
if (cmatrices is None):
if (self._class_type == 'Pfaffian'):
raise NotImplementedError("At this stage, Pfaffian forms cannot be derived from (metric) connections. Please use the argument 'cmatrices' to insert a dictionary of skew-symmetric curvature matrices by hand, instead.")
cmatrices = {}
for frame in self._get_min_frames(connection._coefficients.keys()):
cmatrix = [[connection.curvature_form(i, j, frame) for j in self._vbundle.irange()] for i in self._vbundle.irange()]
cmatrices[frame] = cmatrix
(name, latex_name) = (self._name, self._latex_name)
if ((name is not None) and (connection._name is not None)):
name += (((('(' + self._vbundle._name) + ', ') + connection._name) + ')')
if ((latex_name is not None) and (connection._latex_name is not None)):
latex_name += (((('(' + self._vbundle._latex_name) + ', ') + connection._latex_name) + ')')
res = self._base_space.mixed_form(name=name, latex_name=latex_name)
from sage.matrix.matrix_space import MatrixSpace
for (frame, cmatrix) in cmatrices.items():
dom = frame._domain
alg = dom.mixed_form_algebra()
mspace = MatrixSpace(alg, self._rank)
cmatrix = mspace(cmatrix)
ncmatrix = self._normalize_matrix(cmatrix)
rmatrix = self._insert_in_polynomial(ncmatrix)
if (self._class_type == 'additive'):
rst = rmatrix.trace()
elif (self._class_type == 'multiplicative'):
rst = rmatrix.det()
elif (self._class_type == 'Pfaffian'):
rst = rmatrix.pfaffian()
res.set_restriction(rst)
if (self._class_type == 'Pfaffian'):
deg_dist = self._rank
elif (self._vbundle._field_type == 'real'):
deg_dist = 4
elif (self._vbundle._field_type == 'complex'):
deg_dist = 2
else:
deg_dist = 1
for k in res.irange():
if (((k % deg_dist) != 0) or ((self._class_type == 'Pfaffian') and (k == 0))):
res[k] = 0
else:
if (self._name is not None):
name = ((((self._name + '_') + str((k // deg_dist))) + '(') + self._vbundle._name)
if (connection._name is not None):
name += (', ' + connection._name)
name += ')'
if (self._latex_name is not None):
latex_name = (((((self._latex_name + '_{') + str((k // deg_dist))) + '}') + '(') + self._vbundle._latex_name)
if (connection._latex_name is not None):
latex_name += (', ' + connection._latex_name)
latex_name += ')'
res[k].set_name(name=name, latex_name=latex_name)
self._mixed_forms[connection] = res
return self._mixed_forms[connection] | Return the form representing ``self`` with respect to the given
connection ``connection``.
INPUT:
- ``connection`` -- connection to which the form should be associated to;
this can be either a bundle connection as an instance of
:class:`~sage.manifolds.differentiable.bundle_connection.BundleConnection`
or, in case of the tensor bundle, an affine connection as an instance
of :class:`~sage.manifolds.differentiable.affine_connection.AffineConnection`
- ``cmatrices`` -- (default: ``None``) a dictionary of curvature
matrices with local frames as keys and curvature matrices as items; if
``None``, Sage tries to get the curvature matrices from the connection
OUTPUT:
- mixed form as an instance of
:class:`~sage.manifolds.differentiable.mixed_form.MixedForm`
representing the total characteristic class
.. NOTE::
Be aware that depending on the characteristic class and complexity
of the manifold, computation times may vary a lot. In addition, if
not done before, the curvature form is computed from the connection,
here. If this behaviour is not wanted and the curvature form is
already known, please use the argument ``cmatrices``.
EXAMPLES:
Again, consider the Chern character on some 2-dimensional spacetime::
sage: M = Manifold(2, 'M', structure='Lorentzian')
sage: X.<t,x> = M.chart()
sage: E = M.vector_bundle(1, 'E', field='complex'); E
Differentiable complex vector bundle E -> M of rank 1 over the base
space 2-dimensional Lorentzian manifold M
sage: e = E.local_frame('e')
And again, we define the connection `\nabla^E` in terms of an
electro-magnetic potential `A(t)`::
sage: nab = E.bundle_connection('nabla^E', latex_name=r'\nabla^E')
sage: omega = M.one_form(name='omega')
sage: A = function('A')
sage: omega[1] = I*A(t)
sage: omega.display()
omega = I*A(t) dx
sage: nab.set_connection_form(0, 0, omega)
The Chern character is then given by::
sage: ch = E.characteristic_class('ChernChar'); ch
Characteristic class ch of additive type associated to e^x on the
Differentiable complex vector bundle E -> M of rank 1 over the base
space 2-dimensional Lorentzian manifold M
Inserting the connection, the result is a mixed differential form with
a priori non-zero components in even degrees::
sage: ch_form = ch.get_form(nab); ch_form
Mixed differential form ch(E, nabla^E) on the 2-dimensional
Lorentzian manifold M
sage: ch_form.display()
ch(E, nabla^E) = ch_0(E, nabla^E) + zero + ch_1(E, nabla^E)
sage: ch_form.display_expansion()
ch(E, nabla^E) = [1] + [0] + [1/2*d(A)/dt/pi dt/\dx]
Due to long computation times, the form is saved::
sage: ch_form is ch.get_form(nab)
True | src/sage/manifolds/differentiable/characteristic_class.py | get_form | tashakim/sage | 4 | python | def get_form(self, connection, cmatrices=None):
"\n Return the form representing ``self`` with respect to the given\n connection ``connection``.\n\n INPUT:\n\n - ``connection`` -- connection to which the form should be associated to;\n this can be either a bundle connection as an instance of\n :class:`~sage.manifolds.differentiable.bundle_connection.BundleConnection`\n or, in case of the tensor bundle, an affine connection as an instance\n of :class:`~sage.manifolds.differentiable.affine_connection.AffineConnection`\n - ``cmatrices`` -- (default: ``None``) a dictionary of curvature\n matrices with local frames as keys and curvature matrices as items; if\n ``None``, Sage tries to get the curvature matrices from the connection\n\n OUTPUT:\n\n - mixed form as an instance of\n :class:`~sage.manifolds.differentiable.mixed_form.MixedForm`\n representing the total characteristic class\n\n .. NOTE::\n\n Be aware that depending on the characteristic class and complexity\n of the manifold, computation times may vary a lot. In addition, if\n not done before, the curvature form is computed from the connection,\n here. If this behaviour is not wanted and the curvature form is\n already known, please use the argument ``cmatrices``.\n\n EXAMPLES:\n\n Again, consider the Chern character on some 2-dimensional spacetime::\n\n sage: M = Manifold(2, 'M', structure='Lorentzian')\n sage: X.<t,x> = M.chart()\n sage: E = M.vector_bundle(1, 'E', field='complex'); E\n Differentiable complex vector bundle E -> M of rank 1 over the base\n space 2-dimensional Lorentzian manifold M\n sage: e = E.local_frame('e')\n\n And again, we define the connection `\\nabla^E` in terms of an\n electro-magnetic potential `A(t)`::\n\n sage: nab = E.bundle_connection('nabla^E', latex_name=r'\\nabla^E')\n sage: omega = M.one_form(name='omega')\n sage: A = function('A')\n sage: omega[1] = I*A(t)\n sage: omega.display()\n omega = I*A(t) dx\n sage: nab.set_connection_form(0, 0, omega)\n\n The Chern character is then given by::\n\n sage: ch = E.characteristic_class('ChernChar'); ch\n Characteristic class ch of additive type associated to e^x on the\n Differentiable complex vector bundle E -> M of rank 1 over the base\n space 2-dimensional Lorentzian manifold M\n\n Inserting the connection, the result is a mixed differential form with\n a priori non-zero components in even degrees::\n\n sage: ch_form = ch.get_form(nab); ch_form\n Mixed differential form ch(E, nabla^E) on the 2-dimensional\n Lorentzian manifold M\n sage: ch_form.display()\n ch(E, nabla^E) = ch_0(E, nabla^E) + zero + ch_1(E, nabla^E)\n sage: ch_form.display_expansion()\n ch(E, nabla^E) = [1] + [0] + [1/2*d(A)/dt/pi dt/\\dx]\n\n Due to long computation times, the form is saved::\n\n sage: ch_form is ch.get_form(nab)\n True\n\n "
from .bundle_connection import BundleConnection
from .affine_connection import AffineConnection
if (not isinstance(connection, (AffineConnection, BundleConnection))):
raise TypeError('argument must be an affine connection on the manifold or bundle connection on the vector bundle')
if (connection not in self._mixed_forms):
if (cmatrices is None):
if (self._class_type == 'Pfaffian'):
raise NotImplementedError("At this stage, Pfaffian forms cannot be derived from (metric) connections. Please use the argument 'cmatrices' to insert a dictionary of skew-symmetric curvature matrices by hand, instead.")
cmatrices = {}
for frame in self._get_min_frames(connection._coefficients.keys()):
cmatrix = [[connection.curvature_form(i, j, frame) for j in self._vbundle.irange()] for i in self._vbundle.irange()]
cmatrices[frame] = cmatrix
(name, latex_name) = (self._name, self._latex_name)
if ((name is not None) and (connection._name is not None)):
name += (((('(' + self._vbundle._name) + ', ') + connection._name) + ')')
if ((latex_name is not None) and (connection._latex_name is not None)):
latex_name += (((('(' + self._vbundle._latex_name) + ', ') + connection._latex_name) + ')')
res = self._base_space.mixed_form(name=name, latex_name=latex_name)
from sage.matrix.matrix_space import MatrixSpace
for (frame, cmatrix) in cmatrices.items():
dom = frame._domain
alg = dom.mixed_form_algebra()
mspace = MatrixSpace(alg, self._rank)
cmatrix = mspace(cmatrix)
ncmatrix = self._normalize_matrix(cmatrix)
rmatrix = self._insert_in_polynomial(ncmatrix)
if (self._class_type == 'additive'):
rst = rmatrix.trace()
elif (self._class_type == 'multiplicative'):
rst = rmatrix.det()
elif (self._class_type == 'Pfaffian'):
rst = rmatrix.pfaffian()
res.set_restriction(rst)
if (self._class_type == 'Pfaffian'):
deg_dist = self._rank
elif (self._vbundle._field_type == 'real'):
deg_dist = 4
elif (self._vbundle._field_type == 'complex'):
deg_dist = 2
else:
deg_dist = 1
for k in res.irange():
if (((k % deg_dist) != 0) or ((self._class_type == 'Pfaffian') and (k == 0))):
res[k] = 0
else:
if (self._name is not None):
name = ((((self._name + '_') + str((k // deg_dist))) + '(') + self._vbundle._name)
if (connection._name is not None):
name += (', ' + connection._name)
name += ')'
if (self._latex_name is not None):
latex_name = (((((self._latex_name + '_{') + str((k // deg_dist))) + '}') + '(') + self._vbundle._latex_name)
if (connection._latex_name is not None):
latex_name += (', ' + connection._latex_name)
latex_name += ')'
res[k].set_name(name=name, latex_name=latex_name)
self._mixed_forms[connection] = res
return self._mixed_forms[connection] | def get_form(self, connection, cmatrices=None):
"\n Return the form representing ``self`` with respect to the given\n connection ``connection``.\n\n INPUT:\n\n - ``connection`` -- connection to which the form should be associated to;\n this can be either a bundle connection as an instance of\n :class:`~sage.manifolds.differentiable.bundle_connection.BundleConnection`\n or, in case of the tensor bundle, an affine connection as an instance\n of :class:`~sage.manifolds.differentiable.affine_connection.AffineConnection`\n - ``cmatrices`` -- (default: ``None``) a dictionary of curvature\n matrices with local frames as keys and curvature matrices as items; if\n ``None``, Sage tries to get the curvature matrices from the connection\n\n OUTPUT:\n\n - mixed form as an instance of\n :class:`~sage.manifolds.differentiable.mixed_form.MixedForm`\n representing the total characteristic class\n\n .. NOTE::\n\n Be aware that depending on the characteristic class and complexity\n of the manifold, computation times may vary a lot. In addition, if\n not done before, the curvature form is computed from the connection,\n here. If this behaviour is not wanted and the curvature form is\n already known, please use the argument ``cmatrices``.\n\n EXAMPLES:\n\n Again, consider the Chern character on some 2-dimensional spacetime::\n\n sage: M = Manifold(2, 'M', structure='Lorentzian')\n sage: X.<t,x> = M.chart()\n sage: E = M.vector_bundle(1, 'E', field='complex'); E\n Differentiable complex vector bundle E -> M of rank 1 over the base\n space 2-dimensional Lorentzian manifold M\n sage: e = E.local_frame('e')\n\n And again, we define the connection `\\nabla^E` in terms of an\n electro-magnetic potential `A(t)`::\n\n sage: nab = E.bundle_connection('nabla^E', latex_name=r'\\nabla^E')\n sage: omega = M.one_form(name='omega')\n sage: A = function('A')\n sage: omega[1] = I*A(t)\n sage: omega.display()\n omega = I*A(t) dx\n sage: nab.set_connection_form(0, 0, omega)\n\n The Chern character is then given by::\n\n sage: ch = E.characteristic_class('ChernChar'); ch\n Characteristic class ch of additive type associated to e^x on the\n Differentiable complex vector bundle E -> M of rank 1 over the base\n space 2-dimensional Lorentzian manifold M\n\n Inserting the connection, the result is a mixed differential form with\n a priori non-zero components in even degrees::\n\n sage: ch_form = ch.get_form(nab); ch_form\n Mixed differential form ch(E, nabla^E) on the 2-dimensional\n Lorentzian manifold M\n sage: ch_form.display()\n ch(E, nabla^E) = ch_0(E, nabla^E) + zero + ch_1(E, nabla^E)\n sage: ch_form.display_expansion()\n ch(E, nabla^E) = [1] + [0] + [1/2*d(A)/dt/pi dt/\\dx]\n\n Due to long computation times, the form is saved::\n\n sage: ch_form is ch.get_form(nab)\n True\n\n "
from .bundle_connection import BundleConnection
from .affine_connection import AffineConnection
if (not isinstance(connection, (AffineConnection, BundleConnection))):
raise TypeError('argument must be an affine connection on the manifold or bundle connection on the vector bundle')
if (connection not in self._mixed_forms):
if (cmatrices is None):
if (self._class_type == 'Pfaffian'):
raise NotImplementedError("At this stage, Pfaffian forms cannot be derived from (metric) connections. Please use the argument 'cmatrices' to insert a dictionary of skew-symmetric curvature matrices by hand, instead.")
cmatrices = {}
for frame in self._get_min_frames(connection._coefficients.keys()):
cmatrix = [[connection.curvature_form(i, j, frame) for j in self._vbundle.irange()] for i in self._vbundle.irange()]
cmatrices[frame] = cmatrix
(name, latex_name) = (self._name, self._latex_name)
if ((name is not None) and (connection._name is not None)):
name += (((('(' + self._vbundle._name) + ', ') + connection._name) + ')')
if ((latex_name is not None) and (connection._latex_name is not None)):
latex_name += (((('(' + self._vbundle._latex_name) + ', ') + connection._latex_name) + ')')
res = self._base_space.mixed_form(name=name, latex_name=latex_name)
from sage.matrix.matrix_space import MatrixSpace
for (frame, cmatrix) in cmatrices.items():
dom = frame._domain
alg = dom.mixed_form_algebra()
mspace = MatrixSpace(alg, self._rank)
cmatrix = mspace(cmatrix)
ncmatrix = self._normalize_matrix(cmatrix)
rmatrix = self._insert_in_polynomial(ncmatrix)
if (self._class_type == 'additive'):
rst = rmatrix.trace()
elif (self._class_type == 'multiplicative'):
rst = rmatrix.det()
elif (self._class_type == 'Pfaffian'):
rst = rmatrix.pfaffian()
res.set_restriction(rst)
if (self._class_type == 'Pfaffian'):
deg_dist = self._rank
elif (self._vbundle._field_type == 'real'):
deg_dist = 4
elif (self._vbundle._field_type == 'complex'):
deg_dist = 2
else:
deg_dist = 1
for k in res.irange():
if (((k % deg_dist) != 0) or ((self._class_type == 'Pfaffian') and (k == 0))):
res[k] = 0
else:
if (self._name is not None):
name = ((((self._name + '_') + str((k // deg_dist))) + '(') + self._vbundle._name)
if (connection._name is not None):
name += (', ' + connection._name)
name += ')'
if (self._latex_name is not None):
latex_name = (((((self._latex_name + '_{') + str((k // deg_dist))) + '}') + '(') + self._vbundle._latex_name)
if (connection._latex_name is not None):
latex_name += (', ' + connection._latex_name)
latex_name += ')'
res[k].set_name(name=name, latex_name=latex_name)
self._mixed_forms[connection] = res
return self._mixed_forms[connection]<|docstring|>Return the form representing ``self`` with respect to the given
connection ``connection``.
INPUT:
- ``connection`` -- connection to which the form should be associated to;
this can be either a bundle connection as an instance of
:class:`~sage.manifolds.differentiable.bundle_connection.BundleConnection`
or, in case of the tensor bundle, an affine connection as an instance
of :class:`~sage.manifolds.differentiable.affine_connection.AffineConnection`
- ``cmatrices`` -- (default: ``None``) a dictionary of curvature
matrices with local frames as keys and curvature matrices as items; if
``None``, Sage tries to get the curvature matrices from the connection
OUTPUT:
- mixed form as an instance of
:class:`~sage.manifolds.differentiable.mixed_form.MixedForm`
representing the total characteristic class
.. NOTE::
Be aware that depending on the characteristic class and complexity
of the manifold, computation times may vary a lot. In addition, if
not done before, the curvature form is computed from the connection,
here. If this behaviour is not wanted and the curvature form is
already known, please use the argument ``cmatrices``.
EXAMPLES:
Again, consider the Chern character on some 2-dimensional spacetime::
sage: M = Manifold(2, 'M', structure='Lorentzian')
sage: X.<t,x> = M.chart()
sage: E = M.vector_bundle(1, 'E', field='complex'); E
Differentiable complex vector bundle E -> M of rank 1 over the base
space 2-dimensional Lorentzian manifold M
sage: e = E.local_frame('e')
And again, we define the connection `\nabla^E` in terms of an
electro-magnetic potential `A(t)`::
sage: nab = E.bundle_connection('nabla^E', latex_name=r'\nabla^E')
sage: omega = M.one_form(name='omega')
sage: A = function('A')
sage: omega[1] = I*A(t)
sage: omega.display()
omega = I*A(t) dx
sage: nab.set_connection_form(0, 0, omega)
The Chern character is then given by::
sage: ch = E.characteristic_class('ChernChar'); ch
Characteristic class ch of additive type associated to e^x on the
Differentiable complex vector bundle E -> M of rank 1 over the base
space 2-dimensional Lorentzian manifold M
Inserting the connection, the result is a mixed differential form with
a priori non-zero components in even degrees::
sage: ch_form = ch.get_form(nab); ch_form
Mixed differential form ch(E, nabla^E) on the 2-dimensional
Lorentzian manifold M
sage: ch_form.display()
ch(E, nabla^E) = ch_0(E, nabla^E) + zero + ch_1(E, nabla^E)
sage: ch_form.display_expansion()
ch(E, nabla^E) = [1] + [0] + [1/2*d(A)/dt/pi dt/\dx]
Due to long computation times, the form is saved::
sage: ch_form is ch.get_form(nab)
True<|endoftext|> |
a7557dda181053608ec345fd3e3040ad514808d74f1bbf8d08ade0a152fd7a71 | def _insert_in_polynomial(self, cmatrix):
"\n Return the matrix after inserting `cmatrix` into the polynomial given by\n the taylor expansion of `self._func`.\n\n TESTS::\n\n sage: M = Manifold(4, 'M')\n sage: c = M.tangent_bundle().characteristic_class('Pontryagin')\n sage: c._insert_in_polynomial(x)\n 1/2*x^2 + 1\n\n "
mspace = cmatrix.parent()
power_list = [mspace.one()]
for pow in range((len(self._coeff_list) - 1)):
power_list.append((cmatrix * power_list[pow]))
rmatrix = sum(((self._coeff_list[k] * power_list[k]) for k in range(len(self._coeff_list))))
return rmatrix | Return the matrix after inserting `cmatrix` into the polynomial given by
the taylor expansion of `self._func`.
TESTS::
sage: M = Manifold(4, 'M')
sage: c = M.tangent_bundle().characteristic_class('Pontryagin')
sage: c._insert_in_polynomial(x)
1/2*x^2 + 1 | src/sage/manifolds/differentiable/characteristic_class.py | _insert_in_polynomial | tashakim/sage | 4 | python | def _insert_in_polynomial(self, cmatrix):
"\n Return the matrix after inserting `cmatrix` into the polynomial given by\n the taylor expansion of `self._func`.\n\n TESTS::\n\n sage: M = Manifold(4, 'M')\n sage: c = M.tangent_bundle().characteristic_class('Pontryagin')\n sage: c._insert_in_polynomial(x)\n 1/2*x^2 + 1\n\n "
mspace = cmatrix.parent()
power_list = [mspace.one()]
for pow in range((len(self._coeff_list) - 1)):
power_list.append((cmatrix * power_list[pow]))
rmatrix = sum(((self._coeff_list[k] * power_list[k]) for k in range(len(self._coeff_list))))
return rmatrix | def _insert_in_polynomial(self, cmatrix):
"\n Return the matrix after inserting `cmatrix` into the polynomial given by\n the taylor expansion of `self._func`.\n\n TESTS::\n\n sage: M = Manifold(4, 'M')\n sage: c = M.tangent_bundle().characteristic_class('Pontryagin')\n sage: c._insert_in_polynomial(x)\n 1/2*x^2 + 1\n\n "
mspace = cmatrix.parent()
power_list = [mspace.one()]
for pow in range((len(self._coeff_list) - 1)):
power_list.append((cmatrix * power_list[pow]))
rmatrix = sum(((self._coeff_list[k] * power_list[k]) for k in range(len(self._coeff_list))))
return rmatrix<|docstring|>Return the matrix after inserting `cmatrix` into the polynomial given by
the taylor expansion of `self._func`.
TESTS::
sage: M = Manifold(4, 'M')
sage: c = M.tangent_bundle().characteristic_class('Pontryagin')
sage: c._insert_in_polynomial(x)
1/2*x^2 + 1<|endoftext|> |
8661389b6f5b859ab55f01753b161515ee12d5430fd85ff5aa7c7080bc5a86ef | def _normalize_matrix(self, cmatrix):
'\n Return the curvature matrix "normalized" with `i/(2 \\pi)` or `1/(2 \\pi)`\n respectively.\n\n INPUT:\n\n - ``cmatrix`` -- curvature matrix\n\n OUTPUT:\n\n - ``I/(2*pi)*cmatrix``\n\n TESTS::\n\n sage: M = Manifold(2, \'M\')\n sage: TM = M.tangent_bundle()\n sage: c = TM.characteristic_class(1+x)\n sage: c._normalize_matrix(x)\n -1/2*I*x/pi\n\n '
from sage.symbolic.constants import pi
fac = (1 / (2 * pi))
if (self._class_type != 'Pfaffian'):
from sage.libs.pynac.pynac import I
fac = (fac / I)
return (fac * cmatrix) | Return the curvature matrix "normalized" with `i/(2 \pi)` or `1/(2 \pi)`
respectively.
INPUT:
- ``cmatrix`` -- curvature matrix
OUTPUT:
- ``I/(2*pi)*cmatrix``
TESTS::
sage: M = Manifold(2, 'M')
sage: TM = M.tangent_bundle()
sage: c = TM.characteristic_class(1+x)
sage: c._normalize_matrix(x)
-1/2*I*x/pi | src/sage/manifolds/differentiable/characteristic_class.py | _normalize_matrix | tashakim/sage | 4 | python | def _normalize_matrix(self, cmatrix):
'\n Return the curvature matrix "normalized" with `i/(2 \\pi)` or `1/(2 \\pi)`\n respectively.\n\n INPUT:\n\n - ``cmatrix`` -- curvature matrix\n\n OUTPUT:\n\n - ``I/(2*pi)*cmatrix``\n\n TESTS::\n\n sage: M = Manifold(2, \'M\')\n sage: TM = M.tangent_bundle()\n sage: c = TM.characteristic_class(1+x)\n sage: c._normalize_matrix(x)\n -1/2*I*x/pi\n\n '
from sage.symbolic.constants import pi
fac = (1 / (2 * pi))
if (self._class_type != 'Pfaffian'):
from sage.libs.pynac.pynac import I
fac = (fac / I)
return (fac * cmatrix) | def _normalize_matrix(self, cmatrix):
'\n Return the curvature matrix "normalized" with `i/(2 \\pi)` or `1/(2 \\pi)`\n respectively.\n\n INPUT:\n\n - ``cmatrix`` -- curvature matrix\n\n OUTPUT:\n\n - ``I/(2*pi)*cmatrix``\n\n TESTS::\n\n sage: M = Manifold(2, \'M\')\n sage: TM = M.tangent_bundle()\n sage: c = TM.characteristic_class(1+x)\n sage: c._normalize_matrix(x)\n -1/2*I*x/pi\n\n '
from sage.symbolic.constants import pi
fac = (1 / (2 * pi))
if (self._class_type != 'Pfaffian'):
from sage.libs.pynac.pynac import I
fac = (fac / I)
return (fac * cmatrix)<|docstring|>Return the curvature matrix "normalized" with `i/(2 \pi)` or `1/(2 \pi)`
respectively.
INPUT:
- ``cmatrix`` -- curvature matrix
OUTPUT:
- ``I/(2*pi)*cmatrix``
TESTS::
sage: M = Manifold(2, 'M')
sage: TM = M.tangent_bundle()
sage: c = TM.characteristic_class(1+x)
sage: c._normalize_matrix(x)
-1/2*I*x/pi<|endoftext|> |
2207eb280220c067cea82b2b5a1e609c94bcdac6e0591d2097c0f61b3bd86122 | def _get_min_frames(self, frame_list):
"\n Return the minimal amount of frames necessary to cover the union of all\n frame's domains.\n\n INPUT:\n\n - list of frames\n\n OUTPUT:\n\n - set of frames\n\n TESTS::\n\n sage: M = Manifold(2, 'M')\n sage: U = M.open_subset('U'); V = M.open_subset('V')\n sage: e = U.vector_frame('e'); f = V.vector_frame('f')\n sage: g = M.vector_frame('g')\n sage: c = M.tangent_bundle().characteristic_class('Pontryagin')\n sage: c._get_min_frames([e, f, g])\n {Vector frame (M, (g_0,g_1))}\n\n "
min_frame_set = set()
for frame in frame_list:
redund_frame_set = set()
for oframe in min_frame_set:
if frame._domain.is_subset(oframe._domain):
break
elif oframe._domain.is_subset(frame._domain):
redund_frame_set.add(oframe)
else:
min_frame_set.add(frame)
min_frame_set.difference_update(redund_frame_set)
return min_frame_set | Return the minimal amount of frames necessary to cover the union of all
frame's domains.
INPUT:
- list of frames
OUTPUT:
- set of frames
TESTS::
sage: M = Manifold(2, 'M')
sage: U = M.open_subset('U'); V = M.open_subset('V')
sage: e = U.vector_frame('e'); f = V.vector_frame('f')
sage: g = M.vector_frame('g')
sage: c = M.tangent_bundle().characteristic_class('Pontryagin')
sage: c._get_min_frames([e, f, g])
{Vector frame (M, (g_0,g_1))} | src/sage/manifolds/differentiable/characteristic_class.py | _get_min_frames | tashakim/sage | 4 | python | def _get_min_frames(self, frame_list):
"\n Return the minimal amount of frames necessary to cover the union of all\n frame's domains.\n\n INPUT:\n\n - list of frames\n\n OUTPUT:\n\n - set of frames\n\n TESTS::\n\n sage: M = Manifold(2, 'M')\n sage: U = M.open_subset('U'); V = M.open_subset('V')\n sage: e = U.vector_frame('e'); f = V.vector_frame('f')\n sage: g = M.vector_frame('g')\n sage: c = M.tangent_bundle().characteristic_class('Pontryagin')\n sage: c._get_min_frames([e, f, g])\n {Vector frame (M, (g_0,g_1))}\n\n "
min_frame_set = set()
for frame in frame_list:
redund_frame_set = set()
for oframe in min_frame_set:
if frame._domain.is_subset(oframe._domain):
break
elif oframe._domain.is_subset(frame._domain):
redund_frame_set.add(oframe)
else:
min_frame_set.add(frame)
min_frame_set.difference_update(redund_frame_set)
return min_frame_set | def _get_min_frames(self, frame_list):
"\n Return the minimal amount of frames necessary to cover the union of all\n frame's domains.\n\n INPUT:\n\n - list of frames\n\n OUTPUT:\n\n - set of frames\n\n TESTS::\n\n sage: M = Manifold(2, 'M')\n sage: U = M.open_subset('U'); V = M.open_subset('V')\n sage: e = U.vector_frame('e'); f = V.vector_frame('f')\n sage: g = M.vector_frame('g')\n sage: c = M.tangent_bundle().characteristic_class('Pontryagin')\n sage: c._get_min_frames([e, f, g])\n {Vector frame (M, (g_0,g_1))}\n\n "
min_frame_set = set()
for frame in frame_list:
redund_frame_set = set()
for oframe in min_frame_set:
if frame._domain.is_subset(oframe._domain):
break
elif oframe._domain.is_subset(frame._domain):
redund_frame_set.add(oframe)
else:
min_frame_set.add(frame)
min_frame_set.difference_update(redund_frame_set)
return min_frame_set<|docstring|>Return the minimal amount of frames necessary to cover the union of all
frame's domains.
INPUT:
- list of frames
OUTPUT:
- set of frames
TESTS::
sage: M = Manifold(2, 'M')
sage: U = M.open_subset('U'); V = M.open_subset('V')
sage: e = U.vector_frame('e'); f = V.vector_frame('f')
sage: g = M.vector_frame('g')
sage: c = M.tangent_bundle().characteristic_class('Pontryagin')
sage: c._get_min_frames([e, f, g])
{Vector frame (M, (g_0,g_1))}<|endoftext|> |
43a4c0acc8fb0c0e12bc9d4860cf89fd2cef8e78137437ced0d197fe4b168c94 | def check_type(value_name, value, dtype, desire=True):
'\n Checks the type of a variable and raises an error if not the desired type.\n\n Parameters\n ----------\n value_name : str\n The name of the variable that will be printed in the error message.\n\n value :\n The value of the variable\n\n dtype : dtype\n The data type to compare with isinstance\n\n desire : boolean, optional\n If `desire = True`, then the error will be raised if value does not\n have a data type of `dtype`. If `desire = False`, then the error will\n be raised if value does have a data type of `dtype`.\n\n Returns\n -------\n None\n\n '
if (isinstance(value, dtype) is not desire):
if desire:
msg_add_in = 'have'
elif (not desire):
msg_add_in = 'not have'
msg = 'The value of {0} should {3} type: {1}. Instead type({0}) = {2}'.format(value_name, dtype, type(value), msg_add_in)
raise ValueError(msg)
else:
pass | Checks the type of a variable and raises an error if not the desired type.
Parameters
----------
value_name : str
The name of the variable that will be printed in the error message.
value :
The value of the variable
dtype : dtype
The data type to compare with isinstance
desire : boolean, optional
If `desire = True`, then the error will be raised if value does not
have a data type of `dtype`. If `desire = False`, then the error will
be raised if value does have a data type of `dtype`.
Returns
-------
None | fruitbat/utils.py | check_type | abatten/ready | 17 | python | def check_type(value_name, value, dtype, desire=True):
'\n Checks the type of a variable and raises an error if not the desired type.\n\n Parameters\n ----------\n value_name : str\n The name of the variable that will be printed in the error message.\n\n value :\n The value of the variable\n\n dtype : dtype\n The data type to compare with isinstance\n\n desire : boolean, optional\n If `desire = True`, then the error will be raised if value does not\n have a data type of `dtype`. If `desire = False`, then the error will\n be raised if value does have a data type of `dtype`.\n\n Returns\n -------\n None\n\n '
if (isinstance(value, dtype) is not desire):
if desire:
msg_add_in = 'have'
elif (not desire):
msg_add_in = 'not have'
msg = 'The value of {0} should {3} type: {1}. Instead type({0}) = {2}'.format(value_name, dtype, type(value), msg_add_in)
raise ValueError(msg)
else:
pass | def check_type(value_name, value, dtype, desire=True):
'\n Checks the type of a variable and raises an error if not the desired type.\n\n Parameters\n ----------\n value_name : str\n The name of the variable that will be printed in the error message.\n\n value :\n The value of the variable\n\n dtype : dtype\n The data type to compare with isinstance\n\n desire : boolean, optional\n If `desire = True`, then the error will be raised if value does not\n have a data type of `dtype`. If `desire = False`, then the error will\n be raised if value does have a data type of `dtype`.\n\n Returns\n -------\n None\n\n '
if (isinstance(value, dtype) is not desire):
if desire:
msg_add_in = 'have'
elif (not desire):
msg_add_in = 'not have'
msg = 'The value of {0} should {3} type: {1}. Instead type({0}) = {2}'.format(value_name, dtype, type(value), msg_add_in)
raise ValueError(msg)
else:
pass<|docstring|>Checks the type of a variable and raises an error if not the desired type.
Parameters
----------
value_name : str
The name of the variable that will be printed in the error message.
value :
The value of the variable
dtype : dtype
The data type to compare with isinstance
desire : boolean, optional
If `desire = True`, then the error will be raised if value does not
have a data type of `dtype`. If `desire = False`, then the error will
be raised if value does have a data type of `dtype`.
Returns
-------
None<|endoftext|> |
385e50a13c2d4a5939ebb05dfd97cdbf28dbc829653c696f26a24fe1f714cac2 | def check_keys_in_dict(dictionary, keys):
'\n Checks that a list of keys exist in a dictionary.\n\n Parameters\n ----------\n dictionary : dict\n The input dictionary.\n\n keys: list of strings\n The keys that the dictionary must contain.\n\n Returns\n -------\n bool:\n Returns *True* is all required keys exist in the dictionary.\n Otherwise a KeyError is raised.\n '
if (not all(((key in dictionary) for key in keys))):
raise KeyError('Dictionary missing key values.Requires: {}'.format(keys))
return True | Checks that a list of keys exist in a dictionary.
Parameters
----------
dictionary : dict
The input dictionary.
keys: list of strings
The keys that the dictionary must contain.
Returns
-------
bool:
Returns *True* is all required keys exist in the dictionary.
Otherwise a KeyError is raised. | fruitbat/utils.py | check_keys_in_dict | abatten/ready | 17 | python | def check_keys_in_dict(dictionary, keys):
'\n Checks that a list of keys exist in a dictionary.\n\n Parameters\n ----------\n dictionary : dict\n The input dictionary.\n\n keys: list of strings\n The keys that the dictionary must contain.\n\n Returns\n -------\n bool:\n Returns *True* is all required keys exist in the dictionary.\n Otherwise a KeyError is raised.\n '
if (not all(((key in dictionary) for key in keys))):
raise KeyError('Dictionary missing key values.Requires: {}'.format(keys))
return True | def check_keys_in_dict(dictionary, keys):
'\n Checks that a list of keys exist in a dictionary.\n\n Parameters\n ----------\n dictionary : dict\n The input dictionary.\n\n keys: list of strings\n The keys that the dictionary must contain.\n\n Returns\n -------\n bool:\n Returns *True* is all required keys exist in the dictionary.\n Otherwise a KeyError is raised.\n '
if (not all(((key in dictionary) for key in keys))):
raise KeyError('Dictionary missing key values.Requires: {}'.format(keys))
return True<|docstring|>Checks that a list of keys exist in a dictionary.
Parameters
----------
dictionary : dict
The input dictionary.
keys: list of strings
The keys that the dictionary must contain.
Returns
-------
bool:
Returns *True* is all required keys exist in the dictionary.
Otherwise a KeyError is raised.<|endoftext|> |
cb19457f27947c30da88d6628784978b94f8b263df800e0cc09f8e326e3755a1 | def get_path_to_file_from_here(filename, subdirs=None):
'\n Returns the whole path to a file that is in the same directory\n or subdirectory as the file this function is called from.\n\n Parameters\n ----------\n filename : str\n The name of the file\n\n subdirs : list of strs, optional\n A list of strings containing any subdirectory names.\n Default: None\n\n Returns\n -------\n str\n The whole path to the file\n\n '
if (subdirs is None):
path = os.path.join(os.path.dirname(__file__), filename)
elif isinstance(subdirs, list):
path = os.path.join(os.path.dirname(__file__), *subdirs, filename)
else:
msg = "subdirs must have type list. If you want a single subdirectory, use subdirs=['data']"
raise ValueError(msg)
return path | Returns the whole path to a file that is in the same directory
or subdirectory as the file this function is called from.
Parameters
----------
filename : str
The name of the file
subdirs : list of strs, optional
A list of strings containing any subdirectory names.
Default: None
Returns
-------
str
The whole path to the file | fruitbat/utils.py | get_path_to_file_from_here | abatten/ready | 17 | python | def get_path_to_file_from_here(filename, subdirs=None):
'\n Returns the whole path to a file that is in the same directory\n or subdirectory as the file this function is called from.\n\n Parameters\n ----------\n filename : str\n The name of the file\n\n subdirs : list of strs, optional\n A list of strings containing any subdirectory names.\n Default: None\n\n Returns\n -------\n str\n The whole path to the file\n\n '
if (subdirs is None):
path = os.path.join(os.path.dirname(__file__), filename)
elif isinstance(subdirs, list):
path = os.path.join(os.path.dirname(__file__), *subdirs, filename)
else:
msg = "subdirs must have type list. If you want a single subdirectory, use subdirs=['data']"
raise ValueError(msg)
return path | def get_path_to_file_from_here(filename, subdirs=None):
'\n Returns the whole path to a file that is in the same directory\n or subdirectory as the file this function is called from.\n\n Parameters\n ----------\n filename : str\n The name of the file\n\n subdirs : list of strs, optional\n A list of strings containing any subdirectory names.\n Default: None\n\n Returns\n -------\n str\n The whole path to the file\n\n '
if (subdirs is None):
path = os.path.join(os.path.dirname(__file__), filename)
elif isinstance(subdirs, list):
path = os.path.join(os.path.dirname(__file__), *subdirs, filename)
else:
msg = "subdirs must have type list. If you want a single subdirectory, use subdirs=['data']"
raise ValueError(msg)
return path<|docstring|>Returns the whole path to a file that is in the same directory
or subdirectory as the file this function is called from.
Parameters
----------
filename : str
The name of the file
subdirs : list of strs, optional
A list of strings containing any subdirectory names.
Default: None
Returns
-------
str
The whole path to the file<|endoftext|> |
c1a119a6a1d8472776248b9fe742abdc12129f7e0051c4bc9a84ef55ab9b13a5 | def calc_mean_from_pdf(x, pdf, dx=None):
'\n Calculates the mean of a probability density function\n\n Parameters\n ----------\n x : np.ndarray\n The x values.\n\n pdf : np.ndarray\n The value of the PDF at x.\n\n dx : np.ndarray or None, optional\n The spacing between the x bins. \n If `None`, then the bins are assumed to be linearly spaced.\n\n Returns\n -------\n mean : float\n The mean of the PDF.\n\n '
if (dx is None):
dx = ((x[(- 1)] - x[0]) / len(x))
return np.sum(((pdf * x) * dx)) | Calculates the mean of a probability density function
Parameters
----------
x : np.ndarray
The x values.
pdf : np.ndarray
The value of the PDF at x.
dx : np.ndarray or None, optional
The spacing between the x bins.
If `None`, then the bins are assumed to be linearly spaced.
Returns
-------
mean : float
The mean of the PDF. | fruitbat/utils.py | calc_mean_from_pdf | abatten/ready | 17 | python | def calc_mean_from_pdf(x, pdf, dx=None):
'\n Calculates the mean of a probability density function\n\n Parameters\n ----------\n x : np.ndarray\n The x values.\n\n pdf : np.ndarray\n The value of the PDF at x.\n\n dx : np.ndarray or None, optional\n The spacing between the x bins. \n If `None`, then the bins are assumed to be linearly spaced.\n\n Returns\n -------\n mean : float\n The mean of the PDF.\n\n '
if (dx is None):
dx = ((x[(- 1)] - x[0]) / len(x))
return np.sum(((pdf * x) * dx)) | def calc_mean_from_pdf(x, pdf, dx=None):
'\n Calculates the mean of a probability density function\n\n Parameters\n ----------\n x : np.ndarray\n The x values.\n\n pdf : np.ndarray\n The value of the PDF at x.\n\n dx : np.ndarray or None, optional\n The spacing between the x bins. \n If `None`, then the bins are assumed to be linearly spaced.\n\n Returns\n -------\n mean : float\n The mean of the PDF.\n\n '
if (dx is None):
dx = ((x[(- 1)] - x[0]) / len(x))
return np.sum(((pdf * x) * dx))<|docstring|>Calculates the mean of a probability density function
Parameters
----------
x : np.ndarray
The x values.
pdf : np.ndarray
The value of the PDF at x.
dx : np.ndarray or None, optional
The spacing between the x bins.
If `None`, then the bins are assumed to be linearly spaced.
Returns
-------
mean : float
The mean of the PDF.<|endoftext|> |
dcf947c8d298f155e54322dedb61a351088b4ec132d992eb55efd49d69a191ff | def calc_variance_from_pdf(x, pdf, dx=None):
'\n Calculates the variance from a probability density\n function.\n\n Parameters\n ----------\n x : np.ndarray\n The x values.\n\n pdf : np.ndarray\n The value of the PDF at x.\n\n dx : np.ndarray or None, optional\n The spacing between the x bins. \n If `None`, then the bins are assumed to be linearly spaced.\n\n Returns\n -------\n variance : float\n The variance of the PDF.\n\n '
if (dx is None):
dx = ((x[(- 1)] - x[0]) / len(x))
mean = calc_mean_from_pdf(x, pdf, dx)
return np.sum(((pdf * dx) * ((x - mean) ** 2))) | Calculates the variance from a probability density
function.
Parameters
----------
x : np.ndarray
The x values.
pdf : np.ndarray
The value of the PDF at x.
dx : np.ndarray or None, optional
The spacing between the x bins.
If `None`, then the bins are assumed to be linearly spaced.
Returns
-------
variance : float
The variance of the PDF. | fruitbat/utils.py | calc_variance_from_pdf | abatten/ready | 17 | python | def calc_variance_from_pdf(x, pdf, dx=None):
'\n Calculates the variance from a probability density\n function.\n\n Parameters\n ----------\n x : np.ndarray\n The x values.\n\n pdf : np.ndarray\n The value of the PDF at x.\n\n dx : np.ndarray or None, optional\n The spacing between the x bins. \n If `None`, then the bins are assumed to be linearly spaced.\n\n Returns\n -------\n variance : float\n The variance of the PDF.\n\n '
if (dx is None):
dx = ((x[(- 1)] - x[0]) / len(x))
mean = calc_mean_from_pdf(x, pdf, dx)
return np.sum(((pdf * dx) * ((x - mean) ** 2))) | def calc_variance_from_pdf(x, pdf, dx=None):
'\n Calculates the variance from a probability density\n function.\n\n Parameters\n ----------\n x : np.ndarray\n The x values.\n\n pdf : np.ndarray\n The value of the PDF at x.\n\n dx : np.ndarray or None, optional\n The spacing between the x bins. \n If `None`, then the bins are assumed to be linearly spaced.\n\n Returns\n -------\n variance : float\n The variance of the PDF.\n\n '
if (dx is None):
dx = ((x[(- 1)] - x[0]) / len(x))
mean = calc_mean_from_pdf(x, pdf, dx)
return np.sum(((pdf * dx) * ((x - mean) ** 2)))<|docstring|>Calculates the variance from a probability density
function.
Parameters
----------
x : np.ndarray
The x values.
pdf : np.ndarray
The value of the PDF at x.
dx : np.ndarray or None, optional
The spacing between the x bins.
If `None`, then the bins are assumed to be linearly spaced.
Returns
-------
variance : float
The variance of the PDF.<|endoftext|> |
213de70f3890aa23c43446bf53f1c2c09fa70897659c45f688a756499454c540 | def calc_std_from_pdf(x, pdf, dx=None):
'\n Calculates the standard deviation from a probability\n density function.\n\n Parameters\n ----------\n x : np.ndarray\n The x values.\n\n pdf : np.ndarray\n The value of the PDF at x.\n\n dx : np.ndarray or None, optional\n The spacing between the x bins. \n If `None`, then the bins are assumed to be linearly spaced.\n\n Returns\n -------\n std : float\n The standard deviation of the PDF.\n\n '
if (dx is None):
dx = ((x[(- 1)] - x[0]) / len(x))
return np.sqrt(calc_variance_from_pdf(x, pdf, dx)) | Calculates the standard deviation from a probability
density function.
Parameters
----------
x : np.ndarray
The x values.
pdf : np.ndarray
The value of the PDF at x.
dx : np.ndarray or None, optional
The spacing between the x bins.
If `None`, then the bins are assumed to be linearly spaced.
Returns
-------
std : float
The standard deviation of the PDF. | fruitbat/utils.py | calc_std_from_pdf | abatten/ready | 17 | python | def calc_std_from_pdf(x, pdf, dx=None):
'\n Calculates the standard deviation from a probability\n density function.\n\n Parameters\n ----------\n x : np.ndarray\n The x values.\n\n pdf : np.ndarray\n The value of the PDF at x.\n\n dx : np.ndarray or None, optional\n The spacing between the x bins. \n If `None`, then the bins are assumed to be linearly spaced.\n\n Returns\n -------\n std : float\n The standard deviation of the PDF.\n\n '
if (dx is None):
dx = ((x[(- 1)] - x[0]) / len(x))
return np.sqrt(calc_variance_from_pdf(x, pdf, dx)) | def calc_std_from_pdf(x, pdf, dx=None):
'\n Calculates the standard deviation from a probability\n density function.\n\n Parameters\n ----------\n x : np.ndarray\n The x values.\n\n pdf : np.ndarray\n The value of the PDF at x.\n\n dx : np.ndarray or None, optional\n The spacing between the x bins. \n If `None`, then the bins are assumed to be linearly spaced.\n\n Returns\n -------\n std : float\n The standard deviation of the PDF.\n\n '
if (dx is None):
dx = ((x[(- 1)] - x[0]) / len(x))
return np.sqrt(calc_variance_from_pdf(x, pdf, dx))<|docstring|>Calculates the standard deviation from a probability
density function.
Parameters
----------
x : np.ndarray
The x values.
pdf : np.ndarray
The value of the PDF at x.
dx : np.ndarray or None, optional
The spacing between the x bins.
If `None`, then the bins are assumed to be linearly spaced.
Returns
-------
std : float
The standard deviation of the PDF.<|endoftext|> |
7bd96811530dc2cfc139bd26c93ca73239e17cfb0b897caaaf9e4cbece7e3c34 | def calc_z_from_pdf_percentile(x, pdf, percentile):
'\n\n\n Parameters\n ----------\n x : np.ndarray\n The x values of the PDF.\n\n pdf : np.ndarray\n The value of the PDF at x.\n\n percentile : float\n The percentile of the PDF.\n\n Returns\n -------\n redshift : float\n The redshift at the given percentile.\n\n '
cumsum = np.cumsum(pdf)
normed_cumsum = (cumsum / cumsum[(- 1)])
interpolated_cumsum = interpolate.interp1d(normed_cumsum, x)
return interpolated_cumsum(percentile) | Parameters
----------
x : np.ndarray
The x values of the PDF.
pdf : np.ndarray
The value of the PDF at x.
percentile : float
The percentile of the PDF.
Returns
-------
redshift : float
The redshift at the given percentile. | fruitbat/utils.py | calc_z_from_pdf_percentile | abatten/ready | 17 | python | def calc_z_from_pdf_percentile(x, pdf, percentile):
'\n\n\n Parameters\n ----------\n x : np.ndarray\n The x values of the PDF.\n\n pdf : np.ndarray\n The value of the PDF at x.\n\n percentile : float\n The percentile of the PDF.\n\n Returns\n -------\n redshift : float\n The redshift at the given percentile.\n\n '
cumsum = np.cumsum(pdf)
normed_cumsum = (cumsum / cumsum[(- 1)])
interpolated_cumsum = interpolate.interp1d(normed_cumsum, x)
return interpolated_cumsum(percentile) | def calc_z_from_pdf_percentile(x, pdf, percentile):
'\n\n\n Parameters\n ----------\n x : np.ndarray\n The x values of the PDF.\n\n pdf : np.ndarray\n The value of the PDF at x.\n\n percentile : float\n The percentile of the PDF.\n\n Returns\n -------\n redshift : float\n The redshift at the given percentile.\n\n '
cumsum = np.cumsum(pdf)
normed_cumsum = (cumsum / cumsum[(- 1)])
interpolated_cumsum = interpolate.interp1d(normed_cumsum, x)
return interpolated_cumsum(percentile)<|docstring|>Parameters
----------
x : np.ndarray
The x values of the PDF.
pdf : np.ndarray
The value of the PDF at x.
percentile : float
The percentile of the PDF.
Returns
-------
redshift : float
The redshift at the given percentile.<|endoftext|> |
5240b6246cad8a0886ae5c8cd418394a2e54abc41393296ff6f683484c0fb6d9 | def calc_median_from_pdf(x, pdf):
'\n Calculates the median of a PDF.\n\n Parameters\n ----------\n x : np.ndarray\n The x values.\n\n pdf : np.ndarray\n The value of the PDF at x.\n\n Returns\n -------\n median: float\n The median of the PDF.\n\n '
return calc_z_from_pdf_percentile(x, pdf, percentile=0.5) | Calculates the median of a PDF.
Parameters
----------
x : np.ndarray
The x values.
pdf : np.ndarray
The value of the PDF at x.
Returns
-------
median: float
The median of the PDF. | fruitbat/utils.py | calc_median_from_pdf | abatten/ready | 17 | python | def calc_median_from_pdf(x, pdf):
'\n Calculates the median of a PDF.\n\n Parameters\n ----------\n x : np.ndarray\n The x values.\n\n pdf : np.ndarray\n The value of the PDF at x.\n\n Returns\n -------\n median: float\n The median of the PDF.\n\n '
return calc_z_from_pdf_percentile(x, pdf, percentile=0.5) | def calc_median_from_pdf(x, pdf):
'\n Calculates the median of a PDF.\n\n Parameters\n ----------\n x : np.ndarray\n The x values.\n\n pdf : np.ndarray\n The value of the PDF at x.\n\n Returns\n -------\n median: float\n The median of the PDF.\n\n '
return calc_z_from_pdf_percentile(x, pdf, percentile=0.5)<|docstring|>Calculates the median of a PDF.
Parameters
----------
x : np.ndarray
The x values.
pdf : np.ndarray
The value of the PDF at x.
Returns
-------
median: float
The median of the PDF.<|endoftext|> |
03064233ac0b9a45d5ce73ec68804485945504315dcd9c1524337bd81f528034 | def linear_interpolate_pdfs(sample, xvals, pdfs):
'\n\n Parameters\n ----------\n sample\n\n xvals: \n\n Returns\n -------\n PDF: np.ndarray\n The PDF at sample.\n '
(x1, x2) = xvals
(pdf1, pdf2) = pdfs
grad = ((pdf2 - pdf1) / (x2 - x1))
dist = (sample - x1)
return ((grad * dist) + pdf1) | Parameters
----------
sample
xvals:
Returns
-------
PDF: np.ndarray
The PDF at sample. | fruitbat/utils.py | linear_interpolate_pdfs | abatten/ready | 17 | python | def linear_interpolate_pdfs(sample, xvals, pdfs):
'\n\n Parameters\n ----------\n sample\n\n xvals: \n\n Returns\n -------\n PDF: np.ndarray\n The PDF at sample.\n '
(x1, x2) = xvals
(pdf1, pdf2) = pdfs
grad = ((pdf2 - pdf1) / (x2 - x1))
dist = (sample - x1)
return ((grad * dist) + pdf1) | def linear_interpolate_pdfs(sample, xvals, pdfs):
'\n\n Parameters\n ----------\n sample\n\n xvals: \n\n Returns\n -------\n PDF: np.ndarray\n The PDF at sample.\n '
(x1, x2) = xvals
(pdf1, pdf2) = pdfs
grad = ((pdf2 - pdf1) / (x2 - x1))
dist = (sample - x1)
return ((grad * dist) + pdf1)<|docstring|>Parameters
----------
sample
xvals:
Returns
-------
PDF: np.ndarray
The PDF at sample.<|endoftext|> |
930cc5dbfc9829f5f62b4c146603ba9828172a0287a9103ac99643ad34af2d1a | def sigma_to_pdf_percentiles(sigma):
'\n Looks up the percentile range of Gaussian for a given\n standard deviation.\n\n Parameters\n ----------\n sigma: [1, 2, 3, 4, 5]\n The standard deviation to calculate a percentile.\n\n Returns\n -------\n Lower: float\n The lower percentile\n Higher: float\n The higher percentile\n\n Example\n -------\n >>> sigma_to_pdf_percentiles(1)\n (0.158655254, 0.841344746)\n\n '
std = int(sigma)
std_prop = {1: 0.682689492, 2: 0.954499736, 3: 0.997300204, 4: 0.99993666, 5: 0.999999426697}
std_limits = {1: (((1 - std_prop[1]) / 2), ((1 + std_prop[1]) / 2)), 2: (((1 - std_prop[2]) / 2), ((1 + std_prop[2]) / 2)), 3: (((1 - std_prop[3]) / 2), ((1 + std_prop[3]) / 2)), 4: (((1 - std_prop[4]) / 2), ((1 + std_prop[4]) / 2)), 5: (((1 - std_prop[5]) / 2), ((1 + std_prop[5]) / 2))}
return std_limits[std] | Looks up the percentile range of Gaussian for a given
standard deviation.
Parameters
----------
sigma: [1, 2, 3, 4, 5]
The standard deviation to calculate a percentile.
Returns
-------
Lower: float
The lower percentile
Higher: float
The higher percentile
Example
-------
>>> sigma_to_pdf_percentiles(1)
(0.158655254, 0.841344746) | fruitbat/utils.py | sigma_to_pdf_percentiles | abatten/ready | 17 | python | def sigma_to_pdf_percentiles(sigma):
'\n Looks up the percentile range of Gaussian for a given\n standard deviation.\n\n Parameters\n ----------\n sigma: [1, 2, 3, 4, 5]\n The standard deviation to calculate a percentile.\n\n Returns\n -------\n Lower: float\n The lower percentile\n Higher: float\n The higher percentile\n\n Example\n -------\n >>> sigma_to_pdf_percentiles(1)\n (0.158655254, 0.841344746)\n\n '
std = int(sigma)
std_prop = {1: 0.682689492, 2: 0.954499736, 3: 0.997300204, 4: 0.99993666, 5: 0.999999426697}
std_limits = {1: (((1 - std_prop[1]) / 2), ((1 + std_prop[1]) / 2)), 2: (((1 - std_prop[2]) / 2), ((1 + std_prop[2]) / 2)), 3: (((1 - std_prop[3]) / 2), ((1 + std_prop[3]) / 2)), 4: (((1 - std_prop[4]) / 2), ((1 + std_prop[4]) / 2)), 5: (((1 - std_prop[5]) / 2), ((1 + std_prop[5]) / 2))}
return std_limits[std] | def sigma_to_pdf_percentiles(sigma):
'\n Looks up the percentile range of Gaussian for a given\n standard deviation.\n\n Parameters\n ----------\n sigma: [1, 2, 3, 4, 5]\n The standard deviation to calculate a percentile.\n\n Returns\n -------\n Lower: float\n The lower percentile\n Higher: float\n The higher percentile\n\n Example\n -------\n >>> sigma_to_pdf_percentiles(1)\n (0.158655254, 0.841344746)\n\n '
std = int(sigma)
std_prop = {1: 0.682689492, 2: 0.954499736, 3: 0.997300204, 4: 0.99993666, 5: 0.999999426697}
std_limits = {1: (((1 - std_prop[1]) / 2), ((1 + std_prop[1]) / 2)), 2: (((1 - std_prop[2]) / 2), ((1 + std_prop[2]) / 2)), 3: (((1 - std_prop[3]) / 2), ((1 + std_prop[3]) / 2)), 4: (((1 - std_prop[4]) / 2), ((1 + std_prop[4]) / 2)), 5: (((1 - std_prop[5]) / 2), ((1 + std_prop[5]) / 2))}
return std_limits[std]<|docstring|>Looks up the percentile range of Gaussian for a given
standard deviation.
Parameters
----------
sigma: [1, 2, 3, 4, 5]
The standard deviation to calculate a percentile.
Returns
-------
Lower: float
The lower percentile
Higher: float
The higher percentile
Example
-------
>>> sigma_to_pdf_percentiles(1)
(0.158655254, 0.841344746)<|endoftext|> |
6573714b0807e3d36f97aa3b444840fea1bdbd654905549e1b6f873f50f7019e | def test_create(self):
'Ensure we can upload a new Photo'
self._test_create(exclude=('image',)) | Ensure we can upload a new Photo | api/tests/test_photos.py | test_create | KrakSat-2016/kraksat-server | 0 | python | def test_create(self):
self._test_create(exclude=('image',)) | def test_create(self):
self._test_create(exclude=('image',))<|docstring|>Ensure we can upload a new Photo<|endoftext|> |
d96a9f17d02b47a9962217d19915eba05f11b5d843976930a2579fe76b31ff7f | @override_settings(ALLOWED_IMAGE_EXTENSIONS=('PNG',))
def test_invalid_params(self):
'Ensure sending invalid parameters to /photos returns error 400'
invalid_contents = SUF('test.png', b'test image contents', 'image/png')
invalid_ext = SUF('invalid.ext1337', self.valid_data['image'].read(), 'image/png')
self._test_invalid_params(('Invalid timestamp', {'timestamp': 'foobar'}), ('Invalid file contents', {'image': invalid_contents}), ('Invalid file extension', {'image': invalid_ext}), ('Invalid is_panorama', {'is_panorama': 'foobar'})) | Ensure sending invalid parameters to /photos returns error 400 | api/tests/test_photos.py | test_invalid_params | KrakSat-2016/kraksat-server | 0 | python | @override_settings(ALLOWED_IMAGE_EXTENSIONS=('PNG',))
def test_invalid_params(self):
invalid_contents = SUF('test.png', b'test image contents', 'image/png')
invalid_ext = SUF('invalid.ext1337', self.valid_data['image'].read(), 'image/png')
self._test_invalid_params(('Invalid timestamp', {'timestamp': 'foobar'}), ('Invalid file contents', {'image': invalid_contents}), ('Invalid file extension', {'image': invalid_ext}), ('Invalid is_panorama', {'is_panorama': 'foobar'})) | @override_settings(ALLOWED_IMAGE_EXTENSIONS=('PNG',))
def test_invalid_params(self):
invalid_contents = SUF('test.png', b'test image contents', 'image/png')
invalid_ext = SUF('invalid.ext1337', self.valid_data['image'].read(), 'image/png')
self._test_invalid_params(('Invalid timestamp', {'timestamp': 'foobar'}), ('Invalid file contents', {'image': invalid_contents}), ('Invalid file extension', {'image': invalid_ext}), ('Invalid is_panorama', {'is_panorama': 'foobar'}))<|docstring|>Ensure sending invalid parameters to /photos returns error 400<|endoftext|> |
9d888d0aab6a86401d27a094e7b2f4137ac8ff0a0f9e4ba24701cb00f9e281bf | def track_xml(self, year, month):
'\n Sometimes the server block us or fail. We sould retry\n '
url = self._prepare_url(year, month)
s = requests.Session()
s.mount(url, HTTPAdapter(max_retries=10))
result = requests.get(url).content
return result | Sometimes the server block us or fail. We sould retry | FoncierImporter/es/weso/foncier/importer/xml_management/rest_xml_tracker.py | track_xml | weso/landportal-importers | 0 | python | def track_xml(self, year, month):
'\n \n '
url = self._prepare_url(year, month)
s = requests.Session()
s.mount(url, HTTPAdapter(max_retries=10))
result = requests.get(url).content
return result | def track_xml(self, year, month):
'\n \n '
url = self._prepare_url(year, month)
s = requests.Session()
s.mount(url, HTTPAdapter(max_retries=10))
result = requests.get(url).content
return result<|docstring|>Sometimes the server block us or fail. We sould retry<|endoftext|> |
eccb8ae98e8fd3c1720a6fe582e7ddec58dcac7fbedb1a3342ea004a665b7bbb | def send_mail(to_address, subject, contents, subtype='html'):
'\n Send email\n '
connected = False
attempts = 0
while (not connected):
attempts = (attempts + 1)
try:
connection = connect_smtp()
connected = True
except Exception as e:
logger.error(f'Problem with create smtp connection: {str(e)}')
if (attempts < 3):
logger.debug('Try connecting to smtp server again...')
time.sleep(3)
else:
raise
try:
email = EmailMessage()
email['Subject'] = subject
email['From'] = config.get('email', 'address')
email['To'] = to_address
email.set_content(contents, subtype=subtype)
connection.send_message(email)
finally:
connection.close() | Send email | pitschi/mail.py | send_mail | UQ-RCC/pitschi-xapi | 0 | python | def send_mail(to_address, subject, contents, subtype='html'):
'\n \n '
connected = False
attempts = 0
while (not connected):
attempts = (attempts + 1)
try:
connection = connect_smtp()
connected = True
except Exception as e:
logger.error(f'Problem with create smtp connection: {str(e)}')
if (attempts < 3):
logger.debug('Try connecting to smtp server again...')
time.sleep(3)
else:
raise
try:
email = EmailMessage()
email['Subject'] = subject
email['From'] = config.get('email', 'address')
email['To'] = to_address
email.set_content(contents, subtype=subtype)
connection.send_message(email)
finally:
connection.close() | def send_mail(to_address, subject, contents, subtype='html'):
'\n \n '
connected = False
attempts = 0
while (not connected):
attempts = (attempts + 1)
try:
connection = connect_smtp()
connected = True
except Exception as e:
logger.error(f'Problem with create smtp connection: {str(e)}')
if (attempts < 3):
logger.debug('Try connecting to smtp server again...')
time.sleep(3)
else:
raise
try:
email = EmailMessage()
email['Subject'] = subject
email['From'] = config.get('email', 'address')
email['To'] = to_address
email.set_content(contents, subtype=subtype)
connection.send_message(email)
finally:
connection.close()<|docstring|>Send email<|endoftext|> |
7f14a012789a2569fc1b28876db540bc24155d375ddfb66593eb91c595f3e5f1 | def main(argv):
'\n main method\n '
print(config.get('email', 'address'))
print(config.get('email', 'user'))
print(config.get('email', 'password'))
you = 'xxxx'
contents = '\n <html>\n <head></head>\n <body>\n <p>Hi!<br>\n These are the following samples need to be fixed:<br>\n <ul>\n <li>sample 1</li>\n <li>sample 2</li>\n <li>sample 3</li>\n </ul> \n </p>\n </body>\n </html>\n '
send_mail(you, 'This is another test', contents) | main method | pitschi/mail.py | main | UQ-RCC/pitschi-xapi | 0 | python | def main(argv):
'\n \n '
print(config.get('email', 'address'))
print(config.get('email', 'user'))
print(config.get('email', 'password'))
you = 'xxxx'
contents = '\n <html>\n <head></head>\n <body>\n <p>Hi!<br>\n These are the following samples need to be fixed:<br>\n <ul>\n <li>sample 1</li>\n <li>sample 2</li>\n <li>sample 3</li>\n </ul> \n </p>\n </body>\n </html>\n '
send_mail(you, 'This is another test', contents) | def main(argv):
'\n \n '
print(config.get('email', 'address'))
print(config.get('email', 'user'))
print(config.get('email', 'password'))
you = 'xxxx'
contents = '\n <html>\n <head></head>\n <body>\n <p>Hi!<br>\n These are the following samples need to be fixed:<br>\n <ul>\n <li>sample 1</li>\n <li>sample 2</li>\n <li>sample 3</li>\n </ul> \n </p>\n </body>\n </html>\n '
send_mail(you, 'This is another test', contents)<|docstring|>main method<|endoftext|> |
43c967e58de3d336eb84301f0100b480f4e15b830affc1fad8a95eacf8b646ff | def read_string_table(xml_source):
'Read in all shared strings in the table'
strings = []
src = _get_xml_iter(xml_source)
STRING_TAG = ('{%s}si' % SHEET_MAIN_NS)
for (_, node) in iterparse(src):
if (node.tag == STRING_TAG):
text = Text.from_tree(node).content
text = text.replace('x005F_', '')
node.clear()
strings.append(text)
return strings | Read in all shared strings in the table | desktop/core/ext-py/openpyxl-2.5.3/openpyxl/reader/strings.py | read_string_table | hombin/hue | 34 | python | def read_string_table(xml_source):
strings = []
src = _get_xml_iter(xml_source)
STRING_TAG = ('{%s}si' % SHEET_MAIN_NS)
for (_, node) in iterparse(src):
if (node.tag == STRING_TAG):
text = Text.from_tree(node).content
text = text.replace('x005F_', )
node.clear()
strings.append(text)
return strings | def read_string_table(xml_source):
strings = []
src = _get_xml_iter(xml_source)
STRING_TAG = ('{%s}si' % SHEET_MAIN_NS)
for (_, node) in iterparse(src):
if (node.tag == STRING_TAG):
text = Text.from_tree(node).content
text = text.replace('x005F_', )
node.clear()
strings.append(text)
return strings<|docstring|>Read in all shared strings in the table<|endoftext|> |
6714dd1b6a1a96a1c347923ec4e317e79bc98b6fb31558cd2f69c96253561f1c | def floats():
'\n Helper function to generate parsable floats, we exclude inf, nan and\n negative. Negatives are tested explicitly.\n '
return _floats(min_value=0, allow_infinity=False, allow_nan=False) | Helper function to generate parsable floats, we exclude inf, nan and
negative. Negatives are tested explicitly. | tests/transformer/strategies.py | floats | stufraser1/OasisDataConverter | 2 | python | def floats():
'\n Helper function to generate parsable floats, we exclude inf, nan and\n negative. Negatives are tested explicitly.\n '
return _floats(min_value=0, allow_infinity=False, allow_nan=False) | def floats():
'\n Helper function to generate parsable floats, we exclude inf, nan and\n negative. Negatives are tested explicitly.\n '
return _floats(min_value=0, allow_infinity=False, allow_nan=False)<|docstring|>Helper function to generate parsable floats, we exclude inf, nan and
negative. Negatives are tested explicitly.<|endoftext|> |
0990ce8379fd96d2764c6eacbdb3f97972f7ba07c70a0dabc32c2e758a087ccf | def integers():
'\n Helper function to generate parsable integers, we exclude negative\n as these are tested explicitly.\n '
return _integers(min_value=0, max_value=1000000) | Helper function to generate parsable integers, we exclude negative
as these are tested explicitly. | tests/transformer/strategies.py | integers | stufraser1/OasisDataConverter | 2 | python | def integers():
'\n Helper function to generate parsable integers, we exclude negative\n as these are tested explicitly.\n '
return _integers(min_value=0, max_value=1000000) | def integers():
'\n Helper function to generate parsable integers, we exclude negative\n as these are tested explicitly.\n '
return _integers(min_value=0, max_value=1000000)<|docstring|>Helper function to generate parsable integers, we exclude negative
as these are tested explicitly.<|endoftext|> |
e41b23d53d171d5f52cd66a934549128b20b186325d7e64932f30ef1d233edfc | def strings():
"\n Helper for generating parsable strings excluding ' and ` as they\n needs to be escaped and are tested explicitly\n "
return text(alphabet=characters(blacklist_categories=('Cs',), blacklist_characters=("'", '`'))) | Helper for generating parsable strings excluding ' and ` as they
needs to be escaped and are tested explicitly | tests/transformer/strategies.py | strings | stufraser1/OasisDataConverter | 2 | python | def strings():
"\n Helper for generating parsable strings excluding ' and ` as they\n needs to be escaped and are tested explicitly\n "
return text(alphabet=characters(blacklist_categories=('Cs',), blacklist_characters=("'", '`'))) | def strings():
"\n Helper for generating parsable strings excluding ' and ` as they\n needs to be escaped and are tested explicitly\n "
return text(alphabet=characters(blacklist_categories=('Cs',), blacklist_characters=("'", '`')))<|docstring|>Helper for generating parsable strings excluding ' and ` as they
needs to be escaped and are tested explicitly<|endoftext|> |
36e6dc9c6efc9dd6a86838d5448e47b5058f4e3cd29892aee885e589bc4a62ea | def fixxpath(root, xpath):
'ElementTree wants namespaces in its xpaths, so here we add them.'
(namespace, root_tag) = root.tag[1:].split('}', 1)
fixed_xpath = '/'.join([('{%s}%s' % (namespace, e)) for e in xpath.split('/')])
return fixed_xpath | ElementTree wants namespaces in its xpaths, so here we add them. | libcloud/compute/drivers/vcloud.py | fixxpath | ggreer/libcloud | 1 | python | def fixxpath(root, xpath):
(namespace, root_tag) = root.tag[1:].split('}', 1)
fixed_xpath = '/'.join([('{%s}%s' % (namespace, e)) for e in xpath.split('/')])
return fixed_xpath | def fixxpath(root, xpath):
(namespace, root_tag) = root.tag[1:].split('}', 1)
fixed_xpath = '/'.join([('{%s}%s' % (namespace, e)) for e in xpath.split('/')])
return fixed_xpath<|docstring|>ElementTree wants namespaces in its xpaths, so here we add them.<|endoftext|> |
6b9fa98ceb1a5705b1a98fc5ba5edd7ea764956e2f4dd91f31b9ee9c33f498e5 | def _get_auth_headers(self):
'Some providers need different headers than others'
return {'Authorization': ('Basic %s' % base64.b64encode(b(('%s:%s' % (self.user_id, self.key)))).decode('utf-8')), 'Content-Length': 0, 'Accept': 'application/*+xml'} | Some providers need different headers than others | libcloud/compute/drivers/vcloud.py | _get_auth_headers | ggreer/libcloud | 1 | python | def _get_auth_headers(self):
return {'Authorization': ('Basic %s' % base64.b64encode(b(('%s:%s' % (self.user_id, self.key)))).decode('utf-8')), 'Content-Length': 0, 'Accept': 'application/*+xml'} | def _get_auth_headers(self):
return {'Authorization': ('Basic %s' % base64.b64encode(b(('%s:%s' % (self.user_id, self.key)))).decode('utf-8')), 'Content-Length': 0, 'Accept': 'application/*+xml'}<|docstring|>Some providers need different headers than others<|endoftext|> |
776ac6c40afde39564dcebc8828fd49d89d306b81dbd294010c46a3b8cdf99c0 | @property
def vdcs(self):
'\n vCloud virtual data centers (vDCs).\n @return: C{list} of L{Vdc} objects\n '
if (not self._vdcs):
self.connection.check_org()
res = self.connection.request(self.org)
self._vdcs = [Vdc(i.get('href'), i.get('name'), self) for i in res.object.findall(fixxpath(res.object, 'Link')) if (i.get('type') == 'application/vnd.vmware.vcloud.vdc+xml')]
return self._vdcs | vCloud virtual data centers (vDCs).
@return: C{list} of L{Vdc} objects | libcloud/compute/drivers/vcloud.py | vdcs | ggreer/libcloud | 1 | python | @property
def vdcs(self):
'\n vCloud virtual data centers (vDCs).\n @return: C{list} of L{Vdc} objects\n '
if (not self._vdcs):
self.connection.check_org()
res = self.connection.request(self.org)
self._vdcs = [Vdc(i.get('href'), i.get('name'), self) for i in res.object.findall(fixxpath(res.object, 'Link')) if (i.get('type') == 'application/vnd.vmware.vcloud.vdc+xml')]
return self._vdcs | @property
def vdcs(self):
'\n vCloud virtual data centers (vDCs).\n @return: C{list} of L{Vdc} objects\n '
if (not self._vdcs):
self.connection.check_org()
res = self.connection.request(self.org)
self._vdcs = [Vdc(i.get('href'), i.get('name'), self) for i in res.object.findall(fixxpath(res.object, 'Link')) if (i.get('type') == 'application/vnd.vmware.vcloud.vdc+xml')]
return self._vdcs<|docstring|>vCloud virtual data centers (vDCs).
@return: C{list} of L{Vdc} objects<|endoftext|> |
24c6a286767366e0993371e0b01b58c72a3c4ff4a164b81d8ffa932750080eef | def _get_catalogitems_hrefs(self, catalog):
'Given a catalog href returns contained catalog item hrefs'
res = self.connection.request(catalog, headers={'Content-Type': 'application/vnd.vmware.vcloud.catalog+xml'}).object
cat_items = res.findall(fixxpath(res, 'CatalogItems/CatalogItem'))
cat_item_hrefs = [i.get('href') for i in cat_items if (i.get('type') == 'application/vnd.vmware.vcloud.catalogItem+xml')]
return cat_item_hrefs | Given a catalog href returns contained catalog item hrefs | libcloud/compute/drivers/vcloud.py | _get_catalogitems_hrefs | ggreer/libcloud | 1 | python | def _get_catalogitems_hrefs(self, catalog):
res = self.connection.request(catalog, headers={'Content-Type': 'application/vnd.vmware.vcloud.catalog+xml'}).object
cat_items = res.findall(fixxpath(res, 'CatalogItems/CatalogItem'))
cat_item_hrefs = [i.get('href') for i in cat_items if (i.get('type') == 'application/vnd.vmware.vcloud.catalogItem+xml')]
return cat_item_hrefs | def _get_catalogitems_hrefs(self, catalog):
res = self.connection.request(catalog, headers={'Content-Type': 'application/vnd.vmware.vcloud.catalog+xml'}).object
cat_items = res.findall(fixxpath(res, 'CatalogItems/CatalogItem'))
cat_item_hrefs = [i.get('href') for i in cat_items if (i.get('type') == 'application/vnd.vmware.vcloud.catalogItem+xml')]
return cat_item_hrefs<|docstring|>Given a catalog href returns contained catalog item hrefs<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.