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 |
|---|---|---|---|---|---|---|---|---|---|
454fbb869ab9c0f5ccf08454e5b122bde74e5bf1f8200181054c3c0776532362 | @commands.command(name='discordgramreply', aliases=['dgr'])
async def discordgramreply(self, ctx, discordgram_id, *, msg):
'Reply to Discordgram by ID.'
guild = ctx.guild
channel_id = (await self.config.guild(guild).channel_id())
if (channel_id is None):
return
try:
discordgram_id = int(discordgram_id)
except ValueError:
bot_msg = (await ctx.send('discordgram_id must be a number'))
(await bot_msg.delete(delay=5))
return
author = ctx.author
messages = (await self.config.guild(guild).messages())
if (discordgram_id >= len(messages)):
bot_msg = (await ctx.send('This is not a valid Discordgram id'))
(await bot_msg.delete(delay=5))
return
message = None
for m in messages:
if (m.get('discordgram_id') == discordgram_id):
message = m
if (message is None):
bot_msg = (await ctx.send('Cannot find the discordgram'))
(await bot_msg.delete(delay=5))
return
channel = self.bot.get_channel(channel_id)
dg_message = DGMessage.parse_obj(message)
bot_msg = (await channel.fetch_message(dg_message.bot_message_id))
em = bot_msg.embeds[0]
em.add_field(name=author.display_name, value=msg, inline=False)
em.timestamp = dt.datetime.now(tz=dt.timezone.utc)
(await bot_msg.edit(embed=em)) | Reply to Discordgram by ID. | discordgram/dicsordgram.py | discordgramreply | smlbiobot/SML-Cogs-v3 | 5 | python | @commands.command(name='discordgramreply', aliases=['dgr'])
async def discordgramreply(self, ctx, discordgram_id, *, msg):
guild = ctx.guild
channel_id = (await self.config.guild(guild).channel_id())
if (channel_id is None):
return
try:
discordgram_id = int(discordgram_id)
except ValueError:
bot_msg = (await ctx.send('discordgram_id must be a number'))
(await bot_msg.delete(delay=5))
return
author = ctx.author
messages = (await self.config.guild(guild).messages())
if (discordgram_id >= len(messages)):
bot_msg = (await ctx.send('This is not a valid Discordgram id'))
(await bot_msg.delete(delay=5))
return
message = None
for m in messages:
if (m.get('discordgram_id') == discordgram_id):
message = m
if (message is None):
bot_msg = (await ctx.send('Cannot find the discordgram'))
(await bot_msg.delete(delay=5))
return
channel = self.bot.get_channel(channel_id)
dg_message = DGMessage.parse_obj(message)
bot_msg = (await channel.fetch_message(dg_message.bot_message_id))
em = bot_msg.embeds[0]
em.add_field(name=author.display_name, value=msg, inline=False)
em.timestamp = dt.datetime.now(tz=dt.timezone.utc)
(await bot_msg.edit(embed=em)) | @commands.command(name='discordgramreply', aliases=['dgr'])
async def discordgramreply(self, ctx, discordgram_id, *, msg):
guild = ctx.guild
channel_id = (await self.config.guild(guild).channel_id())
if (channel_id is None):
return
try:
discordgram_id = int(discordgram_id)
except ValueError:
bot_msg = (await ctx.send('discordgram_id must be a number'))
(await bot_msg.delete(delay=5))
return
author = ctx.author
messages = (await self.config.guild(guild).messages())
if (discordgram_id >= len(messages)):
bot_msg = (await ctx.send('This is not a valid Discordgram id'))
(await bot_msg.delete(delay=5))
return
message = None
for m in messages:
if (m.get('discordgram_id') == discordgram_id):
message = m
if (message is None):
bot_msg = (await ctx.send('Cannot find the discordgram'))
(await bot_msg.delete(delay=5))
return
channel = self.bot.get_channel(channel_id)
dg_message = DGMessage.parse_obj(message)
bot_msg = (await channel.fetch_message(dg_message.bot_message_id))
em = bot_msg.embeds[0]
em.add_field(name=author.display_name, value=msg, inline=False)
em.timestamp = dt.datetime.now(tz=dt.timezone.utc)
(await bot_msg.edit(embed=em))<|docstring|>Reply to Discordgram by ID.<|endoftext|> |
40c12c1798cac0e56f1f553a02fbb0a9d9af07b435f5d74f98d6f583cd0dcbe8 | def is_valid_path(file_path):
'\n Check if the given path is any of the invalid file type in the given constants.py\n\n :param file_path: `str` abs file path\n :return: `bool` returns True if is valid file otherwise False\n '
if os.path.isfile(file_path):
ext = os.path.splitext(file_path)[(- 1)]
if (ext in scm_constants.INVALID_FORMATS):
return False
for token in scm_constants.INVALID_FORMATS:
if (token == str(file_path)):
return False
if (token in str(file_path)):
return False
return True | Check if the given path is any of the invalid file type in the given constants.py
:param file_path: `str` abs file path
:return: `bool` returns True if is valid file otherwise False | common.py | is_valid_path | arjun-namdeo/scm_tools | 0 | python | def is_valid_path(file_path):
'\n Check if the given path is any of the invalid file type in the given constants.py\n\n :param file_path: `str` abs file path\n :return: `bool` returns True if is valid file otherwise False\n '
if os.path.isfile(file_path):
ext = os.path.splitext(file_path)[(- 1)]
if (ext in scm_constants.INVALID_FORMATS):
return False
for token in scm_constants.INVALID_FORMATS:
if (token == str(file_path)):
return False
if (token in str(file_path)):
return False
return True | def is_valid_path(file_path):
'\n Check if the given path is any of the invalid file type in the given constants.py\n\n :param file_path: `str` abs file path\n :return: `bool` returns True if is valid file otherwise False\n '
if os.path.isfile(file_path):
ext = os.path.splitext(file_path)[(- 1)]
if (ext in scm_constants.INVALID_FORMATS):
return False
for token in scm_constants.INVALID_FORMATS:
if (token == str(file_path)):
return False
if (token in str(file_path)):
return False
return True<|docstring|>Check if the given path is any of the invalid file type in the given constants.py
:param file_path: `str` abs file path
:return: `bool` returns True if is valid file otherwise False<|endoftext|> |
81ac90044ac34a705d14300c4a407a293a2d1571d8da5c2aac442feec0e266ff | def scm_install_package(source, for_qc=False, override=False):
'\n Compile the source code and generate a skeleton for production use.\n This method will take your active directory and\n\n :param source: s\n :param for_qc:\n :param override: `bool` Override old files.?\n :return:\n '
if for_qc:
installation_path = os.path.join(scm_constants.PY_TESTING_DIR, os.path.basename(source))
file_manager.create_symlinks(source=source, destination=installation_path, override=override)
return True
installation_path = os.path.join(scm_constants.PY_BUILDS_DIR, os.path.basename(source))
if (not os.path.isdir(installation_path)):
os.makedirs(installation_path)
for (root, dirs, files) in os.walk(source):
if (not is_valid_path(file_path=root)):
continue
for each_file in files:
if (not is_valid_path(file_path=each_file)):
continue
file_path = os.path.join(root, each_file)
dest_path = file_path.replace(source, installation_path)
logger.debug("Installing : '{0}'".format(each_file))
file_manager.copy_files(src_path=file_path, dst_path=dest_path) | Compile the source code and generate a skeleton for production use.
This method will take your active directory and
:param source: s
:param for_qc:
:param override: `bool` Override old files.?
:return: | common.py | scm_install_package | arjun-namdeo/scm_tools | 0 | python | def scm_install_package(source, for_qc=False, override=False):
'\n Compile the source code and generate a skeleton for production use.\n This method will take your active directory and\n\n :param source: s\n :param for_qc:\n :param override: `bool` Override old files.?\n :return:\n '
if for_qc:
installation_path = os.path.join(scm_constants.PY_TESTING_DIR, os.path.basename(source))
file_manager.create_symlinks(source=source, destination=installation_path, override=override)
return True
installation_path = os.path.join(scm_constants.PY_BUILDS_DIR, os.path.basename(source))
if (not os.path.isdir(installation_path)):
os.makedirs(installation_path)
for (root, dirs, files) in os.walk(source):
if (not is_valid_path(file_path=root)):
continue
for each_file in files:
if (not is_valid_path(file_path=each_file)):
continue
file_path = os.path.join(root, each_file)
dest_path = file_path.replace(source, installation_path)
logger.debug("Installing : '{0}'".format(each_file))
file_manager.copy_files(src_path=file_path, dst_path=dest_path) | def scm_install_package(source, for_qc=False, override=False):
'\n Compile the source code and generate a skeleton for production use.\n This method will take your active directory and\n\n :param source: s\n :param for_qc:\n :param override: `bool` Override old files.?\n :return:\n '
if for_qc:
installation_path = os.path.join(scm_constants.PY_TESTING_DIR, os.path.basename(source))
file_manager.create_symlinks(source=source, destination=installation_path, override=override)
return True
installation_path = os.path.join(scm_constants.PY_BUILDS_DIR, os.path.basename(source))
if (not os.path.isdir(installation_path)):
os.makedirs(installation_path)
for (root, dirs, files) in os.walk(source):
if (not is_valid_path(file_path=root)):
continue
for each_file in files:
if (not is_valid_path(file_path=each_file)):
continue
file_path = os.path.join(root, each_file)
dest_path = file_path.replace(source, installation_path)
logger.debug("Installing : '{0}'".format(each_file))
file_manager.copy_files(src_path=file_path, dst_path=dest_path)<|docstring|>Compile the source code and generate a skeleton for production use.
This method will take your active directory and
:param source: s
:param for_qc:
:param override: `bool` Override old files.?
:return:<|endoftext|> |
74cb4b0840ab29f535c752481807cb57c2919f7732841acee35e614e61bb1fbf | def scm_install_bin_files(bin_directory, for_qc=False, override=False):
'\n Compile the source code and generate a skeleton for production use.\n This method will take your active directory and\n\n :param bin_directory: s\n :param for_qc:\n :param override: `bool` Override old files.?\n :return:\n '
if (not os.path.isdir(bin_directory)):
logger.warning('Expected a bin/script directory. Found file.!')
return False
install_dir = (scm_constants.BIN_TESTING_DIR if for_qc else scm_constants.BIN_BUILDS_DIR)
existing_files = list()
for bin_file in os.listdir(bin_directory):
src_file_path = os.path.join(bin_directory, bin_file)
dst_file_path = os.path.join(install_dir, bin_file)
if (os.path.exists(dst_file_path) and (not override)):
existing_files.append(dst_file_path)
continue
if for_qc:
logger.info("Installing for testing: '{0}' >>> '{1}' ".format(src_file_path, dst_file_path))
file_manager.create_symlinks(source=src_file_path, destination=dst_file_path)
else:
logger.info("Installing package: '{0}' >>> '{1}' ".format(src_file_path, dst_file_path))
file_manager.copy_files(src_path=src_file_path, dst_path=dst_file_path)
if existing_files:
msg = 'File(s) already exists in the destination place. Please use force/override command to overwrite them.'
logger.info(msg)
return True | Compile the source code and generate a skeleton for production use.
This method will take your active directory and
:param bin_directory: s
:param for_qc:
:param override: `bool` Override old files.?
:return: | common.py | scm_install_bin_files | arjun-namdeo/scm_tools | 0 | python | def scm_install_bin_files(bin_directory, for_qc=False, override=False):
'\n Compile the source code and generate a skeleton for production use.\n This method will take your active directory and\n\n :param bin_directory: s\n :param for_qc:\n :param override: `bool` Override old files.?\n :return:\n '
if (not os.path.isdir(bin_directory)):
logger.warning('Expected a bin/script directory. Found file.!')
return False
install_dir = (scm_constants.BIN_TESTING_DIR if for_qc else scm_constants.BIN_BUILDS_DIR)
existing_files = list()
for bin_file in os.listdir(bin_directory):
src_file_path = os.path.join(bin_directory, bin_file)
dst_file_path = os.path.join(install_dir, bin_file)
if (os.path.exists(dst_file_path) and (not override)):
existing_files.append(dst_file_path)
continue
if for_qc:
logger.info("Installing for testing: '{0}' >>> '{1}' ".format(src_file_path, dst_file_path))
file_manager.create_symlinks(source=src_file_path, destination=dst_file_path)
else:
logger.info("Installing package: '{0}' >>> '{1}' ".format(src_file_path, dst_file_path))
file_manager.copy_files(src_path=src_file_path, dst_path=dst_file_path)
if existing_files:
msg = 'File(s) already exists in the destination place. Please use force/override command to overwrite them.'
logger.info(msg)
return True | def scm_install_bin_files(bin_directory, for_qc=False, override=False):
'\n Compile the source code and generate a skeleton for production use.\n This method will take your active directory and\n\n :param bin_directory: s\n :param for_qc:\n :param override: `bool` Override old files.?\n :return:\n '
if (not os.path.isdir(bin_directory)):
logger.warning('Expected a bin/script directory. Found file.!')
return False
install_dir = (scm_constants.BIN_TESTING_DIR if for_qc else scm_constants.BIN_BUILDS_DIR)
existing_files = list()
for bin_file in os.listdir(bin_directory):
src_file_path = os.path.join(bin_directory, bin_file)
dst_file_path = os.path.join(install_dir, bin_file)
if (os.path.exists(dst_file_path) and (not override)):
existing_files.append(dst_file_path)
continue
if for_qc:
logger.info("Installing for testing: '{0}' >>> '{1}' ".format(src_file_path, dst_file_path))
file_manager.create_symlinks(source=src_file_path, destination=dst_file_path)
else:
logger.info("Installing package: '{0}' >>> '{1}' ".format(src_file_path, dst_file_path))
file_manager.copy_files(src_path=src_file_path, dst_path=dst_file_path)
if existing_files:
msg = 'File(s) already exists in the destination place. Please use force/override command to overwrite them.'
logger.info(msg)
return True<|docstring|>Compile the source code and generate a skeleton for production use.
This method will take your active directory and
:param bin_directory: s
:param for_qc:
:param override: `bool` Override old files.?
:return:<|endoftext|> |
a3807c6d3eb9a8fe79a621eef4a3ccd5f4f50685c26c1e527275c3dd40c048fa | def AddInnerProfile(self, innerProfile):
'\n AddInnerProfile(self: Extrusion,innerProfile: Curve) -> bool\n\n \n\n Adds an inner profile.\n\n \n\n innerProfile: Closed curve in the XY plane or a 2d curve.\n\n Returns: true if the profile was set.\n '
pass | AddInnerProfile(self: Extrusion,innerProfile: Curve) -> bool
Adds an inner profile.
innerProfile: Closed curve in the XY plane or a 2d curve.
Returns: true if the profile was set. | release/stubs.min/Rhino/Geometry/__init___parts/Extrusion.py | AddInnerProfile | htlcnn/ironpython-stubs | 182 | python | def AddInnerProfile(self, innerProfile):
'\n AddInnerProfile(self: Extrusion,innerProfile: Curve) -> bool\n\n \n\n Adds an inner profile.\n\n \n\n innerProfile: Closed curve in the XY plane or a 2d curve.\n\n Returns: true if the profile was set.\n '
pass | def AddInnerProfile(self, innerProfile):
'\n AddInnerProfile(self: Extrusion,innerProfile: Curve) -> bool\n\n \n\n Adds an inner profile.\n\n \n\n innerProfile: Closed curve in the XY plane or a 2d curve.\n\n Returns: true if the profile was set.\n '
pass<|docstring|>AddInnerProfile(self: Extrusion,innerProfile: Curve) -> bool
Adds an inner profile.
innerProfile: Closed curve in the XY plane or a 2d curve.
Returns: true if the profile was set.<|endoftext|> |
df710cf55686b186fb68605b821de82625eda614279cde7b57f65d93a2c9026f | def ConstructConstObject(self, *args):
'\n ConstructConstObject(self: CommonObject,parentObject: object,subobject_index: int)\n\n Assigns a parent object and a subobject index to this.\n\n \n\n parentObject: The parent object.\n\n subobject_index: The subobject index.\n '
pass | ConstructConstObject(self: CommonObject,parentObject: object,subobject_index: int)
Assigns a parent object and a subobject index to this.
parentObject: The parent object.
subobject_index: The subobject index. | release/stubs.min/Rhino/Geometry/__init___parts/Extrusion.py | ConstructConstObject | htlcnn/ironpython-stubs | 182 | python | def ConstructConstObject(self, *args):
'\n ConstructConstObject(self: CommonObject,parentObject: object,subobject_index: int)\n\n Assigns a parent object and a subobject index to this.\n\n \n\n parentObject: The parent object.\n\n subobject_index: The subobject index.\n '
pass | def ConstructConstObject(self, *args):
'\n ConstructConstObject(self: CommonObject,parentObject: object,subobject_index: int)\n\n Assigns a parent object and a subobject index to this.\n\n \n\n parentObject: The parent object.\n\n subobject_index: The subobject index.\n '
pass<|docstring|>ConstructConstObject(self: CommonObject,parentObject: object,subobject_index: int)
Assigns a parent object and a subobject index to this.
parentObject: The parent object.
subobject_index: The subobject index.<|endoftext|> |
de3962c1a92cd0f2d37482ce9a3e61c9a4181210a54aad06e14609dca27ed4f9 | @staticmethod
def Create(planarCurve, height, cap):
"\n Create(planarCurve: Curve,height: float,cap: bool) -> Extrusion\n\n \n\n Creates an extrusion of a 3d curve (which must be planar) and a height.\n\n \n\n planarCurve: Planar curve used as profile\n\n height: If the height > 0,the bottom of the extrusion will be in plane and\n\n the top will be \n\n height units above the plane.\n\n If the height < 0,the top of the extrusion will be \n\n in plane and\n\n the bottom will be height units below the plane.\n\n The \n\n plane used is the one that is returned from the curve's TryGetPlane function.\n\n \n\n cap: If the curve is closed and cap is true,then the resulting extrusion is capped.\n\n Returns: If the input is valid,then a new extrusion is returned. Otherwise null is returned\n "
pass | Create(planarCurve: Curve,height: float,cap: bool) -> Extrusion
Creates an extrusion of a 3d curve (which must be planar) and a height.
planarCurve: Planar curve used as profile
height: If the height > 0,the bottom of the extrusion will be in plane and
the top will be
height units above the plane.
If the height < 0,the top of the extrusion will be
in plane and
the bottom will be height units below the plane.
The
plane used is the one that is returned from the curve's TryGetPlane function.
cap: If the curve is closed and cap is true,then the resulting extrusion is capped.
Returns: If the input is valid,then a new extrusion is returned. Otherwise null is returned | release/stubs.min/Rhino/Geometry/__init___parts/Extrusion.py | Create | htlcnn/ironpython-stubs | 182 | python | @staticmethod
def Create(planarCurve, height, cap):
"\n Create(planarCurve: Curve,height: float,cap: bool) -> Extrusion\n\n \n\n Creates an extrusion of a 3d curve (which must be planar) and a height.\n\n \n\n planarCurve: Planar curve used as profile\n\n height: If the height > 0,the bottom of the extrusion will be in plane and\n\n the top will be \n\n height units above the plane.\n\n If the height < 0,the top of the extrusion will be \n\n in plane and\n\n the bottom will be height units below the plane.\n\n The \n\n plane used is the one that is returned from the curve's TryGetPlane function.\n\n \n\n cap: If the curve is closed and cap is true,then the resulting extrusion is capped.\n\n Returns: If the input is valid,then a new extrusion is returned. Otherwise null is returned\n "
pass | @staticmethod
def Create(planarCurve, height, cap):
"\n Create(planarCurve: Curve,height: float,cap: bool) -> Extrusion\n\n \n\n Creates an extrusion of a 3d curve (which must be planar) and a height.\n\n \n\n planarCurve: Planar curve used as profile\n\n height: If the height > 0,the bottom of the extrusion will be in plane and\n\n the top will be \n\n height units above the plane.\n\n If the height < 0,the top of the extrusion will be \n\n in plane and\n\n the bottom will be height units below the plane.\n\n The \n\n plane used is the one that is returned from the curve's TryGetPlane function.\n\n \n\n cap: If the curve is closed and cap is true,then the resulting extrusion is capped.\n\n Returns: If the input is valid,then a new extrusion is returned. Otherwise null is returned\n "
pass<|docstring|>Create(planarCurve: Curve,height: float,cap: bool) -> Extrusion
Creates an extrusion of a 3d curve (which must be planar) and a height.
planarCurve: Planar curve used as profile
height: If the height > 0,the bottom of the extrusion will be in plane and
the top will be
height units above the plane.
If the height < 0,the top of the extrusion will be
in plane and
the bottom will be height units below the plane.
The
plane used is the one that is returned from the curve's TryGetPlane function.
cap: If the curve is closed and cap is true,then the resulting extrusion is capped.
Returns: If the input is valid,then a new extrusion is returned. Otherwise null is returned<|endoftext|> |
8fe42a248ca211ef811d3efd3a3476c9e1a9a584039af5d31a446b1658a89478 | @staticmethod
def CreateCylinderExtrusion(cylinder, capBottom, capTop):
'\n CreateCylinderExtrusion(cylinder: Cylinder,capBottom: bool,capTop: bool) -> Extrusion\n\n \n\n Gets an extrusion form of a cylinder.\n\n \n\n cylinder: IsFinite must be true.\n\n capBottom: If true,the end at cylinder.Height1 will be capped.\n\n capTop: If true,the end at cylinder.Height2 will be capped.\n\n Returns: Extrusion on success. null on failure.\n '
pass | CreateCylinderExtrusion(cylinder: Cylinder,capBottom: bool,capTop: bool) -> Extrusion
Gets an extrusion form of a cylinder.
cylinder: IsFinite must be true.
capBottom: If true,the end at cylinder.Height1 will be capped.
capTop: If true,the end at cylinder.Height2 will be capped.
Returns: Extrusion on success. null on failure. | release/stubs.min/Rhino/Geometry/__init___parts/Extrusion.py | CreateCylinderExtrusion | htlcnn/ironpython-stubs | 182 | python | @staticmethod
def CreateCylinderExtrusion(cylinder, capBottom, capTop):
'\n CreateCylinderExtrusion(cylinder: Cylinder,capBottom: bool,capTop: bool) -> Extrusion\n\n \n\n Gets an extrusion form of a cylinder.\n\n \n\n cylinder: IsFinite must be true.\n\n capBottom: If true,the end at cylinder.Height1 will be capped.\n\n capTop: If true,the end at cylinder.Height2 will be capped.\n\n Returns: Extrusion on success. null on failure.\n '
pass | @staticmethod
def CreateCylinderExtrusion(cylinder, capBottom, capTop):
'\n CreateCylinderExtrusion(cylinder: Cylinder,capBottom: bool,capTop: bool) -> Extrusion\n\n \n\n Gets an extrusion form of a cylinder.\n\n \n\n cylinder: IsFinite must be true.\n\n capBottom: If true,the end at cylinder.Height1 will be capped.\n\n capTop: If true,the end at cylinder.Height2 will be capped.\n\n Returns: Extrusion on success. null on failure.\n '
pass<|docstring|>CreateCylinderExtrusion(cylinder: Cylinder,capBottom: bool,capTop: bool) -> Extrusion
Gets an extrusion form of a cylinder.
cylinder: IsFinite must be true.
capBottom: If true,the end at cylinder.Height1 will be capped.
capTop: If true,the end at cylinder.Height2 will be capped.
Returns: Extrusion on success. null on failure.<|endoftext|> |
1819aba8e5c657cb80852d058c29c496a51b15c12ba58860b86d2d5addec3e56 | @staticmethod
def CreatePipeExtrusion(cylinder, otherRadius, capTop, capBottom):
'\n CreatePipeExtrusion(cylinder: Cylinder,otherRadius: float,capTop: bool,capBottom: bool) -> Extrusion\n\n \n\n Gets an extrusion form of a pipe.\n\n \n\n cylinder: IsFinite must be true.\n\n otherRadius: If cylinder.Radius is less than other radius,then the cylinder will be the inside\n\n \n\n of the pipe.\n\n \n\n capTop: If true,the end at cylinder.Height2 will be capped.\n\n capBottom: If true,the end at cylinder.Height1 will be capped.\n\n Returns: Extrusion on success. null on failure.\n '
pass | CreatePipeExtrusion(cylinder: Cylinder,otherRadius: float,capTop: bool,capBottom: bool) -> Extrusion
Gets an extrusion form of a pipe.
cylinder: IsFinite must be true.
otherRadius: If cylinder.Radius is less than other radius,then the cylinder will be the inside
of the pipe.
capTop: If true,the end at cylinder.Height2 will be capped.
capBottom: If true,the end at cylinder.Height1 will be capped.
Returns: Extrusion on success. null on failure. | release/stubs.min/Rhino/Geometry/__init___parts/Extrusion.py | CreatePipeExtrusion | htlcnn/ironpython-stubs | 182 | python | @staticmethod
def CreatePipeExtrusion(cylinder, otherRadius, capTop, capBottom):
'\n CreatePipeExtrusion(cylinder: Cylinder,otherRadius: float,capTop: bool,capBottom: bool) -> Extrusion\n\n \n\n Gets an extrusion form of a pipe.\n\n \n\n cylinder: IsFinite must be true.\n\n otherRadius: If cylinder.Radius is less than other radius,then the cylinder will be the inside\n\n \n\n of the pipe.\n\n \n\n capTop: If true,the end at cylinder.Height2 will be capped.\n\n capBottom: If true,the end at cylinder.Height1 will be capped.\n\n Returns: Extrusion on success. null on failure.\n '
pass | @staticmethod
def CreatePipeExtrusion(cylinder, otherRadius, capTop, capBottom):
'\n CreatePipeExtrusion(cylinder: Cylinder,otherRadius: float,capTop: bool,capBottom: bool) -> Extrusion\n\n \n\n Gets an extrusion form of a pipe.\n\n \n\n cylinder: IsFinite must be true.\n\n otherRadius: If cylinder.Radius is less than other radius,then the cylinder will be the inside\n\n \n\n of the pipe.\n\n \n\n capTop: If true,the end at cylinder.Height2 will be capped.\n\n capBottom: If true,the end at cylinder.Height1 will be capped.\n\n Returns: Extrusion on success. null on failure.\n '
pass<|docstring|>CreatePipeExtrusion(cylinder: Cylinder,otherRadius: float,capTop: bool,capBottom: bool) -> Extrusion
Gets an extrusion form of a pipe.
cylinder: IsFinite must be true.
otherRadius: If cylinder.Radius is less than other radius,then the cylinder will be the inside
of the pipe.
capTop: If true,the end at cylinder.Height2 will be capped.
capBottom: If true,the end at cylinder.Height1 will be capped.
Returns: Extrusion on success. null on failure.<|endoftext|> |
f0cc5bae375b4a8b07308b2c7b3ce1b269bcbf8072bea17301ad2a1babc7924c | def Dispose(self):
'\n Dispose(self: CommonObject,disposing: bool)\n\n For derived class implementers.\n\n This method is called with argument true when class \n\n user calls Dispose(),while with argument false when\n\n the Garbage Collector invokes \n\n the finalizer,or Finalize() method.You must reclaim all used unmanaged resources in both cases,\n\n and can use this chance to call Dispose on disposable fields if the argument is true.Also,you \n\n must call the base virtual method within your overriding method.\n\n \n\n \n\n disposing: true if the call comes from the Dispose() method; false if it comes from the Garbage Collector \n\n finalizer.\n '
pass | Dispose(self: CommonObject,disposing: bool)
For derived class implementers.
This method is called with argument true when class
user calls Dispose(),while with argument false when
the Garbage Collector invokes
the finalizer,or Finalize() method.You must reclaim all used unmanaged resources in both cases,
and can use this chance to call Dispose on disposable fields if the argument is true.Also,you
must call the base virtual method within your overriding method.
disposing: true if the call comes from the Dispose() method; false if it comes from the Garbage Collector
finalizer. | release/stubs.min/Rhino/Geometry/__init___parts/Extrusion.py | Dispose | htlcnn/ironpython-stubs | 182 | python | def Dispose(self):
'\n Dispose(self: CommonObject,disposing: bool)\n\n For derived class implementers.\n\n This method is called with argument true when class \n\n user calls Dispose(),while with argument false when\n\n the Garbage Collector invokes \n\n the finalizer,or Finalize() method.You must reclaim all used unmanaged resources in both cases,\n\n and can use this chance to call Dispose on disposable fields if the argument is true.Also,you \n\n must call the base virtual method within your overriding method.\n\n \n\n \n\n disposing: true if the call comes from the Dispose() method; false if it comes from the Garbage Collector \n\n finalizer.\n '
pass | def Dispose(self):
'\n Dispose(self: CommonObject,disposing: bool)\n\n For derived class implementers.\n\n This method is called with argument true when class \n\n user calls Dispose(),while with argument false when\n\n the Garbage Collector invokes \n\n the finalizer,or Finalize() method.You must reclaim all used unmanaged resources in both cases,\n\n and can use this chance to call Dispose on disposable fields if the argument is true.Also,you \n\n must call the base virtual method within your overriding method.\n\n \n\n \n\n disposing: true if the call comes from the Dispose() method; false if it comes from the Garbage Collector \n\n finalizer.\n '
pass<|docstring|>Dispose(self: CommonObject,disposing: bool)
For derived class implementers.
This method is called with argument true when class
user calls Dispose(),while with argument false when
the Garbage Collector invokes
the finalizer,or Finalize() method.You must reclaim all used unmanaged resources in both cases,
and can use this chance to call Dispose on disposable fields if the argument is true.Also,you
must call the base virtual method within your overriding method.
disposing: true if the call comes from the Dispose() method; false if it comes from the Garbage Collector
finalizer.<|endoftext|> |
cd554768ab3cb16457ab5c49bbfff0010484ce4b9119872dfa23890e6134df63 | def GetMesh(self, meshType):
'\n GetMesh(self: Extrusion,meshType: MeshType) -> Mesh\n\n \n\n Obtains a reference to a specified type of mesh for this extrusion.\n\n \n\n meshType: The mesh type.\n\n Returns: A mesh.\n '
pass | GetMesh(self: Extrusion,meshType: MeshType) -> Mesh
Obtains a reference to a specified type of mesh for this extrusion.
meshType: The mesh type.
Returns: A mesh. | release/stubs.min/Rhino/Geometry/__init___parts/Extrusion.py | GetMesh | htlcnn/ironpython-stubs | 182 | python | def GetMesh(self, meshType):
'\n GetMesh(self: Extrusion,meshType: MeshType) -> Mesh\n\n \n\n Obtains a reference to a specified type of mesh for this extrusion.\n\n \n\n meshType: The mesh type.\n\n Returns: A mesh.\n '
pass | def GetMesh(self, meshType):
'\n GetMesh(self: Extrusion,meshType: MeshType) -> Mesh\n\n \n\n Obtains a reference to a specified type of mesh for this extrusion.\n\n \n\n meshType: The mesh type.\n\n Returns: A mesh.\n '
pass<|docstring|>GetMesh(self: Extrusion,meshType: MeshType) -> Mesh
Obtains a reference to a specified type of mesh for this extrusion.
meshType: The mesh type.
Returns: A mesh.<|endoftext|> |
bc462b4e448220cc069c45878cdf1857f8b62cf4d4116497f26122ebb499daac | def GetPathPlane(self, s):
'\n GetPathPlane(self: Extrusion,s: float) -> Plane\n\n \n\n Gets the 3D plane perpendicular to the path at a normalized path parameter.\n\n \n\n s: 0.0=starting profile\n\n 1.0=ending profile.\n\n Returns: A plane. The plane is Invalid on failure.\n '
pass | GetPathPlane(self: Extrusion,s: float) -> Plane
Gets the 3D plane perpendicular to the path at a normalized path parameter.
s: 0.0=starting profile
1.0=ending profile.
Returns: A plane. The plane is Invalid on failure. | release/stubs.min/Rhino/Geometry/__init___parts/Extrusion.py | GetPathPlane | htlcnn/ironpython-stubs | 182 | python | def GetPathPlane(self, s):
'\n GetPathPlane(self: Extrusion,s: float) -> Plane\n\n \n\n Gets the 3D plane perpendicular to the path at a normalized path parameter.\n\n \n\n s: 0.0=starting profile\n\n 1.0=ending profile.\n\n Returns: A plane. The plane is Invalid on failure.\n '
pass | def GetPathPlane(self, s):
'\n GetPathPlane(self: Extrusion,s: float) -> Plane\n\n \n\n Gets the 3D plane perpendicular to the path at a normalized path parameter.\n\n \n\n s: 0.0=starting profile\n\n 1.0=ending profile.\n\n Returns: A plane. The plane is Invalid on failure.\n '
pass<|docstring|>GetPathPlane(self: Extrusion,s: float) -> Plane
Gets the 3D plane perpendicular to the path at a normalized path parameter.
s: 0.0=starting profile
1.0=ending profile.
Returns: A plane. The plane is Invalid on failure.<|endoftext|> |
501d7c21a6e98920c3c698a3b1d76706bd20d04584c032eb15ac575cb6cce1f1 | def GetProfilePlane(self, s):
'\n GetProfilePlane(self: Extrusion,s: float) -> Plane\n\n \n\n Gets the 3D plane containing the profile curve at a normalized path parameter.\n\n \n\n s: 0.0=starting profile\n\n 1.0=ending profile.\n\n Returns: A plane. The plane is Invalid on failure.\n '
pass | GetProfilePlane(self: Extrusion,s: float) -> Plane
Gets the 3D plane containing the profile curve at a normalized path parameter.
s: 0.0=starting profile
1.0=ending profile.
Returns: A plane. The plane is Invalid on failure. | release/stubs.min/Rhino/Geometry/__init___parts/Extrusion.py | GetProfilePlane | htlcnn/ironpython-stubs | 182 | python | def GetProfilePlane(self, s):
'\n GetProfilePlane(self: Extrusion,s: float) -> Plane\n\n \n\n Gets the 3D plane containing the profile curve at a normalized path parameter.\n\n \n\n s: 0.0=starting profile\n\n 1.0=ending profile.\n\n Returns: A plane. The plane is Invalid on failure.\n '
pass | def GetProfilePlane(self, s):
'\n GetProfilePlane(self: Extrusion,s: float) -> Plane\n\n \n\n Gets the 3D plane containing the profile curve at a normalized path parameter.\n\n \n\n s: 0.0=starting profile\n\n 1.0=ending profile.\n\n Returns: A plane. The plane is Invalid on failure.\n '
pass<|docstring|>GetProfilePlane(self: Extrusion,s: float) -> Plane
Gets the 3D plane containing the profile curve at a normalized path parameter.
s: 0.0=starting profile
1.0=ending profile.
Returns: A plane. The plane is Invalid on failure.<|endoftext|> |
5206ee1cf7f2108442e948506a5ca84c3886010bcb68d57025a1d12663a4fd33 | def GetProfileTransformation(self, s):
'\n GetProfileTransformation(self: Extrusion,s: float) -> Transform\n\n \n\n Gets the transformation that maps the xy profile curve to its 3d location.\n\n \n\n s: 0.0=starting profile\n\n 1.0=ending profile.\n\n Returns: A Transformation. The transform is Invalid on failure.\n '
pass | GetProfileTransformation(self: Extrusion,s: float) -> Transform
Gets the transformation that maps the xy profile curve to its 3d location.
s: 0.0=starting profile
1.0=ending profile.
Returns: A Transformation. The transform is Invalid on failure. | release/stubs.min/Rhino/Geometry/__init___parts/Extrusion.py | GetProfileTransformation | htlcnn/ironpython-stubs | 182 | python | def GetProfileTransformation(self, s):
'\n GetProfileTransformation(self: Extrusion,s: float) -> Transform\n\n \n\n Gets the transformation that maps the xy profile curve to its 3d location.\n\n \n\n s: 0.0=starting profile\n\n 1.0=ending profile.\n\n Returns: A Transformation. The transform is Invalid on failure.\n '
pass | def GetProfileTransformation(self, s):
'\n GetProfileTransformation(self: Extrusion,s: float) -> Transform\n\n \n\n Gets the transformation that maps the xy profile curve to its 3d location.\n\n \n\n s: 0.0=starting profile\n\n 1.0=ending profile.\n\n Returns: A Transformation. The transform is Invalid on failure.\n '
pass<|docstring|>GetProfileTransformation(self: Extrusion,s: float) -> Transform
Gets the transformation that maps the xy profile curve to its 3d location.
s: 0.0=starting profile
1.0=ending profile.
Returns: A Transformation. The transform is Invalid on failure.<|endoftext|> |
e0683fd63848b379140c661688bcfe61c6337c8d8161d85e7d18ce15c1c808c3 | def GetWireframe(self):
'\n GetWireframe(self: Extrusion) -> Array[Curve]\n\n \n\n Constructs all the Wireframe curves for this Extrusion.\n\n Returns: An array of Wireframe curves.\n '
pass | GetWireframe(self: Extrusion) -> Array[Curve]
Constructs all the Wireframe curves for this Extrusion.
Returns: An array of Wireframe curves. | release/stubs.min/Rhino/Geometry/__init___parts/Extrusion.py | GetWireframe | htlcnn/ironpython-stubs | 182 | python | def GetWireframe(self):
'\n GetWireframe(self: Extrusion) -> Array[Curve]\n\n \n\n Constructs all the Wireframe curves for this Extrusion.\n\n Returns: An array of Wireframe curves.\n '
pass | def GetWireframe(self):
'\n GetWireframe(self: Extrusion) -> Array[Curve]\n\n \n\n Constructs all the Wireframe curves for this Extrusion.\n\n Returns: An array of Wireframe curves.\n '
pass<|docstring|>GetWireframe(self: Extrusion) -> Array[Curve]
Constructs all the Wireframe curves for this Extrusion.
Returns: An array of Wireframe curves.<|endoftext|> |
66bf08a375956ea11ad5dad35017da9fe801e5a7c9dcc0d639323457d0811238 | def NonConstOperation(self, *args):
'\n NonConstOperation(self: CommonObject)\n\n For derived classes implementers.\n\n Defines the necessary implementation to free the \n\n instance from being const.\n '
pass | NonConstOperation(self: CommonObject)
For derived classes implementers.
Defines the necessary implementation to free the
instance from being const. | release/stubs.min/Rhino/Geometry/__init___parts/Extrusion.py | NonConstOperation | htlcnn/ironpython-stubs | 182 | python | def NonConstOperation(self, *args):
'\n NonConstOperation(self: CommonObject)\n\n For derived classes implementers.\n\n Defines the necessary implementation to free the \n\n instance from being const.\n '
pass | def NonConstOperation(self, *args):
'\n NonConstOperation(self: CommonObject)\n\n For derived classes implementers.\n\n Defines the necessary implementation to free the \n\n instance from being const.\n '
pass<|docstring|>NonConstOperation(self: CommonObject)
For derived classes implementers.
Defines the necessary implementation to free the
instance from being const.<|endoftext|> |
9ec97edb4402eb85d97df9e8631c6185d29506f354315ffd1d619ded8eba6151 | def OnSwitchToNonConst(self, *args):
'\n OnSwitchToNonConst(self: GeometryBase)\n\n Is called when a non-const operation occurs.\n '
pass | OnSwitchToNonConst(self: GeometryBase)
Is called when a non-const operation occurs. | release/stubs.min/Rhino/Geometry/__init___parts/Extrusion.py | OnSwitchToNonConst | htlcnn/ironpython-stubs | 182 | python | def OnSwitchToNonConst(self, *args):
'\n OnSwitchToNonConst(self: GeometryBase)\n\n Is called when a non-const operation occurs.\n '
pass | def OnSwitchToNonConst(self, *args):
'\n OnSwitchToNonConst(self: GeometryBase)\n\n Is called when a non-const operation occurs.\n '
pass<|docstring|>OnSwitchToNonConst(self: GeometryBase)
Is called when a non-const operation occurs.<|endoftext|> |
bd05f943ba0a65d7c21c098121d6bd64609a2c964e7a378229a99722c172dbe2 | def PathLineCurve(self):
'\n PathLineCurve(self: Extrusion) -> LineCurve\n\n \n\n Gets the line-like curve that is the conceptual axis of the extrusion.\n\n Returns: The path as a line curve.\n '
pass | PathLineCurve(self: Extrusion) -> LineCurve
Gets the line-like curve that is the conceptual axis of the extrusion.
Returns: The path as a line curve. | release/stubs.min/Rhino/Geometry/__init___parts/Extrusion.py | PathLineCurve | htlcnn/ironpython-stubs | 182 | python | def PathLineCurve(self):
'\n PathLineCurve(self: Extrusion) -> LineCurve\n\n \n\n Gets the line-like curve that is the conceptual axis of the extrusion.\n\n Returns: The path as a line curve.\n '
pass | def PathLineCurve(self):
'\n PathLineCurve(self: Extrusion) -> LineCurve\n\n \n\n Gets the line-like curve that is the conceptual axis of the extrusion.\n\n Returns: The path as a line curve.\n '
pass<|docstring|>PathLineCurve(self: Extrusion) -> LineCurve
Gets the line-like curve that is the conceptual axis of the extrusion.
Returns: The path as a line curve.<|endoftext|> |
ee914318d3060132f1eddf1878daf8f365f419b9a5eea066e1703f094da48b36 | def Profile3d(self, *__args):
'\n Profile3d(self: Extrusion,ci: ComponentIndex) -> Curve\n\n \n\n Gets one of the profiles.\n\n \n\n ci: The index of this profile.\n\n Returns: The profile.\n\n Profile3d(self: Extrusion,profileIndex: int,s: float) -> Curve\n\n \n\n Gets a transversal isocurve of the extruded profile.\n\n \n\n profileIndex: 0 <= profileIndex < ProfileCount\n\n The outer profile has index 0.\n\n s: 0.0 <= s <= 1.0\n\n A relative parameter controling which profile is returned.\n\n \n\n 0=bottom profile and 1=top profile.\n\n \n\n Returns: The profile.\n '
pass | Profile3d(self: Extrusion,ci: ComponentIndex) -> Curve
Gets one of the profiles.
ci: The index of this profile.
Returns: The profile.
Profile3d(self: Extrusion,profileIndex: int,s: float) -> Curve
Gets a transversal isocurve of the extruded profile.
profileIndex: 0 <= profileIndex < ProfileCount
The outer profile has index 0.
s: 0.0 <= s <= 1.0
A relative parameter controling which profile is returned.
0=bottom profile and 1=top profile.
Returns: The profile. | release/stubs.min/Rhino/Geometry/__init___parts/Extrusion.py | Profile3d | htlcnn/ironpython-stubs | 182 | python | def Profile3d(self, *__args):
'\n Profile3d(self: Extrusion,ci: ComponentIndex) -> Curve\n\n \n\n Gets one of the profiles.\n\n \n\n ci: The index of this profile.\n\n Returns: The profile.\n\n Profile3d(self: Extrusion,profileIndex: int,s: float) -> Curve\n\n \n\n Gets a transversal isocurve of the extruded profile.\n\n \n\n profileIndex: 0 <= profileIndex < ProfileCount\n\n The outer profile has index 0.\n\n s: 0.0 <= s <= 1.0\n\n A relative parameter controling which profile is returned.\n\n \n\n 0=bottom profile and 1=top profile.\n\n \n\n Returns: The profile.\n '
pass | def Profile3d(self, *__args):
'\n Profile3d(self: Extrusion,ci: ComponentIndex) -> Curve\n\n \n\n Gets one of the profiles.\n\n \n\n ci: The index of this profile.\n\n Returns: The profile.\n\n Profile3d(self: Extrusion,profileIndex: int,s: float) -> Curve\n\n \n\n Gets a transversal isocurve of the extruded profile.\n\n \n\n profileIndex: 0 <= profileIndex < ProfileCount\n\n The outer profile has index 0.\n\n s: 0.0 <= s <= 1.0\n\n A relative parameter controling which profile is returned.\n\n \n\n 0=bottom profile and 1=top profile.\n\n \n\n Returns: The profile.\n '
pass<|docstring|>Profile3d(self: Extrusion,ci: ComponentIndex) -> Curve
Gets one of the profiles.
ci: The index of this profile.
Returns: The profile.
Profile3d(self: Extrusion,profileIndex: int,s: float) -> Curve
Gets a transversal isocurve of the extruded profile.
profileIndex: 0 <= profileIndex < ProfileCount
The outer profile has index 0.
s: 0.0 <= s <= 1.0
A relative parameter controling which profile is returned.
0=bottom profile and 1=top profile.
Returns: The profile.<|endoftext|> |
844477d12ac13f27d722521fa487d0249ca12d332fe23b2988521b6afc888442 | def ProfileIndex(self, profileParameter):
'\n ProfileIndex(self: Extrusion,profileParameter: float) -> int\n\n \n\n Gets the index of the profile curve at a domain related to a parameter.\n\n \n\n profileParameter: Parameter on profile curve.\n\n Returns: -1 if profileParameter does not correspond to a point on the profile curve.\n\n When \n\n the profileParameter corresponds to the end of one profile and the\n\n beginning of the \n\n next profile,the index of the next profile is returned.\n '
pass | ProfileIndex(self: Extrusion,profileParameter: float) -> int
Gets the index of the profile curve at a domain related to a parameter.
profileParameter: Parameter on profile curve.
Returns: -1 if profileParameter does not correspond to a point on the profile curve.
When
the profileParameter corresponds to the end of one profile and the
beginning of the
next profile,the index of the next profile is returned. | release/stubs.min/Rhino/Geometry/__init___parts/Extrusion.py | ProfileIndex | htlcnn/ironpython-stubs | 182 | python | def ProfileIndex(self, profileParameter):
'\n ProfileIndex(self: Extrusion,profileParameter: float) -> int\n\n \n\n Gets the index of the profile curve at a domain related to a parameter.\n\n \n\n profileParameter: Parameter on profile curve.\n\n Returns: -1 if profileParameter does not correspond to a point on the profile curve.\n\n When \n\n the profileParameter corresponds to the end of one profile and the\n\n beginning of the \n\n next profile,the index of the next profile is returned.\n '
pass | def ProfileIndex(self, profileParameter):
'\n ProfileIndex(self: Extrusion,profileParameter: float) -> int\n\n \n\n Gets the index of the profile curve at a domain related to a parameter.\n\n \n\n profileParameter: Parameter on profile curve.\n\n Returns: -1 if profileParameter does not correspond to a point on the profile curve.\n\n When \n\n the profileParameter corresponds to the end of one profile and the\n\n beginning of the \n\n next profile,the index of the next profile is returned.\n '
pass<|docstring|>ProfileIndex(self: Extrusion,profileParameter: float) -> int
Gets the index of the profile curve at a domain related to a parameter.
profileParameter: Parameter on profile curve.
Returns: -1 if profileParameter does not correspond to a point on the profile curve.
When
the profileParameter corresponds to the end of one profile and the
beginning of the
next profile,the index of the next profile is returned.<|endoftext|> |
b8a398e9b9f49237ad07c0e0f4f329f49c44fbd3b1c92d600c4f68d5cc632dc8 | def SetOuterProfile(self, outerProfile, cap):
'\n SetOuterProfile(self: Extrusion,outerProfile: Curve,cap: bool) -> bool\n\n \n\n Sets the outer profile of the extrusion.\n\n \n\n outerProfile: curve in the XY plane or a 2D curve.\n\n cap: If outerProfile is a closed curve,then cap determines if the extrusion\n\n has end \n\n caps. If outerProfile is an open curve,cap is ignored.\n\n \n\n Returns: true if the profile was set. If the outer profile is closed,then the\n\n extrusion may \n\n also have inner profiles. If the outer profile is open,\n\n the extrusion may not have \n\n inner profiles. If the extrusion already\n\n has a profile,the set will fail.\n '
pass | SetOuterProfile(self: Extrusion,outerProfile: Curve,cap: bool) -> bool
Sets the outer profile of the extrusion.
outerProfile: curve in the XY plane or a 2D curve.
cap: If outerProfile is a closed curve,then cap determines if the extrusion
has end
caps. If outerProfile is an open curve,cap is ignored.
Returns: true if the profile was set. If the outer profile is closed,then the
extrusion may
also have inner profiles. If the outer profile is open,
the extrusion may not have
inner profiles. If the extrusion already
has a profile,the set will fail. | release/stubs.min/Rhino/Geometry/__init___parts/Extrusion.py | SetOuterProfile | htlcnn/ironpython-stubs | 182 | python | def SetOuterProfile(self, outerProfile, cap):
'\n SetOuterProfile(self: Extrusion,outerProfile: Curve,cap: bool) -> bool\n\n \n\n Sets the outer profile of the extrusion.\n\n \n\n outerProfile: curve in the XY plane or a 2D curve.\n\n cap: If outerProfile is a closed curve,then cap determines if the extrusion\n\n has end \n\n caps. If outerProfile is an open curve,cap is ignored.\n\n \n\n Returns: true if the profile was set. If the outer profile is closed,then the\n\n extrusion may \n\n also have inner profiles. If the outer profile is open,\n\n the extrusion may not have \n\n inner profiles. If the extrusion already\n\n has a profile,the set will fail.\n '
pass | def SetOuterProfile(self, outerProfile, cap):
'\n SetOuterProfile(self: Extrusion,outerProfile: Curve,cap: bool) -> bool\n\n \n\n Sets the outer profile of the extrusion.\n\n \n\n outerProfile: curve in the XY plane or a 2D curve.\n\n cap: If outerProfile is a closed curve,then cap determines if the extrusion\n\n has end \n\n caps. If outerProfile is an open curve,cap is ignored.\n\n \n\n Returns: true if the profile was set. If the outer profile is closed,then the\n\n extrusion may \n\n also have inner profiles. If the outer profile is open,\n\n the extrusion may not have \n\n inner profiles. If the extrusion already\n\n has a profile,the set will fail.\n '
pass<|docstring|>SetOuterProfile(self: Extrusion,outerProfile: Curve,cap: bool) -> bool
Sets the outer profile of the extrusion.
outerProfile: curve in the XY plane or a 2D curve.
cap: If outerProfile is a closed curve,then cap determines if the extrusion
has end
caps. If outerProfile is an open curve,cap is ignored.
Returns: true if the profile was set. If the outer profile is closed,then the
extrusion may
also have inner profiles. If the outer profile is open,
the extrusion may not have
inner profiles. If the extrusion already
has a profile,the set will fail.<|endoftext|> |
43abe47b7d618b289d76808a4ca1a0c87255682d5444efaccf7ededc4d701b0b | def SetPathAndUp(self, a, b, up):
'\n SetPathAndUp(self: Extrusion,a: Point3d,b: Point3d,up: Vector3d) -> bool\n\n \n\n Allows to set the two points at the extremes and the up vector.\n\n \n\n a: The start point.\n\n b: The end point.\n\n up: The up vector.\n\n Returns: true if the operation succeeded; otherwise false.\n\n Setting up=a-b will make the \n\n operation fail.\n '
pass | SetPathAndUp(self: Extrusion,a: Point3d,b: Point3d,up: Vector3d) -> bool
Allows to set the two points at the extremes and the up vector.
a: The start point.
b: The end point.
up: The up vector.
Returns: true if the operation succeeded; otherwise false.
Setting up=a-b will make the
operation fail. | release/stubs.min/Rhino/Geometry/__init___parts/Extrusion.py | SetPathAndUp | htlcnn/ironpython-stubs | 182 | python | def SetPathAndUp(self, a, b, up):
'\n SetPathAndUp(self: Extrusion,a: Point3d,b: Point3d,up: Vector3d) -> bool\n\n \n\n Allows to set the two points at the extremes and the up vector.\n\n \n\n a: The start point.\n\n b: The end point.\n\n up: The up vector.\n\n Returns: true if the operation succeeded; otherwise false.\n\n Setting up=a-b will make the \n\n operation fail.\n '
pass | def SetPathAndUp(self, a, b, up):
'\n SetPathAndUp(self: Extrusion,a: Point3d,b: Point3d,up: Vector3d) -> bool\n\n \n\n Allows to set the two points at the extremes and the up vector.\n\n \n\n a: The start point.\n\n b: The end point.\n\n up: The up vector.\n\n Returns: true if the operation succeeded; otherwise false.\n\n Setting up=a-b will make the \n\n operation fail.\n '
pass<|docstring|>SetPathAndUp(self: Extrusion,a: Point3d,b: Point3d,up: Vector3d) -> bool
Allows to set the two points at the extremes and the up vector.
a: The start point.
b: The end point.
up: The up vector.
Returns: true if the operation succeeded; otherwise false.
Setting up=a-b will make the
operation fail.<|endoftext|> |
4c533ea9938f7a53474a0293943b42507f01cb658c049e447a2df778f7c40039 | def ToBrep(self, splitKinkyFaces=None):
'\n ToBrep(self: Extrusion,splitKinkyFaces: bool) -> Brep\n\n \n\n Constructs a brep form of the extrusion. The outer profile is always the first face of the brep.\n\n\n \n If there are inner profiles,additional brep faces are created for each profile. If \n\n the\n\n outer profile is closed,then end caps are added as the last two faces of the \n\n brep.\n\n \n\n \n\n splitKinkyFaces: If true and the profiles have kinks,then the faces corresponding to those profiles are split\n\n \n\n so they will be G1.\n\n \n\n Returns: A brep with a similar shape like this extrustion,or null on error.\n '
pass | ToBrep(self: Extrusion,splitKinkyFaces: bool) -> Brep
Constructs a brep form of the extrusion. The outer profile is always the first face of the brep.
If there are inner profiles,additional brep faces are created for each profile. If
the
outer profile is closed,then end caps are added as the last two faces of the
brep.
splitKinkyFaces: If true and the profiles have kinks,then the faces corresponding to those profiles are split
so they will be G1.
Returns: A brep with a similar shape like this extrustion,or null on error. | release/stubs.min/Rhino/Geometry/__init___parts/Extrusion.py | ToBrep | htlcnn/ironpython-stubs | 182 | python | def ToBrep(self, splitKinkyFaces=None):
'\n ToBrep(self: Extrusion,splitKinkyFaces: bool) -> Brep\n\n \n\n Constructs a brep form of the extrusion. The outer profile is always the first face of the brep.\n\n\n \n If there are inner profiles,additional brep faces are created for each profile. If \n\n the\n\n outer profile is closed,then end caps are added as the last two faces of the \n\n brep.\n\n \n\n \n\n splitKinkyFaces: If true and the profiles have kinks,then the faces corresponding to those profiles are split\n\n \n\n so they will be G1.\n\n \n\n Returns: A brep with a similar shape like this extrustion,or null on error.\n '
pass | def ToBrep(self, splitKinkyFaces=None):
'\n ToBrep(self: Extrusion,splitKinkyFaces: bool) -> Brep\n\n \n\n Constructs a brep form of the extrusion. The outer profile is always the first face of the brep.\n\n\n \n If there are inner profiles,additional brep faces are created for each profile. If \n\n the\n\n outer profile is closed,then end caps are added as the last two faces of the \n\n brep.\n\n \n\n \n\n splitKinkyFaces: If true and the profiles have kinks,then the faces corresponding to those profiles are split\n\n \n\n so they will be G1.\n\n \n\n Returns: A brep with a similar shape like this extrustion,or null on error.\n '
pass<|docstring|>ToBrep(self: Extrusion,splitKinkyFaces: bool) -> Brep
Constructs a brep form of the extrusion. The outer profile is always the first face of the brep.
If there are inner profiles,additional brep faces are created for each profile. If
the
outer profile is closed,then end caps are added as the last two faces of the
brep.
splitKinkyFaces: If true and the profiles have kinks,then the faces corresponding to those profiles are split
so they will be G1.
Returns: A brep with a similar shape like this extrustion,or null on error.<|endoftext|> |
ef216495fe6628f771044ea47c42f5c9bcbdfc468e52244b14b2db9c1706328b | def WallEdge(self, ci):
'\n WallEdge(self: Extrusion,ci: ComponentIndex) -> Curve\n\n \n\n Gets one of the longitudinal curves along the beam or extrusion.\n\n \n\n ci: The index of this profile.\n\n Returns: The profile.\n '
pass | WallEdge(self: Extrusion,ci: ComponentIndex) -> Curve
Gets one of the longitudinal curves along the beam or extrusion.
ci: The index of this profile.
Returns: The profile. | release/stubs.min/Rhino/Geometry/__init___parts/Extrusion.py | WallEdge | htlcnn/ironpython-stubs | 182 | python | def WallEdge(self, ci):
'\n WallEdge(self: Extrusion,ci: ComponentIndex) -> Curve\n\n \n\n Gets one of the longitudinal curves along the beam or extrusion.\n\n \n\n ci: The index of this profile.\n\n Returns: The profile.\n '
pass | def WallEdge(self, ci):
'\n WallEdge(self: Extrusion,ci: ComponentIndex) -> Curve\n\n \n\n Gets one of the longitudinal curves along the beam or extrusion.\n\n \n\n ci: The index of this profile.\n\n Returns: The profile.\n '
pass<|docstring|>WallEdge(self: Extrusion,ci: ComponentIndex) -> Curve
Gets one of the longitudinal curves along the beam or extrusion.
ci: The index of this profile.
Returns: The profile.<|endoftext|> |
993edfb86e7f8b79f2c1a32db2d70f245ea6b3f9b1677ca2bbe3877044678757 | def WallSurface(self, ci):
'\n WallSurface(self: Extrusion,ci: ComponentIndex) -> Surface\n\n \n\n Gets one of the longitudinal surfaces of the extrusion.\n\n \n\n ci: The index specifying which precise item to retrieve.\n\n Returns: The surface.\n '
pass | WallSurface(self: Extrusion,ci: ComponentIndex) -> Surface
Gets one of the longitudinal surfaces of the extrusion.
ci: The index specifying which precise item to retrieve.
Returns: The surface. | release/stubs.min/Rhino/Geometry/__init___parts/Extrusion.py | WallSurface | htlcnn/ironpython-stubs | 182 | python | def WallSurface(self, ci):
'\n WallSurface(self: Extrusion,ci: ComponentIndex) -> Surface\n\n \n\n Gets one of the longitudinal surfaces of the extrusion.\n\n \n\n ci: The index specifying which precise item to retrieve.\n\n Returns: The surface.\n '
pass | def WallSurface(self, ci):
'\n WallSurface(self: Extrusion,ci: ComponentIndex) -> Surface\n\n \n\n Gets one of the longitudinal surfaces of the extrusion.\n\n \n\n ci: The index specifying which precise item to retrieve.\n\n Returns: The surface.\n '
pass<|docstring|>WallSurface(self: Extrusion,ci: ComponentIndex) -> Surface
Gets one of the longitudinal surfaces of the extrusion.
ci: The index specifying which precise item to retrieve.
Returns: The surface.<|endoftext|> |
5a4090a811415d67ba87d7e2a53da6bed91482ea1b22c4116e484560e9f7c715 | def __enter__(self, *args):
'\n __enter__(self: IDisposable) -> object\n\n \n\n Provides the implementation of __enter__ for objects which implement IDisposable.\n '
pass | __enter__(self: IDisposable) -> object
Provides the implementation of __enter__ for objects which implement IDisposable. | release/stubs.min/Rhino/Geometry/__init___parts/Extrusion.py | __enter__ | htlcnn/ironpython-stubs | 182 | python | def __enter__(self, *args):
'\n __enter__(self: IDisposable) -> object\n\n \n\n Provides the implementation of __enter__ for objects which implement IDisposable.\n '
pass | def __enter__(self, *args):
'\n __enter__(self: IDisposable) -> object\n\n \n\n Provides the implementation of __enter__ for objects which implement IDisposable.\n '
pass<|docstring|>__enter__(self: IDisposable) -> object
Provides the implementation of __enter__ for objects which implement IDisposable.<|endoftext|> |
7cd059b57e7559e25e077e0a8f26049d9380a7dfd831237aa69c8222448a96a0 | def __exit__(self, *args):
'\n __exit__(self: IDisposable,exc_type: object,exc_value: object,exc_back: object)\n\n Provides the implementation of __exit__ for objects which implement IDisposable.\n '
pass | __exit__(self: IDisposable,exc_type: object,exc_value: object,exc_back: object)
Provides the implementation of __exit__ for objects which implement IDisposable. | release/stubs.min/Rhino/Geometry/__init___parts/Extrusion.py | __exit__ | htlcnn/ironpython-stubs | 182 | python | def __exit__(self, *args):
'\n __exit__(self: IDisposable,exc_type: object,exc_value: object,exc_back: object)\n\n Provides the implementation of __exit__ for objects which implement IDisposable.\n '
pass | def __exit__(self, *args):
'\n __exit__(self: IDisposable,exc_type: object,exc_value: object,exc_back: object)\n\n Provides the implementation of __exit__ for objects which implement IDisposable.\n '
pass<|docstring|>__exit__(self: IDisposable,exc_type: object,exc_value: object,exc_back: object)
Provides the implementation of __exit__ for objects which implement IDisposable.<|endoftext|> |
32b5271afcd5ecc37febb67dd854fa2d1b2c4c68b2c41d2ec119d33157e9bbaa | def __init__(self, *args):
' x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature '
pass | x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature | release/stubs.min/Rhino/Geometry/__init___parts/Extrusion.py | __init__ | htlcnn/ironpython-stubs | 182 | python | def __init__(self, *args):
' '
pass | def __init__(self, *args):
' '
pass<|docstring|>x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature<|endoftext|> |
b874233051cbbfe4b4ac0627502b4e3c6674f06ac07063cc730b1f8b5b7faacb | @staticmethod
def __new__(self):
'\n __new__(cls: type,info: SerializationInfo,context: StreamingContext)\n\n __new__(cls: type)\n '
pass | __new__(cls: type,info: SerializationInfo,context: StreamingContext)
__new__(cls: type) | release/stubs.min/Rhino/Geometry/__init___parts/Extrusion.py | __new__ | htlcnn/ironpython-stubs | 182 | python | @staticmethod
def __new__(self):
'\n __new__(cls: type,info: SerializationInfo,context: StreamingContext)\n\n __new__(cls: type)\n '
pass | @staticmethod
def __new__(self):
'\n __new__(cls: type,info: SerializationInfo,context: StreamingContext)\n\n __new__(cls: type)\n '
pass<|docstring|>__new__(cls: type,info: SerializationInfo,context: StreamingContext)
__new__(cls: type)<|endoftext|> |
473db30aaf6a75c4f00b882eea8228e8288bda4b6caa2ef4c82580abbd23cb1a | def get_speaker(lang='ko', gender='f'):
'Get the API name for the chosen speaker.'
try:
speakers = SPEAKERS[lang]
except KeyError:
raise ValueError('No speaker for language {}. Available languages: {}'.format(lang, list(SPEAKERS.keys())))
try:
return speakers[gender]
except KeyError:
warnings.warn('Gender {} not available for language {}'.format(gender, lang))
return list(speakers.values())[0] | Get the API name for the chosen speaker. | navertts/constants.py | get_speaker | scottgigante/NaverTTS | 10 | python | def get_speaker(lang='ko', gender='f'):
try:
speakers = SPEAKERS[lang]
except KeyError:
raise ValueError('No speaker for language {}. Available languages: {}'.format(lang, list(SPEAKERS.keys())))
try:
return speakers[gender]
except KeyError:
warnings.warn('Gender {} not available for language {}'.format(gender, lang))
return list(speakers.values())[0] | def get_speaker(lang='ko', gender='f'):
try:
speakers = SPEAKERS[lang]
except KeyError:
raise ValueError('No speaker for language {}. Available languages: {}'.format(lang, list(SPEAKERS.keys())))
try:
return speakers[gender]
except KeyError:
warnings.warn('Gender {} not available for language {}'.format(gender, lang))
return list(speakers.values())[0]<|docstring|>Get the API name for the chosen speaker.<|endoftext|> |
4c4a875e4b4843a6839e265a17c125811019c7849cf28cbe4740c16a5954b3cc | def translate_base(tld='com'):
'Get the base URL.'
return TRANSLATE_ENDPOINT.format(tld=tld) | Get the base URL. | navertts/constants.py | translate_base | scottgigante/NaverTTS | 10 | python | def translate_base(tld='com'):
return TRANSLATE_ENDPOINT.format(tld=tld) | def translate_base(tld='com'):
return TRANSLATE_ENDPOINT.format(tld=tld)<|docstring|>Get the base URL.<|endoftext|> |
c6ec087b2c0090c68c06676e264e60bdc1a0373d0dd17167990c59114c969f1b | def translate_endpoint(text, speaker='kyuri', speed=0, tld='com'):
'Get the endpoint URL.'
url = translate_base(tld=tld)
return (url + TRANSLATE_PARAMS.format(text=text, speaker=speaker, speed=speed)) | Get the endpoint URL. | navertts/constants.py | translate_endpoint | scottgigante/NaverTTS | 10 | python | def translate_endpoint(text, speaker='kyuri', speed=0, tld='com'):
url = translate_base(tld=tld)
return (url + TRANSLATE_PARAMS.format(text=text, speaker=speaker, speed=speed)) | def translate_endpoint(text, speaker='kyuri', speed=0, tld='com'):
url = translate_base(tld=tld)
return (url + TRANSLATE_PARAMS.format(text=text, speaker=speaker, speed=speed))<|docstring|>Get the endpoint URL.<|endoftext|> |
546ef86e045ed48d9a9ed9dfa432d41a23804ba8ef6a18722576a5de5473bd1c | def read_wave(filename):
'\n Reads a wave file.\n\n Args:\n filename: string\n\n Returns:\n wave object\n '
fp = wave.open(filename, 'rb')
nchannels = fp.getnchannels()
nframes = fp.getnframes()
sampwidth = fp.getsampwidth()
framerate = fp.getframerate()
z_str = fp.readframes(nframes)
fp.close()
dtype_map = {1: np.int8, 2: np.int16, 3: 'special', 4: np.int32}
if (sampwidth not in dtype_map):
raise ValueError(('sampwidth %d unknown' % sampwidth))
if (sampwidth == 3):
xs = np.fromstring(z_str, dtype=np.int8).astype(np.int32)
ys = ((((xs[2::3] * 256) + xs[1::3]) * 256) + xs[0::3])
else:
ys = np.fromstring(z_str, dtype=dtype_map[sampwidth])
if (nchannels == 2):
ys = ys[::2]
waveform = Waveform(ys, framerate=framerate)
waveform.normalize()
return waveform | Reads a wave file.
Args:
filename: string
Returns:
wave object | saturn/common/audio.py | read_wave | LAdaKid/saturn | 0 | python | def read_wave(filename):
'\n Reads a wave file.\n\n Args:\n filename: string\n\n Returns:\n wave object\n '
fp = wave.open(filename, 'rb')
nchannels = fp.getnchannels()
nframes = fp.getnframes()
sampwidth = fp.getsampwidth()
framerate = fp.getframerate()
z_str = fp.readframes(nframes)
fp.close()
dtype_map = {1: np.int8, 2: np.int16, 3: 'special', 4: np.int32}
if (sampwidth not in dtype_map):
raise ValueError(('sampwidth %d unknown' % sampwidth))
if (sampwidth == 3):
xs = np.fromstring(z_str, dtype=np.int8).astype(np.int32)
ys = ((((xs[2::3] * 256) + xs[1::3]) * 256) + xs[0::3])
else:
ys = np.fromstring(z_str, dtype=dtype_map[sampwidth])
if (nchannels == 2):
ys = ys[::2]
waveform = Waveform(ys, framerate=framerate)
waveform.normalize()
return waveform | def read_wave(filename):
'\n Reads a wave file.\n\n Args:\n filename: string\n\n Returns:\n wave object\n '
fp = wave.open(filename, 'rb')
nchannels = fp.getnchannels()
nframes = fp.getnframes()
sampwidth = fp.getsampwidth()
framerate = fp.getframerate()
z_str = fp.readframes(nframes)
fp.close()
dtype_map = {1: np.int8, 2: np.int16, 3: 'special', 4: np.int32}
if (sampwidth not in dtype_map):
raise ValueError(('sampwidth %d unknown' % sampwidth))
if (sampwidth == 3):
xs = np.fromstring(z_str, dtype=np.int8).astype(np.int32)
ys = ((((xs[2::3] * 256) + xs[1::3]) * 256) + xs[0::3])
else:
ys = np.fromstring(z_str, dtype=dtype_map[sampwidth])
if (nchannels == 2):
ys = ys[::2]
waveform = Waveform(ys, framerate=framerate)
waveform.normalize()
return waveform<|docstring|>Reads a wave file.
Args:
filename: string
Returns:
wave object<|endoftext|> |
a03055f84c7a9e60a8620aa17b3f74973977f04f93801b158656bf4ddeb7dc43 | def normalize(ys, amp=1.0):
'\n Normalizes a wave array so the maximum amplitude is +amp or -amp.\n\n Args:\n ys: wave array\n amp: max amplitude (pos or neg) in result\n\n Returns:\n wave array\n '
(high, low) = (abs(max(ys)), abs(min(ys)))
return ((amp * ys) / max(high, low)) | Normalizes a wave array so the maximum amplitude is +amp or -amp.
Args:
ys: wave array
amp: max amplitude (pos or neg) in result
Returns:
wave array | saturn/common/audio.py | normalize | LAdaKid/saturn | 0 | python | def normalize(ys, amp=1.0):
'\n Normalizes a wave array so the maximum amplitude is +amp or -amp.\n\n Args:\n ys: wave array\n amp: max amplitude (pos or neg) in result\n\n Returns:\n wave array\n '
(high, low) = (abs(max(ys)), abs(min(ys)))
return ((amp * ys) / max(high, low)) | def normalize(ys, amp=1.0):
'\n Normalizes a wave array so the maximum amplitude is +amp or -amp.\n\n Args:\n ys: wave array\n amp: max amplitude (pos or neg) in result\n\n Returns:\n wave array\n '
(high, low) = (abs(max(ys)), abs(min(ys)))
return ((amp * ys) / max(high, low))<|docstring|>Normalizes a wave array so the maximum amplitude is +amp or -amp.
Args:
ys: wave array
amp: max amplitude (pos or neg) in result
Returns:
wave array<|endoftext|> |
1f3b5944574509b252970ff8bed2a54b0a81bfd7f82710b98052ae1c51107dd4 | def find_index(x, xs):
'\n Find the index corresponding to a given value in an array.\n '
n = len(xs)
start = xs[0]
end = xs[(- 1)]
i = round((((n - 1) * (x - start)) / (end - start)))
return int(i) | Find the index corresponding to a given value in an array. | saturn/common/audio.py | find_index | LAdaKid/saturn | 0 | python | def find_index(x, xs):
'\n \n '
n = len(xs)
start = xs[0]
end = xs[(- 1)]
i = round((((n - 1) * (x - start)) / (end - start)))
return int(i) | def find_index(x, xs):
'\n \n '
n = len(xs)
start = xs[0]
end = xs[(- 1)]
i = round((((n - 1) * (x - start)) / (end - start)))
return int(i)<|docstring|>Find the index corresponding to a given value in an array.<|endoftext|> |
91ba815a42033219913fa024f661417983d2a019b78ed98a1a999abf2d4e58d9 | def __init__(self, ys, ts=None, framerate=None):
'\n Initializes the wave.\n\n Args:\n ys: wave array\n ts: array of times\n framerate: samples per second\n '
self.ys = np.asanyarray(ys)
self.framerate = (framerate if (framerate is not None) else 11025)
if (ts is None):
self.ts = (np.arange(len(ys)) / self.framerate)
else:
self.ts = np.asanyarray(ts)
self.duration = max(self.ts) | Initializes the wave.
Args:
ys: wave array
ts: array of times
framerate: samples per second | saturn/common/audio.py | __init__ | LAdaKid/saturn | 0 | python | def __init__(self, ys, ts=None, framerate=None):
'\n Initializes the wave.\n\n Args:\n ys: wave array\n ts: array of times\n framerate: samples per second\n '
self.ys = np.asanyarray(ys)
self.framerate = (framerate if (framerate is not None) else 11025)
if (ts is None):
self.ts = (np.arange(len(ys)) / self.framerate)
else:
self.ts = np.asanyarray(ts)
self.duration = max(self.ts) | def __init__(self, ys, ts=None, framerate=None):
'\n Initializes the wave.\n\n Args:\n ys: wave array\n ts: array of times\n framerate: samples per second\n '
self.ys = np.asanyarray(ys)
self.framerate = (framerate if (framerate is not None) else 11025)
if (ts is None):
self.ts = (np.arange(len(ys)) / self.framerate)
else:
self.ts = np.asanyarray(ts)
self.duration = max(self.ts)<|docstring|>Initializes the wave.
Args:
ys: wave array
ts: array of times
framerate: samples per second<|endoftext|> |
85266a6fd6dcd1b0a11d2161bcf6fa55b3cef39c2d87247365ee0a3b5a2ee43d | def segment(self, start=None, duration=None):
'\n Extracts a segment.\n\n Args:\n start: float start time in seconds\n duration: float duration in seconds\n\n Returns:\n Wave\n '
if (start is None):
start = self.ts[0]
i = 0
else:
i = self.find_index(start)
j = (None if (duration is None) else self.find_index((start + duration)))
return self.slice(i, j) | Extracts a segment.
Args:
start: float start time in seconds
duration: float duration in seconds
Returns:
Wave | saturn/common/audio.py | segment | LAdaKid/saturn | 0 | python | def segment(self, start=None, duration=None):
'\n Extracts a segment.\n\n Args:\n start: float start time in seconds\n duration: float duration in seconds\n\n Returns:\n Wave\n '
if (start is None):
start = self.ts[0]
i = 0
else:
i = self.find_index(start)
j = (None if (duration is None) else self.find_index((start + duration)))
return self.slice(i, j) | def segment(self, start=None, duration=None):
'\n Extracts a segment.\n\n Args:\n start: float start time in seconds\n duration: float duration in seconds\n\n Returns:\n Wave\n '
if (start is None):
start = self.ts[0]
i = 0
else:
i = self.find_index(start)
j = (None if (duration is None) else self.find_index((start + duration)))
return self.slice(i, j)<|docstring|>Extracts a segment.
Args:
start: float start time in seconds
duration: float duration in seconds
Returns:
Wave<|endoftext|> |
951c8809cab5c0bb4817f1bc254289147d820e6c448730a5fae433937e3289bd | def normalize(self, amp=1.0):
'\n Normalizes the signal to the given amplitude.\n\n Args:\n amp: float amplitude\n '
self.ys = normalize(self.ys, amp=amp) | Normalizes the signal to the given amplitude.
Args:
amp: float amplitude | saturn/common/audio.py | normalize | LAdaKid/saturn | 0 | python | def normalize(self, amp=1.0):
'\n Normalizes the signal to the given amplitude.\n\n Args:\n amp: float amplitude\n '
self.ys = normalize(self.ys, amp=amp) | def normalize(self, amp=1.0):
'\n Normalizes the signal to the given amplitude.\n\n Args:\n amp: float amplitude\n '
self.ys = normalize(self.ys, amp=amp)<|docstring|>Normalizes the signal to the given amplitude.
Args:
amp: float amplitude<|endoftext|> |
bfb75fa8e151403b1f7eb23df065e819f010d7936989f7ef470315db1a1ee028 | def slice(self, i, j):
'\n Makes a slice from a Wave.\n\n Args:\n i: first slice index\n j: second slice index\n\n Returns:\n waveform instance of slice\n '
ys = self.ys[i:j].copy()
ts = self.ts[i:j].copy()
return Waveform(ys, ts, self.framerate) | Makes a slice from a Wave.
Args:
i: first slice index
j: second slice index
Returns:
waveform instance of slice | saturn/common/audio.py | slice | LAdaKid/saturn | 0 | python | def slice(self, i, j):
'\n Makes a slice from a Wave.\n\n Args:\n i: first slice index\n j: second slice index\n\n Returns:\n waveform instance of slice\n '
ys = self.ys[i:j].copy()
ts = self.ts[i:j].copy()
return Waveform(ys, ts, self.framerate) | def slice(self, i, j):
'\n Makes a slice from a Wave.\n\n Args:\n i: first slice index\n j: second slice index\n\n Returns:\n waveform instance of slice\n '
ys = self.ys[i:j].copy()
ts = self.ts[i:j].copy()
return Waveform(ys, ts, self.framerate)<|docstring|>Makes a slice from a Wave.
Args:
i: first slice index
j: second slice index
Returns:
waveform instance of slice<|endoftext|> |
4f33dc68c4899673c605d0d626b289020b8a06a8d3701e4548001d6ec7c0e5af | def make_spectrum(self, full=False):
'\n Computes the spectrum using FFT.\n\n Args:\n full: boolean, whethere to compute a full FFT\n (as opposed to a real FFT)\n\n Returns: Spectrum\n '
n = len(self.ys)
d = (1 / self.framerate)
if full:
hs = np.fft.fft(self.ys)
fs = np.fft.fftfreq(n, d)
else:
hs = np.fft.rfft(self.ys)
fs = np.fft.rfftfreq(n, d)
return Spectrum(hs, fs, self.framerate, full) | Computes the spectrum using FFT.
Args:
full: boolean, whethere to compute a full FFT
(as opposed to a real FFT)
Returns: Spectrum | saturn/common/audio.py | make_spectrum | LAdaKid/saturn | 0 | python | def make_spectrum(self, full=False):
'\n Computes the spectrum using FFT.\n\n Args:\n full: boolean, whethere to compute a full FFT\n (as opposed to a real FFT)\n\n Returns: Spectrum\n '
n = len(self.ys)
d = (1 / self.framerate)
if full:
hs = np.fft.fft(self.ys)
fs = np.fft.fftfreq(n, d)
else:
hs = np.fft.rfft(self.ys)
fs = np.fft.rfftfreq(n, d)
return Spectrum(hs, fs, self.framerate, full) | def make_spectrum(self, full=False):
'\n Computes the spectrum using FFT.\n\n Args:\n full: boolean, whethere to compute a full FFT\n (as opposed to a real FFT)\n\n Returns: Spectrum\n '
n = len(self.ys)
d = (1 / self.framerate)
if full:
hs = np.fft.fft(self.ys)
fs = np.fft.fftfreq(n, d)
else:
hs = np.fft.rfft(self.ys)
fs = np.fft.rfftfreq(n, d)
return Spectrum(hs, fs, self.framerate, full)<|docstring|>Computes the spectrum using FFT.
Args:
full: boolean, whethere to compute a full FFT
(as opposed to a real FFT)
Returns: Spectrum<|endoftext|> |
9de19e7f5153a61c0c64612d01a2a994cff68e3b457efc4abf01f789f7915af3 | def find_index(self, t):
'Find the index corresponding to a given time.'
n = len(self)
start = self.start
end = self.end
i = round((((n - 1) * (t - start)) / (end - start)))
return int(i) | Find the index corresponding to a given time. | saturn/common/audio.py | find_index | LAdaKid/saturn | 0 | python | def find_index(self, t):
n = len(self)
start = self.start
end = self.end
i = round((((n - 1) * (t - start)) / (end - start)))
return int(i) | def find_index(self, t):
n = len(self)
start = self.start
end = self.end
i = round((((n - 1) * (t - start)) / (end - start)))
return int(i)<|docstring|>Find the index corresponding to a given time.<|endoftext|> |
110526dfd25e1519812269edfe1d6345958db6fd46f109f70e3c90ecb1b78736 | def __init__(self, hs, fs, framerate, full=False):
'\n Initializes a spectrum.\n\n Args:\n hs: array of amplitudes (real or complex)\n fs: array of frequencies\n framerate: frames per second\n full: boolean to indicate full or real FFT\n '
self.hs = np.asanyarray(hs)
self.fs = np.asanyarray(fs)
self.framerate = framerate
self.full = full | Initializes a spectrum.
Args:
hs: array of amplitudes (real or complex)
fs: array of frequencies
framerate: frames per second
full: boolean to indicate full or real FFT | saturn/common/audio.py | __init__ | LAdaKid/saturn | 0 | python | def __init__(self, hs, fs, framerate, full=False):
'\n Initializes a spectrum.\n\n Args:\n hs: array of amplitudes (real or complex)\n fs: array of frequencies\n framerate: frames per second\n full: boolean to indicate full or real FFT\n '
self.hs = np.asanyarray(hs)
self.fs = np.asanyarray(fs)
self.framerate = framerate
self.full = full | def __init__(self, hs, fs, framerate, full=False):
'\n Initializes a spectrum.\n\n Args:\n hs: array of amplitudes (real or complex)\n fs: array of frequencies\n framerate: frames per second\n full: boolean to indicate full or real FFT\n '
self.hs = np.asanyarray(hs)
self.fs = np.asanyarray(fs)
self.framerate = framerate
self.full = full<|docstring|>Initializes a spectrum.
Args:
hs: array of amplitudes (real or complex)
fs: array of frequencies
framerate: frames per second
full: boolean to indicate full or real FFT<|endoftext|> |
6ad3def509078aaff9bd6ca8533de2d994bb95029f632eed922fda76204f7002 | def render_full(self, high=None):
'\n Extracts amps and fs from a full spectrum.\n\n Args:\n high: cutoff frequency\n\n Returns: fs, amps\n '
hs = np.fft.fftshift(self.hs)
amps = np.abs(hs)
fs = np.fft.fftshift(self.fs)
i = (0 if (high is None) else find_index((- high), fs))
j = (None if (high is None) else (find_index(high, fs) + 1))
return (fs[i:j], amps[i:j]) | Extracts amps and fs from a full spectrum.
Args:
high: cutoff frequency
Returns: fs, amps | saturn/common/audio.py | render_full | LAdaKid/saturn | 0 | python | def render_full(self, high=None):
'\n Extracts amps and fs from a full spectrum.\n\n Args:\n high: cutoff frequency\n\n Returns: fs, amps\n '
hs = np.fft.fftshift(self.hs)
amps = np.abs(hs)
fs = np.fft.fftshift(self.fs)
i = (0 if (high is None) else find_index((- high), fs))
j = (None if (high is None) else (find_index(high, fs) + 1))
return (fs[i:j], amps[i:j]) | def render_full(self, high=None):
'\n Extracts amps and fs from a full spectrum.\n\n Args:\n high: cutoff frequency\n\n Returns: fs, amps\n '
hs = np.fft.fftshift(self.hs)
amps = np.abs(hs)
fs = np.fft.fftshift(self.fs)
i = (0 if (high is None) else find_index((- high), fs))
j = (None if (high is None) else (find_index(high, fs) + 1))
return (fs[i:j], amps[i:j])<|docstring|>Extracts amps and fs from a full spectrum.
Args:
high: cutoff frequency
Returns: fs, amps<|endoftext|> |
012d1fd9486f9d50d1a7d430b70dab7c798830bfb0056a061ddc706c42599714 | def get_children(self):
' overwrite this if you want nested extensions using recursetree '
return [] | overwrite this if you want nested extensions using recursetree | meitan/feincms/module/page/extensions/navigation.py | get_children | danealton/meitan-final | 1 | python | def get_children(self):
' '
return [] | def get_children(self):
' '
return []<|docstring|>overwrite this if you want nested extensions using recursetree<|endoftext|> |
4ad887527427d2e73ddd657fa6bc5557aef83380202af5ee8b2ae96c6d9bd160 | def children(self, page, **kwargs):
'\n This is the method which must be overridden in every navigation\n extension.\n\n It receives the page the extension is attached to, the depth up to\n which the navigation should be resolved, and the current request object\n if it is available.\n '
raise NotImplementedError | This is the method which must be overridden in every navigation
extension.
It receives the page the extension is attached to, the depth up to
which the navigation should be resolved, and the current request object
if it is available. | meitan/feincms/module/page/extensions/navigation.py | children | danealton/meitan-final | 1 | python | def children(self, page, **kwargs):
'\n This is the method which must be overridden in every navigation\n extension.\n\n It receives the page the extension is attached to, the depth up to\n which the navigation should be resolved, and the current request object\n if it is available.\n '
raise NotImplementedError | def children(self, page, **kwargs):
'\n This is the method which must be overridden in every navigation\n extension.\n\n It receives the page the extension is attached to, the depth up to\n which the navigation should be resolved, and the current request object\n if it is available.\n '
raise NotImplementedError<|docstring|>This is the method which must be overridden in every navigation
extension.
It receives the page the extension is attached to, the depth up to
which the navigation should be resolved, and the current request object
if it is available.<|endoftext|> |
f084576e6d9db8b01fdf286785aacd03a6ed24ff6121abecda03c9c52c7d84cb | def import_submodules(package_name):
' Import all submodules of a module, recursively\n\n :param package_name: Package name\n :type package_name: str\n :rtype: dict[types.ModuleType]\n '
package = sys.modules[package_name]
return {name: importlib.import_module(((package_name + '.') + name)) for (loader, name, is_pkg) in pkgutil.walk_packages(package.__path__)} | Import all submodules of a module, recursively
:param package_name: Package name
:type package_name: str
:rtype: dict[types.ModuleType] | gobblegobble/bot.py | import_submodules | ejesse/gobblegobble | 1 | python | def import_submodules(package_name):
' Import all submodules of a module, recursively\n\n :param package_name: Package name\n :type package_name: str\n :rtype: dict[types.ModuleType]\n '
package = sys.modules[package_name]
return {name: importlib.import_module(((package_name + '.') + name)) for (loader, name, is_pkg) in pkgutil.walk_packages(package.__path__)} | def import_submodules(package_name):
' Import all submodules of a module, recursively\n\n :param package_name: Package name\n :type package_name: str\n :rtype: dict[types.ModuleType]\n '
package = sys.modules[package_name]
return {name: importlib.import_module(((package_name + '.') + name)) for (loader, name, is_pkg) in pkgutil.walk_packages(package.__path__)}<|docstring|>Import all submodules of a module, recursively
:param package_name: Package name
:type package_name: str
:rtype: dict[types.ModuleType]<|endoftext|> |
ef775c2839ed330e233333c60e92bc14055b00e66f7c1a904972526d056a62b9 | def reply(self, reply_text):
"\n '@'s the original sender with a new message from the bot\n to the same channel as the original\n "
return self.respond(('<@%s> %s' % (self.sender, reply_text))) | '@'s the original sender with a new message from the bot
to the same channel as the original | gobblegobble/bot.py | reply | ejesse/gobblegobble | 1 | python | def reply(self, reply_text):
"\n '@'s the original sender with a new message from the bot\n to the same channel as the original\n "
return self.respond(('<@%s> %s' % (self.sender, reply_text))) | def reply(self, reply_text):
"\n '@'s the original sender with a new message from the bot\n to the same channel as the original\n "
return self.respond(('<@%s> %s' % (self.sender, reply_text)))<|docstring|>'@'s the original sender with a new message from the bot
to the same channel as the original<|endoftext|> |
48d2d1535652dfcc2cc96b775a1592eaf064710f0f27deb586e9834799453b0a | def respond(self, response_text):
'\n Effectively just sends a new message from the bot\n to the same channel as the original\n '
message = Message()
message.channel = self.channel
message.text = response_text
message.full_text = response_text
self.response = message
bot = GobbleBot()
return bot.send_message(message) | Effectively just sends a new message from the bot
to the same channel as the original | gobblegobble/bot.py | respond | ejesse/gobblegobble | 1 | python | def respond(self, response_text):
'\n Effectively just sends a new message from the bot\n to the same channel as the original\n '
message = Message()
message.channel = self.channel
message.text = response_text
message.full_text = response_text
self.response = message
bot = GobbleBot()
return bot.send_message(message) | def respond(self, response_text):
'\n Effectively just sends a new message from the bot\n to the same channel as the original\n '
message = Message()
message.channel = self.channel
message.text = response_text
message.full_text = response_text
self.response = message
bot = GobbleBot()
return bot.send_message(message)<|docstring|>Effectively just sends a new message from the bot
to the same channel as the original<|endoftext|> |
34cb3885d9a70dae1ac6fb62bb364977ca207def3f617f61bee78ba28d050305 | def sink_serial_port(conn, stop_ev):
"Consume data from a pexpect file descriptor to prevent stall.\n\n If the FIFO of the PTY fills up, the QEMU thread of the respective target\n processor simply stalls -- this has been observed. Also, this way we\n capture asynchronous output, that may show up at the console at a time not\n tied to our pexpect send-expect calls (e.g. while we're running commands\n over SSH).\n "
while (not stop_ev.is_set()):
poll_interval = 2
r = conn.expect([pexpect.TIMEOUT, pexpect.EOF], poll_interval)
if (r == 0):
continue
elif (r == 1):
return | Consume data from a pexpect file descriptor to prevent stall.
If the FIFO of the PTY fills up, the QEMU thread of the respective target
processor simply stalls -- this has been observed. Also, this way we
capture asynchronous output, that may show up at the console at a time not
tied to our pexpect send-expect calls (e.g. while we're running commands
over SSH). | test/pytest/conftest.py | sink_serial_port | ISI-apex/hpsc-utils | 0 | python | def sink_serial_port(conn, stop_ev):
"Consume data from a pexpect file descriptor to prevent stall.\n\n If the FIFO of the PTY fills up, the QEMU thread of the respective target\n processor simply stalls -- this has been observed. Also, this way we\n capture asynchronous output, that may show up at the console at a time not\n tied to our pexpect send-expect calls (e.g. while we're running commands\n over SSH).\n "
while (not stop_ev.is_set()):
poll_interval = 2
r = conn.expect([pexpect.TIMEOUT, pexpect.EOF], poll_interval)
if (r == 0):
continue
elif (r == 1):
return | def sink_serial_port(conn, stop_ev):
"Consume data from a pexpect file descriptor to prevent stall.\n\n If the FIFO of the PTY fills up, the QEMU thread of the respective target\n processor simply stalls -- this has been observed. Also, this way we\n capture asynchronous output, that may show up at the console at a time not\n tied to our pexpect send-expect calls (e.g. while we're running commands\n over SSH).\n "
while (not stop_ev.is_set()):
poll_interval = 2
r = conn.expect([pexpect.TIMEOUT, pexpect.EOF], poll_interval)
if (r == 0):
continue
elif (r == 1):
return<|docstring|>Consume data from a pexpect file descriptor to prevent stall.
If the FIFO of the PTY fills up, the QEMU thread of the respective target
processor simply stalls -- this has been observed. Also, this way we
capture asynchronous output, that may show up at the console at a time not
tied to our pexpect send-expect calls (e.g. while we're running commands
over SSH).<|endoftext|> |
4263e18063256e90ec57801cb3fa80566117d0c0507913c4c821fd09f8428b55 | def always_none(m):
'Always return None'
return None | Always return None | python/maketexdeps.py | always_none | jcpernias/slides_1004 | 0 | python | def always_none(m):
return None | def always_none(m):
return None<|docstring|>Always return None<|endoftext|> |
d0ebdee4f8e26abac5daa79719b4e0255b1898db83093d6ab182c0b66554c4df | def first_group(m):
'Returns the first group of the match'
return m.group(1) | Returns the first group of the match | python/maketexdeps.py | first_group | jcpernias/slides_1004 | 0 | python | def first_group(m):
return m.group(1) | def first_group(m):
return m.group(1)<|docstring|>Returns the first group of the match<|endoftext|> |
430612c7007f6f64d71bd57c626e9f7d43b3f195b4edf5c112c5640f78bf71ac | def second_group(m):
'Returns the first group of the match'
return m.group(2) | Returns the first group of the match | python/maketexdeps.py | second_group | jcpernias/slides_1004 | 0 | python | def second_group(m):
return m.group(2) | def second_group(m):
return m.group(2)<|docstring|>Returns the first group of the match<|endoftext|> |
613103f3d181f70283fda2ea3f7a86bea03961b42582a1b5e315ed8be8a9bf1c | def process_line(line, matchers):
'Process line with every Matcher until a match is found'
result = None
for m in matchers:
result = m.process(line)
if result:
break
return result | Process line with every Matcher until a match is found | python/maketexdeps.py | process_line | jcpernias/slides_1004 | 0 | python | def process_line(line, matchers):
result = None
for m in matchers:
result = m.process(line)
if result:
break
return result | def process_line(line, matchers):
result = None
for m in matchers:
result = m.process(line)
if result:
break
return result<|docstring|>Process line with every Matcher until a match is found<|endoftext|> |
4332cd8bddbccc77c76093b6e5241a8639808119e2b409d813d9a0dfa1d94d9b | def make_dummy_protein_sequence(n_supporting_variant_reads, n_supporting_variant_sequences, n_supporting_reference_transcripts, n_total_variant_sequences=None, n_total_variant_reads=None, n_total_reference_transcripts=None, gene=['TP53'], amino_acids='MKHW', cdna_sequence='CCCATGAAACACTGGTAG', variant_cdna_interval_start=8, variant_cdna_interval_end=9, variant_aa_interval_start=1, variant_aa_interval_end=2, number_mismatches=1):
'\n Creates ProteinSequence object with None filled in for most fields\n '
if (n_total_variant_reads is None):
n_total_variant_reads = n_supporting_variant_reads
if (n_total_variant_sequences is None):
n_total_variant_sequences = n_supporting_variant_sequences
if (n_total_reference_transcripts is None):
n_total_reference_transcripts = n_total_reference_transcripts
assert (n_supporting_variant_sequences <= n_supporting_variant_reads)
assert (n_supporting_variant_sequences <= n_total_variant_sequences)
assert (n_supporting_reference_transcripts <= n_total_reference_transcripts)
n_translations = (n_total_reference_transcripts * n_total_variant_sequences)
translation = make_dummy_translation()
return ProteinSequence(translations=([translation] * n_translations), overlapping_reads=([None] * n_total_variant_reads), ref_reads=[], alt_reads=([None] * n_total_variant_reads), alt_reads_supporting_protein_sequence=([None] * n_supporting_variant_reads), transcripts_supporting_protein_sequence=([None] * n_supporting_reference_transcripts), transcripts_overlapping_variant=([None] * n_supporting_reference_transcripts), gene=gene, amino_acids=amino_acids, variant_aa_interval_start=variant_aa_interval_start, variant_aa_interval_end=variant_aa_interval_end, ends_with_stop_codon=translation.ends_with_stop_codon, frameshift=translation.frameshift) | Creates ProteinSequence object with None filled in for most fields | test/test_protein_sequences.py | make_dummy_protein_sequence | carnivorouspeanut/isovar_comp | 0 | python | def make_dummy_protein_sequence(n_supporting_variant_reads, n_supporting_variant_sequences, n_supporting_reference_transcripts, n_total_variant_sequences=None, n_total_variant_reads=None, n_total_reference_transcripts=None, gene=['TP53'], amino_acids='MKHW', cdna_sequence='CCCATGAAACACTGGTAG', variant_cdna_interval_start=8, variant_cdna_interval_end=9, variant_aa_interval_start=1, variant_aa_interval_end=2, number_mismatches=1):
'\n \n '
if (n_total_variant_reads is None):
n_total_variant_reads = n_supporting_variant_reads
if (n_total_variant_sequences is None):
n_total_variant_sequences = n_supporting_variant_sequences
if (n_total_reference_transcripts is None):
n_total_reference_transcripts = n_total_reference_transcripts
assert (n_supporting_variant_sequences <= n_supporting_variant_reads)
assert (n_supporting_variant_sequences <= n_total_variant_sequences)
assert (n_supporting_reference_transcripts <= n_total_reference_transcripts)
n_translations = (n_total_reference_transcripts * n_total_variant_sequences)
translation = make_dummy_translation()
return ProteinSequence(translations=([translation] * n_translations), overlapping_reads=([None] * n_total_variant_reads), ref_reads=[], alt_reads=([None] * n_total_variant_reads), alt_reads_supporting_protein_sequence=([None] * n_supporting_variant_reads), transcripts_supporting_protein_sequence=([None] * n_supporting_reference_transcripts), transcripts_overlapping_variant=([None] * n_supporting_reference_transcripts), gene=gene, amino_acids=amino_acids, variant_aa_interval_start=variant_aa_interval_start, variant_aa_interval_end=variant_aa_interval_end, ends_with_stop_codon=translation.ends_with_stop_codon, frameshift=translation.frameshift) | def make_dummy_protein_sequence(n_supporting_variant_reads, n_supporting_variant_sequences, n_supporting_reference_transcripts, n_total_variant_sequences=None, n_total_variant_reads=None, n_total_reference_transcripts=None, gene=['TP53'], amino_acids='MKHW', cdna_sequence='CCCATGAAACACTGGTAG', variant_cdna_interval_start=8, variant_cdna_interval_end=9, variant_aa_interval_start=1, variant_aa_interval_end=2, number_mismatches=1):
'\n \n '
if (n_total_variant_reads is None):
n_total_variant_reads = n_supporting_variant_reads
if (n_total_variant_sequences is None):
n_total_variant_sequences = n_supporting_variant_sequences
if (n_total_reference_transcripts is None):
n_total_reference_transcripts = n_total_reference_transcripts
assert (n_supporting_variant_sequences <= n_supporting_variant_reads)
assert (n_supporting_variant_sequences <= n_total_variant_sequences)
assert (n_supporting_reference_transcripts <= n_total_reference_transcripts)
n_translations = (n_total_reference_transcripts * n_total_variant_sequences)
translation = make_dummy_translation()
return ProteinSequence(translations=([translation] * n_translations), overlapping_reads=([None] * n_total_variant_reads), ref_reads=[], alt_reads=([None] * n_total_variant_reads), alt_reads_supporting_protein_sequence=([None] * n_supporting_variant_reads), transcripts_supporting_protein_sequence=([None] * n_supporting_reference_transcripts), transcripts_overlapping_variant=([None] * n_supporting_reference_transcripts), gene=gene, amino_acids=amino_acids, variant_aa_interval_start=variant_aa_interval_start, variant_aa_interval_end=variant_aa_interval_end, ends_with_stop_codon=translation.ends_with_stop_codon, frameshift=translation.frameshift)<|docstring|>Creates ProteinSequence object with None filled in for most fields<|endoftext|> |
cb04a1d3122a0a4c2a158e80a480946ff96308c077ec9fe8a3234616f95616b7 | def variants_to_protein_sequences_dataframe(expressed_vcf='data/b16.f10/b16.expressed.vcf', not_expressed_vcf='data/b16.f10/b16.not-expressed.vcf', tumor_rna_bam='data/b16.f10/b16.combined.sorted.bam', min_mapping_quality=0, max_protein_sequences_per_variant=1, variant_sequence_assembly=False):
'\n Helper function to load pair of VCFs and tumor RNA BAM\n and use them to generate a DataFrame of expressed variant protein\n sequences.\n '
expressed_variants = load_vcf(expressed_vcf)
not_expressed_variants = load_vcf(not_expressed_vcf)
combined_variants = VariantCollection((list(expressed_variants) + list(not_expressed_variants)))
samfile = load_bam(tumor_rna_bam)
allele_reads_generator = reads_overlapping_variants(variants=combined_variants, samfile=samfile, min_mapping_quality=min_mapping_quality)
protein_sequences_generator = reads_generator_to_protein_sequences_generator(allele_reads_generator, max_protein_sequences_per_variant=max_protein_sequences_per_variant, variant_sequence_assembly=variant_sequence_assembly)
df = protein_sequences_generator_to_dataframe(protein_sequences_generator)
return (df, expressed_variants, combined_variants) | Helper function to load pair of VCFs and tumor RNA BAM
and use them to generate a DataFrame of expressed variant protein
sequences. | test/test_protein_sequences.py | variants_to_protein_sequences_dataframe | carnivorouspeanut/isovar_comp | 0 | python | def variants_to_protein_sequences_dataframe(expressed_vcf='data/b16.f10/b16.expressed.vcf', not_expressed_vcf='data/b16.f10/b16.not-expressed.vcf', tumor_rna_bam='data/b16.f10/b16.combined.sorted.bam', min_mapping_quality=0, max_protein_sequences_per_variant=1, variant_sequence_assembly=False):
'\n Helper function to load pair of VCFs and tumor RNA BAM\n and use them to generate a DataFrame of expressed variant protein\n sequences.\n '
expressed_variants = load_vcf(expressed_vcf)
not_expressed_variants = load_vcf(not_expressed_vcf)
combined_variants = VariantCollection((list(expressed_variants) + list(not_expressed_variants)))
samfile = load_bam(tumor_rna_bam)
allele_reads_generator = reads_overlapping_variants(variants=combined_variants, samfile=samfile, min_mapping_quality=min_mapping_quality)
protein_sequences_generator = reads_generator_to_protein_sequences_generator(allele_reads_generator, max_protein_sequences_per_variant=max_protein_sequences_per_variant, variant_sequence_assembly=variant_sequence_assembly)
df = protein_sequences_generator_to_dataframe(protein_sequences_generator)
return (df, expressed_variants, combined_variants) | def variants_to_protein_sequences_dataframe(expressed_vcf='data/b16.f10/b16.expressed.vcf', not_expressed_vcf='data/b16.f10/b16.not-expressed.vcf', tumor_rna_bam='data/b16.f10/b16.combined.sorted.bam', min_mapping_quality=0, max_protein_sequences_per_variant=1, variant_sequence_assembly=False):
'\n Helper function to load pair of VCFs and tumor RNA BAM\n and use them to generate a DataFrame of expressed variant protein\n sequences.\n '
expressed_variants = load_vcf(expressed_vcf)
not_expressed_variants = load_vcf(not_expressed_vcf)
combined_variants = VariantCollection((list(expressed_variants) + list(not_expressed_variants)))
samfile = load_bam(tumor_rna_bam)
allele_reads_generator = reads_overlapping_variants(variants=combined_variants, samfile=samfile, min_mapping_quality=min_mapping_quality)
protein_sequences_generator = reads_generator_to_protein_sequences_generator(allele_reads_generator, max_protein_sequences_per_variant=max_protein_sequences_per_variant, variant_sequence_assembly=variant_sequence_assembly)
df = protein_sequences_generator_to_dataframe(protein_sequences_generator)
return (df, expressed_variants, combined_variants)<|docstring|>Helper function to load pair of VCFs and tumor RNA BAM
and use them to generate a DataFrame of expressed variant protein
sequences.<|endoftext|> |
2764ecf2c648be1ecf5e7217aa15d95d86d15e5ac20d96788cb4c15565f24989 | def parse_args():
'\n Load command line args.\n '
parser = argparse.ArgumentParser()
parser.add_argument('--input', metavar='<str>', type=str, required=True)
parser.add_argument('--output', metavar='<str>', help='Output', type=str, required=True)
args = parser.parse_args()
return args | Load command line args. | scripts/make_FINNGEN_study_table.py | parse_args | opentargets/v2d_data | 1 | python | def parse_args():
'\n \n '
parser = argparse.ArgumentParser()
parser.add_argument('--input', metavar='<str>', type=str, required=True)
parser.add_argument('--output', metavar='<str>', help='Output', type=str, required=True)
args = parser.parse_args()
return args | def parse_args():
'\n \n '
parser = argparse.ArgumentParser()
parser.add_argument('--input', metavar='<str>', type=str, required=True)
parser.add_argument('--output', metavar='<str>', help='Output', type=str, required=True)
args = parser.parse_args()
return args<|docstring|>Load command line args.<|endoftext|> |
166df5c1d829af0654e208b937d9db1507f79408d19343721772ab2e2ab3081f | def unpack(self, data):
'Unpack struct from binary string and return a dict.'
s = self.struct
return dict(zip(self.names, s.unpack(data))) | Unpack struct from binary string and return a dict. | microdbf/parsers.py | unpack | s0rg/microdbf | 0 | python | def unpack(self, data):
s = self.struct
return dict(zip(self.names, s.unpack(data))) | def unpack(self, data):
s = self.struct
return dict(zip(self.names, s.unpack(data)))<|docstring|>Unpack struct from binary string and return a dict.<|endoftext|> |
711de9b6fe66eb8aa619ca9b55feda1422ff2358e2234484ee2192b63503168a | def read(self, fd):
'Read struct from a file-like object (implenting read()).'
return self.unpack(fd.read(self.size)) | Read struct from a file-like object (implenting read()). | microdbf/parsers.py | read | s0rg/microdbf | 0 | python | def read(self, fd):
return self.unpack(fd.read(self.size)) | def read(self, fd):
return self.unpack(fd.read(self.size))<|docstring|>Read struct from a file-like object (implenting read()).<|endoftext|> |
4ee13ae06ec190b961d123470e84741e733ce5744c665aeb4633f93819b88222 | def __init__(self, version, encoding):
'Create a new field parser\n\n encoding is the character encoding to use when parsing\n strings.'
self.dbversion = version
self.encoding = encoding
self._lookup = self._create_lookup_table() | Create a new field parser
encoding is the character encoding to use when parsing
strings. | microdbf/parsers.py | __init__ | s0rg/microdbf | 0 | python | def __init__(self, version, encoding):
'Create a new field parser\n\n encoding is the character encoding to use when parsing\n strings.'
self.dbversion = version
self.encoding = encoding
self._lookup = self._create_lookup_table() | def __init__(self, version, encoding):
'Create a new field parser\n\n encoding is the character encoding to use when parsing\n strings.'
self.dbversion = version
self.encoding = encoding
self._lookup = self._create_lookup_table()<|docstring|>Create a new field parser
encoding is the character encoding to use when parsing
strings.<|endoftext|> |
a9613fb082e6a67efa0e6d28f04dec7500fcd15c67387190abd3372c6eac7128 | def _create_lookup_table(self):
'Create a lookup table for field types.'
lookup = {}
for name in dir(self):
if name.startswith('parse_'):
fld_type = name[6:]
if (len(fld_type) == 2):
lookup[int(fld_type)] = getattr(self, name)
return lookup | Create a lookup table for field types. | microdbf/parsers.py | _create_lookup_table | s0rg/microdbf | 0 | python | def _create_lookup_table(self):
lookup = {}
for name in dir(self):
if name.startswith('parse_'):
fld_type = name[6:]
if (len(fld_type) == 2):
lookup[int(fld_type)] = getattr(self, name)
return lookup | def _create_lookup_table(self):
lookup = {}
for name in dir(self):
if name.startswith('parse_'):
fld_type = name[6:]
if (len(fld_type) == 2):
lookup[int(fld_type)] = getattr(self, name)
return lookup<|docstring|>Create a lookup table for field types.<|endoftext|> |
f24748a8ae00a8fa4bb4f650257373bc9b5d588db367fefc5490e3e9eb73849b | def parse(self, field_type, data):
'Parse field and return value'
fn = self._lookup.get(field_type, (lambda d: d))
return fn(data) | Parse field and return value | microdbf/parsers.py | parse | s0rg/microdbf | 0 | python | def parse(self, field_type, data):
fn = self._lookup.get(field_type, (lambda d: d))
return fn(data) | def parse(self, field_type, data):
fn = self._lookup.get(field_type, (lambda d: d))
return fn(data)<|docstring|>Parse field and return value<|endoftext|> |
132c83c807461f81d2fa06e9d3062d8a77a6391e838c46a433496a20829f4756 | def parse_48(self, data):
'Parse flags field and return as byte string'
return data | Parse flags field and return as byte string | microdbf/parsers.py | parse_48 | s0rg/microdbf | 0 | python | def parse_48(self, data):
return data | def parse_48(self, data):
return data<|docstring|>Parse flags field and return as byte string<|endoftext|> |
0d28e16139248cc8fc04bd46f4308286030c87ca3653f56552fb687219ffe622 | def parse_67(self, data):
'Parse char field and return unicode string'
return str(data.rstrip(b'\x00 '), self.encoding) | Parse char field and return unicode string | microdbf/parsers.py | parse_67 | s0rg/microdbf | 0 | python | def parse_67(self, data):
return str(data.rstrip(b'\x00 '), self.encoding) | def parse_67(self, data):
return str(data.rstrip(b'\x00 '), self.encoding)<|docstring|>Parse char field and return unicode string<|endoftext|> |
8654c772044a2afe46938c84abeee9c1bf223750467eb65c9613c2a8b255db53 | def parse_68(self, data):
'Parse date field and return datetime.date or None'
try:
return datetime.date(int(data[:4]), int(data[4:6]), int(data[6:8]))
except ValueError:
if (data.strip(b' 0') == b''):
return None
raise ValueError('invalid date {!r}'.format(data)) | Parse date field and return datetime.date or None | microdbf/parsers.py | parse_68 | s0rg/microdbf | 0 | python | def parse_68(self, data):
try:
return datetime.date(int(data[:4]), int(data[4:6]), int(data[6:8]))
except ValueError:
if (data.strip(b' 0') == b):
return None
raise ValueError('invalid date {!r}'.format(data)) | def parse_68(self, data):
try:
return datetime.date(int(data[:4]), int(data[4:6]), int(data[6:8]))
except ValueError:
if (data.strip(b' 0') == b):
return None
raise ValueError('invalid date {!r}'.format(data))<|docstring|>Parse date field and return datetime.date or None<|endoftext|> |
45df2480566e64f1f437c5fc506bccce5fc2f237d80b4f92768bf544db637989 | def parse_70(self, data):
'Parse float field and return float or None'
if data.strip():
return float(data) | Parse float field and return float or None | microdbf/parsers.py | parse_70 | s0rg/microdbf | 0 | python | def parse_70(self, data):
if data.strip():
return float(data) | def parse_70(self, data):
if data.strip():
return float(data)<|docstring|>Parse float field and return float or None<|endoftext|> |
682991de82bdaba85e038952c431830550c3553e359e59d7687b4a323fb8f8ad | def parse_73(self, data):
'Parse integer or autoincrement field and return int.'
return struct.unpack('<i', data)[0] | Parse integer or autoincrement field and return int. | microdbf/parsers.py | parse_73 | s0rg/microdbf | 0 | python | def parse_73(self, data):
return struct.unpack('<i', data)[0] | def parse_73(self, data):
return struct.unpack('<i', data)[0]<|docstring|>Parse integer or autoincrement field and return int.<|endoftext|> |
e1d813aab0e8c137a4efcafbca510a46bb2fc614773eed1295b20ca3a62df4fe | def parse_76(self, data):
'Parse logical field and return True, False or None'
if (data in b'TtYy'):
return True
elif (data in b'FfNn'):
return False
elif (data in b'? '):
return None
message = 'Illegal value for logical field: {!r}'
raise ValueError(message.format(data)) | Parse logical field and return True, False or None | microdbf/parsers.py | parse_76 | s0rg/microdbf | 0 | python | def parse_76(self, data):
if (data in b'TtYy'):
return True
elif (data in b'FfNn'):
return False
elif (data in b'? '):
return None
message = 'Illegal value for logical field: {!r}'
raise ValueError(message.format(data)) | def parse_76(self, data):
if (data in b'TtYy'):
return True
elif (data in b'FfNn'):
return False
elif (data in b'? '):
return None
message = 'Illegal value for logical field: {!r}'
raise ValueError(message.format(data))<|docstring|>Parse logical field and return True, False or None<|endoftext|> |
7d262c70e712907cd9a019b9d1077386fe0c6d79d79e06c5b7edd0de2341db9e | def parse_78(self, data):
'Parse numeric field (N)\n\n Returns int, float or None if the field is empty.\n '
try:
return int(data)
except ValueError:
if data.strip():
return float(data.replace(b',', b'.')) | Parse numeric field (N)
Returns int, float or None if the field is empty. | microdbf/parsers.py | parse_78 | s0rg/microdbf | 0 | python | def parse_78(self, data):
'Parse numeric field (N)\n\n Returns int, float or None if the field is empty.\n '
try:
return int(data)
except ValueError:
if data.strip():
return float(data.replace(b',', b'.')) | def parse_78(self, data):
'Parse numeric field (N)\n\n Returns int, float or None if the field is empty.\n '
try:
return int(data)
except ValueError:
if data.strip():
return float(data.replace(b',', b'.'))<|docstring|>Parse numeric field (N)
Returns int, float or None if the field is empty.<|endoftext|> |
f28011f33111aa053a600b44478a0e7c3e3bd024fca1f2e902f8b58bbbbccaa4 | def parse_79(self, data):
'Parse long field (O) and return float.'
return struct.unpack('d', data)[0] | Parse long field (O) and return float. | microdbf/parsers.py | parse_79 | s0rg/microdbf | 0 | python | def parse_79(self, data):
return struct.unpack('d', data)[0] | def parse_79(self, data):
return struct.unpack('d', data)[0]<|docstring|>Parse long field (O) and return float.<|endoftext|> |
5a1293560a42786adfd87483270b1e3b9445e3e2ee5eb7a2a547c19eb0470aa0 | def parse_84(self, data):
'Parse time field (T)\n\n Returns datetime.datetime or None'
offset = 1721425
if data.strip():
(day, msec) = struct.unpack('<LL', data)
if day:
dt = datetime.datetime.fromordinal((day - offset))
delta = datetime.timedelta(seconds=(msec / 1000))
return (dt + delta) | Parse time field (T)
Returns datetime.datetime or None | microdbf/parsers.py | parse_84 | s0rg/microdbf | 0 | python | def parse_84(self, data):
'Parse time field (T)\n\n Returns datetime.datetime or None'
offset = 1721425
if data.strip():
(day, msec) = struct.unpack('<LL', data)
if day:
dt = datetime.datetime.fromordinal((day - offset))
delta = datetime.timedelta(seconds=(msec / 1000))
return (dt + delta) | def parse_84(self, data):
'Parse time field (T)\n\n Returns datetime.datetime or None'
offset = 1721425
if data.strip():
(day, msec) = struct.unpack('<LL', data)
if day:
dt = datetime.datetime.fromordinal((day - offset))
delta = datetime.timedelta(seconds=(msec / 1000))
return (dt + delta)<|docstring|>Parse time field (T)
Returns datetime.datetime or None<|endoftext|> |
1ce4754534c3433e3a1132a14d28d2b572acf236002ecfc9b19ca0156c836e7d | def parse_89(self, data):
'Parse currency field (Y) and return decimal.Decimal.\n\n The field is encoded as a 8-byte little endian integer\n with 4 digits of precision.'
value = struct.unpack('<q', data)[0]
return (Decimal(value) / 10000) | Parse currency field (Y) and return decimal.Decimal.
The field is encoded as a 8-byte little endian integer
with 4 digits of precision. | microdbf/parsers.py | parse_89 | s0rg/microdbf | 0 | python | def parse_89(self, data):
'Parse currency field (Y) and return decimal.Decimal.\n\n The field is encoded as a 8-byte little endian integer\n with 4 digits of precision.'
value = struct.unpack('<q', data)[0]
return (Decimal(value) / 10000) | def parse_89(self, data):
'Parse currency field (Y) and return decimal.Decimal.\n\n The field is encoded as a 8-byte little endian integer\n with 4 digits of precision.'
value = struct.unpack('<q', data)[0]
return (Decimal(value) / 10000)<|docstring|>Parse currency field (Y) and return decimal.Decimal.
The field is encoded as a 8-byte little endian integer
with 4 digits of precision.<|endoftext|> |
e60e7fcc6868a2b00e64292f5e9e7a2980d00a25a21bc7967b8b93898951bfd2 | def parse_66(self, data):
'Binary memo field or double precision floating point number\n\n dBase uses B to represent a memo index (10 bytes), while\n Visual FoxPro uses it to store a double precision floating\n point number (8 bytes).\n '
if (self.dbversion in (48, 49, 50)):
return struct.unpack('d', data)[0] | Binary memo field or double precision floating point number
dBase uses B to represent a memo index (10 bytes), while
Visual FoxPro uses it to store a double precision floating
point number (8 bytes). | microdbf/parsers.py | parse_66 | s0rg/microdbf | 0 | python | def parse_66(self, data):
'Binary memo field or double precision floating point number\n\n dBase uses B to represent a memo index (10 bytes), while\n Visual FoxPro uses it to store a double precision floating\n point number (8 bytes).\n '
if (self.dbversion in (48, 49, 50)):
return struct.unpack('d', data)[0] | def parse_66(self, data):
'Binary memo field or double precision floating point number\n\n dBase uses B to represent a memo index (10 bytes), while\n Visual FoxPro uses it to store a double precision floating\n point number (8 bytes).\n '
if (self.dbversion in (48, 49, 50)):
return struct.unpack('d', data)[0]<|docstring|>Binary memo field or double precision floating point number
dBase uses B to represent a memo index (10 bytes), while
Visual FoxPro uses it to store a double precision floating
point number (8 bytes).<|endoftext|> |
95eea786b8bca3bffac87da3cf31b40ac841784d373d5eae885c509e49390e9b | def split_gpxs(xml):
'\n Split single tracks from this one, without parsing with gpxpy\n '
dom = mod_minidom.parseString(xml)
gpx_node = _find_gpx_node(dom)
gpx_track_nodes = []
if gpx_node:
for child_node in gpx_node.childNodes:
if (child_node.nodeName == 'trk'):
gpx_track_nodes.append(child_node)
gpx_node.removeChild(child_node)
for gpx_track_node in gpx_track_nodes:
gpx_node.appendChild(gpx_track_node)
(yield dom.toxml())
gpx_node.removeChild(gpx_track_node) | Split single tracks from this one, without parsing with gpxpy | InternalPythonModules/GPX_Module/gpxpy/gpxxml.py | split_gpxs | drwetter/autopsy | 1,473 | python | def split_gpxs(xml):
'\n \n '
dom = mod_minidom.parseString(xml)
gpx_node = _find_gpx_node(dom)
gpx_track_nodes = []
if gpx_node:
for child_node in gpx_node.childNodes:
if (child_node.nodeName == 'trk'):
gpx_track_nodes.append(child_node)
gpx_node.removeChild(child_node)
for gpx_track_node in gpx_track_nodes:
gpx_node.appendChild(gpx_track_node)
(yield dom.toxml())
gpx_node.removeChild(gpx_track_node) | def split_gpxs(xml):
'\n \n '
dom = mod_minidom.parseString(xml)
gpx_node = _find_gpx_node(dom)
gpx_track_nodes = []
if gpx_node:
for child_node in gpx_node.childNodes:
if (child_node.nodeName == 'trk'):
gpx_track_nodes.append(child_node)
gpx_node.removeChild(child_node)
for gpx_track_node in gpx_track_nodes:
gpx_node.appendChild(gpx_track_node)
(yield dom.toxml())
gpx_node.removeChild(gpx_track_node)<|docstring|>Split single tracks from this one, without parsing with gpxpy<|endoftext|> |
d56d00330e0a360e74666cc29d5a2d29da5a91f5390e7b1f6b7075680e57446f | def join_gpxs(xmls):
'\n Utility to join GPX files without parsing them with gpxpy\n '
result = None
wpt_elements = []
rte_elements = []
trk_elements = []
for xml in xmls:
dom = mod_minidom.parseString(xml)
if (not result):
result = dom
gpx_node = _find_gpx_node(dom)
if gpx_node:
for child_node in gpx_node.childNodes:
if (child_node.nodeName == 'wpt'):
wpt_elements.append(child_node)
gpx_node.removeChild(child_node)
elif (child_node.nodeName == 'rte'):
rte_elements.append(child_node)
gpx_node.removeChild(child_node)
elif (child_node.nodeName == 'trk'):
trk_elements.append(child_node)
gpx_node.removeChild(child_node)
gpx_node = _find_gpx_node(result)
if gpx_node:
for wpt_element in wpt_elements:
gpx_node.appendChild(wpt_element)
for rte_element in rte_elements:
gpx_node.appendChild(rte_element)
for trk_element in trk_elements:
gpx_node.appendChild(trk_element)
return result.toxml() | Utility to join GPX files without parsing them with gpxpy | InternalPythonModules/GPX_Module/gpxpy/gpxxml.py | join_gpxs | drwetter/autopsy | 1,473 | python | def join_gpxs(xmls):
'\n \n '
result = None
wpt_elements = []
rte_elements = []
trk_elements = []
for xml in xmls:
dom = mod_minidom.parseString(xml)
if (not result):
result = dom
gpx_node = _find_gpx_node(dom)
if gpx_node:
for child_node in gpx_node.childNodes:
if (child_node.nodeName == 'wpt'):
wpt_elements.append(child_node)
gpx_node.removeChild(child_node)
elif (child_node.nodeName == 'rte'):
rte_elements.append(child_node)
gpx_node.removeChild(child_node)
elif (child_node.nodeName == 'trk'):
trk_elements.append(child_node)
gpx_node.removeChild(child_node)
gpx_node = _find_gpx_node(result)
if gpx_node:
for wpt_element in wpt_elements:
gpx_node.appendChild(wpt_element)
for rte_element in rte_elements:
gpx_node.appendChild(rte_element)
for trk_element in trk_elements:
gpx_node.appendChild(trk_element)
return result.toxml() | def join_gpxs(xmls):
'\n \n '
result = None
wpt_elements = []
rte_elements = []
trk_elements = []
for xml in xmls:
dom = mod_minidom.parseString(xml)
if (not result):
result = dom
gpx_node = _find_gpx_node(dom)
if gpx_node:
for child_node in gpx_node.childNodes:
if (child_node.nodeName == 'wpt'):
wpt_elements.append(child_node)
gpx_node.removeChild(child_node)
elif (child_node.nodeName == 'rte'):
rte_elements.append(child_node)
gpx_node.removeChild(child_node)
elif (child_node.nodeName == 'trk'):
trk_elements.append(child_node)
gpx_node.removeChild(child_node)
gpx_node = _find_gpx_node(result)
if gpx_node:
for wpt_element in wpt_elements:
gpx_node.appendChild(wpt_element)
for rte_element in rte_elements:
gpx_node.appendChild(rte_element)
for trk_element in trk_elements:
gpx_node.appendChild(trk_element)
return result.toxml()<|docstring|>Utility to join GPX files without parsing them with gpxpy<|endoftext|> |
e1a155709dfbdc93cde1bb7cd941a4fc0d43c795a30b2e5e7ebdb2af5d29e140 | def broadcast(self, parameter):
"Broadcast the parameter to the object of ``self``.\n\n Parameters\n ----------\n\n parameters : scalar, numpy array or pandas object\n The parameter to broadcast to\n\n Returns\n -------\n parameter, object : index aligned numerical objects\n\n\n The\n\n\n Examples\n --------\n\n The behavior of the Broadcaster is best illustrated by examples:\n\n .. jupyter-execute::\n :hide-code:\n\n import pandas as pd\n from pylife import Broadcaster\n\n * Broadcasting :class:`pandas.Series` to a scalar results in a scalar\n and a :class:`pandas.Series`.\n\n .. jupyter-execute::\n\n obj = pd.Series([1.0, 2.0], index=pd.Index(['foo', 'bar'], name='idx'))\n obj\n\n .. jupyter-execute::\n\n parameter, obj = Broadcaster(obj).broadcast(5.0)\n\n parameter\n\n .. jupyter-execute::\n\n obj\n\n\n * Broadcasting :class:`pandas.DataFrame` to a scalar results in a\n :class:`pandas.DataFrame` and a :class:`pandas.Series`.\n\n .. jupyter-execute::\n\n obj = pd.DataFrame({\n 'foo': [1.0, 2.0],\n 'bar': [3.0, 4.0]\n }, index=pd.Index([1, 2], name='idx'))\n obj\n\n .. jupyter-execute::\n\n parameter, obj = Broadcaster(obj).broadcast(5.0)\n\n parameter\n\n .. jupyter-execute::\n\n obj\n\n\n * Broadcasting :class:`pandas.DataFrame` to a a :class:`pandas.Series`\n results in a :class:`pandas.DataFrame` and a :class:`pandas.Series`,\n **if and only if** the index name of the object is ``None``.\n\n .. jupyter-execute::\n\n obj = pd.Series([1.0, 2.0], index=pd.Index(['tau', 'chi']))\n obj\n\n .. jupyter-execute::\n\n parameter = pd.Series([3.0, 4.0], index=pd.Index(['foo', 'bar'], name='idx'))\n parameter\n\n .. jupyter-execute::\n\n parameter, obj = Broadcaster(obj).broadcast(parameter)\n\n parameter\n\n .. jupyter-execute::\n\n obj\n\n "
if ((not isinstance(parameter, pd.Series)) and (not isinstance(parameter, pd.DataFrame))):
if isinstance(self._obj, pd.Series):
return self._broadcast_series(parameter)
return self._broadcast_frame(parameter)
if ((self._obj.index.names == [None]) and isinstance(self._obj, pd.Series)):
df = pd.DataFrame(index=parameter.index, columns=self._obj.index)
for c in self._obj.index:
df.loc[(:, c)] = self._obj[c]
return (parameter, df)
return self._broadcast_frame_to_frame(parameter) | Broadcast the parameter to the object of ``self``.
Parameters
----------
parameters : scalar, numpy array or pandas object
The parameter to broadcast to
Returns
-------
parameter, object : index aligned numerical objects
The
Examples
--------
The behavior of the Broadcaster is best illustrated by examples:
.. jupyter-execute::
:hide-code:
import pandas as pd
from pylife import Broadcaster
* Broadcasting :class:`pandas.Series` to a scalar results in a scalar
and a :class:`pandas.Series`.
.. jupyter-execute::
obj = pd.Series([1.0, 2.0], index=pd.Index(['foo', 'bar'], name='idx'))
obj
.. jupyter-execute::
parameter, obj = Broadcaster(obj).broadcast(5.0)
parameter
.. jupyter-execute::
obj
* Broadcasting :class:`pandas.DataFrame` to a scalar results in a
:class:`pandas.DataFrame` and a :class:`pandas.Series`.
.. jupyter-execute::
obj = pd.DataFrame({
'foo': [1.0, 2.0],
'bar': [3.0, 4.0]
}, index=pd.Index([1, 2], name='idx'))
obj
.. jupyter-execute::
parameter, obj = Broadcaster(obj).broadcast(5.0)
parameter
.. jupyter-execute::
obj
* Broadcasting :class:`pandas.DataFrame` to a a :class:`pandas.Series`
results in a :class:`pandas.DataFrame` and a :class:`pandas.Series`,
**if and only if** the index name of the object is ``None``.
.. jupyter-execute::
obj = pd.Series([1.0, 2.0], index=pd.Index(['tau', 'chi']))
obj
.. jupyter-execute::
parameter = pd.Series([3.0, 4.0], index=pd.Index(['foo', 'bar'], name='idx'))
parameter
.. jupyter-execute::
parameter, obj = Broadcaster(obj).broadcast(parameter)
parameter
.. jupyter-execute::
obj | src/pylife/core/broadcaster.py | broadcast | alexander-maier/pylife | 57 | python | def broadcast(self, parameter):
"Broadcast the parameter to the object of ``self``.\n\n Parameters\n ----------\n\n parameters : scalar, numpy array or pandas object\n The parameter to broadcast to\n\n Returns\n -------\n parameter, object : index aligned numerical objects\n\n\n The\n\n\n Examples\n --------\n\n The behavior of the Broadcaster is best illustrated by examples:\n\n .. jupyter-execute::\n :hide-code:\n\n import pandas as pd\n from pylife import Broadcaster\n\n * Broadcasting :class:`pandas.Series` to a scalar results in a scalar\n and a :class:`pandas.Series`.\n\n .. jupyter-execute::\n\n obj = pd.Series([1.0, 2.0], index=pd.Index(['foo', 'bar'], name='idx'))\n obj\n\n .. jupyter-execute::\n\n parameter, obj = Broadcaster(obj).broadcast(5.0)\n\n parameter\n\n .. jupyter-execute::\n\n obj\n\n\n * Broadcasting :class:`pandas.DataFrame` to a scalar results in a\n :class:`pandas.DataFrame` and a :class:`pandas.Series`.\n\n .. jupyter-execute::\n\n obj = pd.DataFrame({\n 'foo': [1.0, 2.0],\n 'bar': [3.0, 4.0]\n }, index=pd.Index([1, 2], name='idx'))\n obj\n\n .. jupyter-execute::\n\n parameter, obj = Broadcaster(obj).broadcast(5.0)\n\n parameter\n\n .. jupyter-execute::\n\n obj\n\n\n * Broadcasting :class:`pandas.DataFrame` to a a :class:`pandas.Series`\n results in a :class:`pandas.DataFrame` and a :class:`pandas.Series`,\n **if and only if** the index name of the object is ``None``.\n\n .. jupyter-execute::\n\n obj = pd.Series([1.0, 2.0], index=pd.Index(['tau', 'chi']))\n obj\n\n .. jupyter-execute::\n\n parameter = pd.Series([3.0, 4.0], index=pd.Index(['foo', 'bar'], name='idx'))\n parameter\n\n .. jupyter-execute::\n\n parameter, obj = Broadcaster(obj).broadcast(parameter)\n\n parameter\n\n .. jupyter-execute::\n\n obj\n\n "
if ((not isinstance(parameter, pd.Series)) and (not isinstance(parameter, pd.DataFrame))):
if isinstance(self._obj, pd.Series):
return self._broadcast_series(parameter)
return self._broadcast_frame(parameter)
if ((self._obj.index.names == [None]) and isinstance(self._obj, pd.Series)):
df = pd.DataFrame(index=parameter.index, columns=self._obj.index)
for c in self._obj.index:
df.loc[(:, c)] = self._obj[c]
return (parameter, df)
return self._broadcast_frame_to_frame(parameter) | def broadcast(self, parameter):
"Broadcast the parameter to the object of ``self``.\n\n Parameters\n ----------\n\n parameters : scalar, numpy array or pandas object\n The parameter to broadcast to\n\n Returns\n -------\n parameter, object : index aligned numerical objects\n\n\n The\n\n\n Examples\n --------\n\n The behavior of the Broadcaster is best illustrated by examples:\n\n .. jupyter-execute::\n :hide-code:\n\n import pandas as pd\n from pylife import Broadcaster\n\n * Broadcasting :class:`pandas.Series` to a scalar results in a scalar\n and a :class:`pandas.Series`.\n\n .. jupyter-execute::\n\n obj = pd.Series([1.0, 2.0], index=pd.Index(['foo', 'bar'], name='idx'))\n obj\n\n .. jupyter-execute::\n\n parameter, obj = Broadcaster(obj).broadcast(5.0)\n\n parameter\n\n .. jupyter-execute::\n\n obj\n\n\n * Broadcasting :class:`pandas.DataFrame` to a scalar results in a\n :class:`pandas.DataFrame` and a :class:`pandas.Series`.\n\n .. jupyter-execute::\n\n obj = pd.DataFrame({\n 'foo': [1.0, 2.0],\n 'bar': [3.0, 4.0]\n }, index=pd.Index([1, 2], name='idx'))\n obj\n\n .. jupyter-execute::\n\n parameter, obj = Broadcaster(obj).broadcast(5.0)\n\n parameter\n\n .. jupyter-execute::\n\n obj\n\n\n * Broadcasting :class:`pandas.DataFrame` to a a :class:`pandas.Series`\n results in a :class:`pandas.DataFrame` and a :class:`pandas.Series`,\n **if and only if** the index name of the object is ``None``.\n\n .. jupyter-execute::\n\n obj = pd.Series([1.0, 2.0], index=pd.Index(['tau', 'chi']))\n obj\n\n .. jupyter-execute::\n\n parameter = pd.Series([3.0, 4.0], index=pd.Index(['foo', 'bar'], name='idx'))\n parameter\n\n .. jupyter-execute::\n\n parameter, obj = Broadcaster(obj).broadcast(parameter)\n\n parameter\n\n .. jupyter-execute::\n\n obj\n\n "
if ((not isinstance(parameter, pd.Series)) and (not isinstance(parameter, pd.DataFrame))):
if isinstance(self._obj, pd.Series):
return self._broadcast_series(parameter)
return self._broadcast_frame(parameter)
if ((self._obj.index.names == [None]) and isinstance(self._obj, pd.Series)):
df = pd.DataFrame(index=parameter.index, columns=self._obj.index)
for c in self._obj.index:
df.loc[(:, c)] = self._obj[c]
return (parameter, df)
return self._broadcast_frame_to_frame(parameter)<|docstring|>Broadcast the parameter to the object of ``self``.
Parameters
----------
parameters : scalar, numpy array or pandas object
The parameter to broadcast to
Returns
-------
parameter, object : index aligned numerical objects
The
Examples
--------
The behavior of the Broadcaster is best illustrated by examples:
.. jupyter-execute::
:hide-code:
import pandas as pd
from pylife import Broadcaster
* Broadcasting :class:`pandas.Series` to a scalar results in a scalar
and a :class:`pandas.Series`.
.. jupyter-execute::
obj = pd.Series([1.0, 2.0], index=pd.Index(['foo', 'bar'], name='idx'))
obj
.. jupyter-execute::
parameter, obj = Broadcaster(obj).broadcast(5.0)
parameter
.. jupyter-execute::
obj
* Broadcasting :class:`pandas.DataFrame` to a scalar results in a
:class:`pandas.DataFrame` and a :class:`pandas.Series`.
.. jupyter-execute::
obj = pd.DataFrame({
'foo': [1.0, 2.0],
'bar': [3.0, 4.0]
}, index=pd.Index([1, 2], name='idx'))
obj
.. jupyter-execute::
parameter, obj = Broadcaster(obj).broadcast(5.0)
parameter
.. jupyter-execute::
obj
* Broadcasting :class:`pandas.DataFrame` to a a :class:`pandas.Series`
results in a :class:`pandas.DataFrame` and a :class:`pandas.Series`,
**if and only if** the index name of the object is ``None``.
.. jupyter-execute::
obj = pd.Series([1.0, 2.0], index=pd.Index(['tau', 'chi']))
obj
.. jupyter-execute::
parameter = pd.Series([3.0, 4.0], index=pd.Index(['foo', 'bar'], name='idx'))
parameter
.. jupyter-execute::
parameter, obj = Broadcaster(obj).broadcast(parameter)
parameter
.. jupyter-execute::
obj<|endoftext|> |
8ffe061aa0e445f089e1b66a69494b231d613520caac169807db0b88aca4ca85 | def cli():
'\n Entrypoint for the cli\n '
if (len(sys.argv) == 1):
raise Exception('Providing only stdin input is not yet supported (at least one argument must be given)')
else:
app = App(sys.stdin)
fire.Fire(app) | Entrypoint for the cli | modelator_py/cli.py | cli | informalsystems/modelator-py | 0 | python | def cli():
'\n \n '
if (len(sys.argv) == 1):
raise Exception('Providing only stdin input is not yet supported (at least one argument must be given)')
else:
app = App(sys.stdin)
fire.Fire(app) | def cli():
'\n \n '
if (len(sys.argv) == 1):
raise Exception('Providing only stdin input is not yet supported (at least one argument must be given)')
else:
app = App(sys.stdin)
fire.Fire(app)<|docstring|>Entrypoint for the cli<|endoftext|> |
ea5b1826278e3bee55a75574b9cf28925aaf08ee8eea3ff28191702be657e25a | def easter(self, fizz, *, foo=True, bar=None, wiz):
'\n This is an easter egg function designed as an example.\n\n You can read this documentation with `<prefix> easter --help`.\n\n Arguments:\n fizz : Crackle, pop!\n foo : Is it a bird, is it a plane?\n bar : How much wood would a woodchuck chuck?\n wiz : If Peter Piper picked a peck of pickled peppers...\n '
print(f'Warning: this is just an example command: foo={foo!r} bar={bar!r} wiz={wiz!r}') | This is an easter egg function designed as an example.
You can read this documentation with `<prefix> easter --help`.
Arguments:
fizz : Crackle, pop!
foo : Is it a bird, is it a plane?
bar : How much wood would a woodchuck chuck?
wiz : If Peter Piper picked a peck of pickled peppers... | modelator_py/cli.py | easter | informalsystems/modelator-py | 0 | python | def easter(self, fizz, *, foo=True, bar=None, wiz):
'\n This is an easter egg function designed as an example.\n\n You can read this documentation with `<prefix> easter --help`.\n\n Arguments:\n fizz : Crackle, pop!\n foo : Is it a bird, is it a plane?\n bar : How much wood would a woodchuck chuck?\n wiz : If Peter Piper picked a peck of pickled peppers...\n '
print(f'Warning: this is just an example command: foo={foo!r} bar={bar!r} wiz={wiz!r}') | def easter(self, fizz, *, foo=True, bar=None, wiz):
'\n This is an easter egg function designed as an example.\n\n You can read this documentation with `<prefix> easter --help`.\n\n Arguments:\n fizz : Crackle, pop!\n foo : Is it a bird, is it a plane?\n bar : How much wood would a woodchuck chuck?\n wiz : If Peter Piper picked a peck of pickled peppers...\n '
print(f'Warning: this is just an example command: foo={foo!r} bar={bar!r} wiz={wiz!r}')<|docstring|>This is an easter egg function designed as an example.
You can read this documentation with `<prefix> easter --help`.
Arguments:
fizz : Crackle, pop!
foo : Is it a bird, is it a plane?
bar : How much wood would a woodchuck chuck?
wiz : If Peter Piper picked a peck of pickled peppers...<|endoftext|> |
d2fe7989fe6c2633d8fe2a06e9045abbbffaaa9917a15bb3ded411a6845e88a8 | def dms_to_decimal(degrees, minutes, seconds, sign=' '):
"Convert degrees, minutes, seconds into decimal degrees.\n\n >>> dms_to_decimal(10, 10, 10)\n 10.169444444444444\n >>> dms_to_decimal(8, 9, 10, 'S')\n -8.152777777777779\n "
return (((- 1) if (sign[0] in 'SWsw') else 1) * ((float((degrees[0] / degrees[1])) + (float((minutes[0] / minutes[1])) / 60)) + (float((seconds[0] / seconds[1])) / 3600))) | Convert degrees, minutes, seconds into decimal degrees.
>>> dms_to_decimal(10, 10, 10)
10.169444444444444
>>> dms_to_decimal(8, 9, 10, 'S')
-8.152777777777779 | scripts/lib/exif.py | dms_to_decimal | UASLab/ImageAnalysis | 93 | python | def dms_to_decimal(degrees, minutes, seconds, sign=' '):
"Convert degrees, minutes, seconds into decimal degrees.\n\n >>> dms_to_decimal(10, 10, 10)\n 10.169444444444444\n >>> dms_to_decimal(8, 9, 10, 'S')\n -8.152777777777779\n "
return (((- 1) if (sign[0] in 'SWsw') else 1) * ((float((degrees[0] / degrees[1])) + (float((minutes[0] / minutes[1])) / 60)) + (float((seconds[0] / seconds[1])) / 3600))) | def dms_to_decimal(degrees, minutes, seconds, sign=' '):
"Convert degrees, minutes, seconds into decimal degrees.\n\n >>> dms_to_decimal(10, 10, 10)\n 10.169444444444444\n >>> dms_to_decimal(8, 9, 10, 'S')\n -8.152777777777779\n "
return (((- 1) if (sign[0] in 'SWsw') else 1) * ((float((degrees[0] / degrees[1])) + (float((minutes[0] / minutes[1])) / 60)) + (float((seconds[0] / seconds[1])) / 3600)))<|docstring|>Convert degrees, minutes, seconds into decimal degrees.
>>> dms_to_decimal(10, 10, 10)
10.169444444444444
>>> dms_to_decimal(8, 9, 10, 'S')
-8.152777777777779<|endoftext|> |
6c59cacbdbae9d14993c0abe74ff7a0b926dcdadc3d619ac9080a756a1bfb3f6 | @authorize_wsgi.authorize_wsgi('cyborg:deployable', 'program', False)
@expose.expose(Deployable, types.uuid, body=[DeployablePatchType])
def program(self, uuid, program_info):
'Program a new deployable(FPGA).\n\n :param uuid: The uuid of the target deployable.\n :param program_info: JSON string containing what to program.\n :raise: FPGAProgramError: If fpga program failed raise exception.\n :return: If fpga program success return deployable object.\n '
image_uuid = program_info[0]['value'][0]['image_uuid']
try:
types.UUIDType().validate(image_uuid)
except Exception:
raise
obj_dep = objects.Deployable.get(pecan.request.context, uuid)
obj_dev = objects.Device.get_by_device_id(pecan.request.context, obj_dep.device_id)
hostname = obj_dev.hostname
driver_name = obj_dep.driver_name
cpid_list = obj_dep.get_cpid_list(pecan.request.context)
controlpath_id = cpid_list[0]
controlpath_id['cpid_info'] = jsonutils.loads(cpid_list[0]['cpid_info'])
self.agent_rpcapi = AgentAPI()
ret = self.agent_rpcapi.fpga_program(pecan.request.context, hostname, controlpath_id, image_uuid, driver_name)
if ret:
return self.convert_with_link(obj_dep)
else:
raise exc.FPGAProgramError(ret=ret) | Program a new deployable(FPGA).
:param uuid: The uuid of the target deployable.
:param program_info: JSON string containing what to program.
:raise: FPGAProgramError: If fpga program failed raise exception.
:return: If fpga program success return deployable object. | cyborg/api/controllers/v2/deployables.py | program | NeCTAR-RC/cyborg | 37 | python | @authorize_wsgi.authorize_wsgi('cyborg:deployable', 'program', False)
@expose.expose(Deployable, types.uuid, body=[DeployablePatchType])
def program(self, uuid, program_info):
'Program a new deployable(FPGA).\n\n :param uuid: The uuid of the target deployable.\n :param program_info: JSON string containing what to program.\n :raise: FPGAProgramError: If fpga program failed raise exception.\n :return: If fpga program success return deployable object.\n '
image_uuid = program_info[0]['value'][0]['image_uuid']
try:
types.UUIDType().validate(image_uuid)
except Exception:
raise
obj_dep = objects.Deployable.get(pecan.request.context, uuid)
obj_dev = objects.Device.get_by_device_id(pecan.request.context, obj_dep.device_id)
hostname = obj_dev.hostname
driver_name = obj_dep.driver_name
cpid_list = obj_dep.get_cpid_list(pecan.request.context)
controlpath_id = cpid_list[0]
controlpath_id['cpid_info'] = jsonutils.loads(cpid_list[0]['cpid_info'])
self.agent_rpcapi = AgentAPI()
ret = self.agent_rpcapi.fpga_program(pecan.request.context, hostname, controlpath_id, image_uuid, driver_name)
if ret:
return self.convert_with_link(obj_dep)
else:
raise exc.FPGAProgramError(ret=ret) | @authorize_wsgi.authorize_wsgi('cyborg:deployable', 'program', False)
@expose.expose(Deployable, types.uuid, body=[DeployablePatchType])
def program(self, uuid, program_info):
'Program a new deployable(FPGA).\n\n :param uuid: The uuid of the target deployable.\n :param program_info: JSON string containing what to program.\n :raise: FPGAProgramError: If fpga program failed raise exception.\n :return: If fpga program success return deployable object.\n '
image_uuid = program_info[0]['value'][0]['image_uuid']
try:
types.UUIDType().validate(image_uuid)
except Exception:
raise
obj_dep = objects.Deployable.get(pecan.request.context, uuid)
obj_dev = objects.Device.get_by_device_id(pecan.request.context, obj_dep.device_id)
hostname = obj_dev.hostname
driver_name = obj_dep.driver_name
cpid_list = obj_dep.get_cpid_list(pecan.request.context)
controlpath_id = cpid_list[0]
controlpath_id['cpid_info'] = jsonutils.loads(cpid_list[0]['cpid_info'])
self.agent_rpcapi = AgentAPI()
ret = self.agent_rpcapi.fpga_program(pecan.request.context, hostname, controlpath_id, image_uuid, driver_name)
if ret:
return self.convert_with_link(obj_dep)
else:
raise exc.FPGAProgramError(ret=ret)<|docstring|>Program a new deployable(FPGA).
:param uuid: The uuid of the target deployable.
:param program_info: JSON string containing what to program.
:raise: FPGAProgramError: If fpga program failed raise exception.
:return: If fpga program success return deployable object.<|endoftext|> |
28af58d57e99865cc43d201bcce958b633f9cb223e347cc31c46d8dbc71ea0ae | @authorize_wsgi.authorize_wsgi('cyborg:deployable', 'get_one')
@expose.expose(Deployable, types.uuid)
def get_one(self, uuid):
'Retrieve information about the given deployable.\n\n :param uuid: UUID of a deployable.\n '
obj_dep = objects.Deployable.get(pecan.request.context, uuid)
return self.convert_with_link(obj_dep) | Retrieve information about the given deployable.
:param uuid: UUID of a deployable. | cyborg/api/controllers/v2/deployables.py | get_one | NeCTAR-RC/cyborg | 37 | python | @authorize_wsgi.authorize_wsgi('cyborg:deployable', 'get_one')
@expose.expose(Deployable, types.uuid)
def get_one(self, uuid):
'Retrieve information about the given deployable.\n\n :param uuid: UUID of a deployable.\n '
obj_dep = objects.Deployable.get(pecan.request.context, uuid)
return self.convert_with_link(obj_dep) | @authorize_wsgi.authorize_wsgi('cyborg:deployable', 'get_one')
@expose.expose(Deployable, types.uuid)
def get_one(self, uuid):
'Retrieve information about the given deployable.\n\n :param uuid: UUID of a deployable.\n '
obj_dep = objects.Deployable.get(pecan.request.context, uuid)
return self.convert_with_link(obj_dep)<|docstring|>Retrieve information about the given deployable.
:param uuid: UUID of a deployable.<|endoftext|> |
6f95d1b835d93b54eb2b33dc8b36f92de5115ea7cfb1509c650ed404cfe729b6 | @authorize_wsgi.authorize_wsgi('cyborg:deployable', 'get_all')
@expose.expose(DeployableCollection, wtypes.ArrayType(types.FilterType))
def get_all(self, filters=None):
'Retrieve a list of deployables.\n :param filters: a filter of FilterType to get deployables list by\n filter.\n '
filters_dict = {}
if filters:
for filter in filters:
filters_dict.update(filter.as_dict())
context = pecan.request.context
obj_deps = objects.Deployable.list(context, filters=filters_dict)
return self.convert_with_links(obj_deps) | Retrieve a list of deployables.
:param filters: a filter of FilterType to get deployables list by
filter. | cyborg/api/controllers/v2/deployables.py | get_all | NeCTAR-RC/cyborg | 37 | python | @authorize_wsgi.authorize_wsgi('cyborg:deployable', 'get_all')
@expose.expose(DeployableCollection, wtypes.ArrayType(types.FilterType))
def get_all(self, filters=None):
'Retrieve a list of deployables.\n :param filters: a filter of FilterType to get deployables list by\n filter.\n '
filters_dict = {}
if filters:
for filter in filters:
filters_dict.update(filter.as_dict())
context = pecan.request.context
obj_deps = objects.Deployable.list(context, filters=filters_dict)
return self.convert_with_links(obj_deps) | @authorize_wsgi.authorize_wsgi('cyborg:deployable', 'get_all')
@expose.expose(DeployableCollection, wtypes.ArrayType(types.FilterType))
def get_all(self, filters=None):
'Retrieve a list of deployables.\n :param filters: a filter of FilterType to get deployables list by\n filter.\n '
filters_dict = {}
if filters:
for filter in filters:
filters_dict.update(filter.as_dict())
context = pecan.request.context
obj_deps = objects.Deployable.list(context, filters=filters_dict)
return self.convert_with_links(obj_deps)<|docstring|>Retrieve a list of deployables.
:param filters: a filter of FilterType to get deployables list by
filter.<|endoftext|> |
25a61517fd7aaafcd9db015bc1931e0658053b45fc91e1b87cdf5598a00f4d74 | def _get_aggregate_sid_counters(self):
'\n Getter method for aggregate_sid_counters, mapped from YANG variable /network_instances/network_instance/mpls/signaling_protocols/segment_routing/aggregate_sid_counters (container)\n\n YANG Description: Per-SID counters aggregated across all interfaces on the local system\n '
return self.__aggregate_sid_counters | Getter method for aggregate_sid_counters, mapped from YANG variable /network_instances/network_instance/mpls/signaling_protocols/segment_routing/aggregate_sid_counters (container)
YANG Description: Per-SID counters aggregated across all interfaces on the local system | napalm_yang/models/openconfig/network_instances/network_instance/mpls/signaling_protocols/segment_routing/__init__.py | _get_aggregate_sid_counters | ckishimo/napalm-yang | 64 | python | def _get_aggregate_sid_counters(self):
'\n Getter method for aggregate_sid_counters, mapped from YANG variable /network_instances/network_instance/mpls/signaling_protocols/segment_routing/aggregate_sid_counters (container)\n\n YANG Description: Per-SID counters aggregated across all interfaces on the local system\n '
return self.__aggregate_sid_counters | def _get_aggregate_sid_counters(self):
'\n Getter method for aggregate_sid_counters, mapped from YANG variable /network_instances/network_instance/mpls/signaling_protocols/segment_routing/aggregate_sid_counters (container)\n\n YANG Description: Per-SID counters aggregated across all interfaces on the local system\n '
return self.__aggregate_sid_counters<|docstring|>Getter method for aggregate_sid_counters, mapped from YANG variable /network_instances/network_instance/mpls/signaling_protocols/segment_routing/aggregate_sid_counters (container)
YANG Description: Per-SID counters aggregated across all interfaces on the local system<|endoftext|> |
b423bcaa4ccec12b33c5fb50412160f3dfe487fea85ecc0fc88a63e5e927ed36 | def _set_aggregate_sid_counters(self, v, load=False):
'\n Setter method for aggregate_sid_counters, mapped from YANG variable /network_instances/network_instance/mpls/signaling_protocols/segment_routing/aggregate_sid_counters (container)\n If this variable is read-only (config: false) in the\n source YANG file, then _set_aggregate_sid_counters is considered as a private\n method. Backends looking to populate this variable should\n do so via calling thisObj._set_aggregate_sid_counters() directly.\n\n YANG Description: Per-SID counters aggregated across all interfaces on the local system\n '
if hasattr(v, '_utype'):
v = v._utype(v)
try:
t = YANGDynClass(v, base=aggregate_sid_counters.aggregate_sid_counters, is_container='container', yang_name='aggregate-sid-counters', parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/network-instance', defining_module='openconfig-network-instance', yang_type='container', is_config=True)
except (TypeError, ValueError):
raise ValueError({'error-string': 'aggregate_sid_counters must be of a type compatible with container', 'defined-type': 'container', 'generated-type': 'YANGDynClass(base=aggregate_sid_counters.aggregate_sid_counters, is_container=\'container\', yang_name="aggregate-sid-counters", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace=\'http://openconfig.net/yang/network-instance\', defining_module=\'openconfig-network-instance\', yang_type=\'container\', is_config=True)'})
self.__aggregate_sid_counters = t
if hasattr(self, '_set'):
self._set() | Setter method for aggregate_sid_counters, mapped from YANG variable /network_instances/network_instance/mpls/signaling_protocols/segment_routing/aggregate_sid_counters (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_aggregate_sid_counters is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_aggregate_sid_counters() directly.
YANG Description: Per-SID counters aggregated across all interfaces on the local system | napalm_yang/models/openconfig/network_instances/network_instance/mpls/signaling_protocols/segment_routing/__init__.py | _set_aggregate_sid_counters | ckishimo/napalm-yang | 64 | python | def _set_aggregate_sid_counters(self, v, load=False):
'\n Setter method for aggregate_sid_counters, mapped from YANG variable /network_instances/network_instance/mpls/signaling_protocols/segment_routing/aggregate_sid_counters (container)\n If this variable is read-only (config: false) in the\n source YANG file, then _set_aggregate_sid_counters is considered as a private\n method. Backends looking to populate this variable should\n do so via calling thisObj._set_aggregate_sid_counters() directly.\n\n YANG Description: Per-SID counters aggregated across all interfaces on the local system\n '
if hasattr(v, '_utype'):
v = v._utype(v)
try:
t = YANGDynClass(v, base=aggregate_sid_counters.aggregate_sid_counters, is_container='container', yang_name='aggregate-sid-counters', parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/network-instance', defining_module='openconfig-network-instance', yang_type='container', is_config=True)
except (TypeError, ValueError):
raise ValueError({'error-string': 'aggregate_sid_counters must be of a type compatible with container', 'defined-type': 'container', 'generated-type': 'YANGDynClass(base=aggregate_sid_counters.aggregate_sid_counters, is_container=\'container\', yang_name="aggregate-sid-counters", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace=\'http://openconfig.net/yang/network-instance\', defining_module=\'openconfig-network-instance\', yang_type=\'container\', is_config=True)'})
self.__aggregate_sid_counters = t
if hasattr(self, '_set'):
self._set() | def _set_aggregate_sid_counters(self, v, load=False):
'\n Setter method for aggregate_sid_counters, mapped from YANG variable /network_instances/network_instance/mpls/signaling_protocols/segment_routing/aggregate_sid_counters (container)\n If this variable is read-only (config: false) in the\n source YANG file, then _set_aggregate_sid_counters is considered as a private\n method. Backends looking to populate this variable should\n do so via calling thisObj._set_aggregate_sid_counters() directly.\n\n YANG Description: Per-SID counters aggregated across all interfaces on the local system\n '
if hasattr(v, '_utype'):
v = v._utype(v)
try:
t = YANGDynClass(v, base=aggregate_sid_counters.aggregate_sid_counters, is_container='container', yang_name='aggregate-sid-counters', parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/network-instance', defining_module='openconfig-network-instance', yang_type='container', is_config=True)
except (TypeError, ValueError):
raise ValueError({'error-string': 'aggregate_sid_counters must be of a type compatible with container', 'defined-type': 'container', 'generated-type': 'YANGDynClass(base=aggregate_sid_counters.aggregate_sid_counters, is_container=\'container\', yang_name="aggregate-sid-counters", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace=\'http://openconfig.net/yang/network-instance\', defining_module=\'openconfig-network-instance\', yang_type=\'container\', is_config=True)'})
self.__aggregate_sid_counters = t
if hasattr(self, '_set'):
self._set()<|docstring|>Setter method for aggregate_sid_counters, mapped from YANG variable /network_instances/network_instance/mpls/signaling_protocols/segment_routing/aggregate_sid_counters (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_aggregate_sid_counters is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_aggregate_sid_counters() directly.
YANG Description: Per-SID counters aggregated across all interfaces on the local system<|endoftext|> |
572f57cb2d1f5cf00ccc7fc946ae92f2e286c9432f6ee9721df17da46d95668e | def _get_interfaces(self):
'\n Getter method for interfaces, mapped from YANG variable /network_instances/network_instance/mpls/signaling_protocols/segment_routing/interfaces (container)\n\n YANG Description: Interface related Segment Routing parameters.\n '
return self.__interfaces | Getter method for interfaces, mapped from YANG variable /network_instances/network_instance/mpls/signaling_protocols/segment_routing/interfaces (container)
YANG Description: Interface related Segment Routing parameters. | napalm_yang/models/openconfig/network_instances/network_instance/mpls/signaling_protocols/segment_routing/__init__.py | _get_interfaces | ckishimo/napalm-yang | 64 | python | def _get_interfaces(self):
'\n Getter method for interfaces, mapped from YANG variable /network_instances/network_instance/mpls/signaling_protocols/segment_routing/interfaces (container)\n\n YANG Description: Interface related Segment Routing parameters.\n '
return self.__interfaces | def _get_interfaces(self):
'\n Getter method for interfaces, mapped from YANG variable /network_instances/network_instance/mpls/signaling_protocols/segment_routing/interfaces (container)\n\n YANG Description: Interface related Segment Routing parameters.\n '
return self.__interfaces<|docstring|>Getter method for interfaces, mapped from YANG variable /network_instances/network_instance/mpls/signaling_protocols/segment_routing/interfaces (container)
YANG Description: Interface related Segment Routing parameters.<|endoftext|> |
0ece33397cc54d59376ca9ff6596f17f71500f2cb3eff1170170d07eeb4e458b | def _set_interfaces(self, v, load=False):
'\n Setter method for interfaces, mapped from YANG variable /network_instances/network_instance/mpls/signaling_protocols/segment_routing/interfaces (container)\n If this variable is read-only (config: false) in the\n source YANG file, then _set_interfaces is considered as a private\n method. Backends looking to populate this variable should\n do so via calling thisObj._set_interfaces() directly.\n\n YANG Description: Interface related Segment Routing parameters.\n '
if hasattr(v, '_utype'):
v = v._utype(v)
try:
t = YANGDynClass(v, base=interfaces.interfaces, is_container='container', yang_name='interfaces', parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/network-instance', defining_module='openconfig-network-instance', yang_type='container', is_config=True)
except (TypeError, ValueError):
raise ValueError({'error-string': 'interfaces must be of a type compatible with container', 'defined-type': 'container', 'generated-type': 'YANGDynClass(base=interfaces.interfaces, is_container=\'container\', yang_name="interfaces", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace=\'http://openconfig.net/yang/network-instance\', defining_module=\'openconfig-network-instance\', yang_type=\'container\', is_config=True)'})
self.__interfaces = t
if hasattr(self, '_set'):
self._set() | Setter method for interfaces, mapped from YANG variable /network_instances/network_instance/mpls/signaling_protocols/segment_routing/interfaces (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_interfaces is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_interfaces() directly.
YANG Description: Interface related Segment Routing parameters. | napalm_yang/models/openconfig/network_instances/network_instance/mpls/signaling_protocols/segment_routing/__init__.py | _set_interfaces | ckishimo/napalm-yang | 64 | python | def _set_interfaces(self, v, load=False):
'\n Setter method for interfaces, mapped from YANG variable /network_instances/network_instance/mpls/signaling_protocols/segment_routing/interfaces (container)\n If this variable is read-only (config: false) in the\n source YANG file, then _set_interfaces is considered as a private\n method. Backends looking to populate this variable should\n do so via calling thisObj._set_interfaces() directly.\n\n YANG Description: Interface related Segment Routing parameters.\n '
if hasattr(v, '_utype'):
v = v._utype(v)
try:
t = YANGDynClass(v, base=interfaces.interfaces, is_container='container', yang_name='interfaces', parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/network-instance', defining_module='openconfig-network-instance', yang_type='container', is_config=True)
except (TypeError, ValueError):
raise ValueError({'error-string': 'interfaces must be of a type compatible with container', 'defined-type': 'container', 'generated-type': 'YANGDynClass(base=interfaces.interfaces, is_container=\'container\', yang_name="interfaces", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace=\'http://openconfig.net/yang/network-instance\', defining_module=\'openconfig-network-instance\', yang_type=\'container\', is_config=True)'})
self.__interfaces = t
if hasattr(self, '_set'):
self._set() | def _set_interfaces(self, v, load=False):
'\n Setter method for interfaces, mapped from YANG variable /network_instances/network_instance/mpls/signaling_protocols/segment_routing/interfaces (container)\n If this variable is read-only (config: false) in the\n source YANG file, then _set_interfaces is considered as a private\n method. Backends looking to populate this variable should\n do so via calling thisObj._set_interfaces() directly.\n\n YANG Description: Interface related Segment Routing parameters.\n '
if hasattr(v, '_utype'):
v = v._utype(v)
try:
t = YANGDynClass(v, base=interfaces.interfaces, is_container='container', yang_name='interfaces', parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/network-instance', defining_module='openconfig-network-instance', yang_type='container', is_config=True)
except (TypeError, ValueError):
raise ValueError({'error-string': 'interfaces must be of a type compatible with container', 'defined-type': 'container', 'generated-type': 'YANGDynClass(base=interfaces.interfaces, is_container=\'container\', yang_name="interfaces", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace=\'http://openconfig.net/yang/network-instance\', defining_module=\'openconfig-network-instance\', yang_type=\'container\', is_config=True)'})
self.__interfaces = t
if hasattr(self, '_set'):
self._set()<|docstring|>Setter method for interfaces, mapped from YANG variable /network_instances/network_instance/mpls/signaling_protocols/segment_routing/interfaces (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_interfaces is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_interfaces() directly.
YANG Description: Interface related Segment Routing parameters.<|endoftext|> |
25a61517fd7aaafcd9db015bc1931e0658053b45fc91e1b87cdf5598a00f4d74 | def _get_aggregate_sid_counters(self):
'\n Getter method for aggregate_sid_counters, mapped from YANG variable /network_instances/network_instance/mpls/signaling_protocols/segment_routing/aggregate_sid_counters (container)\n\n YANG Description: Per-SID counters aggregated across all interfaces on the local system\n '
return self.__aggregate_sid_counters | Getter method for aggregate_sid_counters, mapped from YANG variable /network_instances/network_instance/mpls/signaling_protocols/segment_routing/aggregate_sid_counters (container)
YANG Description: Per-SID counters aggregated across all interfaces on the local system | napalm_yang/models/openconfig/network_instances/network_instance/mpls/signaling_protocols/segment_routing/__init__.py | _get_aggregate_sid_counters | ckishimo/napalm-yang | 64 | python | def _get_aggregate_sid_counters(self):
'\n Getter method for aggregate_sid_counters, mapped from YANG variable /network_instances/network_instance/mpls/signaling_protocols/segment_routing/aggregate_sid_counters (container)\n\n YANG Description: Per-SID counters aggregated across all interfaces on the local system\n '
return self.__aggregate_sid_counters | def _get_aggregate_sid_counters(self):
'\n Getter method for aggregate_sid_counters, mapped from YANG variable /network_instances/network_instance/mpls/signaling_protocols/segment_routing/aggregate_sid_counters (container)\n\n YANG Description: Per-SID counters aggregated across all interfaces on the local system\n '
return self.__aggregate_sid_counters<|docstring|>Getter method for aggregate_sid_counters, mapped from YANG variable /network_instances/network_instance/mpls/signaling_protocols/segment_routing/aggregate_sid_counters (container)
YANG Description: Per-SID counters aggregated across all interfaces on the local system<|endoftext|> |
b423bcaa4ccec12b33c5fb50412160f3dfe487fea85ecc0fc88a63e5e927ed36 | def _set_aggregate_sid_counters(self, v, load=False):
'\n Setter method for aggregate_sid_counters, mapped from YANG variable /network_instances/network_instance/mpls/signaling_protocols/segment_routing/aggregate_sid_counters (container)\n If this variable is read-only (config: false) in the\n source YANG file, then _set_aggregate_sid_counters is considered as a private\n method. Backends looking to populate this variable should\n do so via calling thisObj._set_aggregate_sid_counters() directly.\n\n YANG Description: Per-SID counters aggregated across all interfaces on the local system\n '
if hasattr(v, '_utype'):
v = v._utype(v)
try:
t = YANGDynClass(v, base=aggregate_sid_counters.aggregate_sid_counters, is_container='container', yang_name='aggregate-sid-counters', parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/network-instance', defining_module='openconfig-network-instance', yang_type='container', is_config=True)
except (TypeError, ValueError):
raise ValueError({'error-string': 'aggregate_sid_counters must be of a type compatible with container', 'defined-type': 'container', 'generated-type': 'YANGDynClass(base=aggregate_sid_counters.aggregate_sid_counters, is_container=\'container\', yang_name="aggregate-sid-counters", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace=\'http://openconfig.net/yang/network-instance\', defining_module=\'openconfig-network-instance\', yang_type=\'container\', is_config=True)'})
self.__aggregate_sid_counters = t
if hasattr(self, '_set'):
self._set() | Setter method for aggregate_sid_counters, mapped from YANG variable /network_instances/network_instance/mpls/signaling_protocols/segment_routing/aggregate_sid_counters (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_aggregate_sid_counters is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_aggregate_sid_counters() directly.
YANG Description: Per-SID counters aggregated across all interfaces on the local system | napalm_yang/models/openconfig/network_instances/network_instance/mpls/signaling_protocols/segment_routing/__init__.py | _set_aggregate_sid_counters | ckishimo/napalm-yang | 64 | python | def _set_aggregate_sid_counters(self, v, load=False):
'\n Setter method for aggregate_sid_counters, mapped from YANG variable /network_instances/network_instance/mpls/signaling_protocols/segment_routing/aggregate_sid_counters (container)\n If this variable is read-only (config: false) in the\n source YANG file, then _set_aggregate_sid_counters is considered as a private\n method. Backends looking to populate this variable should\n do so via calling thisObj._set_aggregate_sid_counters() directly.\n\n YANG Description: Per-SID counters aggregated across all interfaces on the local system\n '
if hasattr(v, '_utype'):
v = v._utype(v)
try:
t = YANGDynClass(v, base=aggregate_sid_counters.aggregate_sid_counters, is_container='container', yang_name='aggregate-sid-counters', parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/network-instance', defining_module='openconfig-network-instance', yang_type='container', is_config=True)
except (TypeError, ValueError):
raise ValueError({'error-string': 'aggregate_sid_counters must be of a type compatible with container', 'defined-type': 'container', 'generated-type': 'YANGDynClass(base=aggregate_sid_counters.aggregate_sid_counters, is_container=\'container\', yang_name="aggregate-sid-counters", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace=\'http://openconfig.net/yang/network-instance\', defining_module=\'openconfig-network-instance\', yang_type=\'container\', is_config=True)'})
self.__aggregate_sid_counters = t
if hasattr(self, '_set'):
self._set() | def _set_aggregate_sid_counters(self, v, load=False):
'\n Setter method for aggregate_sid_counters, mapped from YANG variable /network_instances/network_instance/mpls/signaling_protocols/segment_routing/aggregate_sid_counters (container)\n If this variable is read-only (config: false) in the\n source YANG file, then _set_aggregate_sid_counters is considered as a private\n method. Backends looking to populate this variable should\n do so via calling thisObj._set_aggregate_sid_counters() directly.\n\n YANG Description: Per-SID counters aggregated across all interfaces on the local system\n '
if hasattr(v, '_utype'):
v = v._utype(v)
try:
t = YANGDynClass(v, base=aggregate_sid_counters.aggregate_sid_counters, is_container='container', yang_name='aggregate-sid-counters', parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/network-instance', defining_module='openconfig-network-instance', yang_type='container', is_config=True)
except (TypeError, ValueError):
raise ValueError({'error-string': 'aggregate_sid_counters must be of a type compatible with container', 'defined-type': 'container', 'generated-type': 'YANGDynClass(base=aggregate_sid_counters.aggregate_sid_counters, is_container=\'container\', yang_name="aggregate-sid-counters", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace=\'http://openconfig.net/yang/network-instance\', defining_module=\'openconfig-network-instance\', yang_type=\'container\', is_config=True)'})
self.__aggregate_sid_counters = t
if hasattr(self, '_set'):
self._set()<|docstring|>Setter method for aggregate_sid_counters, mapped from YANG variable /network_instances/network_instance/mpls/signaling_protocols/segment_routing/aggregate_sid_counters (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_aggregate_sid_counters is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_aggregate_sid_counters() directly.
YANG Description: Per-SID counters aggregated across all interfaces on the local system<|endoftext|> |
572f57cb2d1f5cf00ccc7fc946ae92f2e286c9432f6ee9721df17da46d95668e | def _get_interfaces(self):
'\n Getter method for interfaces, mapped from YANG variable /network_instances/network_instance/mpls/signaling_protocols/segment_routing/interfaces (container)\n\n YANG Description: Interface related Segment Routing parameters.\n '
return self.__interfaces | Getter method for interfaces, mapped from YANG variable /network_instances/network_instance/mpls/signaling_protocols/segment_routing/interfaces (container)
YANG Description: Interface related Segment Routing parameters. | napalm_yang/models/openconfig/network_instances/network_instance/mpls/signaling_protocols/segment_routing/__init__.py | _get_interfaces | ckishimo/napalm-yang | 64 | python | def _get_interfaces(self):
'\n Getter method for interfaces, mapped from YANG variable /network_instances/network_instance/mpls/signaling_protocols/segment_routing/interfaces (container)\n\n YANG Description: Interface related Segment Routing parameters.\n '
return self.__interfaces | def _get_interfaces(self):
'\n Getter method for interfaces, mapped from YANG variable /network_instances/network_instance/mpls/signaling_protocols/segment_routing/interfaces (container)\n\n YANG Description: Interface related Segment Routing parameters.\n '
return self.__interfaces<|docstring|>Getter method for interfaces, mapped from YANG variable /network_instances/network_instance/mpls/signaling_protocols/segment_routing/interfaces (container)
YANG Description: Interface related Segment Routing parameters.<|endoftext|> |
0ece33397cc54d59376ca9ff6596f17f71500f2cb3eff1170170d07eeb4e458b | def _set_interfaces(self, v, load=False):
'\n Setter method for interfaces, mapped from YANG variable /network_instances/network_instance/mpls/signaling_protocols/segment_routing/interfaces (container)\n If this variable is read-only (config: false) in the\n source YANG file, then _set_interfaces is considered as a private\n method. Backends looking to populate this variable should\n do so via calling thisObj._set_interfaces() directly.\n\n YANG Description: Interface related Segment Routing parameters.\n '
if hasattr(v, '_utype'):
v = v._utype(v)
try:
t = YANGDynClass(v, base=interfaces.interfaces, is_container='container', yang_name='interfaces', parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/network-instance', defining_module='openconfig-network-instance', yang_type='container', is_config=True)
except (TypeError, ValueError):
raise ValueError({'error-string': 'interfaces must be of a type compatible with container', 'defined-type': 'container', 'generated-type': 'YANGDynClass(base=interfaces.interfaces, is_container=\'container\', yang_name="interfaces", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace=\'http://openconfig.net/yang/network-instance\', defining_module=\'openconfig-network-instance\', yang_type=\'container\', is_config=True)'})
self.__interfaces = t
if hasattr(self, '_set'):
self._set() | Setter method for interfaces, mapped from YANG variable /network_instances/network_instance/mpls/signaling_protocols/segment_routing/interfaces (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_interfaces is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_interfaces() directly.
YANG Description: Interface related Segment Routing parameters. | napalm_yang/models/openconfig/network_instances/network_instance/mpls/signaling_protocols/segment_routing/__init__.py | _set_interfaces | ckishimo/napalm-yang | 64 | python | def _set_interfaces(self, v, load=False):
'\n Setter method for interfaces, mapped from YANG variable /network_instances/network_instance/mpls/signaling_protocols/segment_routing/interfaces (container)\n If this variable is read-only (config: false) in the\n source YANG file, then _set_interfaces is considered as a private\n method. Backends looking to populate this variable should\n do so via calling thisObj._set_interfaces() directly.\n\n YANG Description: Interface related Segment Routing parameters.\n '
if hasattr(v, '_utype'):
v = v._utype(v)
try:
t = YANGDynClass(v, base=interfaces.interfaces, is_container='container', yang_name='interfaces', parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/network-instance', defining_module='openconfig-network-instance', yang_type='container', is_config=True)
except (TypeError, ValueError):
raise ValueError({'error-string': 'interfaces must be of a type compatible with container', 'defined-type': 'container', 'generated-type': 'YANGDynClass(base=interfaces.interfaces, is_container=\'container\', yang_name="interfaces", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace=\'http://openconfig.net/yang/network-instance\', defining_module=\'openconfig-network-instance\', yang_type=\'container\', is_config=True)'})
self.__interfaces = t
if hasattr(self, '_set'):
self._set() | def _set_interfaces(self, v, load=False):
'\n Setter method for interfaces, mapped from YANG variable /network_instances/network_instance/mpls/signaling_protocols/segment_routing/interfaces (container)\n If this variable is read-only (config: false) in the\n source YANG file, then _set_interfaces is considered as a private\n method. Backends looking to populate this variable should\n do so via calling thisObj._set_interfaces() directly.\n\n YANG Description: Interface related Segment Routing parameters.\n '
if hasattr(v, '_utype'):
v = v._utype(v)
try:
t = YANGDynClass(v, base=interfaces.interfaces, is_container='container', yang_name='interfaces', parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/network-instance', defining_module='openconfig-network-instance', yang_type='container', is_config=True)
except (TypeError, ValueError):
raise ValueError({'error-string': 'interfaces must be of a type compatible with container', 'defined-type': 'container', 'generated-type': 'YANGDynClass(base=interfaces.interfaces, is_container=\'container\', yang_name="interfaces", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace=\'http://openconfig.net/yang/network-instance\', defining_module=\'openconfig-network-instance\', yang_type=\'container\', is_config=True)'})
self.__interfaces = t
if hasattr(self, '_set'):
self._set()<|docstring|>Setter method for interfaces, mapped from YANG variable /network_instances/network_instance/mpls/signaling_protocols/segment_routing/interfaces (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_interfaces is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_interfaces() directly.
YANG Description: Interface related Segment Routing parameters.<|endoftext|> |
9cec24dc096981a67f74b73977f0df2af0f6a2eecf762c3b7247ce7899efc7db | def negL_rhoomega(rhoomega=None, rho=None, omega=None, sumLogPiActiveVec=None, sumLogPiRemVec=None, sumLogPiRem=None, nDoc=0, gamma=1.0, alpha=1.0, approx_grad=False, do_grad_omega=1, do_grad_rho=1, **kwargs):
' Returns negative ELBO objective function and its gradient.\n\n Args\n -------\n rhoomega := 1D array, size 2*K\n First K entries are vector rho\n Final K entries are vector omega\n\n Returns\n -------\n f := -1 * L(rho, omega), up to additive constant\n where L is ELBO objective function (log posterior prob)\n g := gradient of f\n '
if (rhoomega is not None):
assert (not np.any(np.isnan(rhoomega)))
assert (not np.any(np.isinf(rhoomega)))
(rho, omega, K) = _unpack(rhoomega)
else:
assert np.all(np.isfinite(rho))
assert np.all(np.isfinite(omega))
K = rho.size
assert (K == omega.size)
eta1 = (rho * omega)
eta0 = ((1 - rho) * omega)
digammaomega = digamma(omega)
assert (not np.any(np.isinf(digammaomega)))
Elogu = (digamma(eta1) - digammaomega)
Elog1mu = (digamma(eta0) - digammaomega)
if (nDoc > 0):
if (sumLogPiRem is not None):
sumLogPiRemVec = np.zeros(K)
sumLogPiRemVec[(- 1)] = sumLogPiRem
ONcoef = ((nDoc + 1.0) - eta1)
OFFcoef = (((nDoc * kvec(K)) + gamma) - eta0)
Tvec = (alpha * sumLogPiActiveVec)
Uvec = (alpha * sumLogPiRemVec)
Ebeta_gtm1 = np.hstack([1.0, np.cumprod((1 - rho[:(- 1)]))])
Ebeta = (rho * Ebeta_gtm1)
assert (Ebeta.size == Tvec.size)
Ebeta_gt = ((1 - rho) * Ebeta_gtm1)
L_local = (np.inner(Ebeta, Tvec) + np.inner(Ebeta_gt, Uvec))
else:
ONcoef = (1 - eta1)
OFFcoef = (gamma - eta0)
L_local = 0
L = (((((- 1) * c_Beta(eta1, eta0)) + np.inner(ONcoef, Elogu)) + np.inner(OFFcoef, Elog1mu)) + L_local)
negL = ((- 1.0) * L)
if approx_grad:
return negL
trigamma_omega = polygamma(1, omega)
trigamma_eta1 = polygamma(1, eta1)
trigamma_eta0 = polygamma(1, eta0)
assert np.all(np.isfinite(trigamma_omega))
assert np.all(np.isfinite(trigamma_eta1))
if do_grad_omega:
gradomega = ((ONcoef * ((rho * trigamma_eta1) - trigamma_omega)) + (OFFcoef * (((1 - rho) * trigamma_eta0) - trigamma_omega)))
if do_grad_rho:
gradrho = (omega * ((ONcoef * trigamma_eta1) - (OFFcoef * trigamma_eta0)))
if (nDoc > 0):
Psi = calc_Psi(Ebeta, rho, K)
gradrho += np.dot(Psi, Uvec)
Delta = calc_dEbeta_drho(Ebeta, rho, K)[(:, :K)]
gradrho += np.dot(Delta, Tvec)
if (do_grad_rho and do_grad_omega):
grad = np.hstack([gradrho, gradomega])
return (negL, ((- 1.0) * grad))
elif do_grad_rho:
return (negL, ((- 1.0) * gradrho))
elif do_grad_omega:
return (negL, ((- 1.0) * gradomega))
else:
return negL | Returns negative ELBO objective function and its gradient.
Args
-------
rhoomega := 1D array, size 2*K
First K entries are vector rho
Final K entries are vector omega
Returns
-------
f := -1 * L(rho, omega), up to additive constant
where L is ELBO objective function (log posterior prob)
g := gradient of f | bnpy/allocmodel/topics/OptimizerRhoOmegaBetter.py | negL_rhoomega | tinnguyen96/bnpy | 184 | python | def negL_rhoomega(rhoomega=None, rho=None, omega=None, sumLogPiActiveVec=None, sumLogPiRemVec=None, sumLogPiRem=None, nDoc=0, gamma=1.0, alpha=1.0, approx_grad=False, do_grad_omega=1, do_grad_rho=1, **kwargs):
' Returns negative ELBO objective function and its gradient.\n\n Args\n -------\n rhoomega := 1D array, size 2*K\n First K entries are vector rho\n Final K entries are vector omega\n\n Returns\n -------\n f := -1 * L(rho, omega), up to additive constant\n where L is ELBO objective function (log posterior prob)\n g := gradient of f\n '
if (rhoomega is not None):
assert (not np.any(np.isnan(rhoomega)))
assert (not np.any(np.isinf(rhoomega)))
(rho, omega, K) = _unpack(rhoomega)
else:
assert np.all(np.isfinite(rho))
assert np.all(np.isfinite(omega))
K = rho.size
assert (K == omega.size)
eta1 = (rho * omega)
eta0 = ((1 - rho) * omega)
digammaomega = digamma(omega)
assert (not np.any(np.isinf(digammaomega)))
Elogu = (digamma(eta1) - digammaomega)
Elog1mu = (digamma(eta0) - digammaomega)
if (nDoc > 0):
if (sumLogPiRem is not None):
sumLogPiRemVec = np.zeros(K)
sumLogPiRemVec[(- 1)] = sumLogPiRem
ONcoef = ((nDoc + 1.0) - eta1)
OFFcoef = (((nDoc * kvec(K)) + gamma) - eta0)
Tvec = (alpha * sumLogPiActiveVec)
Uvec = (alpha * sumLogPiRemVec)
Ebeta_gtm1 = np.hstack([1.0, np.cumprod((1 - rho[:(- 1)]))])
Ebeta = (rho * Ebeta_gtm1)
assert (Ebeta.size == Tvec.size)
Ebeta_gt = ((1 - rho) * Ebeta_gtm1)
L_local = (np.inner(Ebeta, Tvec) + np.inner(Ebeta_gt, Uvec))
else:
ONcoef = (1 - eta1)
OFFcoef = (gamma - eta0)
L_local = 0
L = (((((- 1) * c_Beta(eta1, eta0)) + np.inner(ONcoef, Elogu)) + np.inner(OFFcoef, Elog1mu)) + L_local)
negL = ((- 1.0) * L)
if approx_grad:
return negL
trigamma_omega = polygamma(1, omega)
trigamma_eta1 = polygamma(1, eta1)
trigamma_eta0 = polygamma(1, eta0)
assert np.all(np.isfinite(trigamma_omega))
assert np.all(np.isfinite(trigamma_eta1))
if do_grad_omega:
gradomega = ((ONcoef * ((rho * trigamma_eta1) - trigamma_omega)) + (OFFcoef * (((1 - rho) * trigamma_eta0) - trigamma_omega)))
if do_grad_rho:
gradrho = (omega * ((ONcoef * trigamma_eta1) - (OFFcoef * trigamma_eta0)))
if (nDoc > 0):
Psi = calc_Psi(Ebeta, rho, K)
gradrho += np.dot(Psi, Uvec)
Delta = calc_dEbeta_drho(Ebeta, rho, K)[(:, :K)]
gradrho += np.dot(Delta, Tvec)
if (do_grad_rho and do_grad_omega):
grad = np.hstack([gradrho, gradomega])
return (negL, ((- 1.0) * grad))
elif do_grad_rho:
return (negL, ((- 1.0) * gradrho))
elif do_grad_omega:
return (negL, ((- 1.0) * gradomega))
else:
return negL | def negL_rhoomega(rhoomega=None, rho=None, omega=None, sumLogPiActiveVec=None, sumLogPiRemVec=None, sumLogPiRem=None, nDoc=0, gamma=1.0, alpha=1.0, approx_grad=False, do_grad_omega=1, do_grad_rho=1, **kwargs):
' Returns negative ELBO objective function and its gradient.\n\n Args\n -------\n rhoomega := 1D array, size 2*K\n First K entries are vector rho\n Final K entries are vector omega\n\n Returns\n -------\n f := -1 * L(rho, omega), up to additive constant\n where L is ELBO objective function (log posterior prob)\n g := gradient of f\n '
if (rhoomega is not None):
assert (not np.any(np.isnan(rhoomega)))
assert (not np.any(np.isinf(rhoomega)))
(rho, omega, K) = _unpack(rhoomega)
else:
assert np.all(np.isfinite(rho))
assert np.all(np.isfinite(omega))
K = rho.size
assert (K == omega.size)
eta1 = (rho * omega)
eta0 = ((1 - rho) * omega)
digammaomega = digamma(omega)
assert (not np.any(np.isinf(digammaomega)))
Elogu = (digamma(eta1) - digammaomega)
Elog1mu = (digamma(eta0) - digammaomega)
if (nDoc > 0):
if (sumLogPiRem is not None):
sumLogPiRemVec = np.zeros(K)
sumLogPiRemVec[(- 1)] = sumLogPiRem
ONcoef = ((nDoc + 1.0) - eta1)
OFFcoef = (((nDoc * kvec(K)) + gamma) - eta0)
Tvec = (alpha * sumLogPiActiveVec)
Uvec = (alpha * sumLogPiRemVec)
Ebeta_gtm1 = np.hstack([1.0, np.cumprod((1 - rho[:(- 1)]))])
Ebeta = (rho * Ebeta_gtm1)
assert (Ebeta.size == Tvec.size)
Ebeta_gt = ((1 - rho) * Ebeta_gtm1)
L_local = (np.inner(Ebeta, Tvec) + np.inner(Ebeta_gt, Uvec))
else:
ONcoef = (1 - eta1)
OFFcoef = (gamma - eta0)
L_local = 0
L = (((((- 1) * c_Beta(eta1, eta0)) + np.inner(ONcoef, Elogu)) + np.inner(OFFcoef, Elog1mu)) + L_local)
negL = ((- 1.0) * L)
if approx_grad:
return negL
trigamma_omega = polygamma(1, omega)
trigamma_eta1 = polygamma(1, eta1)
trigamma_eta0 = polygamma(1, eta0)
assert np.all(np.isfinite(trigamma_omega))
assert np.all(np.isfinite(trigamma_eta1))
if do_grad_omega:
gradomega = ((ONcoef * ((rho * trigamma_eta1) - trigamma_omega)) + (OFFcoef * (((1 - rho) * trigamma_eta0) - trigamma_omega)))
if do_grad_rho:
gradrho = (omega * ((ONcoef * trigamma_eta1) - (OFFcoef * trigamma_eta0)))
if (nDoc > 0):
Psi = calc_Psi(Ebeta, rho, K)
gradrho += np.dot(Psi, Uvec)
Delta = calc_dEbeta_drho(Ebeta, rho, K)[(:, :K)]
gradrho += np.dot(Delta, Tvec)
if (do_grad_rho and do_grad_omega):
grad = np.hstack([gradrho, gradomega])
return (negL, ((- 1.0) * grad))
elif do_grad_rho:
return (negL, ((- 1.0) * gradrho))
elif do_grad_omega:
return (negL, ((- 1.0) * gradomega))
else:
return negL<|docstring|>Returns negative ELBO objective function and its gradient.
Args
-------
rhoomega := 1D array, size 2*K
First K entries are vector rho
Final K entries are vector omega
Returns
-------
f := -1 * L(rho, omega), up to additive constant
where L is ELBO objective function (log posterior prob)
g := gradient of f<|endoftext|> |
f6509792ce2b9b80aae8ef277625a71bbdc2da5d9d0a11b6ce1e69077458240b | def find_optimum_multiple_tries(factrList=[10000.0, 1000000.0, 100000000.0, 10000000000.0, 1000000000000.0], **kwargs):
' Robustly estimate optimal rho/omega via gradient descent on ELBO.\n\n Will gracefully using multiple restarts with progressively\n weaker tolerances until one succeeds.\n\n Args\n ----\n factrList : list of progressively weaker tolerances to try\n According to fmin_l_bfgs_b documentation:\n factr ~= 1e12 yields low accuracy,\n factr ~= 1e7 yields moderate accuracy\n factr ~= 1e2 yields extremely high accuracy\n\n Returns\n --------\n rho : 1D array, length K\n omega : 1D array, length K\n f : scalar value of minimization objective\n Info : dict\n\n Raises\n --------\n ValueError with FAILURE in message if all restarts fail\n '
rho_opt = None
omega_opt = None
Info = dict()
errmsg = ''
nOverflow = 0
for (trial, factr) in enumerate(factrList):
try:
(rho_opt, omega_opt, f_opt, Info) = find_optimum(factr=factr, **kwargs)
Info['nRestarts'] = trial
Info['factr'] = factr
Info['msg'] = Info['task']
del Info['grad']
del Info['task']
break
except ValueError as err:
errmsg = str(err)
Info['errmsg'] = errmsg
if (errmsg.count('overflow') > 0):
nOverflow += 1
elif (errmsg.count('ABNORMAL_TERMINATION_IN_LNSRCH') > 0):
pass
else:
raise err
if (rho_opt is None):
raise ValueError(errmsg)
Info['nOverflow'] = nOverflow
return (rho_opt, omega_opt, f_opt, Info) | Robustly estimate optimal rho/omega via gradient descent on ELBO.
Will gracefully using multiple restarts with progressively
weaker tolerances until one succeeds.
Args
----
factrList : list of progressively weaker tolerances to try
According to fmin_l_bfgs_b documentation:
factr ~= 1e12 yields low accuracy,
factr ~= 1e7 yields moderate accuracy
factr ~= 1e2 yields extremely high accuracy
Returns
--------
rho : 1D array, length K
omega : 1D array, length K
f : scalar value of minimization objective
Info : dict
Raises
--------
ValueError with FAILURE in message if all restarts fail | bnpy/allocmodel/topics/OptimizerRhoOmegaBetter.py | find_optimum_multiple_tries | tinnguyen96/bnpy | 184 | python | def find_optimum_multiple_tries(factrList=[10000.0, 1000000.0, 100000000.0, 10000000000.0, 1000000000000.0], **kwargs):
' Robustly estimate optimal rho/omega via gradient descent on ELBO.\n\n Will gracefully using multiple restarts with progressively\n weaker tolerances until one succeeds.\n\n Args\n ----\n factrList : list of progressively weaker tolerances to try\n According to fmin_l_bfgs_b documentation:\n factr ~= 1e12 yields low accuracy,\n factr ~= 1e7 yields moderate accuracy\n factr ~= 1e2 yields extremely high accuracy\n\n Returns\n --------\n rho : 1D array, length K\n omega : 1D array, length K\n f : scalar value of minimization objective\n Info : dict\n\n Raises\n --------\n ValueError with FAILURE in message if all restarts fail\n '
rho_opt = None
omega_opt = None
Info = dict()
errmsg =
nOverflow = 0
for (trial, factr) in enumerate(factrList):
try:
(rho_opt, omega_opt, f_opt, Info) = find_optimum(factr=factr, **kwargs)
Info['nRestarts'] = trial
Info['factr'] = factr
Info['msg'] = Info['task']
del Info['grad']
del Info['task']
break
except ValueError as err:
errmsg = str(err)
Info['errmsg'] = errmsg
if (errmsg.count('overflow') > 0):
nOverflow += 1
elif (errmsg.count('ABNORMAL_TERMINATION_IN_LNSRCH') > 0):
pass
else:
raise err
if (rho_opt is None):
raise ValueError(errmsg)
Info['nOverflow'] = nOverflow
return (rho_opt, omega_opt, f_opt, Info) | def find_optimum_multiple_tries(factrList=[10000.0, 1000000.0, 100000000.0, 10000000000.0, 1000000000000.0], **kwargs):
' Robustly estimate optimal rho/omega via gradient descent on ELBO.\n\n Will gracefully using multiple restarts with progressively\n weaker tolerances until one succeeds.\n\n Args\n ----\n factrList : list of progressively weaker tolerances to try\n According to fmin_l_bfgs_b documentation:\n factr ~= 1e12 yields low accuracy,\n factr ~= 1e7 yields moderate accuracy\n factr ~= 1e2 yields extremely high accuracy\n\n Returns\n --------\n rho : 1D array, length K\n omega : 1D array, length K\n f : scalar value of minimization objective\n Info : dict\n\n Raises\n --------\n ValueError with FAILURE in message if all restarts fail\n '
rho_opt = None
omega_opt = None
Info = dict()
errmsg =
nOverflow = 0
for (trial, factr) in enumerate(factrList):
try:
(rho_opt, omega_opt, f_opt, Info) = find_optimum(factr=factr, **kwargs)
Info['nRestarts'] = trial
Info['factr'] = factr
Info['msg'] = Info['task']
del Info['grad']
del Info['task']
break
except ValueError as err:
errmsg = str(err)
Info['errmsg'] = errmsg
if (errmsg.count('overflow') > 0):
nOverflow += 1
elif (errmsg.count('ABNORMAL_TERMINATION_IN_LNSRCH') > 0):
pass
else:
raise err
if (rho_opt is None):
raise ValueError(errmsg)
Info['nOverflow'] = nOverflow
return (rho_opt, omega_opt, f_opt, Info)<|docstring|>Robustly estimate optimal rho/omega via gradient descent on ELBO.
Will gracefully using multiple restarts with progressively
weaker tolerances until one succeeds.
Args
----
factrList : list of progressively weaker tolerances to try
According to fmin_l_bfgs_b documentation:
factr ~= 1e12 yields low accuracy,
factr ~= 1e7 yields moderate accuracy
factr ~= 1e2 yields extremely high accuracy
Returns
--------
rho : 1D array, length K
omega : 1D array, length K
f : scalar value of minimization objective
Info : dict
Raises
--------
ValueError with FAILURE in message if all restarts fail<|endoftext|> |
218c8db981d8ade7b2b324d0e1d27057fe75b4b061bb875e7d060d70da808579 | def find_optimum(initrho=None, initomega=None, do_grad_rho=1, do_grad_omega=1, approx_grad=0, nDoc=None, sumLogPiActiveVec=None, sumLogPiRemVec=None, sumLogPiRem=None, alpha=1.0, gamma=1.0, factr=100.0, Log=None, **kwargs):
" Estimate optimal rho and omega via gradient descent on ELBO objective.\n\n Returns\n --------\n rho : 1D array, length K\n omega : 1D array, length K\n f : scalar value of minimization objective\n Info : dict\n\n Raises\n --------\n ValueError on an overflow, any NaN, or failure to converge.\n\n Examples\n --------\n When no documents exist, we recover the prior parameters\n >>> r_opt, o_opt, f_opt, Info = find_optimum(\n ... nDoc=0,\n ... sumLogPiActiveVec=np.zeros(3),\n ... sumLogPiRemVec=np.zeros(3),\n ... alpha=0.5, gamma=1.0)\n >>> print (r_opt)\n [0.5 0.5 0.5]\n >>> print (o_opt)\n [2. 2. 2.]\n\n We can optimize for just rho by turning do_grad_omega off.\n This fixes omega at its initial value, but optimizes rho.\n >>> r_opt, o_opt, f_opt, Info = find_optimum(\n ... do_grad_omega=0,\n ... nDoc=10,\n ... sumLogPiActiveVec=np.asarray([-2., -4., -6.]),\n ... sumLogPiRemVec=np.asarray([0, 0, -20.]),\n ... alpha=0.5,\n ... gamma=5.0)\n >>> print (o_opt)\n [46. 36. 26.]\n >>> np.allclose(o_opt, Info['initomega'])\n True\n\n We can optimize for just omega by turning do_grad_rho off.\n This fixes rho at its initial value, but optimizes omega\n >>> r_opt2, o_opt2, f_opt2, Info = find_optimum(\n ... do_grad_rho=0,\n ... initrho=r_opt,\n ... nDoc=10,\n ... sumLogPiActiveVec=np.asarray([-2., -4., -6.]),\n ... sumLogPiRemVec=np.asarray([0, 0, -20.]),\n ... alpha=0.5,\n ... gamma=5.0)\n >>> np.allclose(r_opt, r_opt2)\n True\n >>> np.allclose(o_opt2, o_opt, atol=10, rtol=0)\n True\n "
assert (sumLogPiActiveVec.ndim == 1)
K = sumLogPiActiveVec.size
if (sumLogPiRem is not None):
sumLogPiRemVec = np.zeros(K)
sumLogPiRemVec[(- 1)] = sumLogPiRem
assert (sumLogPiActiveVec.shape == sumLogPiRemVec.shape)
if (nDoc > 0):
maxOmegaVal = (1000.0 * ((nDoc * (K + 1)) + gamma))
else:
maxOmegaVal = (1000.0 * ((K + 1) + gamma))
if (initrho is None):
initrho = make_initrho(K, nDoc, gamma)
initrho = forceRhoInBounds(initrho)
if (initomega is None):
initomega = make_initomega(K, nDoc, gamma)
initomega = forceOmegaInBounds(initomega, maxOmegaVal=(0.5 * maxOmegaVal))
assert (initrho.size == K)
assert (initomega.size == K)
objFuncKwargs = dict(sumLogPiActiveVec=sumLogPiActiveVec, sumLogPiRemVec=sumLogPiRemVec, nDoc=nDoc, gamma=gamma, alpha=alpha, approx_grad=approx_grad, do_grad_rho=do_grad_rho, do_grad_omega=do_grad_omega, initrho=initrho, initomega=initomega)
if (do_grad_rho and do_grad_omega):
rhoomega_init = np.hstack([initrho, initomega])
c_init = rhoomega2c(rhoomega_init)
elif do_grad_rho:
c_init = rho2c(initrho)
objFuncKwargs['omega'] = initomega
else:
c_init = omega2c(initomega)
objFuncKwargs['rho'] = initrho
def objFunc(c):
return negL_c(c, **objFuncKwargs)
fminKwargs = dict(factr=factr, approx_grad=approx_grad, disp=None)
fminPossibleKwargs = set(scipy.optimize.fmin_l_bfgs_b.__code__.co_varnames)
for key in kwargs:
if (key in fminPossibleKwargs):
fminKwargs[key] = kwargs[key]
with warnings.catch_warnings():
warnings.filterwarnings('error')
try:
(c_opt, f_opt, Info) = scipy.optimize.fmin_l_bfgs_b(objFunc, c_init, **fminKwargs)
except RuntimeWarning as e:
raise ValueError(('FAILURE: ' + str(e)))
except AssertionError as e:
raise ValueError('FAILURE: NaN/Inf detected!')
if (Info['warnflag'] > 1):
raise ValueError(('FAILURE: ' + Info['task']))
Info['initrho'] = initrho
Info['initomega'] = initomega
if (do_grad_rho and do_grad_omega):
(rho_opt, omega_opt) = c2rhoomega(c_opt)
elif do_grad_rho:
rho_opt = c2rho(c_opt)
omega_opt = initomega
else:
omega_opt = c2omega(c_opt)
rho_opt = initrho
Info['estrho'] = rho_opt
Info['estomega'] = omega_opt
rho_safe = forceRhoInBounds(rho_opt)
omega_safe = forceOmegaInBounds(omega_opt, maxOmegaVal=maxOmegaVal, Log=Log)
objFuncKwargs['approx_grad'] = 1.0
with warnings.catch_warnings():
warnings.filterwarnings('error')
objFuncKwargs['rho'] = initrho
objFuncKwargs['omega'] = initomega
f_init = negL_rhoomega(**objFuncKwargs)
with warnings.catch_warnings():
warnings.filterwarnings('error')
objFuncKwargs['rho'] = rho_safe
objFuncKwargs['omega'] = omega_safe
f_safe = negL_rhoomega(**objFuncKwargs)
if (not np.allclose(rho_safe, rho_opt)):
if Log:
Log.error('rho_opt_CHANGED_TO_LIE_IN_BOUNDS')
Info['rho_opt_CHANGED_TO_LIE_IN_BOUNDS'] = 1
if (not np.allclose(omega_safe, omega_opt)):
if Log:
Log.error('omega_opt_CHANGED_TO_LIE_IN_BOUNDS')
Info['omega_opt_CHANGED_TO_LIE_IN_BOUNDS'] = 1
if (f_safe < f_init):
return (rho_safe, omega_safe, f_safe, Info)
else:
return (initrho, initomega, f_init, Info) | Estimate optimal rho and omega via gradient descent on ELBO objective.
Returns
--------
rho : 1D array, length K
omega : 1D array, length K
f : scalar value of minimization objective
Info : dict
Raises
--------
ValueError on an overflow, any NaN, or failure to converge.
Examples
--------
When no documents exist, we recover the prior parameters
>>> r_opt, o_opt, f_opt, Info = find_optimum(
... nDoc=0,
... sumLogPiActiveVec=np.zeros(3),
... sumLogPiRemVec=np.zeros(3),
... alpha=0.5, gamma=1.0)
>>> print (r_opt)
[0.5 0.5 0.5]
>>> print (o_opt)
[2. 2. 2.]
We can optimize for just rho by turning do_grad_omega off.
This fixes omega at its initial value, but optimizes rho.
>>> r_opt, o_opt, f_opt, Info = find_optimum(
... do_grad_omega=0,
... nDoc=10,
... sumLogPiActiveVec=np.asarray([-2., -4., -6.]),
... sumLogPiRemVec=np.asarray([0, 0, -20.]),
... alpha=0.5,
... gamma=5.0)
>>> print (o_opt)
[46. 36. 26.]
>>> np.allclose(o_opt, Info['initomega'])
True
We can optimize for just omega by turning do_grad_rho off.
This fixes rho at its initial value, but optimizes omega
>>> r_opt2, o_opt2, f_opt2, Info = find_optimum(
... do_grad_rho=0,
... initrho=r_opt,
... nDoc=10,
... sumLogPiActiveVec=np.asarray([-2., -4., -6.]),
... sumLogPiRemVec=np.asarray([0, 0, -20.]),
... alpha=0.5,
... gamma=5.0)
>>> np.allclose(r_opt, r_opt2)
True
>>> np.allclose(o_opt2, o_opt, atol=10, rtol=0)
True | bnpy/allocmodel/topics/OptimizerRhoOmegaBetter.py | find_optimum | tinnguyen96/bnpy | 184 | python | def find_optimum(initrho=None, initomega=None, do_grad_rho=1, do_grad_omega=1, approx_grad=0, nDoc=None, sumLogPiActiveVec=None, sumLogPiRemVec=None, sumLogPiRem=None, alpha=1.0, gamma=1.0, factr=100.0, Log=None, **kwargs):
" Estimate optimal rho and omega via gradient descent on ELBO objective.\n\n Returns\n --------\n rho : 1D array, length K\n omega : 1D array, length K\n f : scalar value of minimization objective\n Info : dict\n\n Raises\n --------\n ValueError on an overflow, any NaN, or failure to converge.\n\n Examples\n --------\n When no documents exist, we recover the prior parameters\n >>> r_opt, o_opt, f_opt, Info = find_optimum(\n ... nDoc=0,\n ... sumLogPiActiveVec=np.zeros(3),\n ... sumLogPiRemVec=np.zeros(3),\n ... alpha=0.5, gamma=1.0)\n >>> print (r_opt)\n [0.5 0.5 0.5]\n >>> print (o_opt)\n [2. 2. 2.]\n\n We can optimize for just rho by turning do_grad_omega off.\n This fixes omega at its initial value, but optimizes rho.\n >>> r_opt, o_opt, f_opt, Info = find_optimum(\n ... do_grad_omega=0,\n ... nDoc=10,\n ... sumLogPiActiveVec=np.asarray([-2., -4., -6.]),\n ... sumLogPiRemVec=np.asarray([0, 0, -20.]),\n ... alpha=0.5,\n ... gamma=5.0)\n >>> print (o_opt)\n [46. 36. 26.]\n >>> np.allclose(o_opt, Info['initomega'])\n True\n\n We can optimize for just omega by turning do_grad_rho off.\n This fixes rho at its initial value, but optimizes omega\n >>> r_opt2, o_opt2, f_opt2, Info = find_optimum(\n ... do_grad_rho=0,\n ... initrho=r_opt,\n ... nDoc=10,\n ... sumLogPiActiveVec=np.asarray([-2., -4., -6.]),\n ... sumLogPiRemVec=np.asarray([0, 0, -20.]),\n ... alpha=0.5,\n ... gamma=5.0)\n >>> np.allclose(r_opt, r_opt2)\n True\n >>> np.allclose(o_opt2, o_opt, atol=10, rtol=0)\n True\n "
assert (sumLogPiActiveVec.ndim == 1)
K = sumLogPiActiveVec.size
if (sumLogPiRem is not None):
sumLogPiRemVec = np.zeros(K)
sumLogPiRemVec[(- 1)] = sumLogPiRem
assert (sumLogPiActiveVec.shape == sumLogPiRemVec.shape)
if (nDoc > 0):
maxOmegaVal = (1000.0 * ((nDoc * (K + 1)) + gamma))
else:
maxOmegaVal = (1000.0 * ((K + 1) + gamma))
if (initrho is None):
initrho = make_initrho(K, nDoc, gamma)
initrho = forceRhoInBounds(initrho)
if (initomega is None):
initomega = make_initomega(K, nDoc, gamma)
initomega = forceOmegaInBounds(initomega, maxOmegaVal=(0.5 * maxOmegaVal))
assert (initrho.size == K)
assert (initomega.size == K)
objFuncKwargs = dict(sumLogPiActiveVec=sumLogPiActiveVec, sumLogPiRemVec=sumLogPiRemVec, nDoc=nDoc, gamma=gamma, alpha=alpha, approx_grad=approx_grad, do_grad_rho=do_grad_rho, do_grad_omega=do_grad_omega, initrho=initrho, initomega=initomega)
if (do_grad_rho and do_grad_omega):
rhoomega_init = np.hstack([initrho, initomega])
c_init = rhoomega2c(rhoomega_init)
elif do_grad_rho:
c_init = rho2c(initrho)
objFuncKwargs['omega'] = initomega
else:
c_init = omega2c(initomega)
objFuncKwargs['rho'] = initrho
def objFunc(c):
return negL_c(c, **objFuncKwargs)
fminKwargs = dict(factr=factr, approx_grad=approx_grad, disp=None)
fminPossibleKwargs = set(scipy.optimize.fmin_l_bfgs_b.__code__.co_varnames)
for key in kwargs:
if (key in fminPossibleKwargs):
fminKwargs[key] = kwargs[key]
with warnings.catch_warnings():
warnings.filterwarnings('error')
try:
(c_opt, f_opt, Info) = scipy.optimize.fmin_l_bfgs_b(objFunc, c_init, **fminKwargs)
except RuntimeWarning as e:
raise ValueError(('FAILURE: ' + str(e)))
except AssertionError as e:
raise ValueError('FAILURE: NaN/Inf detected!')
if (Info['warnflag'] > 1):
raise ValueError(('FAILURE: ' + Info['task']))
Info['initrho'] = initrho
Info['initomega'] = initomega
if (do_grad_rho and do_grad_omega):
(rho_opt, omega_opt) = c2rhoomega(c_opt)
elif do_grad_rho:
rho_opt = c2rho(c_opt)
omega_opt = initomega
else:
omega_opt = c2omega(c_opt)
rho_opt = initrho
Info['estrho'] = rho_opt
Info['estomega'] = omega_opt
rho_safe = forceRhoInBounds(rho_opt)
omega_safe = forceOmegaInBounds(omega_opt, maxOmegaVal=maxOmegaVal, Log=Log)
objFuncKwargs['approx_grad'] = 1.0
with warnings.catch_warnings():
warnings.filterwarnings('error')
objFuncKwargs['rho'] = initrho
objFuncKwargs['omega'] = initomega
f_init = negL_rhoomega(**objFuncKwargs)
with warnings.catch_warnings():
warnings.filterwarnings('error')
objFuncKwargs['rho'] = rho_safe
objFuncKwargs['omega'] = omega_safe
f_safe = negL_rhoomega(**objFuncKwargs)
if (not np.allclose(rho_safe, rho_opt)):
if Log:
Log.error('rho_opt_CHANGED_TO_LIE_IN_BOUNDS')
Info['rho_opt_CHANGED_TO_LIE_IN_BOUNDS'] = 1
if (not np.allclose(omega_safe, omega_opt)):
if Log:
Log.error('omega_opt_CHANGED_TO_LIE_IN_BOUNDS')
Info['omega_opt_CHANGED_TO_LIE_IN_BOUNDS'] = 1
if (f_safe < f_init):
return (rho_safe, omega_safe, f_safe, Info)
else:
return (initrho, initomega, f_init, Info) | def find_optimum(initrho=None, initomega=None, do_grad_rho=1, do_grad_omega=1, approx_grad=0, nDoc=None, sumLogPiActiveVec=None, sumLogPiRemVec=None, sumLogPiRem=None, alpha=1.0, gamma=1.0, factr=100.0, Log=None, **kwargs):
" Estimate optimal rho and omega via gradient descent on ELBO objective.\n\n Returns\n --------\n rho : 1D array, length K\n omega : 1D array, length K\n f : scalar value of minimization objective\n Info : dict\n\n Raises\n --------\n ValueError on an overflow, any NaN, or failure to converge.\n\n Examples\n --------\n When no documents exist, we recover the prior parameters\n >>> r_opt, o_opt, f_opt, Info = find_optimum(\n ... nDoc=0,\n ... sumLogPiActiveVec=np.zeros(3),\n ... sumLogPiRemVec=np.zeros(3),\n ... alpha=0.5, gamma=1.0)\n >>> print (r_opt)\n [0.5 0.5 0.5]\n >>> print (o_opt)\n [2. 2. 2.]\n\n We can optimize for just rho by turning do_grad_omega off.\n This fixes omega at its initial value, but optimizes rho.\n >>> r_opt, o_opt, f_opt, Info = find_optimum(\n ... do_grad_omega=0,\n ... nDoc=10,\n ... sumLogPiActiveVec=np.asarray([-2., -4., -6.]),\n ... sumLogPiRemVec=np.asarray([0, 0, -20.]),\n ... alpha=0.5,\n ... gamma=5.0)\n >>> print (o_opt)\n [46. 36. 26.]\n >>> np.allclose(o_opt, Info['initomega'])\n True\n\n We can optimize for just omega by turning do_grad_rho off.\n This fixes rho at its initial value, but optimizes omega\n >>> r_opt2, o_opt2, f_opt2, Info = find_optimum(\n ... do_grad_rho=0,\n ... initrho=r_opt,\n ... nDoc=10,\n ... sumLogPiActiveVec=np.asarray([-2., -4., -6.]),\n ... sumLogPiRemVec=np.asarray([0, 0, -20.]),\n ... alpha=0.5,\n ... gamma=5.0)\n >>> np.allclose(r_opt, r_opt2)\n True\n >>> np.allclose(o_opt2, o_opt, atol=10, rtol=0)\n True\n "
assert (sumLogPiActiveVec.ndim == 1)
K = sumLogPiActiveVec.size
if (sumLogPiRem is not None):
sumLogPiRemVec = np.zeros(K)
sumLogPiRemVec[(- 1)] = sumLogPiRem
assert (sumLogPiActiveVec.shape == sumLogPiRemVec.shape)
if (nDoc > 0):
maxOmegaVal = (1000.0 * ((nDoc * (K + 1)) + gamma))
else:
maxOmegaVal = (1000.0 * ((K + 1) + gamma))
if (initrho is None):
initrho = make_initrho(K, nDoc, gamma)
initrho = forceRhoInBounds(initrho)
if (initomega is None):
initomega = make_initomega(K, nDoc, gamma)
initomega = forceOmegaInBounds(initomega, maxOmegaVal=(0.5 * maxOmegaVal))
assert (initrho.size == K)
assert (initomega.size == K)
objFuncKwargs = dict(sumLogPiActiveVec=sumLogPiActiveVec, sumLogPiRemVec=sumLogPiRemVec, nDoc=nDoc, gamma=gamma, alpha=alpha, approx_grad=approx_grad, do_grad_rho=do_grad_rho, do_grad_omega=do_grad_omega, initrho=initrho, initomega=initomega)
if (do_grad_rho and do_grad_omega):
rhoomega_init = np.hstack([initrho, initomega])
c_init = rhoomega2c(rhoomega_init)
elif do_grad_rho:
c_init = rho2c(initrho)
objFuncKwargs['omega'] = initomega
else:
c_init = omega2c(initomega)
objFuncKwargs['rho'] = initrho
def objFunc(c):
return negL_c(c, **objFuncKwargs)
fminKwargs = dict(factr=factr, approx_grad=approx_grad, disp=None)
fminPossibleKwargs = set(scipy.optimize.fmin_l_bfgs_b.__code__.co_varnames)
for key in kwargs:
if (key in fminPossibleKwargs):
fminKwargs[key] = kwargs[key]
with warnings.catch_warnings():
warnings.filterwarnings('error')
try:
(c_opt, f_opt, Info) = scipy.optimize.fmin_l_bfgs_b(objFunc, c_init, **fminKwargs)
except RuntimeWarning as e:
raise ValueError(('FAILURE: ' + str(e)))
except AssertionError as e:
raise ValueError('FAILURE: NaN/Inf detected!')
if (Info['warnflag'] > 1):
raise ValueError(('FAILURE: ' + Info['task']))
Info['initrho'] = initrho
Info['initomega'] = initomega
if (do_grad_rho and do_grad_omega):
(rho_opt, omega_opt) = c2rhoomega(c_opt)
elif do_grad_rho:
rho_opt = c2rho(c_opt)
omega_opt = initomega
else:
omega_opt = c2omega(c_opt)
rho_opt = initrho
Info['estrho'] = rho_opt
Info['estomega'] = omega_opt
rho_safe = forceRhoInBounds(rho_opt)
omega_safe = forceOmegaInBounds(omega_opt, maxOmegaVal=maxOmegaVal, Log=Log)
objFuncKwargs['approx_grad'] = 1.0
with warnings.catch_warnings():
warnings.filterwarnings('error')
objFuncKwargs['rho'] = initrho
objFuncKwargs['omega'] = initomega
f_init = negL_rhoomega(**objFuncKwargs)
with warnings.catch_warnings():
warnings.filterwarnings('error')
objFuncKwargs['rho'] = rho_safe
objFuncKwargs['omega'] = omega_safe
f_safe = negL_rhoomega(**objFuncKwargs)
if (not np.allclose(rho_safe, rho_opt)):
if Log:
Log.error('rho_opt_CHANGED_TO_LIE_IN_BOUNDS')
Info['rho_opt_CHANGED_TO_LIE_IN_BOUNDS'] = 1
if (not np.allclose(omega_safe, omega_opt)):
if Log:
Log.error('omega_opt_CHANGED_TO_LIE_IN_BOUNDS')
Info['omega_opt_CHANGED_TO_LIE_IN_BOUNDS'] = 1
if (f_safe < f_init):
return (rho_safe, omega_safe, f_safe, Info)
else:
return (initrho, initomega, f_init, Info)<|docstring|>Estimate optimal rho and omega via gradient descent on ELBO objective.
Returns
--------
rho : 1D array, length K
omega : 1D array, length K
f : scalar value of minimization objective
Info : dict
Raises
--------
ValueError on an overflow, any NaN, or failure to converge.
Examples
--------
When no documents exist, we recover the prior parameters
>>> r_opt, o_opt, f_opt, Info = find_optimum(
... nDoc=0,
... sumLogPiActiveVec=np.zeros(3),
... sumLogPiRemVec=np.zeros(3),
... alpha=0.5, gamma=1.0)
>>> print (r_opt)
[0.5 0.5 0.5]
>>> print (o_opt)
[2. 2. 2.]
We can optimize for just rho by turning do_grad_omega off.
This fixes omega at its initial value, but optimizes rho.
>>> r_opt, o_opt, f_opt, Info = find_optimum(
... do_grad_omega=0,
... nDoc=10,
... sumLogPiActiveVec=np.asarray([-2., -4., -6.]),
... sumLogPiRemVec=np.asarray([0, 0, -20.]),
... alpha=0.5,
... gamma=5.0)
>>> print (o_opt)
[46. 36. 26.]
>>> np.allclose(o_opt, Info['initomega'])
True
We can optimize for just omega by turning do_grad_rho off.
This fixes rho at its initial value, but optimizes omega
>>> r_opt2, o_opt2, f_opt2, Info = find_optimum(
... do_grad_rho=0,
... initrho=r_opt,
... nDoc=10,
... sumLogPiActiveVec=np.asarray([-2., -4., -6.]),
... sumLogPiRemVec=np.asarray([0, 0, -20.]),
... alpha=0.5,
... gamma=5.0)
>>> np.allclose(r_opt, r_opt2)
True
>>> np.allclose(o_opt2, o_opt, atol=10, rtol=0)
True<|endoftext|> |
1fc97e6eaac636e3a6c2e055de75d316b66c9da12be073f3bf39cc758c9c2bc5 | def c2rhoomega(c, returnSingleVector=False):
' Transform unconstrained variable c into constrained rho, omega\n\n Returns\n --------\n rho : 1D array, size K, entries between [0, 1]\n omega : 1D array, size K, positive entries\n\n OPTIONAL: may return as one concatenated vector (length 2K)\n '
K = (c.size // 2)
rho = sigmoid(c[:K])
omega = np.exp(c[K:])
if returnSingleVector:
return np.hstack([rho, omega])
return (rho, omega) | Transform unconstrained variable c into constrained rho, omega
Returns
--------
rho : 1D array, size K, entries between [0, 1]
omega : 1D array, size K, positive entries
OPTIONAL: may return as one concatenated vector (length 2K) | bnpy/allocmodel/topics/OptimizerRhoOmegaBetter.py | c2rhoomega | tinnguyen96/bnpy | 184 | python | def c2rhoomega(c, returnSingleVector=False):
' Transform unconstrained variable c into constrained rho, omega\n\n Returns\n --------\n rho : 1D array, size K, entries between [0, 1]\n omega : 1D array, size K, positive entries\n\n OPTIONAL: may return as one concatenated vector (length 2K)\n '
K = (c.size // 2)
rho = sigmoid(c[:K])
omega = np.exp(c[K:])
if returnSingleVector:
return np.hstack([rho, omega])
return (rho, omega) | def c2rhoomega(c, returnSingleVector=False):
' Transform unconstrained variable c into constrained rho, omega\n\n Returns\n --------\n rho : 1D array, size K, entries between [0, 1]\n omega : 1D array, size K, positive entries\n\n OPTIONAL: may return as one concatenated vector (length 2K)\n '
K = (c.size // 2)
rho = sigmoid(c[:K])
omega = np.exp(c[K:])
if returnSingleVector:
return np.hstack([rho, omega])
return (rho, omega)<|docstring|>Transform unconstrained variable c into constrained rho, omega
Returns
--------
rho : 1D array, size K, entries between [0, 1]
omega : 1D array, size K, positive entries
OPTIONAL: may return as one concatenated vector (length 2K)<|endoftext|> |
26ad83ad0fd636af6861890afec6358bf034a8e480f0dffd7bcfd83e152f58a5 | def make_initrho(K, nDoc, gamma):
' Make vector rho that is good guess for provided problem specs.\n\n Uses known optimal value for related problem.\n\n Returns\n --------\n rho : 1D array, size K\n Each entry satisfies 0 <= rho[k] <= 1.0\n\n Example\n -------\n >>> rho = make_initrho(3, 0, 1.0)\n >>> print (rho)\n [0.5 0.5 0.5]\n '
eta1 = ((nDoc + 1) * np.ones(K))
eta0 = ((nDoc * kvec(K)) + gamma)
rho = (eta1 / (eta1 + eta0))
return rho | Make vector rho that is good guess for provided problem specs.
Uses known optimal value for related problem.
Returns
--------
rho : 1D array, size K
Each entry satisfies 0 <= rho[k] <= 1.0
Example
-------
>>> rho = make_initrho(3, 0, 1.0)
>>> print (rho)
[0.5 0.5 0.5] | bnpy/allocmodel/topics/OptimizerRhoOmegaBetter.py | make_initrho | tinnguyen96/bnpy | 184 | python | def make_initrho(K, nDoc, gamma):
' Make vector rho that is good guess for provided problem specs.\n\n Uses known optimal value for related problem.\n\n Returns\n --------\n rho : 1D array, size K\n Each entry satisfies 0 <= rho[k] <= 1.0\n\n Example\n -------\n >>> rho = make_initrho(3, 0, 1.0)\n >>> print (rho)\n [0.5 0.5 0.5]\n '
eta1 = ((nDoc + 1) * np.ones(K))
eta0 = ((nDoc * kvec(K)) + gamma)
rho = (eta1 / (eta1 + eta0))
return rho | def make_initrho(K, nDoc, gamma):
' Make vector rho that is good guess for provided problem specs.\n\n Uses known optimal value for related problem.\n\n Returns\n --------\n rho : 1D array, size K\n Each entry satisfies 0 <= rho[k] <= 1.0\n\n Example\n -------\n >>> rho = make_initrho(3, 0, 1.0)\n >>> print (rho)\n [0.5 0.5 0.5]\n '
eta1 = ((nDoc + 1) * np.ones(K))
eta0 = ((nDoc * kvec(K)) + gamma)
rho = (eta1 / (eta1 + eta0))
return rho<|docstring|>Make vector rho that is good guess for provided problem specs.
Uses known optimal value for related problem.
Returns
--------
rho : 1D array, size K
Each entry satisfies 0 <= rho[k] <= 1.0
Example
-------
>>> rho = make_initrho(3, 0, 1.0)
>>> print (rho)
[0.5 0.5 0.5]<|endoftext|> |
b378c65a6cddd551ae14877942790ebc1747ae8711a6aa89cc2e9e8bee75d822 | def make_initomega(K, nDoc, gamma):
' Make vector omega that is good guess for provided problem specs.\n\n Uses known optimal value for related problem.\n\n Returns\n --------\n omega : 1D array, size K\n Each entry omega[k] >= 0.\n '
eta1 = ((nDoc + 1) * np.ones(K))
eta0 = ((nDoc * kvec(K)) + gamma)
omega = (eta1 + eta0)
return omega | Make vector omega that is good guess for provided problem specs.
Uses known optimal value for related problem.
Returns
--------
omega : 1D array, size K
Each entry omega[k] >= 0. | bnpy/allocmodel/topics/OptimizerRhoOmegaBetter.py | make_initomega | tinnguyen96/bnpy | 184 | python | def make_initomega(K, nDoc, gamma):
' Make vector omega that is good guess for provided problem specs.\n\n Uses known optimal value for related problem.\n\n Returns\n --------\n omega : 1D array, size K\n Each entry omega[k] >= 0.\n '
eta1 = ((nDoc + 1) * np.ones(K))
eta0 = ((nDoc * kvec(K)) + gamma)
omega = (eta1 + eta0)
return omega | def make_initomega(K, nDoc, gamma):
' Make vector omega that is good guess for provided problem specs.\n\n Uses known optimal value for related problem.\n\n Returns\n --------\n omega : 1D array, size K\n Each entry omega[k] >= 0.\n '
eta1 = ((nDoc + 1) * np.ones(K))
eta0 = ((nDoc * kvec(K)) + gamma)
omega = (eta1 + eta0)
return omega<|docstring|>Make vector omega that is good guess for provided problem specs.
Uses known optimal value for related problem.
Returns
--------
omega : 1D array, size K
Each entry omega[k] >= 0.<|endoftext|> |
612de89a03355d47d9d0faf83155fa0c48fdcec3ed6b4eab394be63d23fc0148 | def kvec(K):
' Obtain descending vector of [K, K-1, ... 1]\n\n Returns\n --------\n kvec : 1D array, size K\n '
try:
return kvecCache[K]
except KeyError as e:
kvec = ((K + 1) - np.arange(1, (K + 1)))
kvecCache[K] = kvec
return kvec | Obtain descending vector of [K, K-1, ... 1]
Returns
--------
kvec : 1D array, size K | bnpy/allocmodel/topics/OptimizerRhoOmegaBetter.py | kvec | tinnguyen96/bnpy | 184 | python | def kvec(K):
' Obtain descending vector of [K, K-1, ... 1]\n\n Returns\n --------\n kvec : 1D array, size K\n '
try:
return kvecCache[K]
except KeyError as e:
kvec = ((K + 1) - np.arange(1, (K + 1)))
kvecCache[K] = kvec
return kvec | def kvec(K):
' Obtain descending vector of [K, K-1, ... 1]\n\n Returns\n --------\n kvec : 1D array, size K\n '
try:
return kvecCache[K]
except KeyError as e:
kvec = ((K + 1) - np.arange(1, (K + 1)))
kvecCache[K] = kvec
return kvec<|docstring|>Obtain descending vector of [K, K-1, ... 1]
Returns
--------
kvec : 1D array, size K<|endoftext|> |
6580a1da1ce0799e80394aac8da79e71f43035d94785fc9065c788185a097926 | def c_Beta(g1, g0):
' Calculate cumulant function of the Beta distribution\n\n Input can be vectors, in which case we compute sum over\n several cumulant functions of the independent distributions:\n \\prod_k Beta(g1[k], g0[k])\n\n Args\n ----\n g1 : 1D array, size K\n first parameter of a Beta distribution\n g0 : 1D array, size K\n second parameter of a Beta distribution\n\n Returns\n -------\n c : scalar sum of the cumulants defined by provided parameters\n '
return np.sum(((gammaln((g1 + g0)) - gammaln(g1)) - gammaln(g0))) | Calculate cumulant function of the Beta distribution
Input can be vectors, in which case we compute sum over
several cumulant functions of the independent distributions:
\prod_k Beta(g1[k], g0[k])
Args
----
g1 : 1D array, size K
first parameter of a Beta distribution
g0 : 1D array, size K
second parameter of a Beta distribution
Returns
-------
c : scalar sum of the cumulants defined by provided parameters | bnpy/allocmodel/topics/OptimizerRhoOmegaBetter.py | c_Beta | tinnguyen96/bnpy | 184 | python | def c_Beta(g1, g0):
' Calculate cumulant function of the Beta distribution\n\n Input can be vectors, in which case we compute sum over\n several cumulant functions of the independent distributions:\n \\prod_k Beta(g1[k], g0[k])\n\n Args\n ----\n g1 : 1D array, size K\n first parameter of a Beta distribution\n g0 : 1D array, size K\n second parameter of a Beta distribution\n\n Returns\n -------\n c : scalar sum of the cumulants defined by provided parameters\n '
return np.sum(((gammaln((g1 + g0)) - gammaln(g1)) - gammaln(g0))) | def c_Beta(g1, g0):
' Calculate cumulant function of the Beta distribution\n\n Input can be vectors, in which case we compute sum over\n several cumulant functions of the independent distributions:\n \\prod_k Beta(g1[k], g0[k])\n\n Args\n ----\n g1 : 1D array, size K\n first parameter of a Beta distribution\n g0 : 1D array, size K\n second parameter of a Beta distribution\n\n Returns\n -------\n c : scalar sum of the cumulants defined by provided parameters\n '
return np.sum(((gammaln((g1 + g0)) - gammaln(g1)) - gammaln(g0)))<|docstring|>Calculate cumulant function of the Beta distribution
Input can be vectors, in which case we compute sum over
several cumulant functions of the independent distributions:
\prod_k Beta(g1[k], g0[k])
Args
----
g1 : 1D array, size K
first parameter of a Beta distribution
g0 : 1D array, size K
second parameter of a Beta distribution
Returns
-------
c : scalar sum of the cumulants defined by provided parameters<|endoftext|> |
d9b5cd80a2eb51aa56206b405ba116dc29a081a808fe957e2ca5fa879de41301 | def calc_dEbeta_drho(Ebeta, rho, K):
' Calculate partial derivative of Ebeta w.r.t. rho\n\n Returns\n ---------\n Delta : 2D array, size K x K\n '
Delta = np.tile(((- 1) * Ebeta), (K, 1))
Delta /= (1 - rho)[(:, np.newaxis)]
Delta[_get_diagIDs(K)] *= (((- 1) * (1 - rho)) / rho)
Delta.ravel()[_get_flatLowTriIDs_KxK(K)] = 0
return Delta | Calculate partial derivative of Ebeta w.r.t. rho
Returns
---------
Delta : 2D array, size K x K | bnpy/allocmodel/topics/OptimizerRhoOmegaBetter.py | calc_dEbeta_drho | tinnguyen96/bnpy | 184 | python | def calc_dEbeta_drho(Ebeta, rho, K):
' Calculate partial derivative of Ebeta w.r.t. rho\n\n Returns\n ---------\n Delta : 2D array, size K x K\n '
Delta = np.tile(((- 1) * Ebeta), (K, 1))
Delta /= (1 - rho)[(:, np.newaxis)]
Delta[_get_diagIDs(K)] *= (((- 1) * (1 - rho)) / rho)
Delta.ravel()[_get_flatLowTriIDs_KxK(K)] = 0
return Delta | def calc_dEbeta_drho(Ebeta, rho, K):
' Calculate partial derivative of Ebeta w.r.t. rho\n\n Returns\n ---------\n Delta : 2D array, size K x K\n '
Delta = np.tile(((- 1) * Ebeta), (K, 1))
Delta /= (1 - rho)[(:, np.newaxis)]
Delta[_get_diagIDs(K)] *= (((- 1) * (1 - rho)) / rho)
Delta.ravel()[_get_flatLowTriIDs_KxK(K)] = 0
return Delta<|docstring|>Calculate partial derivative of Ebeta w.r.t. rho
Returns
---------
Delta : 2D array, size K x K<|endoftext|> |
afaf9abb5fae410b2849d14868f7eef5acb2e450407cda643d6b33b64d946f56 | def calc_Psi(Ebeta, rho, K):
' Calculate partial derivative of Ebeta_gt w.r.t. rho\n\n Returns\n ---------\n Psi : 2D array, size K x K\n '
Ebeta_gt = (1.0 - np.cumsum(Ebeta[:K]))
Psi = np.tile(((- 1) * Ebeta_gt), (K, 1))
Psi /= (1 - rho)[(:, np.newaxis)]
Psi.ravel()[_get_flatLowTriIDs_KxK(K)] = 0
return Psi | Calculate partial derivative of Ebeta_gt w.r.t. rho
Returns
---------
Psi : 2D array, size K x K | bnpy/allocmodel/topics/OptimizerRhoOmegaBetter.py | calc_Psi | tinnguyen96/bnpy | 184 | python | def calc_Psi(Ebeta, rho, K):
' Calculate partial derivative of Ebeta_gt w.r.t. rho\n\n Returns\n ---------\n Psi : 2D array, size K x K\n '
Ebeta_gt = (1.0 - np.cumsum(Ebeta[:K]))
Psi = np.tile(((- 1) * Ebeta_gt), (K, 1))
Psi /= (1 - rho)[(:, np.newaxis)]
Psi.ravel()[_get_flatLowTriIDs_KxK(K)] = 0
return Psi | def calc_Psi(Ebeta, rho, K):
' Calculate partial derivative of Ebeta_gt w.r.t. rho\n\n Returns\n ---------\n Psi : 2D array, size K x K\n '
Ebeta_gt = (1.0 - np.cumsum(Ebeta[:K]))
Psi = np.tile(((- 1) * Ebeta_gt), (K, 1))
Psi /= (1 - rho)[(:, np.newaxis)]
Psi.ravel()[_get_flatLowTriIDs_KxK(K)] = 0
return Psi<|docstring|>Calculate partial derivative of Ebeta_gt w.r.t. rho
Returns
---------
Psi : 2D array, size K x K<|endoftext|> |
97167875c048444888164dcfa926aa166332cd2ebd8f8de28ec075f0d1d11ebf | def calc_fgrid(o_grid=None, o_pos=None, r_grid=None, r_pos=None, omega=None, rho=None, **kwargs):
' Evaluate the objective across range of values for one entry\n '
K = omega.size
if (o_grid is not None):
assert ((o_pos >= 0) and (o_pos < K))
f_grid = np.zeros_like(o_grid)
omega_n = omega.copy()
for n in range(o_grid.size):
omega_n[o_pos] = o_grid[n]
f_grid[n] = negL_omega(rho=rho, omega=omega_n, approx_grad=1, **kwargs)
elif (r_grid is not None):
assert ((r_pos >= 0) and (r_pos < K))
f_grid = np.zeros_like(r_grid)
rho_n = rho.copy()
for n in range(r_grid.size):
rho_n[o_pos] = r_grid[n]
f_grid[n] = negL_rho(rho=rho_n, omega=omega, approx_grad=1, **kwargs)
else:
raise ValueError('Must specify either o_grid or r_grid')
return f_grid | Evaluate the objective across range of values for one entry | bnpy/allocmodel/topics/OptimizerRhoOmegaBetter.py | calc_fgrid | tinnguyen96/bnpy | 184 | python | def calc_fgrid(o_grid=None, o_pos=None, r_grid=None, r_pos=None, omega=None, rho=None, **kwargs):
' \n '
K = omega.size
if (o_grid is not None):
assert ((o_pos >= 0) and (o_pos < K))
f_grid = np.zeros_like(o_grid)
omega_n = omega.copy()
for n in range(o_grid.size):
omega_n[o_pos] = o_grid[n]
f_grid[n] = negL_omega(rho=rho, omega=omega_n, approx_grad=1, **kwargs)
elif (r_grid is not None):
assert ((r_pos >= 0) and (r_pos < K))
f_grid = np.zeros_like(r_grid)
rho_n = rho.copy()
for n in range(r_grid.size):
rho_n[o_pos] = r_grid[n]
f_grid[n] = negL_rho(rho=rho_n, omega=omega, approx_grad=1, **kwargs)
else:
raise ValueError('Must specify either o_grid or r_grid')
return f_grid | def calc_fgrid(o_grid=None, o_pos=None, r_grid=None, r_pos=None, omega=None, rho=None, **kwargs):
' \n '
K = omega.size
if (o_grid is not None):
assert ((o_pos >= 0) and (o_pos < K))
f_grid = np.zeros_like(o_grid)
omega_n = omega.copy()
for n in range(o_grid.size):
omega_n[o_pos] = o_grid[n]
f_grid[n] = negL_omega(rho=rho, omega=omega_n, approx_grad=1, **kwargs)
elif (r_grid is not None):
assert ((r_pos >= 0) and (r_pos < K))
f_grid = np.zeros_like(r_grid)
rho_n = rho.copy()
for n in range(r_grid.size):
rho_n[o_pos] = r_grid[n]
f_grid[n] = negL_rho(rho=rho_n, omega=omega, approx_grad=1, **kwargs)
else:
raise ValueError('Must specify either o_grid or r_grid')
return f_grid<|docstring|>Evaluate the objective across range of values for one entry<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.