nwo stringlengths 5 86 | sha stringlengths 40 40 | path stringlengths 4 189 | language stringclasses 1 value | identifier stringlengths 1 94 | parameters stringlengths 2 4.03k | argument_list stringclasses 1 value | return_statement stringlengths 0 11.5k | docstring stringlengths 1 33.2k | docstring_summary stringlengths 0 5.15k | docstring_tokens list | function stringlengths 34 151k | function_tokens list | url stringlengths 90 278 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/tools/Editra/src/extern/flatnotebook.py | python | FlatNotebook.DoGetBestSize | (self) | return wx.Size(maxWidth, maxHeight+tabHeight) | Overrides DoGetBestSize to handle sizers nicely. | Overrides DoGetBestSize to handle sizers nicely. | [
"Overrides",
"DoGetBestSize",
"to",
"handle",
"sizers",
"nicely",
"."
] | def DoGetBestSize(self):
""" Overrides DoGetBestSize to handle sizers nicely. """
if not self._windows:
# Something is better than nothing... no pages!
return wx.Size(20, 20)
maxWidth = maxHeight = 0
tabHeight = self.GetPageBestSize().height
for win in self._windows:
# Loop over all the windows to get their best size
width, height = win.GetBestSize()
maxWidth, maxHeight = max(maxWidth, width), max(maxHeight, height)
return wx.Size(maxWidth, maxHeight+tabHeight) | [
"def",
"DoGetBestSize",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_windows",
":",
"# Something is better than nothing... no pages!",
"return",
"wx",
".",
"Size",
"(",
"20",
",",
"20",
")",
"maxWidth",
"=",
"maxHeight",
"=",
"0",
"tabHeight",
"=",
"self",
".",
"GetPageBestSize",
"(",
")",
".",
"height",
"for",
"win",
"in",
"self",
".",
"_windows",
":",
"# Loop over all the windows to get their best size",
"width",
",",
"height",
"=",
"win",
".",
"GetBestSize",
"(",
")",
"maxWidth",
",",
"maxHeight",
"=",
"max",
"(",
"maxWidth",
",",
"width",
")",
",",
"max",
"(",
"maxHeight",
",",
"height",
")",
"return",
"wx",
".",
"Size",
"(",
"maxWidth",
",",
"maxHeight",
"+",
"tabHeight",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/extern/flatnotebook.py#L3058-L3073 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/boto3/session.py | python | Session.get_available_regions | (self, service_name, partition_name='aws',
allow_non_regional=False) | return self._session.get_available_regions(
service_name=service_name, partition_name=partition_name,
allow_non_regional=allow_non_regional) | Lists the region and endpoint names of a particular partition.
:type service_name: string
:param service_name: Name of a service to list endpoint for (e.g., s3).
:type partition_name: string
:param partition_name: Name of the partition to limit endpoints to.
(e.g., aws for the public AWS endpoints, aws-cn for AWS China
endpoints, aws-us-gov for AWS GovCloud (US) Endpoints, etc.)
:type allow_non_regional: bool
:param allow_non_regional: Set to True to include endpoints that are
not regional endpoints (e.g., s3-external-1,
fips-us-gov-west-1, etc).
:return: Returns a list of endpoint names (e.g., ["us-east-1"]). | Lists the region and endpoint names of a particular partition. | [
"Lists",
"the",
"region",
"and",
"endpoint",
"names",
"of",
"a",
"particular",
"partition",
"."
] | def get_available_regions(self, service_name, partition_name='aws',
allow_non_regional=False):
"""Lists the region and endpoint names of a particular partition.
:type service_name: string
:param service_name: Name of a service to list endpoint for (e.g., s3).
:type partition_name: string
:param partition_name: Name of the partition to limit endpoints to.
(e.g., aws for the public AWS endpoints, aws-cn for AWS China
endpoints, aws-us-gov for AWS GovCloud (US) Endpoints, etc.)
:type allow_non_regional: bool
:param allow_non_regional: Set to True to include endpoints that are
not regional endpoints (e.g., s3-external-1,
fips-us-gov-west-1, etc).
:return: Returns a list of endpoint names (e.g., ["us-east-1"]).
"""
return self._session.get_available_regions(
service_name=service_name, partition_name=partition_name,
allow_non_regional=allow_non_regional) | [
"def",
"get_available_regions",
"(",
"self",
",",
"service_name",
",",
"partition_name",
"=",
"'aws'",
",",
"allow_non_regional",
"=",
"False",
")",
":",
"return",
"self",
".",
"_session",
".",
"get_available_regions",
"(",
"service_name",
"=",
"service_name",
",",
"partition_name",
"=",
"partition_name",
",",
"allow_non_regional",
"=",
"allow_non_regional",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/boto3/session.py#L152-L173 | |
LiquidPlayer/LiquidCore | 9405979363f2353ac9a71ad8ab59685dd7f919c9 | deps/node-10.15.3/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/ninja.py | python | NinjaWriter.WriteMacBundleResources | (self, resources, bundle_depends) | return xcassets | Writes ninja edges for 'mac_bundle_resources'. | Writes ninja edges for 'mac_bundle_resources'. | [
"Writes",
"ninja",
"edges",
"for",
"mac_bundle_resources",
"."
] | def WriteMacBundleResources(self, resources, bundle_depends):
"""Writes ninja edges for 'mac_bundle_resources'."""
xcassets = []
for output, res in gyp.xcode_emulation.GetMacBundleResources(
generator_default_variables['PRODUCT_DIR'],
self.xcode_settings, map(self.GypPathToNinja, resources)):
output = self.ExpandSpecial(output)
if os.path.splitext(output)[-1] != '.xcassets':
isBinary = self.xcode_settings.IsBinaryOutputFormat(self.config_name)
self.ninja.build(output, 'mac_tool', res,
variables=[('mactool_cmd', 'copy-bundle-resource'), \
('binary', isBinary)])
bundle_depends.append(output)
else:
xcassets.append(res)
return xcassets | [
"def",
"WriteMacBundleResources",
"(",
"self",
",",
"resources",
",",
"bundle_depends",
")",
":",
"xcassets",
"=",
"[",
"]",
"for",
"output",
",",
"res",
"in",
"gyp",
".",
"xcode_emulation",
".",
"GetMacBundleResources",
"(",
"generator_default_variables",
"[",
"'PRODUCT_DIR'",
"]",
",",
"self",
".",
"xcode_settings",
",",
"map",
"(",
"self",
".",
"GypPathToNinja",
",",
"resources",
")",
")",
":",
"output",
"=",
"self",
".",
"ExpandSpecial",
"(",
"output",
")",
"if",
"os",
".",
"path",
".",
"splitext",
"(",
"output",
")",
"[",
"-",
"1",
"]",
"!=",
"'.xcassets'",
":",
"isBinary",
"=",
"self",
".",
"xcode_settings",
".",
"IsBinaryOutputFormat",
"(",
"self",
".",
"config_name",
")",
"self",
".",
"ninja",
".",
"build",
"(",
"output",
",",
"'mac_tool'",
",",
"res",
",",
"variables",
"=",
"[",
"(",
"'mactool_cmd'",
",",
"'copy-bundle-resource'",
")",
",",
"(",
"'binary'",
",",
"isBinary",
")",
"]",
")",
"bundle_depends",
".",
"append",
"(",
"output",
")",
"else",
":",
"xcassets",
".",
"append",
"(",
"res",
")",
"return",
"xcassets"
] | https://github.com/LiquidPlayer/LiquidCore/blob/9405979363f2353ac9a71ad8ab59685dd7f919c9/deps/node-10.15.3/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/ninja.py#L765-L780 | |
lukasmonk/lucaschess | 13e2e5cb13b38a720ccf897af649054a64bcb914 | Code/SQL/DBFcache.py | python | DBFcache._leerUno | (self, numRecno) | Lectura de un registro, y asignacion a las variables = campos. | Lectura de un registro, y asignacion a las variables = campos. | [
"Lectura",
"de",
"un",
"registro",
"y",
"asignacion",
"a",
"las",
"variables",
"=",
"campos",
"."
] | def _leerUno(self, numRecno):
"""
Lectura de un registro, y asignacion a las variables = campos.
"""
self.ID = self.liIDs[numRecno][0]
recValores = self.readCache(numRecno)
if not recValores:
self.cursor.execute("SELECT %s FROM %s WHERE rowid =%d" % (self.select, self.ctabla, self.ID))
liValores = self.cursor.fetchone()
recValores = Almacen()
for numCampo, campo in enumerate(self.liCampos):
setattr(recValores, campo, liValores[numCampo])
self.writeCache(numRecno, recValores)
self.reg = recValores | [
"def",
"_leerUno",
"(",
"self",
",",
"numRecno",
")",
":",
"self",
".",
"ID",
"=",
"self",
".",
"liIDs",
"[",
"numRecno",
"]",
"[",
"0",
"]",
"recValores",
"=",
"self",
".",
"readCache",
"(",
"numRecno",
")",
"if",
"not",
"recValores",
":",
"self",
".",
"cursor",
".",
"execute",
"(",
"\"SELECT %s FROM %s WHERE rowid =%d\"",
"%",
"(",
"self",
".",
"select",
",",
"self",
".",
"ctabla",
",",
"self",
".",
"ID",
")",
")",
"liValores",
"=",
"self",
".",
"cursor",
".",
"fetchone",
"(",
")",
"recValores",
"=",
"Almacen",
"(",
")",
"for",
"numCampo",
",",
"campo",
"in",
"enumerate",
"(",
"self",
".",
"liCampos",
")",
":",
"setattr",
"(",
"recValores",
",",
"campo",
",",
"liValores",
"[",
"numCampo",
"]",
")",
"self",
".",
"writeCache",
"(",
"numRecno",
",",
"recValores",
")",
"self",
".",
"reg",
"=",
"recValores"
] | https://github.com/lukasmonk/lucaschess/blob/13e2e5cb13b38a720ccf897af649054a64bcb914/Code/SQL/DBFcache.py#L143-L156 | ||
BitMEX/api-connectors | 37a3a5b806ad5d0e0fc975ab86d9ed43c3bcd812 | auto-generated/python/swagger_client/models/settlement.py | python | Settlement.to_dict | (self) | return result | Returns the model properties as a dict | Returns the model properties as a dict | [
"Returns",
"the",
"model",
"properties",
"as",
"a",
"dict"
] | def to_dict(self):
"""Returns the model properties as a dict"""
result = {}
for attr, _ in six.iteritems(self.swagger_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
if issubclass(Settlement, dict):
for key, value in self.items():
result[key] = value
return result | [
"def",
"to_dict",
"(",
"self",
")",
":",
"result",
"=",
"{",
"}",
"for",
"attr",
",",
"_",
"in",
"six",
".",
"iteritems",
"(",
"self",
".",
"swagger_types",
")",
":",
"value",
"=",
"getattr",
"(",
"self",
",",
"attr",
")",
"if",
"isinstance",
"(",
"value",
",",
"list",
")",
":",
"result",
"[",
"attr",
"]",
"=",
"list",
"(",
"map",
"(",
"lambda",
"x",
":",
"x",
".",
"to_dict",
"(",
")",
"if",
"hasattr",
"(",
"x",
",",
"\"to_dict\"",
")",
"else",
"x",
",",
"value",
")",
")",
"elif",
"hasattr",
"(",
"value",
",",
"\"to_dict\"",
")",
":",
"result",
"[",
"attr",
"]",
"=",
"value",
".",
"to_dict",
"(",
")",
"elif",
"isinstance",
"(",
"value",
",",
"dict",
")",
":",
"result",
"[",
"attr",
"]",
"=",
"dict",
"(",
"map",
"(",
"lambda",
"item",
":",
"(",
"item",
"[",
"0",
"]",
",",
"item",
"[",
"1",
"]",
".",
"to_dict",
"(",
")",
")",
"if",
"hasattr",
"(",
"item",
"[",
"1",
"]",
",",
"\"to_dict\"",
")",
"else",
"item",
",",
"value",
".",
"items",
"(",
")",
")",
")",
"else",
":",
"result",
"[",
"attr",
"]",
"=",
"value",
"if",
"issubclass",
"(",
"Settlement",
",",
"dict",
")",
":",
"for",
"key",
",",
"value",
"in",
"self",
".",
"items",
"(",
")",
":",
"result",
"[",
"key",
"]",
"=",
"value",
"return",
"result"
] | https://github.com/BitMEX/api-connectors/blob/37a3a5b806ad5d0e0fc975ab86d9ed43c3bcd812/auto-generated/python/swagger_client/models/settlement.py#L281-L306 | |
PlatformLab/Arachne | e67391471007174dd4002dc2c160628e19c284e8 | scripts/cpplint.py | python | FileInfo.IsSource | (self) | return _IsSourceExtension(self.Extension()[1:]) | File has a source file extension. | File has a source file extension. | [
"File",
"has",
"a",
"source",
"file",
"extension",
"."
] | def IsSource(self):
"""File has a source file extension."""
return _IsSourceExtension(self.Extension()[1:]) | [
"def",
"IsSource",
"(",
"self",
")",
":",
"return",
"_IsSourceExtension",
"(",
"self",
".",
"Extension",
"(",
")",
"[",
"1",
":",
"]",
")"
] | https://github.com/PlatformLab/Arachne/blob/e67391471007174dd4002dc2c160628e19c284e8/scripts/cpplint.py#L1156-L1158 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/_core.py | python | Menu.GetLabel | (*args, **kwargs) | return _core_.Menu_GetLabel(*args, **kwargs) | GetLabel(self, int id) -> String | GetLabel(self, int id) -> String | [
"GetLabel",
"(",
"self",
"int",
"id",
")",
"-",
">",
"String"
] | def GetLabel(*args, **kwargs):
"""GetLabel(self, int id) -> String"""
return _core_.Menu_GetLabel(*args, **kwargs) | [
"def",
"GetLabel",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_core_",
".",
"Menu_GetLabel",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_core.py#L12174-L12176 | |
apache/singa | 93fd9da72694e68bfe3fb29d0183a65263d238a1 | python/singa/sonnx.py | python | SingaFrontend._special_handle_reshape | (cls, op, X, W) | return [
numpy_helper.from_array(np.array(op.shape, dtype=np.int64),
node_name)
] | hanlde the special operators
Args:
op: a given operator
Args:
op_t: the tensor of the operator
Returns:
onnx tensor list | hanlde the special operators
Args:
op: a given operator
Args:
op_t: the tensor of the operator
Returns:
onnx tensor list | [
"hanlde",
"the",
"special",
"operators",
"Args",
":",
"op",
":",
"a",
"given",
"operator",
"Args",
":",
"op_t",
":",
"the",
"tensor",
"of",
"the",
"operator",
"Returns",
":",
"onnx",
"tensor",
"list"
] | def _special_handle_reshape(cls, op, X, W):
"""
hanlde the special operators
Args:
op: a given operator
Args:
op_t: the tensor of the operator
Returns:
onnx tensor list
"""
node_name = op.name + ":shape"
return [
numpy_helper.from_array(np.array(op.shape, dtype=np.int64),
node_name)
] | [
"def",
"_special_handle_reshape",
"(",
"cls",
",",
"op",
",",
"X",
",",
"W",
")",
":",
"node_name",
"=",
"op",
".",
"name",
"+",
"\":shape\"",
"return",
"[",
"numpy_helper",
".",
"from_array",
"(",
"np",
".",
"array",
"(",
"op",
".",
"shape",
",",
"dtype",
"=",
"np",
".",
"int64",
")",
",",
"node_name",
")",
"]"
] | https://github.com/apache/singa/blob/93fd9da72694e68bfe3fb29d0183a65263d238a1/python/singa/sonnx.py#L713-L727 | |
facebook/ThreatExchange | 31914a51820c73c8a0daffe62ccca29a6e3d359e | python-threatexchange/threatexchange/cli/dataset/simple_serialization.py | python | CliIndicatorSerialization.as_csv_row | (self) | return (self.indicator,) + self.rollup.as_row() | As a simple record type for the threatexchange CLI cache | As a simple record type for the threatexchange CLI cache | [
"As",
"a",
"simple",
"record",
"type",
"for",
"the",
"threatexchange",
"CLI",
"cache"
] | def as_csv_row(self) -> t.Tuple:
"""As a simple record type for the threatexchange CLI cache"""
return (self.indicator,) + self.rollup.as_row() | [
"def",
"as_csv_row",
"(",
"self",
")",
"->",
"t",
".",
"Tuple",
":",
"return",
"(",
"self",
".",
"indicator",
",",
")",
"+",
"self",
".",
"rollup",
".",
"as_row",
"(",
")"
] | https://github.com/facebook/ThreatExchange/blob/31914a51820c73c8a0daffe62ccca29a6e3d359e/python-threatexchange/threatexchange/cli/dataset/simple_serialization.py#L36-L38 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/py/py/_path/local.py | python | LocalPath.__init__ | (self, path=None, expanduser=False) | Initialize and return a local Path instance.
Path can be relative to the current directory.
If path is None it defaults to the current working directory.
If expanduser is True, tilde-expansion is performed.
Note that Path instances always carry an absolute path.
Note also that passing in a local path object will simply return
the exact same path object. Use new() to get a new copy. | Initialize and return a local Path instance. | [
"Initialize",
"and",
"return",
"a",
"local",
"Path",
"instance",
"."
] | def __init__(self, path=None, expanduser=False):
""" Initialize and return a local Path instance.
Path can be relative to the current directory.
If path is None it defaults to the current working directory.
If expanduser is True, tilde-expansion is performed.
Note that Path instances always carry an absolute path.
Note also that passing in a local path object will simply return
the exact same path object. Use new() to get a new copy.
"""
if path is None:
self.strpath = py.error.checked_call(os.getcwd)
else:
try:
path = fspath(path)
except TypeError:
raise ValueError("can only pass None, Path instances "
"or non-empty strings to LocalPath")
if expanduser:
path = os.path.expanduser(path)
self.strpath = abspath(path) | [
"def",
"__init__",
"(",
"self",
",",
"path",
"=",
"None",
",",
"expanduser",
"=",
"False",
")",
":",
"if",
"path",
"is",
"None",
":",
"self",
".",
"strpath",
"=",
"py",
".",
"error",
".",
"checked_call",
"(",
"os",
".",
"getcwd",
")",
"else",
":",
"try",
":",
"path",
"=",
"fspath",
"(",
"path",
")",
"except",
"TypeError",
":",
"raise",
"ValueError",
"(",
"\"can only pass None, Path instances \"",
"\"or non-empty strings to LocalPath\"",
")",
"if",
"expanduser",
":",
"path",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"path",
")",
"self",
".",
"strpath",
"=",
"abspath",
"(",
"path",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/py/py/_path/local.py#L143-L163 | ||
su2code/SU2 | 72b2fa977b64b9683a388920f05298a40d39e5c5 | SU2_PY/FSI_tools/FSIInterface.py | python | Interface.getFluidInterfaceNodalForce | (self, FSI_config, FluidSolver) | Gets the fluid interface loads from the fluid solver. | Gets the fluid interface loads from the fluid solver. | [
"Gets",
"the",
"fluid",
"interface",
"loads",
"from",
"the",
"fluid",
"solver",
"."
] | def getFluidInterfaceNodalForce(self, FSI_config, FluidSolver):
"""
Gets the fluid interface loads from the fluid solver.
"""
if self.have_MPI:
myid = self.comm.Get_rank()
else:
myid = 0
GlobalIndex = int()
localIndex = 0
# --- Get the fluid interface loads from the fluid solver and directly fill the corresponding PETSc vector ---
for iVertex in range(self.nLocalFluidInterfaceNodes):
GlobalIndex = FluidSolver.GetVertexGlobalIndex(self.fluidInterfaceIdentifier, iVertex)
if GlobalIndex not in self.FluidHaloNodeList[myid].keys():
loadX, loadY, loadZ = FluidSolver.GetFlowLoad(self.fluidInterfaceIdentifier, iVertex)
iGlobalVertex = self.__getGlobalIndex('fluid', myid, localIndex)
self.fluidLoads_array_X.setValues([iGlobalVertex], loadX)
self.fluidLoads_array_Y.setValues([iGlobalVertex], loadY)
self.fluidLoads_array_Z.setValues([iGlobalVertex], loadZ)
localIndex += 1
self.fluidLoads_array_X.assemblyBegin()
self.fluidLoads_array_X.assemblyEnd()
self.fluidLoads_array_Y.assemblyBegin()
self.fluidLoads_array_Y.assemblyEnd()
self.fluidLoads_array_Z.assemblyBegin()
self.fluidLoads_array_Z.assemblyEnd() | [
"def",
"getFluidInterfaceNodalForce",
"(",
"self",
",",
"FSI_config",
",",
"FluidSolver",
")",
":",
"if",
"self",
".",
"have_MPI",
":",
"myid",
"=",
"self",
".",
"comm",
".",
"Get_rank",
"(",
")",
"else",
":",
"myid",
"=",
"0",
"GlobalIndex",
"=",
"int",
"(",
")",
"localIndex",
"=",
"0",
"# --- Get the fluid interface loads from the fluid solver and directly fill the corresponding PETSc vector ---",
"for",
"iVertex",
"in",
"range",
"(",
"self",
".",
"nLocalFluidInterfaceNodes",
")",
":",
"GlobalIndex",
"=",
"FluidSolver",
".",
"GetVertexGlobalIndex",
"(",
"self",
".",
"fluidInterfaceIdentifier",
",",
"iVertex",
")",
"if",
"GlobalIndex",
"not",
"in",
"self",
".",
"FluidHaloNodeList",
"[",
"myid",
"]",
".",
"keys",
"(",
")",
":",
"loadX",
",",
"loadY",
",",
"loadZ",
"=",
"FluidSolver",
".",
"GetFlowLoad",
"(",
"self",
".",
"fluidInterfaceIdentifier",
",",
"iVertex",
")",
"iGlobalVertex",
"=",
"self",
".",
"__getGlobalIndex",
"(",
"'fluid'",
",",
"myid",
",",
"localIndex",
")",
"self",
".",
"fluidLoads_array_X",
".",
"setValues",
"(",
"[",
"iGlobalVertex",
"]",
",",
"loadX",
")",
"self",
".",
"fluidLoads_array_Y",
".",
"setValues",
"(",
"[",
"iGlobalVertex",
"]",
",",
"loadY",
")",
"self",
".",
"fluidLoads_array_Z",
".",
"setValues",
"(",
"[",
"iGlobalVertex",
"]",
",",
"loadZ",
")",
"localIndex",
"+=",
"1",
"self",
".",
"fluidLoads_array_X",
".",
"assemblyBegin",
"(",
")",
"self",
".",
"fluidLoads_array_X",
".",
"assemblyEnd",
"(",
")",
"self",
".",
"fluidLoads_array_Y",
".",
"assemblyBegin",
"(",
")",
"self",
".",
"fluidLoads_array_Y",
".",
"assemblyEnd",
"(",
")",
"self",
".",
"fluidLoads_array_Z",
".",
"assemblyBegin",
"(",
")",
"self",
".",
"fluidLoads_array_Z",
".",
"assemblyEnd",
"(",
")"
] | https://github.com/su2code/SU2/blob/72b2fa977b64b9683a388920f05298a40d39e5c5/SU2_PY/FSI_tools/FSIInterface.py#L1445-L1473 | ||
trailofbits/llvm-sanitizer-tutorial | d29dfeec7f51fbf234fd0080f28f2b30cd0b6e99 | llvm/tools/clang/bindings/python/clang/cindex.py | python | CursorKind.is_statement | (self) | return conf.lib.clang_isStatement(self) | Test if this is a statement kind. | Test if this is a statement kind. | [
"Test",
"if",
"this",
"is",
"a",
"statement",
"kind",
"."
] | def is_statement(self):
"""Test if this is a statement kind."""
return conf.lib.clang_isStatement(self) | [
"def",
"is_statement",
"(",
"self",
")",
":",
"return",
"conf",
".",
"lib",
".",
"clang_isStatement",
"(",
"self",
")"
] | https://github.com/trailofbits/llvm-sanitizer-tutorial/blob/d29dfeec7f51fbf234fd0080f28f2b30cd0b6e99/llvm/tools/clang/bindings/python/clang/cindex.py#L684-L686 | |
opengauss-mirror/openGauss-server | e383f1b77720a00ddbe4c0655bc85914d9b02a2b | src/gausskernel/dbmind/tools/xtuner/tuner/recommend.py | python | OpenGaussKnobAdvisor.shared_buffers | (self) | If you have a dedicated database server with 1GB or more of RAM,
a reasonable starting value for shared_buffers is 25% of the memory in your system.
There are some workloads where even large settings for shared_buffers are effective,
but because database also relies on the operating system cache,
it is unlikely that an allocation of more than 40% of RAM to shared_buffers will
work better than a smaller amount. | If you have a dedicated database server with 1GB or more of RAM,
a reasonable starting value for shared_buffers is 25% of the memory in your system.
There are some workloads where even large settings for shared_buffers are effective,
but because database also relies on the operating system cache,
it is unlikely that an allocation of more than 40% of RAM to shared_buffers will
work better than a smaller amount. | [
"If",
"you",
"have",
"a",
"dedicated",
"database",
"server",
"with",
"1GB",
"or",
"more",
"of",
"RAM",
"a",
"reasonable",
"starting",
"value",
"for",
"shared_buffers",
"is",
"25%",
"of",
"the",
"memory",
"in",
"your",
"system",
".",
"There",
"are",
"some",
"workloads",
"where",
"even",
"large",
"settings",
"for",
"shared_buffers",
"are",
"effective",
"but",
"because",
"database",
"also",
"relies",
"on",
"the",
"operating",
"system",
"cache",
"it",
"is",
"unlikely",
"that",
"an",
"allocation",
"of",
"more",
"than",
"40%",
"of",
"RAM",
"to",
"shared_buffers",
"will",
"work",
"better",
"than",
"a",
"smaller",
"amount",
"."
] | def shared_buffers(self):
"""If you have a dedicated database server with 1GB or more of RAM,
a reasonable starting value for shared_buffers is 25% of the memory in your system.
There are some workloads where even large settings for shared_buffers are effective,
but because database also relies on the operating system cache,
it is unlikely that an allocation of more than 40% of RAM to shared_buffers will
work better than a smaller amount. """
mem_total = self.max_process_memory.recommend # unit: kB
if mem_total < 1 * SIZE_UNIT_MAP['GB']:
default = 0.15 * mem_total
elif mem_total > 8 * SIZE_UNIT_MAP['GB']:
default = 0.4 * mem_total
else:
default = 0.25 * mem_total
# The value of this knob means the number of maximum cached blocks.
recommend = round4(default / self.metric.block_size)
if self.metric.is_64bit:
database_blocks = self.metric.all_database_size / self.metric.block_size
if database_blocks < recommend:
self.report.print_warn("The total size of all databases is less than the memory size. "
"Therefore, it is unnecessary to set shared_buffers to a large value.")
recommend = round4(min(database_blocks, recommend))
upper = round4(recommend * 1.15)
lower = round4(min(0.15 * mem_total / self.metric.block_size, recommend))
return instantiate_knob(name="shared_buffers",
recommend=recommend,
knob_type=Knob.TYPE.INT,
value_max=upper,
value_min=lower,
restart=True)
else:
upper = round4(
min(recommend, 2 * SIZE_UNIT_MAP["GB"] / self.metric.block_size)) # 32-bit OS only can use 2 GB mem.
lower = round4(min(0.15 * mem_total / self.metric.block_size, recommend))
return instantiate_knob(name="shared_buffers",
recommend=recommend,
knob_type=Knob.TYPE.INT,
value_max=upper,
value_min=lower,
restart=True) | [
"def",
"shared_buffers",
"(",
"self",
")",
":",
"mem_total",
"=",
"self",
".",
"max_process_memory",
".",
"recommend",
"# unit: kB",
"if",
"mem_total",
"<",
"1",
"*",
"SIZE_UNIT_MAP",
"[",
"'GB'",
"]",
":",
"default",
"=",
"0.15",
"*",
"mem_total",
"elif",
"mem_total",
">",
"8",
"*",
"SIZE_UNIT_MAP",
"[",
"'GB'",
"]",
":",
"default",
"=",
"0.4",
"*",
"mem_total",
"else",
":",
"default",
"=",
"0.25",
"*",
"mem_total",
"# The value of this knob means the number of maximum cached blocks.",
"recommend",
"=",
"round4",
"(",
"default",
"/",
"self",
".",
"metric",
".",
"block_size",
")",
"if",
"self",
".",
"metric",
".",
"is_64bit",
":",
"database_blocks",
"=",
"self",
".",
"metric",
".",
"all_database_size",
"/",
"self",
".",
"metric",
".",
"block_size",
"if",
"database_blocks",
"<",
"recommend",
":",
"self",
".",
"report",
".",
"print_warn",
"(",
"\"The total size of all databases is less than the memory size. \"",
"\"Therefore, it is unnecessary to set shared_buffers to a large value.\"",
")",
"recommend",
"=",
"round4",
"(",
"min",
"(",
"database_blocks",
",",
"recommend",
")",
")",
"upper",
"=",
"round4",
"(",
"recommend",
"*",
"1.15",
")",
"lower",
"=",
"round4",
"(",
"min",
"(",
"0.15",
"*",
"mem_total",
"/",
"self",
".",
"metric",
".",
"block_size",
",",
"recommend",
")",
")",
"return",
"instantiate_knob",
"(",
"name",
"=",
"\"shared_buffers\"",
",",
"recommend",
"=",
"recommend",
",",
"knob_type",
"=",
"Knob",
".",
"TYPE",
".",
"INT",
",",
"value_max",
"=",
"upper",
",",
"value_min",
"=",
"lower",
",",
"restart",
"=",
"True",
")",
"else",
":",
"upper",
"=",
"round4",
"(",
"min",
"(",
"recommend",
",",
"2",
"*",
"SIZE_UNIT_MAP",
"[",
"\"GB\"",
"]",
"/",
"self",
".",
"metric",
".",
"block_size",
")",
")",
"# 32-bit OS only can use 2 GB mem.",
"lower",
"=",
"round4",
"(",
"min",
"(",
"0.15",
"*",
"mem_total",
"/",
"self",
".",
"metric",
".",
"block_size",
",",
"recommend",
")",
")",
"return",
"instantiate_knob",
"(",
"name",
"=",
"\"shared_buffers\"",
",",
"recommend",
"=",
"recommend",
",",
"knob_type",
"=",
"Knob",
".",
"TYPE",
".",
"INT",
",",
"value_max",
"=",
"upper",
",",
"value_min",
"=",
"lower",
",",
"restart",
"=",
"True",
")"
] | https://github.com/opengauss-mirror/openGauss-server/blob/e383f1b77720a00ddbe4c0655bc85914d9b02a2b/src/gausskernel/dbmind/tools/xtuner/tuner/recommend.py#L308-L350 | ||
Ewenwan/MVision | 97b394dfa48cb21c82cd003b1a952745e413a17f | CNN/MobileNet/MobileNet_v1_ssd_caffe/ssd_detect.py | python | CaffeDetection.detect | (self, image_file, conf_thresh=0.5, topn=5) | return result | SSD detection | SSD detection | [
"SSD",
"detection"
] | def detect(self, image_file, conf_thresh=0.5, topn=5):
'''
SSD detection
'''
# set net to batch size of 1
# image_resize = 300 1张图片 3通道 300*300
self.net.blobs['data'].reshape(1, 3, self.image_resize, self.image_resize)
image = caffe.io.load_image(image_file)
# Run the net and examine the top_k results
transformed_image = self.transformer.preprocess('data', image)
self.net.blobs['data'].data[...] = transformed_image
# 模型前向传播 并且获取 detection_out 层的输出
detections = self.net.forward()['detection_out']
# 模型输出 解码
det_label = detections[0,0,:,1]# 标签索引
det_conf = detections[0,0,:,2] # 可信度
det_xmin = detections[0,0,:,3] # 坐标
det_ymin = detections[0,0,:,4]
det_xmax = detections[0,0,:,5]
det_ymax = detections[0,0,:,6]
# 获取可行度大于 0.5的索引
top_indices = [i for i, conf in enumerate(det_conf) if conf >= conf_thresh]
top_conf = det_conf[top_indices]# 可信度
top_label_indices = det_label[top_indices].tolist()# 标签索引
top_labels = get_labelname(self.labelmap, top_label_indices)# 标签字符串
top_xmin = det_xmin[top_indices]# 坐标 0~1小数
top_ymin = det_ymin[top_indices]
top_xmax = det_xmax[top_indices]
top_ymax = det_ymax[top_indices]
# 前5个
result = []
for i in xrange(min(topn, top_conf.shape[0])):# 前5个
xmin = top_xmin[i] # xmin = int(round(top_xmin[i] * image.shape[1]))
ymin = top_ymin[i] # ymin = int(round(top_ymin[i] * image.shape[0]))
xmax = top_xmax[i] # xmax = int(round(top_xmax[i] * image.shape[1]))
ymax = top_ymax[i] # ymax = int(round(top_ymax[i] * image.shape[0]))
score = top_conf[i]# 预测得分
label = int(top_label_indices[i])#标签id
label_name = top_labels[i]#标签字符串
result.append([xmin, ymin, xmax, ymax, label, score, label_name])
# result[i][0] xmin
# result[i][1] ymin
# result[i][2] xmax
# result[i][3] ymax
# result[i][4] label
# result[i][5] score
# result[i][6] label_name
return result | [
"def",
"detect",
"(",
"self",
",",
"image_file",
",",
"conf_thresh",
"=",
"0.5",
",",
"topn",
"=",
"5",
")",
":",
"# set net to batch size of 1",
"# image_resize = 300 1张图片 3通道 300*300",
"self",
".",
"net",
".",
"blobs",
"[",
"'data'",
"]",
".",
"reshape",
"(",
"1",
",",
"3",
",",
"self",
".",
"image_resize",
",",
"self",
".",
"image_resize",
")",
"image",
"=",
"caffe",
".",
"io",
".",
"load_image",
"(",
"image_file",
")",
"# Run the net and examine the top_k results",
"transformed_image",
"=",
"self",
".",
"transformer",
".",
"preprocess",
"(",
"'data'",
",",
"image",
")",
"self",
".",
"net",
".",
"blobs",
"[",
"'data'",
"]",
".",
"data",
"[",
"...",
"]",
"=",
"transformed_image",
"# 模型前向传播 并且获取 detection_out 层的输出",
"detections",
"=",
"self",
".",
"net",
".",
"forward",
"(",
")",
"[",
"'detection_out'",
"]",
"# 模型输出 解码",
"det_label",
"=",
"detections",
"[",
"0",
",",
"0",
",",
":",
",",
"1",
"]",
"# 标签索引",
"det_conf",
"=",
"detections",
"[",
"0",
",",
"0",
",",
":",
",",
"2",
"]",
"# 可信度",
"det_xmin",
"=",
"detections",
"[",
"0",
",",
"0",
",",
":",
",",
"3",
"]",
"# 坐标",
"det_ymin",
"=",
"detections",
"[",
"0",
",",
"0",
",",
":",
",",
"4",
"]",
"det_xmax",
"=",
"detections",
"[",
"0",
",",
"0",
",",
":",
",",
"5",
"]",
"det_ymax",
"=",
"detections",
"[",
"0",
",",
"0",
",",
":",
",",
"6",
"]",
"# 获取可行度大于 0.5的索引",
"top_indices",
"=",
"[",
"i",
"for",
"i",
",",
"conf",
"in",
"enumerate",
"(",
"det_conf",
")",
"if",
"conf",
">=",
"conf_thresh",
"]",
"top_conf",
"=",
"det_conf",
"[",
"top_indices",
"]",
"# 可信度",
"top_label_indices",
"=",
"det_label",
"[",
"top_indices",
"]",
".",
"tolist",
"(",
")",
"# 标签索引",
"top_labels",
"=",
"get_labelname",
"(",
"self",
".",
"labelmap",
",",
"top_label_indices",
")",
"# 标签字符串",
"top_xmin",
"=",
"det_xmin",
"[",
"top_indices",
"]",
"# 坐标 0~1小数",
"top_ymin",
"=",
"det_ymin",
"[",
"top_indices",
"]",
"top_xmax",
"=",
"det_xmax",
"[",
"top_indices",
"]",
"top_ymax",
"=",
"det_ymax",
"[",
"top_indices",
"]",
"# 前5个",
"result",
"=",
"[",
"]",
"for",
"i",
"in",
"xrange",
"(",
"min",
"(",
"topn",
",",
"top_conf",
".",
"shape",
"[",
"0",
"]",
")",
")",
":",
"# 前5个",
"xmin",
"=",
"top_xmin",
"[",
"i",
"]",
"# xmin = int(round(top_xmin[i] * image.shape[1]))",
"ymin",
"=",
"top_ymin",
"[",
"i",
"]",
"# ymin = int(round(top_ymin[i] * image.shape[0]))",
"xmax",
"=",
"top_xmax",
"[",
"i",
"]",
"# xmax = int(round(top_xmax[i] * image.shape[1]))",
"ymax",
"=",
"top_ymax",
"[",
"i",
"]",
"# ymax = int(round(top_ymax[i] * image.shape[0]))",
"score",
"=",
"top_conf",
"[",
"i",
"]",
"# 预测得分",
"label",
"=",
"int",
"(",
"top_label_indices",
"[",
"i",
"]",
")",
"#标签id",
"label_name",
"=",
"top_labels",
"[",
"i",
"]",
"#标签字符串",
"result",
".",
"append",
"(",
"[",
"xmin",
",",
"ymin",
",",
"xmax",
",",
"ymax",
",",
"label",
",",
"score",
",",
"label_name",
"]",
")",
"# result[i][0] xmin",
"# result[i][1] ymin",
"# result[i][2] xmax",
"# result[i][3] ymax",
"# result[i][4] label",
"# result[i][5] score",
"# result[i][6] label_name ",
"return",
"result"
] | https://github.com/Ewenwan/MVision/blob/97b394dfa48cb21c82cd003b1a952745e413a17f/CNN/MobileNet/MobileNet_v1_ssd_caffe/ssd_detect.py#L69-L120 | |
google-ar/WebARonTango | e86965d2cbc652156b480e0fcf77c716745578cd | chromium/src/gpu/command_buffer/build_gles2_cmd_buffer.py | python | ToGLExtensionString | (extension_flag) | return "_".join(
[part.upper() if part in uppercase_words else part for part in parts]) | Returns GL-type extension string of a extension flag. | Returns GL-type extension string of a extension flag. | [
"Returns",
"GL",
"-",
"type",
"extension",
"string",
"of",
"a",
"extension",
"flag",
"."
] | def ToGLExtensionString(extension_flag):
"""Returns GL-type extension string of a extension flag."""
if extension_flag == "oes_compressed_etc1_rgb8_texture":
return "OES_compressed_ETC1_RGB8_texture" # Fixup inconsitency with rgb8,
# unfortunate.
uppercase_words = [ 'img', 'ext', 'arb', 'chromium', 'oes', 'amd', 'bgra8888',
'egl', 'atc', 'etc1', 'angle']
parts = extension_flag.split('_')
return "_".join(
[part.upper() if part in uppercase_words else part for part in parts]) | [
"def",
"ToGLExtensionString",
"(",
"extension_flag",
")",
":",
"if",
"extension_flag",
"==",
"\"oes_compressed_etc1_rgb8_texture\"",
":",
"return",
"\"OES_compressed_ETC1_RGB8_texture\"",
"# Fixup inconsitency with rgb8,",
"# unfortunate.",
"uppercase_words",
"=",
"[",
"'img'",
",",
"'ext'",
",",
"'arb'",
",",
"'chromium'",
",",
"'oes'",
",",
"'amd'",
",",
"'bgra8888'",
",",
"'egl'",
",",
"'atc'",
",",
"'etc1'",
",",
"'angle'",
"]",
"parts",
"=",
"extension_flag",
".",
"split",
"(",
"'_'",
")",
"return",
"\"_\"",
".",
"join",
"(",
"[",
"part",
".",
"upper",
"(",
")",
"if",
"part",
"in",
"uppercase_words",
"else",
"part",
"for",
"part",
"in",
"parts",
"]",
")"
] | https://github.com/google-ar/WebARonTango/blob/e86965d2cbc652156b480e0fcf77c716745578cd/chromium/src/gpu/command_buffer/build_gles2_cmd_buffer.py#L4632-L4641 | |
Yelp/MOE | 5b5a6a2c6c3cf47320126f7f5894e2a83e347f5c | moe/optimal_learning/python/python_version/gaussian_process.py | python | GaussianProcess.compute_grad_variance_of_points | (self, points_to_sample, num_derivatives=-1) | return grad_var | r"""Compute the gradient of the variance (matrix) of this GP at each point of ``Xs`` (``points_to_sample``) wrt ``Xs``.
.. Warning:: ``points_to_sample`` should not contain duplicate points.
This function is similar to compute_grad_cholesky_variance_of_points() (below), except this does not include
gradient terms from the cholesky factorization. Description will not be duplicated here.
.. Note:: Comments are copied from
:mod:`moe.optimal_learning.python.interfaces.gaussian_process_interface.GaussianProcessInterface.compute_grad_variance_of_points`
:param points_to_sample: num_to_sample points (in dim dimensions) being sampled from the GP
:type points_to_sample: array of float64 with shape (num_to_sample, dim)
:param num_derivatives: return derivatives wrt points_to_sample[0:num_derivatives]; large or negative values are clamped
:type num_derivatives: int
:return: grad_var: gradient of the variance matrix of this GP
:rtype: array of float64 with shape (num_derivatives, num_to_sample, num_to_sample, dim) | r"""Compute the gradient of the variance (matrix) of this GP at each point of ``Xs`` (``points_to_sample``) wrt ``Xs``. | [
"r",
"Compute",
"the",
"gradient",
"of",
"the",
"variance",
"(",
"matrix",
")",
"of",
"this",
"GP",
"at",
"each",
"point",
"of",
"Xs",
"(",
"points_to_sample",
")",
"wrt",
"Xs",
"."
] | def compute_grad_variance_of_points(self, points_to_sample, num_derivatives=-1):
r"""Compute the gradient of the variance (matrix) of this GP at each point of ``Xs`` (``points_to_sample``) wrt ``Xs``.
.. Warning:: ``points_to_sample`` should not contain duplicate points.
This function is similar to compute_grad_cholesky_variance_of_points() (below), except this does not include
gradient terms from the cholesky factorization. Description will not be duplicated here.
.. Note:: Comments are copied from
:mod:`moe.optimal_learning.python.interfaces.gaussian_process_interface.GaussianProcessInterface.compute_grad_variance_of_points`
:param points_to_sample: num_to_sample points (in dim dimensions) being sampled from the GP
:type points_to_sample: array of float64 with shape (num_to_sample, dim)
:param num_derivatives: return derivatives wrt points_to_sample[0:num_derivatives]; large or negative values are clamped
:type num_derivatives: int
:return: grad_var: gradient of the variance matrix of this GP
:rtype: array of float64 with shape (num_derivatives, num_to_sample, num_to_sample, dim)
"""
num_derivatives = self._clamp_num_derivatives(points_to_sample.shape[0], num_derivatives)
grad_var = numpy.empty((num_derivatives, points_to_sample.shape[0], points_to_sample.shape[0], self.dim))
for i in xrange(num_derivatives):
grad_var[i, ...] = self._compute_grad_variance_of_points_per_point(points_to_sample, i)
return grad_var | [
"def",
"compute_grad_variance_of_points",
"(",
"self",
",",
"points_to_sample",
",",
"num_derivatives",
"=",
"-",
"1",
")",
":",
"num_derivatives",
"=",
"self",
".",
"_clamp_num_derivatives",
"(",
"points_to_sample",
".",
"shape",
"[",
"0",
"]",
",",
"num_derivatives",
")",
"grad_var",
"=",
"numpy",
".",
"empty",
"(",
"(",
"num_derivatives",
",",
"points_to_sample",
".",
"shape",
"[",
"0",
"]",
",",
"points_to_sample",
".",
"shape",
"[",
"0",
"]",
",",
"self",
".",
"dim",
")",
")",
"for",
"i",
"in",
"xrange",
"(",
"num_derivatives",
")",
":",
"grad_var",
"[",
"i",
",",
"...",
"]",
"=",
"self",
".",
"_compute_grad_variance_of_points_per_point",
"(",
"points_to_sample",
",",
"i",
")",
"return",
"grad_var"
] | https://github.com/Yelp/MOE/blob/5b5a6a2c6c3cf47320126f7f5894e2a83e347f5c/moe/optimal_learning/python/python_version/gaussian_process.py#L290-L313 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/_misc.py | python | DataFormat.GetType | (*args, **kwargs) | return _misc_.DataFormat_GetType(*args, **kwargs) | GetType(self) -> int
Returns the platform-specific number identifying the format. | GetType(self) -> int | [
"GetType",
"(",
"self",
")",
"-",
">",
"int"
] | def GetType(*args, **kwargs):
"""
GetType(self) -> int
Returns the platform-specific number identifying the format.
"""
return _misc_.DataFormat_GetType(*args, **kwargs) | [
"def",
"GetType",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_misc_",
".",
"DataFormat_GetType",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_misc.py#L4866-L4872 | |
kamyu104/LeetCode-Solutions | 77605708a927ea3b85aee5a479db733938c7c211 | Python/maximum-ascending-subarray-sum.py | python | Solution.maxAscendingSum | (self, nums) | return result | :type nums: List[int]
:rtype: int | :type nums: List[int]
:rtype: int | [
":",
"type",
"nums",
":",
"List",
"[",
"int",
"]",
":",
"rtype",
":",
"int"
] | def maxAscendingSum(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
result = curr = 0
for i in xrange(len(nums)):
if not (i and nums[i-1] < nums[i]):
curr = 0
curr += nums[i]
result = max(result, curr)
return result | [
"def",
"maxAscendingSum",
"(",
"self",
",",
"nums",
")",
":",
"result",
"=",
"curr",
"=",
"0",
"for",
"i",
"in",
"xrange",
"(",
"len",
"(",
"nums",
")",
")",
":",
"if",
"not",
"(",
"i",
"and",
"nums",
"[",
"i",
"-",
"1",
"]",
"<",
"nums",
"[",
"i",
"]",
")",
":",
"curr",
"=",
"0",
"curr",
"+=",
"nums",
"[",
"i",
"]",
"result",
"=",
"max",
"(",
"result",
",",
"curr",
")",
"return",
"result"
] | https://github.com/kamyu104/LeetCode-Solutions/blob/77605708a927ea3b85aee5a479db733938c7c211/Python/maximum-ascending-subarray-sum.py#L5-L16 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/difflib.py | python | SequenceMatcher.find_longest_match | (self, alo, ahi, blo, bhi) | return Match(besti, bestj, bestsize) | Find longest matching block in a[alo:ahi] and b[blo:bhi].
If isjunk is not defined:
Return (i,j,k) such that a[i:i+k] is equal to b[j:j+k], where
alo <= i <= i+k <= ahi
blo <= j <= j+k <= bhi
and for all (i',j',k') meeting those conditions,
k >= k'
i <= i'
and if i == i', j <= j'
In other words, of all maximal matching blocks, return one that
starts earliest in a, and of all those maximal matching blocks that
start earliest in a, return the one that starts earliest in b.
>>> s = SequenceMatcher(None, " abcd", "abcd abcd")
>>> s.find_longest_match(0, 5, 0, 9)
Match(a=0, b=4, size=5)
If isjunk is defined, first the longest matching block is
determined as above, but with the additional restriction that no
junk element appears in the block. Then that block is extended as
far as possible by matching (only) junk elements on both sides. So
the resulting block never matches on junk except as identical junk
happens to be adjacent to an "interesting" match.
Here's the same example as before, but considering blanks to be
junk. That prevents " abcd" from matching the " abcd" at the tail
end of the second sequence directly. Instead only the "abcd" can
match, and matches the leftmost "abcd" in the second sequence:
>>> s = SequenceMatcher(lambda x: x==" ", " abcd", "abcd abcd")
>>> s.find_longest_match(0, 5, 0, 9)
Match(a=1, b=0, size=4)
If no blocks match, return (alo, blo, 0).
>>> s = SequenceMatcher(None, "ab", "c")
>>> s.find_longest_match(0, 2, 0, 1)
Match(a=0, b=0, size=0) | Find longest matching block in a[alo:ahi] and b[blo:bhi]. | [
"Find",
"longest",
"matching",
"block",
"in",
"a",
"[",
"alo",
":",
"ahi",
"]",
"and",
"b",
"[",
"blo",
":",
"bhi",
"]",
"."
] | def find_longest_match(self, alo, ahi, blo, bhi):
"""Find longest matching block in a[alo:ahi] and b[blo:bhi].
If isjunk is not defined:
Return (i,j,k) such that a[i:i+k] is equal to b[j:j+k], where
alo <= i <= i+k <= ahi
blo <= j <= j+k <= bhi
and for all (i',j',k') meeting those conditions,
k >= k'
i <= i'
and if i == i', j <= j'
In other words, of all maximal matching blocks, return one that
starts earliest in a, and of all those maximal matching blocks that
start earliest in a, return the one that starts earliest in b.
>>> s = SequenceMatcher(None, " abcd", "abcd abcd")
>>> s.find_longest_match(0, 5, 0, 9)
Match(a=0, b=4, size=5)
If isjunk is defined, first the longest matching block is
determined as above, but with the additional restriction that no
junk element appears in the block. Then that block is extended as
far as possible by matching (only) junk elements on both sides. So
the resulting block never matches on junk except as identical junk
happens to be adjacent to an "interesting" match.
Here's the same example as before, but considering blanks to be
junk. That prevents " abcd" from matching the " abcd" at the tail
end of the second sequence directly. Instead only the "abcd" can
match, and matches the leftmost "abcd" in the second sequence:
>>> s = SequenceMatcher(lambda x: x==" ", " abcd", "abcd abcd")
>>> s.find_longest_match(0, 5, 0, 9)
Match(a=1, b=0, size=4)
If no blocks match, return (alo, blo, 0).
>>> s = SequenceMatcher(None, "ab", "c")
>>> s.find_longest_match(0, 2, 0, 1)
Match(a=0, b=0, size=0)
"""
# CAUTION: stripping common prefix or suffix would be incorrect.
# E.g.,
# ab
# acab
# Longest matching block is "ab", but if common prefix is
# stripped, it's "a" (tied with "b"). UNIX(tm) diff does so
# strip, so ends up claiming that ab is changed to acab by
# inserting "ca" in the middle. That's minimal but unintuitive:
# "it's obvious" that someone inserted "ac" at the front.
# Windiff ends up at the same place as diff, but by pairing up
# the unique 'b's and then matching the first two 'a's.
a, b, b2j, isbjunk = self.a, self.b, self.b2j, self.bjunk.__contains__
besti, bestj, bestsize = alo, blo, 0
# find longest junk-free match
# during an iteration of the loop, j2len[j] = length of longest
# junk-free match ending with a[i-1] and b[j]
j2len = {}
nothing = []
for i in range(alo, ahi):
# look at all instances of a[i] in b; note that because
# b2j has no junk keys, the loop is skipped if a[i] is junk
j2lenget = j2len.get
newj2len = {}
for j in b2j.get(a[i], nothing):
# a[i] matches b[j]
if j < blo:
continue
if j >= bhi:
break
k = newj2len[j] = j2lenget(j-1, 0) + 1
if k > bestsize:
besti, bestj, bestsize = i-k+1, j-k+1, k
j2len = newj2len
# Extend the best by non-junk elements on each end. In particular,
# "popular" non-junk elements aren't in b2j, which greatly speeds
# the inner loop above, but also means "the best" match so far
# doesn't contain any junk *or* popular non-junk elements.
while besti > alo and bestj > blo and \
not isbjunk(b[bestj-1]) and \
a[besti-1] == b[bestj-1]:
besti, bestj, bestsize = besti-1, bestj-1, bestsize+1
while besti+bestsize < ahi and bestj+bestsize < bhi and \
not isbjunk(b[bestj+bestsize]) and \
a[besti+bestsize] == b[bestj+bestsize]:
bestsize += 1
# Now that we have a wholly interesting match (albeit possibly
# empty!), we may as well suck up the matching junk on each
# side of it too. Can't think of a good reason not to, and it
# saves post-processing the (possibly considerable) expense of
# figuring out what to do with it. In the case of an empty
# interesting match, this is clearly the right thing to do,
# because no other kind of match is possible in the regions.
while besti > alo and bestj > blo and \
isbjunk(b[bestj-1]) and \
a[besti-1] == b[bestj-1]:
besti, bestj, bestsize = besti-1, bestj-1, bestsize+1
while besti+bestsize < ahi and bestj+bestsize < bhi and \
isbjunk(b[bestj+bestsize]) and \
a[besti+bestsize] == b[bestj+bestsize]:
bestsize = bestsize + 1
return Match(besti, bestj, bestsize) | [
"def",
"find_longest_match",
"(",
"self",
",",
"alo",
",",
"ahi",
",",
"blo",
",",
"bhi",
")",
":",
"# CAUTION: stripping common prefix or suffix would be incorrect.",
"# E.g.,",
"# ab",
"# acab",
"# Longest matching block is \"ab\", but if common prefix is",
"# stripped, it's \"a\" (tied with \"b\"). UNIX(tm) diff does so",
"# strip, so ends up claiming that ab is changed to acab by",
"# inserting \"ca\" in the middle. That's minimal but unintuitive:",
"# \"it's obvious\" that someone inserted \"ac\" at the front.",
"# Windiff ends up at the same place as diff, but by pairing up",
"# the unique 'b's and then matching the first two 'a's.",
"a",
",",
"b",
",",
"b2j",
",",
"isbjunk",
"=",
"self",
".",
"a",
",",
"self",
".",
"b",
",",
"self",
".",
"b2j",
",",
"self",
".",
"bjunk",
".",
"__contains__",
"besti",
",",
"bestj",
",",
"bestsize",
"=",
"alo",
",",
"blo",
",",
"0",
"# find longest junk-free match",
"# during an iteration of the loop, j2len[j] = length of longest",
"# junk-free match ending with a[i-1] and b[j]",
"j2len",
"=",
"{",
"}",
"nothing",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"alo",
",",
"ahi",
")",
":",
"# look at all instances of a[i] in b; note that because",
"# b2j has no junk keys, the loop is skipped if a[i] is junk",
"j2lenget",
"=",
"j2len",
".",
"get",
"newj2len",
"=",
"{",
"}",
"for",
"j",
"in",
"b2j",
".",
"get",
"(",
"a",
"[",
"i",
"]",
",",
"nothing",
")",
":",
"# a[i] matches b[j]",
"if",
"j",
"<",
"blo",
":",
"continue",
"if",
"j",
">=",
"bhi",
":",
"break",
"k",
"=",
"newj2len",
"[",
"j",
"]",
"=",
"j2lenget",
"(",
"j",
"-",
"1",
",",
"0",
")",
"+",
"1",
"if",
"k",
">",
"bestsize",
":",
"besti",
",",
"bestj",
",",
"bestsize",
"=",
"i",
"-",
"k",
"+",
"1",
",",
"j",
"-",
"k",
"+",
"1",
",",
"k",
"j2len",
"=",
"newj2len",
"# Extend the best by non-junk elements on each end. In particular,",
"# \"popular\" non-junk elements aren't in b2j, which greatly speeds",
"# the inner loop above, but also means \"the best\" match so far",
"# doesn't contain any junk *or* popular non-junk elements.",
"while",
"besti",
">",
"alo",
"and",
"bestj",
">",
"blo",
"and",
"not",
"isbjunk",
"(",
"b",
"[",
"bestj",
"-",
"1",
"]",
")",
"and",
"a",
"[",
"besti",
"-",
"1",
"]",
"==",
"b",
"[",
"bestj",
"-",
"1",
"]",
":",
"besti",
",",
"bestj",
",",
"bestsize",
"=",
"besti",
"-",
"1",
",",
"bestj",
"-",
"1",
",",
"bestsize",
"+",
"1",
"while",
"besti",
"+",
"bestsize",
"<",
"ahi",
"and",
"bestj",
"+",
"bestsize",
"<",
"bhi",
"and",
"not",
"isbjunk",
"(",
"b",
"[",
"bestj",
"+",
"bestsize",
"]",
")",
"and",
"a",
"[",
"besti",
"+",
"bestsize",
"]",
"==",
"b",
"[",
"bestj",
"+",
"bestsize",
"]",
":",
"bestsize",
"+=",
"1",
"# Now that we have a wholly interesting match (albeit possibly",
"# empty!), we may as well suck up the matching junk on each",
"# side of it too. Can't think of a good reason not to, and it",
"# saves post-processing the (possibly considerable) expense of",
"# figuring out what to do with it. In the case of an empty",
"# interesting match, this is clearly the right thing to do,",
"# because no other kind of match is possible in the regions.",
"while",
"besti",
">",
"alo",
"and",
"bestj",
">",
"blo",
"and",
"isbjunk",
"(",
"b",
"[",
"bestj",
"-",
"1",
"]",
")",
"and",
"a",
"[",
"besti",
"-",
"1",
"]",
"==",
"b",
"[",
"bestj",
"-",
"1",
"]",
":",
"besti",
",",
"bestj",
",",
"bestsize",
"=",
"besti",
"-",
"1",
",",
"bestj",
"-",
"1",
",",
"bestsize",
"+",
"1",
"while",
"besti",
"+",
"bestsize",
"<",
"ahi",
"and",
"bestj",
"+",
"bestsize",
"<",
"bhi",
"and",
"isbjunk",
"(",
"b",
"[",
"bestj",
"+",
"bestsize",
"]",
")",
"and",
"a",
"[",
"besti",
"+",
"bestsize",
"]",
"==",
"b",
"[",
"bestj",
"+",
"bestsize",
"]",
":",
"bestsize",
"=",
"bestsize",
"+",
"1",
"return",
"Match",
"(",
"besti",
",",
"bestj",
",",
"bestsize",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/difflib.py#L336-L444 | |
xenia-project/xenia | 9b1fdac98665ac091b9660a5d0fbb259ed79e578 | third_party/google-styleguide/cpplint/cpplint.py | python | CheckForNonConstReference | (filename, clean_lines, linenum,
nesting_state, error) | Check for non-const references.
Separate from CheckLanguage since it scans backwards from current
line, instead of scanning forward.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
nesting_state: A NestingState instance which maintains information about
the current stack of nested blocks being parsed.
error: The function to call with any errors found. | Check for non-const references. | [
"Check",
"for",
"non",
"-",
"const",
"references",
"."
] | def CheckForNonConstReference(filename, clean_lines, linenum,
nesting_state, error):
"""Check for non-const references.
Separate from CheckLanguage since it scans backwards from current
line, instead of scanning forward.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
nesting_state: A NestingState instance which maintains information about
the current stack of nested blocks being parsed.
error: The function to call with any errors found.
"""
# Do nothing if there is no '&' on current line.
line = clean_lines.elided[linenum]
if '&' not in line:
return
# If a function is inherited, current function doesn't have much of
# a choice, so any non-const references should not be blamed on
# derived function.
if IsDerivedFunction(clean_lines, linenum):
return
# Long type names may be broken across multiple lines, usually in one
# of these forms:
# LongType
# ::LongTypeContinued &identifier
# LongType::
# LongTypeContinued &identifier
# LongType<
# ...>::LongTypeContinued &identifier
#
# If we detected a type split across two lines, join the previous
# line to current line so that we can match const references
# accordingly.
#
# Note that this only scans back one line, since scanning back
# arbitrary number of lines would be expensive. If you have a type
# that spans more than 2 lines, please use a typedef.
if linenum > 1:
previous = None
if Match(r'\s*::(?:[\w<>]|::)+\s*&\s*\S', line):
# previous_line\n + ::current_line
previous = Search(r'\b((?:const\s*)?(?:[\w<>]|::)+[\w<>])\s*$',
clean_lines.elided[linenum - 1])
elif Match(r'\s*[a-zA-Z_]([\w<>]|::)+\s*&\s*\S', line):
# previous_line::\n + current_line
previous = Search(r'\b((?:const\s*)?(?:[\w<>]|::)+::)\s*$',
clean_lines.elided[linenum - 1])
if previous:
line = previous.group(1) + line.lstrip()
else:
# Check for templated parameter that is split across multiple lines
endpos = line.rfind('>')
if endpos > -1:
(_, startline, startpos) = ReverseCloseExpression(
clean_lines, linenum, endpos)
if startpos > -1 and startline < linenum:
# Found the matching < on an earlier line, collect all
# pieces up to current line.
line = ''
for i in xrange(startline, linenum + 1):
line += clean_lines.elided[i].strip()
# Check for non-const references in function parameters. A single '&' may
# found in the following places:
# inside expression: binary & for bitwise AND
# inside expression: unary & for taking the address of something
# inside declarators: reference parameter
# We will exclude the first two cases by checking that we are not inside a
# function body, including one that was just introduced by a trailing '{'.
# TODO(unknown): Doesn't account for 'catch(Exception& e)' [rare].
if (nesting_state.previous_stack_top and
not (isinstance(nesting_state.previous_stack_top, _ClassInfo) or
isinstance(nesting_state.previous_stack_top, _NamespaceInfo))):
# Not at toplevel, not within a class, and not within a namespace
return
# Avoid preprocessors
if Search(r'\\\s*$', line):
return
# Avoid constructor initializer lists
if IsInitializerList(clean_lines, linenum):
return
# We allow non-const references in a few standard places, like functions
# called "swap()" or iostream operators like "<<" or ">>". Do not check
# those function parameters.
#
# We also accept & in static_assert, which looks like a function but
# it's actually a declaration expression.
whitelisted_functions = (r'(?:[sS]wap(?:<\w:+>)?|'
r'operator\s*[<>][<>]|'
r'static_assert|COMPILE_ASSERT'
r')\s*\(')
if Search(whitelisted_functions, line):
return
elif not Search(r'\S+\([^)]*$', line):
# Don't see a whitelisted function on this line. Actually we
# didn't see any function name on this line, so this is likely a
# multi-line parameter list. Try a bit harder to catch this case.
for i in xrange(2):
if (linenum > i and
Search(whitelisted_functions, clean_lines.elided[linenum - i - 1])):
return
decls = ReplaceAll(r'{[^}]*}', ' ', line) # exclude function body
for parameter in re.findall(_RE_PATTERN_REF_PARAM, decls):
if not Match(_RE_PATTERN_CONST_REF_PARAM, parameter):
error(filename, linenum, 'runtime/references', 2,
'Is this a non-const reference? '
'If so, make const or use a pointer: ' +
ReplaceAll(' *<', '<', parameter)) | [
"def",
"CheckForNonConstReference",
"(",
"filename",
",",
"clean_lines",
",",
"linenum",
",",
"nesting_state",
",",
"error",
")",
":",
"# Do nothing if there is no '&' on current line.",
"line",
"=",
"clean_lines",
".",
"elided",
"[",
"linenum",
"]",
"if",
"'&'",
"not",
"in",
"line",
":",
"return",
"# If a function is inherited, current function doesn't have much of",
"# a choice, so any non-const references should not be blamed on",
"# derived function.",
"if",
"IsDerivedFunction",
"(",
"clean_lines",
",",
"linenum",
")",
":",
"return",
"# Long type names may be broken across multiple lines, usually in one",
"# of these forms:",
"# LongType",
"# ::LongTypeContinued &identifier",
"# LongType::",
"# LongTypeContinued &identifier",
"# LongType<",
"# ...>::LongTypeContinued &identifier",
"#",
"# If we detected a type split across two lines, join the previous",
"# line to current line so that we can match const references",
"# accordingly.",
"#",
"# Note that this only scans back one line, since scanning back",
"# arbitrary number of lines would be expensive. If you have a type",
"# that spans more than 2 lines, please use a typedef.",
"if",
"linenum",
">",
"1",
":",
"previous",
"=",
"None",
"if",
"Match",
"(",
"r'\\s*::(?:[\\w<>]|::)+\\s*&\\s*\\S'",
",",
"line",
")",
":",
"# previous_line\\n + ::current_line",
"previous",
"=",
"Search",
"(",
"r'\\b((?:const\\s*)?(?:[\\w<>]|::)+[\\w<>])\\s*$'",
",",
"clean_lines",
".",
"elided",
"[",
"linenum",
"-",
"1",
"]",
")",
"elif",
"Match",
"(",
"r'\\s*[a-zA-Z_]([\\w<>]|::)+\\s*&\\s*\\S'",
",",
"line",
")",
":",
"# previous_line::\\n + current_line",
"previous",
"=",
"Search",
"(",
"r'\\b((?:const\\s*)?(?:[\\w<>]|::)+::)\\s*$'",
",",
"clean_lines",
".",
"elided",
"[",
"linenum",
"-",
"1",
"]",
")",
"if",
"previous",
":",
"line",
"=",
"previous",
".",
"group",
"(",
"1",
")",
"+",
"line",
".",
"lstrip",
"(",
")",
"else",
":",
"# Check for templated parameter that is split across multiple lines",
"endpos",
"=",
"line",
".",
"rfind",
"(",
"'>'",
")",
"if",
"endpos",
">",
"-",
"1",
":",
"(",
"_",
",",
"startline",
",",
"startpos",
")",
"=",
"ReverseCloseExpression",
"(",
"clean_lines",
",",
"linenum",
",",
"endpos",
")",
"if",
"startpos",
">",
"-",
"1",
"and",
"startline",
"<",
"linenum",
":",
"# Found the matching < on an earlier line, collect all",
"# pieces up to current line.",
"line",
"=",
"''",
"for",
"i",
"in",
"xrange",
"(",
"startline",
",",
"linenum",
"+",
"1",
")",
":",
"line",
"+=",
"clean_lines",
".",
"elided",
"[",
"i",
"]",
".",
"strip",
"(",
")",
"# Check for non-const references in function parameters. A single '&' may",
"# found in the following places:",
"# inside expression: binary & for bitwise AND",
"# inside expression: unary & for taking the address of something",
"# inside declarators: reference parameter",
"# We will exclude the first two cases by checking that we are not inside a",
"# function body, including one that was just introduced by a trailing '{'.",
"# TODO(unknown): Doesn't account for 'catch(Exception& e)' [rare].",
"if",
"(",
"nesting_state",
".",
"previous_stack_top",
"and",
"not",
"(",
"isinstance",
"(",
"nesting_state",
".",
"previous_stack_top",
",",
"_ClassInfo",
")",
"or",
"isinstance",
"(",
"nesting_state",
".",
"previous_stack_top",
",",
"_NamespaceInfo",
")",
")",
")",
":",
"# Not at toplevel, not within a class, and not within a namespace",
"return",
"# Avoid preprocessors",
"if",
"Search",
"(",
"r'\\\\\\s*$'",
",",
"line",
")",
":",
"return",
"# Avoid constructor initializer lists",
"if",
"IsInitializerList",
"(",
"clean_lines",
",",
"linenum",
")",
":",
"return",
"# We allow non-const references in a few standard places, like functions",
"# called \"swap()\" or iostream operators like \"<<\" or \">>\". Do not check",
"# those function parameters.",
"#",
"# We also accept & in static_assert, which looks like a function but",
"# it's actually a declaration expression.",
"whitelisted_functions",
"=",
"(",
"r'(?:[sS]wap(?:<\\w:+>)?|'",
"r'operator\\s*[<>][<>]|'",
"r'static_assert|COMPILE_ASSERT'",
"r')\\s*\\('",
")",
"if",
"Search",
"(",
"whitelisted_functions",
",",
"line",
")",
":",
"return",
"elif",
"not",
"Search",
"(",
"r'\\S+\\([^)]*$'",
",",
"line",
")",
":",
"# Don't see a whitelisted function on this line. Actually we",
"# didn't see any function name on this line, so this is likely a",
"# multi-line parameter list. Try a bit harder to catch this case.",
"for",
"i",
"in",
"xrange",
"(",
"2",
")",
":",
"if",
"(",
"linenum",
">",
"i",
"and",
"Search",
"(",
"whitelisted_functions",
",",
"clean_lines",
".",
"elided",
"[",
"linenum",
"-",
"i",
"-",
"1",
"]",
")",
")",
":",
"return",
"decls",
"=",
"ReplaceAll",
"(",
"r'{[^}]*}'",
",",
"' '",
",",
"line",
")",
"# exclude function body",
"for",
"parameter",
"in",
"re",
".",
"findall",
"(",
"_RE_PATTERN_REF_PARAM",
",",
"decls",
")",
":",
"if",
"not",
"Match",
"(",
"_RE_PATTERN_CONST_REF_PARAM",
",",
"parameter",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'runtime/references'",
",",
"2",
",",
"'Is this a non-const reference? '",
"'If so, make const or use a pointer: '",
"+",
"ReplaceAll",
"(",
"' *<'",
",",
"'<'",
",",
"parameter",
")",
")"
] | https://github.com/xenia-project/xenia/blob/9b1fdac98665ac091b9660a5d0fbb259ed79e578/third_party/google-styleguide/cpplint/cpplint.py#L4663-L4779 | ||
PaddlePaddle/Paddle | 1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c | python/paddle/nn/functional/activation.py | python | softmax_ | (x, axis=-1, dtype=None, name=None) | return _C_ops.softmax_(x, 'axis', axis, 'use_cudnn', use_cudnn) | r"""
Inplace version of ``softmax`` API, the output Tensor will be inplaced with input ``x``.
Please refer to :ref:`api_nn_cn_softmax`. | r"""
Inplace version of ``softmax`` API, the output Tensor will be inplaced with input ``x``.
Please refer to :ref:`api_nn_cn_softmax`. | [
"r",
"Inplace",
"version",
"of",
"softmax",
"API",
"the",
"output",
"Tensor",
"will",
"be",
"inplaced",
"with",
"input",
"x",
".",
"Please",
"refer",
"to",
":",
"ref",
":",
"api_nn_cn_softmax",
"."
] | def softmax_(x, axis=-1, dtype=None, name=None):
r"""
Inplace version of ``softmax`` API, the output Tensor will be inplaced with input ``x``.
Please refer to :ref:`api_nn_cn_softmax`.
"""
if (dtype is not None) and (not isinstance(dtype, core.VarDesc.VarType)):
dtype = convert_np_dtype_to_dtype_(dtype)
use_cudnn = True
return _C_ops.softmax_(x, 'axis', axis, 'use_cudnn', use_cudnn) | [
"def",
"softmax_",
"(",
"x",
",",
"axis",
"=",
"-",
"1",
",",
"dtype",
"=",
"None",
",",
"name",
"=",
"None",
")",
":",
"if",
"(",
"dtype",
"is",
"not",
"None",
")",
"and",
"(",
"not",
"isinstance",
"(",
"dtype",
",",
"core",
".",
"VarDesc",
".",
"VarType",
")",
")",
":",
"dtype",
"=",
"convert_np_dtype_to_dtype_",
"(",
"dtype",
")",
"use_cudnn",
"=",
"True",
"return",
"_C_ops",
".",
"softmax_",
"(",
"x",
",",
"'axis'",
",",
"axis",
",",
"'use_cudnn'",
",",
"use_cudnn",
")"
] | https://github.com/PaddlePaddle/Paddle/blob/1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c/python/paddle/nn/functional/activation.py#L989-L997 | |
natanielruiz/android-yolo | 1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f | jni-build/jni/include/tensorflow/contrib/distributions/python/ops/normal.py | python | Normal.variance | (self, name="variance") | Variance of this distribution. | Variance of this distribution. | [
"Variance",
"of",
"this",
"distribution",
"."
] | def variance(self, name="variance"):
"""Variance of this distribution."""
with ops.name_scope(self.name):
with ops.op_scope([], name):
return math_ops.square(self.std()) | [
"def",
"variance",
"(",
"self",
",",
"name",
"=",
"\"variance\"",
")",
":",
"with",
"ops",
".",
"name_scope",
"(",
"self",
".",
"name",
")",
":",
"with",
"ops",
".",
"op_scope",
"(",
"[",
"]",
",",
"name",
")",
":",
"return",
"math_ops",
".",
"square",
"(",
"self",
".",
"std",
"(",
")",
")"
] | https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/tensorflow/contrib/distributions/python/ops/normal.py#L217-L221 | ||
cms-sw/cmssw | fd9de012d503d3405420bcbeec0ec879baa57cf2 | RecoEgamma/PhotonIdentification/python/Identification/cutBasedPhotonID_tools.py | python | psetPhoFull5x5SigmaIEtaIEtaValueMapCut | (wpEB, wpEE) | return cms.PSet(
cutName = cms.string('PhoFull5x5SigmaIEtaIEtaValueMapCut'),
cutValueEB = cms.double( wpEB.full5x5_sigmaIEtaIEtaCut ),
cutValueEE = cms.double( wpEE.full5x5_sigmaIEtaIEtaCut ),
full5x5SigmaIEtaIEtaMap = cms.InputTag('photonIDValueMapProducer:phoFull5x5SigmaIEtaIEta'),
barrelCutOff = cms.double(ebCutOff),
needsAdditionalProducts = cms.bool(True),
isIgnored = cms.bool(False)
) | Arguments: two containers of working point cut values of the type WorkingPoint_* | Arguments: two containers of working point cut values of the type WorkingPoint_* | [
"Arguments",
":",
"two",
"containers",
"of",
"working",
"point",
"cut",
"values",
"of",
"the",
"type",
"WorkingPoint_",
"*"
] | def psetPhoFull5x5SigmaIEtaIEtaValueMapCut(wpEB, wpEE):
"""
Arguments: two containers of working point cut values of the type WorkingPoint_*
"""
return cms.PSet(
cutName = cms.string('PhoFull5x5SigmaIEtaIEtaValueMapCut'),
cutValueEB = cms.double( wpEB.full5x5_sigmaIEtaIEtaCut ),
cutValueEE = cms.double( wpEE.full5x5_sigmaIEtaIEtaCut ),
full5x5SigmaIEtaIEtaMap = cms.InputTag('photonIDValueMapProducer:phoFull5x5SigmaIEtaIEta'),
barrelCutOff = cms.double(ebCutOff),
needsAdditionalProducts = cms.bool(True),
isIgnored = cms.bool(False)
) | [
"def",
"psetPhoFull5x5SigmaIEtaIEtaValueMapCut",
"(",
"wpEB",
",",
"wpEE",
")",
":",
"return",
"cms",
".",
"PSet",
"(",
"cutName",
"=",
"cms",
".",
"string",
"(",
"'PhoFull5x5SigmaIEtaIEtaValueMapCut'",
")",
",",
"cutValueEB",
"=",
"cms",
".",
"double",
"(",
"wpEB",
".",
"full5x5_sigmaIEtaIEtaCut",
")",
",",
"cutValueEE",
"=",
"cms",
".",
"double",
"(",
"wpEE",
".",
"full5x5_sigmaIEtaIEtaCut",
")",
",",
"full5x5SigmaIEtaIEtaMap",
"=",
"cms",
".",
"InputTag",
"(",
"'photonIDValueMapProducer:phoFull5x5SigmaIEtaIEta'",
")",
",",
"barrelCutOff",
"=",
"cms",
".",
"double",
"(",
"ebCutOff",
")",
",",
"needsAdditionalProducts",
"=",
"cms",
".",
"bool",
"(",
"True",
")",
",",
"isIgnored",
"=",
"cms",
".",
"bool",
"(",
"False",
")",
")"
] | https://github.com/cms-sw/cmssw/blob/fd9de012d503d3405420bcbeec0ec879baa57cf2/RecoEgamma/PhotonIdentification/python/Identification/cutBasedPhotonID_tools.py#L136-L148 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numpy/ma/core.py | python | get_object_signature | (obj) | return sig | Get the signature from obj | Get the signature from obj | [
"Get",
"the",
"signature",
"from",
"obj"
] | def get_object_signature(obj):
"""
Get the signature from obj
"""
try:
sig = formatargspec(*getargspec(obj))
except TypeError:
sig = ''
return sig | [
"def",
"get_object_signature",
"(",
"obj",
")",
":",
"try",
":",
"sig",
"=",
"formatargspec",
"(",
"*",
"getargspec",
"(",
"obj",
")",
")",
"except",
"TypeError",
":",
"sig",
"=",
"''",
"return",
"sig"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numpy/ma/core.py#L145-L154 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/richtext.py | python | RichTextCtrl.GetFullLayoutTime | (*args, **kwargs) | return _richtext.RichTextCtrl_GetFullLayoutTime(*args, **kwargs) | GetFullLayoutTime(self) -> wxLongLong | GetFullLayoutTime(self) -> wxLongLong | [
"GetFullLayoutTime",
"(",
"self",
")",
"-",
">",
"wxLongLong"
] | def GetFullLayoutTime(*args, **kwargs):
"""GetFullLayoutTime(self) -> wxLongLong"""
return _richtext.RichTextCtrl_GetFullLayoutTime(*args, **kwargs) | [
"def",
"GetFullLayoutTime",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_richtext",
".",
"RichTextCtrl_GetFullLayoutTime",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/richtext.py#L2969-L2971 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/PIL/Image.py | python | Image.copy | (self) | return self._new(self.im.copy()) | Copies this image. Use this method if you wish to paste things
into an image, but still retain the original.
:rtype: :py:class:`~PIL.Image.Image`
:returns: An :py:class:`~PIL.Image.Image` object. | Copies this image. Use this method if you wish to paste things
into an image, but still retain the original. | [
"Copies",
"this",
"image",
".",
"Use",
"this",
"method",
"if",
"you",
"wish",
"to",
"paste",
"things",
"into",
"an",
"image",
"but",
"still",
"retain",
"the",
"original",
"."
] | def copy(self):
"""
Copies this image. Use this method if you wish to paste things
into an image, but still retain the original.
:rtype: :py:class:`~PIL.Image.Image`
:returns: An :py:class:`~PIL.Image.Image` object.
"""
self.load()
return self._new(self.im.copy()) | [
"def",
"copy",
"(",
"self",
")",
":",
"self",
".",
"load",
"(",
")",
"return",
"self",
".",
"_new",
"(",
"self",
".",
"im",
".",
"copy",
"(",
")",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/PIL/Image.py#L1104-L1113 | |
ApolloAuto/apollo-platform | 86d9dc6743b496ead18d597748ebabd34a513289 | ros/third_party/lib_x86_64/python2.7/dist-packages/numpy/polynomial/chebyshev.py | python | chebweight | (x) | return w | The weight function of the Chebyshev polynomials.
The weight function is :math:`1/\sqrt{1 - x^2}` and the interval of
integration is :math:`[-1, 1]`. The Chebyshev polynomials are orthogonal, but
not normalized, with respect to this weight function.
Parameters
----------
x : array_like
Values at which the weight function will be computed.
Returns
-------
w : ndarray
The weight function at `x`.
Notes
-----
.. versionadded:: 1.7.0 | The weight function of the Chebyshev polynomials. | [
"The",
"weight",
"function",
"of",
"the",
"Chebyshev",
"polynomials",
"."
] | def chebweight(x):
"""
The weight function of the Chebyshev polynomials.
The weight function is :math:`1/\sqrt{1 - x^2}` and the interval of
integration is :math:`[-1, 1]`. The Chebyshev polynomials are orthogonal, but
not normalized, with respect to this weight function.
Parameters
----------
x : array_like
Values at which the weight function will be computed.
Returns
-------
w : ndarray
The weight function at `x`.
Notes
-----
.. versionadded:: 1.7.0
"""
w = 1./(np.sqrt(1. + x) * np.sqrt(1. - x))
return w | [
"def",
"chebweight",
"(",
"x",
")",
":",
"w",
"=",
"1.",
"/",
"(",
"np",
".",
"sqrt",
"(",
"1.",
"+",
"x",
")",
"*",
"np",
".",
"sqrt",
"(",
"1.",
"-",
"x",
")",
")",
"return",
"w"
] | https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/third_party/lib_x86_64/python2.7/dist-packages/numpy/polynomial/chebyshev.py#L1913-L1938 | |
mindspore-ai/mindspore | fb8fd3338605bb34fa5cea054e535a8b1d753fab | mindspore/python/mindspore/communication/_hccl_management.py | python | create_group | (group, rank_num, rank_ids) | Create group.
A function that creates a collection communication group which includes 'rank_num'
device and 'rank_ids' is the list of these ranks of devices.
Note:
The world group can not be created.
Returns:
None | Create group. | [
"Create",
"group",
"."
] | def create_group(group, rank_num, rank_ids):
"""
Create group.
A function that creates a collection communication group which includes 'rank_num'
device and 'rank_ids' is the list of these ranks of devices.
Note:
The world group can not be created.
Returns:
None
"""
check_group(group)
check_rank_num(rank_num)
if isinstance(rank_ids, (list)):
if rank_num != len(rank_ids):
raise ValueError("The argument 'rank_num' number should be equal to the length "
"of rank_ids, but got 'rank_num' value : {} and 'rank_ids' value : {}."
.format(rank_num, rank_ids))
for rank_id in rank_ids:
if not isinstance(rank_id, (int)) or rank_id < 0:
raise ValueError("The elements of argument 'rank_ids' must be "
"unsigned integer, but got the type : {}".format(type(rank_id)))
c_array_rank_ids = c_array(ctypes.c_uint, rank_ids)
c_rank_num = ctypes.c_uint(rank_num)
c_group = c_str(group)
ret = HCCL_LIB_CTYPES.HcomCreateGroup(c_group, c_rank_num, c_array_rank_ids)
if ret != 0:
raise RuntimeError('Create group error, the error code is ' + str(ret))
else:
raise TypeError("For 'create_group', the argument 'rank_ids' must be type of list, "
"but got 'rank_ids' type : {}.".format(type(rank_ids))) | [
"def",
"create_group",
"(",
"group",
",",
"rank_num",
",",
"rank_ids",
")",
":",
"check_group",
"(",
"group",
")",
"check_rank_num",
"(",
"rank_num",
")",
"if",
"isinstance",
"(",
"rank_ids",
",",
"(",
"list",
")",
")",
":",
"if",
"rank_num",
"!=",
"len",
"(",
"rank_ids",
")",
":",
"raise",
"ValueError",
"(",
"\"The argument 'rank_num' number should be equal to the length \"",
"\"of rank_ids, but got 'rank_num' value : {} and 'rank_ids' value : {}.\"",
".",
"format",
"(",
"rank_num",
",",
"rank_ids",
")",
")",
"for",
"rank_id",
"in",
"rank_ids",
":",
"if",
"not",
"isinstance",
"(",
"rank_id",
",",
"(",
"int",
")",
")",
"or",
"rank_id",
"<",
"0",
":",
"raise",
"ValueError",
"(",
"\"The elements of argument 'rank_ids' must be \"",
"\"unsigned integer, but got the type : {}\"",
".",
"format",
"(",
"type",
"(",
"rank_id",
")",
")",
")",
"c_array_rank_ids",
"=",
"c_array",
"(",
"ctypes",
".",
"c_uint",
",",
"rank_ids",
")",
"c_rank_num",
"=",
"ctypes",
".",
"c_uint",
"(",
"rank_num",
")",
"c_group",
"=",
"c_str",
"(",
"group",
")",
"ret",
"=",
"HCCL_LIB_CTYPES",
".",
"HcomCreateGroup",
"(",
"c_group",
",",
"c_rank_num",
",",
"c_array_rank_ids",
")",
"if",
"ret",
"!=",
"0",
":",
"raise",
"RuntimeError",
"(",
"'Create group error, the error code is '",
"+",
"str",
"(",
"ret",
")",
")",
"else",
":",
"raise",
"TypeError",
"(",
"\"For 'create_group', the argument 'rank_ids' must be type of list, \"",
"\"but got 'rank_ids' type : {}.\"",
".",
"format",
"(",
"type",
"(",
"rank_ids",
")",
")",
")"
] | https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/communication/_hccl_management.py#L102-L134 | ||
eventql/eventql | 7ca0dbb2e683b525620ea30dc40540a22d5eb227 | deps/3rdparty/spidermonkey/mozjs/python/blessings/blessings/__init__.py | python | Location.__exit__ | (self, type, value, tb) | Restore original cursor position. | Restore original cursor position. | [
"Restore",
"original",
"cursor",
"position",
"."
] | def __exit__(self, type, value, tb):
"""Restore original cursor position."""
self.term.stream.write(self.term.restore) | [
"def",
"__exit__",
"(",
"self",
",",
"type",
",",
"value",
",",
"tb",
")",
":",
"self",
".",
"term",
".",
"stream",
".",
"write",
"(",
"self",
".",
"term",
".",
"restore",
")"
] | https://github.com/eventql/eventql/blob/7ca0dbb2e683b525620ea30dc40540a22d5eb227/deps/3rdparty/spidermonkey/mozjs/python/blessings/blessings/__init__.py#L448-L450 | ||
benoitsteiner/tensorflow-opencl | cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5 | tensorflow/contrib/timeseries/python/timeseries/state_space_models/periodic.py | python | CycleStateSpaceModel.transition_power_noise_accumulator | (
self, num_steps, noise_addition_coefficient=1) | return diagonal + lower_band + upper_band | r"""Sum the transitioned covariance matrix over a number of steps.
Assumes that state_transition_noise_covariance is a matrix with a single
non-zero value in the upper left.
Args:
num_steps: A [...] shape integer Tensor with numbers of steps to compute
power sums for.
noise_addition_coefficient: A multiplier for the state transition noise
covariance (used in ResolutionCycleModel to compute multiples of full
period sums).
Returns:
The computed power sum, with shape [..., state dimension, state
dimension] containing:
[\sum_{p=0}^{num_steps - 1} (
state_transition^p
* state_transition_noise_covariance
* (state_transition^p)^T)]_{i, j} = {
-contribution_{j + 1} if j == i - 1
contribution_{j + 1} + contribution{j} if j == i
-contribution_{j} if j == i + 1
0 otherwise
}
contribution_k = noise_scalar
* ((num_steps + self._periodicity - 1 - (k % self._periodicity))
// self._periodicity)
Where contribution_k is the sum of noise_scalar additions to component k
of the periodicity. | r"""Sum the transitioned covariance matrix over a number of steps. | [
"r",
"Sum",
"the",
"transitioned",
"covariance",
"matrix",
"over",
"a",
"number",
"of",
"steps",
"."
] | def transition_power_noise_accumulator(
self, num_steps, noise_addition_coefficient=1):
r"""Sum the transitioned covariance matrix over a number of steps.
Assumes that state_transition_noise_covariance is a matrix with a single
non-zero value in the upper left.
Args:
num_steps: A [...] shape integer Tensor with numbers of steps to compute
power sums for.
noise_addition_coefficient: A multiplier for the state transition noise
covariance (used in ResolutionCycleModel to compute multiples of full
period sums).
Returns:
The computed power sum, with shape [..., state dimension, state
dimension] containing:
[\sum_{p=0}^{num_steps - 1} (
state_transition^p
* state_transition_noise_covariance
* (state_transition^p)^T)]_{i, j} = {
-contribution_{j + 1} if j == i - 1
contribution_{j + 1} + contribution{j} if j == i
-contribution_{j} if j == i + 1
0 otherwise
}
contribution_k = noise_scalar
* ((num_steps + self._periodicity - 1 - (k % self._periodicity))
// self._periodicity)
Where contribution_k is the sum of noise_scalar additions to component k
of the periodicity.
"""
noise_addition_scalar = array_ops.squeeze(
self.state_transition_noise_covariance, axis=[-1, -2])
period_range_reshaped = array_ops.reshape(
math_ops.range(self._periodicity, dtype=num_steps.dtype),
array_ops.concat(
[
array_ops.ones([array_ops.rank(num_steps)], dtype=dtypes.int32),
[self._periodicity]
],
axis=0))
reversed_remaining_steps = ((period_range_reshaped
- (num_steps[..., None] - 1))
% self._periodicity)
period_additions_reversed = (ops.convert_to_tensor(
noise_addition_coefficient,
self.dtype)[..., None] * noise_addition_scalar * math_ops.cast(
(num_steps[..., None] + reversed_remaining_steps) //
self._periodicity,
dtype=self.dtype))
period_additions_diag = array_ops.matrix_diag(period_additions_reversed)
upper_band = array_ops.concat(
[
array_ops.zeros_like(period_additions_diag[..., :-1, 0:1]),
-period_additions_diag[..., :-1, 0:-2]
],
axis=-1)
lower_band = array_ops.concat(
[
array_ops.zeros_like(period_additions_diag[..., 0:1, :-1]),
-period_additions_diag[..., 0:-2, :-1]
],
axis=-2)
period_additions_rotated = array_ops.concat(
[
period_additions_reversed[..., -1:],
period_additions_reversed[..., :-2]
],
axis=-1)
diagonal = array_ops.matrix_diag(period_additions_reversed[..., :-1] +
period_additions_rotated)
return diagonal + lower_band + upper_band | [
"def",
"transition_power_noise_accumulator",
"(",
"self",
",",
"num_steps",
",",
"noise_addition_coefficient",
"=",
"1",
")",
":",
"noise_addition_scalar",
"=",
"array_ops",
".",
"squeeze",
"(",
"self",
".",
"state_transition_noise_covariance",
",",
"axis",
"=",
"[",
"-",
"1",
",",
"-",
"2",
"]",
")",
"period_range_reshaped",
"=",
"array_ops",
".",
"reshape",
"(",
"math_ops",
".",
"range",
"(",
"self",
".",
"_periodicity",
",",
"dtype",
"=",
"num_steps",
".",
"dtype",
")",
",",
"array_ops",
".",
"concat",
"(",
"[",
"array_ops",
".",
"ones",
"(",
"[",
"array_ops",
".",
"rank",
"(",
"num_steps",
")",
"]",
",",
"dtype",
"=",
"dtypes",
".",
"int32",
")",
",",
"[",
"self",
".",
"_periodicity",
"]",
"]",
",",
"axis",
"=",
"0",
")",
")",
"reversed_remaining_steps",
"=",
"(",
"(",
"period_range_reshaped",
"-",
"(",
"num_steps",
"[",
"...",
",",
"None",
"]",
"-",
"1",
")",
")",
"%",
"self",
".",
"_periodicity",
")",
"period_additions_reversed",
"=",
"(",
"ops",
".",
"convert_to_tensor",
"(",
"noise_addition_coefficient",
",",
"self",
".",
"dtype",
")",
"[",
"...",
",",
"None",
"]",
"*",
"noise_addition_scalar",
"*",
"math_ops",
".",
"cast",
"(",
"(",
"num_steps",
"[",
"...",
",",
"None",
"]",
"+",
"reversed_remaining_steps",
")",
"//",
"self",
".",
"_periodicity",
",",
"dtype",
"=",
"self",
".",
"dtype",
")",
")",
"period_additions_diag",
"=",
"array_ops",
".",
"matrix_diag",
"(",
"period_additions_reversed",
")",
"upper_band",
"=",
"array_ops",
".",
"concat",
"(",
"[",
"array_ops",
".",
"zeros_like",
"(",
"period_additions_diag",
"[",
"...",
",",
":",
"-",
"1",
",",
"0",
":",
"1",
"]",
")",
",",
"-",
"period_additions_diag",
"[",
"...",
",",
":",
"-",
"1",
",",
"0",
":",
"-",
"2",
"]",
"]",
",",
"axis",
"=",
"-",
"1",
")",
"lower_band",
"=",
"array_ops",
".",
"concat",
"(",
"[",
"array_ops",
".",
"zeros_like",
"(",
"period_additions_diag",
"[",
"...",
",",
"0",
":",
"1",
",",
":",
"-",
"1",
"]",
")",
",",
"-",
"period_additions_diag",
"[",
"...",
",",
"0",
":",
"-",
"2",
",",
":",
"-",
"1",
"]",
"]",
",",
"axis",
"=",
"-",
"2",
")",
"period_additions_rotated",
"=",
"array_ops",
".",
"concat",
"(",
"[",
"period_additions_reversed",
"[",
"...",
",",
"-",
"1",
":",
"]",
",",
"period_additions_reversed",
"[",
"...",
",",
":",
"-",
"2",
"]",
"]",
",",
"axis",
"=",
"-",
"1",
")",
"diagonal",
"=",
"array_ops",
".",
"matrix_diag",
"(",
"period_additions_reversed",
"[",
"...",
",",
":",
"-",
"1",
"]",
"+",
"period_additions_rotated",
")",
"return",
"diagonal",
"+",
"lower_band",
"+",
"upper_band"
] | https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/contrib/timeseries/python/timeseries/state_space_models/periodic.py#L104-L178 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/tools/Editra/src/extern/aui/framemanager.py | python | AuiFloatingFrame.CopyAttributes | (self, pane) | return contained_pane | Copies all the attributes of the input `pane` into another :class:`AuiPaneInfo`.
:param `pane`: the source :class:`AuiPaneInfo` from where to copy attributes. | Copies all the attributes of the input `pane` into another :class:`AuiPaneInfo`. | [
"Copies",
"all",
"the",
"attributes",
"of",
"the",
"input",
"pane",
"into",
"another",
":",
"class",
":",
"AuiPaneInfo",
"."
] | def CopyAttributes(self, pane):
"""
Copies all the attributes of the input `pane` into another :class:`AuiPaneInfo`.
:param `pane`: the source :class:`AuiPaneInfo` from where to copy attributes.
"""
contained_pane = AuiPaneInfo()
contained_pane.name = pane.name
contained_pane.caption = pane.caption
contained_pane.window = pane.window
contained_pane.frame = pane.frame
contained_pane.state = pane.state
contained_pane.dock_direction = pane.dock_direction
contained_pane.dock_layer = pane.dock_layer
contained_pane.dock_row = pane.dock_row
contained_pane.dock_pos = pane.dock_pos
contained_pane.best_size = wx.Size(*pane.best_size)
contained_pane.min_size = wx.Size(*pane.min_size)
contained_pane.max_size = wx.Size(*pane.max_size)
contained_pane.floating_pos = wx.Point(*pane.floating_pos)
contained_pane.floating_size = wx.Size(*pane.floating_size)
contained_pane.dock_proportion = pane.dock_proportion
contained_pane.buttons = pane.buttons
contained_pane.rect = wx.Rect(*pane.rect)
contained_pane.icon = pane.icon
contained_pane.notebook_id = pane.notebook_id
contained_pane.transparent = pane.transparent
contained_pane.snapped = pane.snapped
contained_pane.minimize_mode = pane.minimize_mode
contained_pane.minimize_target = pane.minimize_target
return contained_pane | [
"def",
"CopyAttributes",
"(",
"self",
",",
"pane",
")",
":",
"contained_pane",
"=",
"AuiPaneInfo",
"(",
")",
"contained_pane",
".",
"name",
"=",
"pane",
".",
"name",
"contained_pane",
".",
"caption",
"=",
"pane",
".",
"caption",
"contained_pane",
".",
"window",
"=",
"pane",
".",
"window",
"contained_pane",
".",
"frame",
"=",
"pane",
".",
"frame",
"contained_pane",
".",
"state",
"=",
"pane",
".",
"state",
"contained_pane",
".",
"dock_direction",
"=",
"pane",
".",
"dock_direction",
"contained_pane",
".",
"dock_layer",
"=",
"pane",
".",
"dock_layer",
"contained_pane",
".",
"dock_row",
"=",
"pane",
".",
"dock_row",
"contained_pane",
".",
"dock_pos",
"=",
"pane",
".",
"dock_pos",
"contained_pane",
".",
"best_size",
"=",
"wx",
".",
"Size",
"(",
"*",
"pane",
".",
"best_size",
")",
"contained_pane",
".",
"min_size",
"=",
"wx",
".",
"Size",
"(",
"*",
"pane",
".",
"min_size",
")",
"contained_pane",
".",
"max_size",
"=",
"wx",
".",
"Size",
"(",
"*",
"pane",
".",
"max_size",
")",
"contained_pane",
".",
"floating_pos",
"=",
"wx",
".",
"Point",
"(",
"*",
"pane",
".",
"floating_pos",
")",
"contained_pane",
".",
"floating_size",
"=",
"wx",
".",
"Size",
"(",
"*",
"pane",
".",
"floating_size",
")",
"contained_pane",
".",
"dock_proportion",
"=",
"pane",
".",
"dock_proportion",
"contained_pane",
".",
"buttons",
"=",
"pane",
".",
"buttons",
"contained_pane",
".",
"rect",
"=",
"wx",
".",
"Rect",
"(",
"*",
"pane",
".",
"rect",
")",
"contained_pane",
".",
"icon",
"=",
"pane",
".",
"icon",
"contained_pane",
".",
"notebook_id",
"=",
"pane",
".",
"notebook_id",
"contained_pane",
".",
"transparent",
"=",
"pane",
".",
"transparent",
"contained_pane",
".",
"snapped",
"=",
"pane",
".",
"snapped",
"contained_pane",
".",
"minimize_mode",
"=",
"pane",
".",
"minimize_mode",
"contained_pane",
".",
"minimize_target",
"=",
"pane",
".",
"minimize_target",
"return",
"contained_pane"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/extern/aui/framemanager.py#L2927-L2960 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/numpy/py2/numpy/core/fromnumeric.py | python | clip | (a, a_min, a_max, out=None) | return _wrapfunc(a, 'clip', a_min, a_max, out=out) | Clip (limit) the values in an array.
Given an interval, values outside the interval are clipped to
the interval edges. For example, if an interval of ``[0, 1]``
is specified, values smaller than 0 become 0, and values larger
than 1 become 1.
Parameters
----------
a : array_like
Array containing elements to clip.
a_min : scalar or array_like or `None`
Minimum value. If `None`, clipping is not performed on lower
interval edge. Not more than one of `a_min` and `a_max` may be
`None`.
a_max : scalar or array_like or `None`
Maximum value. If `None`, clipping is not performed on upper
interval edge. Not more than one of `a_min` and `a_max` may be
`None`. If `a_min` or `a_max` are array_like, then the three
arrays will be broadcasted to match their shapes.
out : ndarray, optional
The results will be placed in this array. It may be the input
array for in-place clipping. `out` must be of the right shape
to hold the output. Its type is preserved.
Returns
-------
clipped_array : ndarray
An array with the elements of `a`, but where values
< `a_min` are replaced with `a_min`, and those > `a_max`
with `a_max`.
See Also
--------
numpy.doc.ufuncs : Section "Output arguments"
Examples
--------
>>> a = np.arange(10)
>>> np.clip(a, 1, 8)
array([1, 1, 2, 3, 4, 5, 6, 7, 8, 8])
>>> a
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> np.clip(a, 3, 6, out=a)
array([3, 3, 3, 3, 4, 5, 6, 6, 6, 6])
>>> a = np.arange(10)
>>> a
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> np.clip(a, [3, 4, 1, 1, 1, 4, 4, 4, 4, 4], 8)
array([3, 4, 2, 3, 4, 5, 6, 7, 8, 8]) | Clip (limit) the values in an array. | [
"Clip",
"(",
"limit",
")",
"the",
"values",
"in",
"an",
"array",
"."
] | def clip(a, a_min, a_max, out=None):
"""
Clip (limit) the values in an array.
Given an interval, values outside the interval are clipped to
the interval edges. For example, if an interval of ``[0, 1]``
is specified, values smaller than 0 become 0, and values larger
than 1 become 1.
Parameters
----------
a : array_like
Array containing elements to clip.
a_min : scalar or array_like or `None`
Minimum value. If `None`, clipping is not performed on lower
interval edge. Not more than one of `a_min` and `a_max` may be
`None`.
a_max : scalar or array_like or `None`
Maximum value. If `None`, clipping is not performed on upper
interval edge. Not more than one of `a_min` and `a_max` may be
`None`. If `a_min` or `a_max` are array_like, then the three
arrays will be broadcasted to match their shapes.
out : ndarray, optional
The results will be placed in this array. It may be the input
array for in-place clipping. `out` must be of the right shape
to hold the output. Its type is preserved.
Returns
-------
clipped_array : ndarray
An array with the elements of `a`, but where values
< `a_min` are replaced with `a_min`, and those > `a_max`
with `a_max`.
See Also
--------
numpy.doc.ufuncs : Section "Output arguments"
Examples
--------
>>> a = np.arange(10)
>>> np.clip(a, 1, 8)
array([1, 1, 2, 3, 4, 5, 6, 7, 8, 8])
>>> a
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> np.clip(a, 3, 6, out=a)
array([3, 3, 3, 3, 4, 5, 6, 6, 6, 6])
>>> a = np.arange(10)
>>> a
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> np.clip(a, [3, 4, 1, 1, 1, 4, 4, 4, 4, 4], 8)
array([3, 4, 2, 3, 4, 5, 6, 7, 8, 8])
"""
return _wrapfunc(a, 'clip', a_min, a_max, out=out) | [
"def",
"clip",
"(",
"a",
",",
"a_min",
",",
"a_max",
",",
"out",
"=",
"None",
")",
":",
"return",
"_wrapfunc",
"(",
"a",
",",
"'clip'",
",",
"a_min",
",",
"a_max",
",",
"out",
"=",
"out",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/numpy/py2/numpy/core/fromnumeric.py#L1904-L1958 | |
ideawu/ssdb-rocks | a3cbb322cafb2f493252829c608e2239df98c9ac | deps/cpy/antlr3/tree.py | python | CommonTreeNodeStream.__str__ | (self) | return ' '.join([str(self.adaptor.getType(node))
for node in self.nodes
]) | Used for testing, just return the token type stream | Used for testing, just return the token type stream | [
"Used",
"for",
"testing",
"just",
"return",
"the",
"token",
"type",
"stream"
] | def __str__(self):
"""Used for testing, just return the token type stream"""
if self.p == -1:
self.fillBuffer()
return ' '.join([str(self.adaptor.getType(node))
for node in self.nodes
]) | [
"def",
"__str__",
"(",
"self",
")",
":",
"if",
"self",
".",
"p",
"==",
"-",
"1",
":",
"self",
".",
"fillBuffer",
"(",
")",
"return",
"' '",
".",
"join",
"(",
"[",
"str",
"(",
"self",
".",
"adaptor",
".",
"getType",
"(",
"node",
")",
")",
"for",
"node",
"in",
"self",
".",
"nodes",
"]",
")"
] | https://github.com/ideawu/ssdb-rocks/blob/a3cbb322cafb2f493252829c608e2239df98c9ac/deps/cpy/antlr3/tree.py#L1952-L1960 | |
junhyukoh/caffe-lstm | 598d45456fa2a1b127a644f4aa38daa8fb9fc722 | scripts/cpp_lint.py | python | _GetTextInside | (text, start_pattern) | return text[start_position:position - 1] | r"""Retrieves all the text between matching open and close parentheses.
Given a string of lines and a regular expression string, retrieve all the text
following the expression and between opening punctuation symbols like
(, [, or {, and the matching close-punctuation symbol. This properly nested
occurrences of the punctuations, so for the text like
printf(a(), b(c()));
a call to _GetTextInside(text, r'printf\(') will return 'a(), b(c())'.
start_pattern must match string having an open punctuation symbol at the end.
Args:
text: The lines to extract text. Its comments and strings must be elided.
It can be single line and can span multiple lines.
start_pattern: The regexp string indicating where to start extracting
the text.
Returns:
The extracted text.
None if either the opening string or ending punctuation could not be found. | r"""Retrieves all the text between matching open and close parentheses. | [
"r",
"Retrieves",
"all",
"the",
"text",
"between",
"matching",
"open",
"and",
"close",
"parentheses",
"."
] | def _GetTextInside(text, start_pattern):
r"""Retrieves all the text between matching open and close parentheses.
Given a string of lines and a regular expression string, retrieve all the text
following the expression and between opening punctuation symbols like
(, [, or {, and the matching close-punctuation symbol. This properly nested
occurrences of the punctuations, so for the text like
printf(a(), b(c()));
a call to _GetTextInside(text, r'printf\(') will return 'a(), b(c())'.
start_pattern must match string having an open punctuation symbol at the end.
Args:
text: The lines to extract text. Its comments and strings must be elided.
It can be single line and can span multiple lines.
start_pattern: The regexp string indicating where to start extracting
the text.
Returns:
The extracted text.
None if either the opening string or ending punctuation could not be found.
"""
# TODO(sugawarayu): Audit cpplint.py to see what places could be profitably
# rewritten to use _GetTextInside (and use inferior regexp matching today).
# Give opening punctuations to get the matching close-punctuations.
matching_punctuation = {'(': ')', '{': '}', '[': ']'}
closing_punctuation = set(matching_punctuation.itervalues())
# Find the position to start extracting text.
match = re.search(start_pattern, text, re.M)
if not match: # start_pattern not found in text.
return None
start_position = match.end(0)
assert start_position > 0, (
'start_pattern must ends with an opening punctuation.')
assert text[start_position - 1] in matching_punctuation, (
'start_pattern must ends with an opening punctuation.')
# Stack of closing punctuations we expect to have in text after position.
punctuation_stack = [matching_punctuation[text[start_position - 1]]]
position = start_position
while punctuation_stack and position < len(text):
if text[position] == punctuation_stack[-1]:
punctuation_stack.pop()
elif text[position] in closing_punctuation:
# A closing punctuation without matching opening punctuations.
return None
elif text[position] in matching_punctuation:
punctuation_stack.append(matching_punctuation[text[position]])
position += 1
if punctuation_stack:
# Opening punctuations left without matching close-punctuations.
return None
# punctuations match.
return text[start_position:position - 1] | [
"def",
"_GetTextInside",
"(",
"text",
",",
"start_pattern",
")",
":",
"# TODO(sugawarayu): Audit cpplint.py to see what places could be profitably",
"# rewritten to use _GetTextInside (and use inferior regexp matching today).",
"# Give opening punctuations to get the matching close-punctuations.",
"matching_punctuation",
"=",
"{",
"'('",
":",
"')'",
",",
"'{'",
":",
"'}'",
",",
"'['",
":",
"']'",
"}",
"closing_punctuation",
"=",
"set",
"(",
"matching_punctuation",
".",
"itervalues",
"(",
")",
")",
"# Find the position to start extracting text.",
"match",
"=",
"re",
".",
"search",
"(",
"start_pattern",
",",
"text",
",",
"re",
".",
"M",
")",
"if",
"not",
"match",
":",
"# start_pattern not found in text.",
"return",
"None",
"start_position",
"=",
"match",
".",
"end",
"(",
"0",
")",
"assert",
"start_position",
">",
"0",
",",
"(",
"'start_pattern must ends with an opening punctuation.'",
")",
"assert",
"text",
"[",
"start_position",
"-",
"1",
"]",
"in",
"matching_punctuation",
",",
"(",
"'start_pattern must ends with an opening punctuation.'",
")",
"# Stack of closing punctuations we expect to have in text after position.",
"punctuation_stack",
"=",
"[",
"matching_punctuation",
"[",
"text",
"[",
"start_position",
"-",
"1",
"]",
"]",
"]",
"position",
"=",
"start_position",
"while",
"punctuation_stack",
"and",
"position",
"<",
"len",
"(",
"text",
")",
":",
"if",
"text",
"[",
"position",
"]",
"==",
"punctuation_stack",
"[",
"-",
"1",
"]",
":",
"punctuation_stack",
".",
"pop",
"(",
")",
"elif",
"text",
"[",
"position",
"]",
"in",
"closing_punctuation",
":",
"# A closing punctuation without matching opening punctuations.",
"return",
"None",
"elif",
"text",
"[",
"position",
"]",
"in",
"matching_punctuation",
":",
"punctuation_stack",
".",
"append",
"(",
"matching_punctuation",
"[",
"text",
"[",
"position",
"]",
"]",
")",
"position",
"+=",
"1",
"if",
"punctuation_stack",
":",
"# Opening punctuations left without matching close-punctuations.",
"return",
"None",
"# punctuations match.",
"return",
"text",
"[",
"start_position",
":",
"position",
"-",
"1",
"]"
] | https://github.com/junhyukoh/caffe-lstm/blob/598d45456fa2a1b127a644f4aa38daa8fb9fc722/scripts/cpp_lint.py#L3752-L3805 | |
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/layers/python/layers/target_column.py | python | _TargetColumn.loss | (self, logits, target, features) | return math_ops.div(
math_ops.reduce_sum(loss_weighted),
math_ops.cast(math_ops.reduce_sum(weight_tensor), dtypes.float32),
name="loss") | Returns loss tensor for this head.
The loss returned is the weighted average.
L = sum_{i} w_{i} * l_{i} / sum_{i} w_{i}
Args:
logits: logits, a float tensor.
target: either a tensor for labels or in multihead case, a dict of string
to target tensor.
features: features dict.
Returns:
Loss tensor. | Returns loss tensor for this head. | [
"Returns",
"loss",
"tensor",
"for",
"this",
"head",
"."
] | def loss(self, logits, target, features):
"""Returns loss tensor for this head.
The loss returned is the weighted average.
L = sum_{i} w_{i} * l_{i} / sum_{i} w_{i}
Args:
logits: logits, a float tensor.
target: either a tensor for labels or in multihead case, a dict of string
to target tensor.
features: features dict.
Returns:
Loss tensor.
"""
target = target[self.name] if isinstance(target, dict) else target
loss_unweighted = self._loss_fn(logits, target)
weight_tensor = self.get_weight_tensor(features)
if weight_tensor is None:
return math_ops.reduce_mean(loss_unweighted, name="loss")
loss_weighted = self._weighted_loss(loss_unweighted, weight_tensor)
return math_ops.div(
math_ops.reduce_sum(loss_weighted),
math_ops.cast(math_ops.reduce_sum(weight_tensor), dtypes.float32),
name="loss") | [
"def",
"loss",
"(",
"self",
",",
"logits",
",",
"target",
",",
"features",
")",
":",
"target",
"=",
"target",
"[",
"self",
".",
"name",
"]",
"if",
"isinstance",
"(",
"target",
",",
"dict",
")",
"else",
"target",
"loss_unweighted",
"=",
"self",
".",
"_loss_fn",
"(",
"logits",
",",
"target",
")",
"weight_tensor",
"=",
"self",
".",
"get_weight_tensor",
"(",
"features",
")",
"if",
"weight_tensor",
"is",
"None",
":",
"return",
"math_ops",
".",
"reduce_mean",
"(",
"loss_unweighted",
",",
"name",
"=",
"\"loss\"",
")",
"loss_weighted",
"=",
"self",
".",
"_weighted_loss",
"(",
"loss_unweighted",
",",
"weight_tensor",
")",
"return",
"math_ops",
".",
"div",
"(",
"math_ops",
".",
"reduce_sum",
"(",
"loss_weighted",
")",
",",
"math_ops",
".",
"cast",
"(",
"math_ops",
".",
"reduce_sum",
"(",
"weight_tensor",
")",
",",
"dtypes",
".",
"float32",
")",
",",
"name",
"=",
"\"loss\"",
")"
] | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/layers/python/layers/target_column.py#L234-L260 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/_controls.py | python | TextAttr.GetBulletFont | (*args, **kwargs) | return _controls_.TextAttr_GetBulletFont(*args, **kwargs) | GetBulletFont(self) -> String | GetBulletFont(self) -> String | [
"GetBulletFont",
"(",
"self",
")",
"-",
">",
"String"
] | def GetBulletFont(*args, **kwargs):
"""GetBulletFont(self) -> String"""
return _controls_.TextAttr_GetBulletFont(*args, **kwargs) | [
"def",
"GetBulletFont",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_controls_",
".",
"TextAttr_GetBulletFont",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_controls.py#L1744-L1746 | |
OSGeo/gdal | 3748fc4ba4fba727492774b2b908a2130c864a83 | swig/python/osgeo/gdal.py | python | Dataset.CreateMaskBand | (self, *args) | return _gdal.Dataset_CreateMaskBand(self, *args) | r"""CreateMaskBand(Dataset self, int nFlags) -> CPLErr | r"""CreateMaskBand(Dataset self, int nFlags) -> CPLErr | [
"r",
"CreateMaskBand",
"(",
"Dataset",
"self",
"int",
"nFlags",
")",
"-",
">",
"CPLErr"
] | def CreateMaskBand(self, *args):
r"""CreateMaskBand(Dataset self, int nFlags) -> CPLErr"""
return _gdal.Dataset_CreateMaskBand(self, *args) | [
"def",
"CreateMaskBand",
"(",
"self",
",",
"*",
"args",
")",
":",
"return",
"_gdal",
".",
"Dataset_CreateMaskBand",
"(",
"self",
",",
"*",
"args",
")"
] | https://github.com/OSGeo/gdal/blob/3748fc4ba4fba727492774b2b908a2130c864a83/swig/python/osgeo/gdal.py#L2209-L2211 | |
nvdla/sw | 79538ba1b52b040a4a4645f630e457fa01839e90 | umd/external/protobuf-2.6/python/google/protobuf/service_reflection.py | python | _ServiceStubBuilder.__init__ | (self, service_descriptor) | Initializes an instance of the service stub class builder.
Args:
service_descriptor: ServiceDescriptor to use when constructing the
stub class. | Initializes an instance of the service stub class builder. | [
"Initializes",
"an",
"instance",
"of",
"the",
"service",
"stub",
"class",
"builder",
"."
] | def __init__(self, service_descriptor):
"""Initializes an instance of the service stub class builder.
Args:
service_descriptor: ServiceDescriptor to use when constructing the
stub class.
"""
self.descriptor = service_descriptor | [
"def",
"__init__",
"(",
"self",
",",
"service_descriptor",
")",
":",
"self",
".",
"descriptor",
"=",
"service_descriptor"
] | https://github.com/nvdla/sw/blob/79538ba1b52b040a4a4645f630e457fa01839e90/umd/external/protobuf-2.6/python/google/protobuf/service_reflection.py#L242-L249 | ||
ceph/ceph | 959663007321a369c83218414a29bd9dbc8bda3a | src/ceph-volume/ceph_volume/devices/lvm/common.py | python | rollback_osd | (args, osd_id=None) | When the process of creating or preparing fails, the OSD needs to be
destroyed so that the ID can be reused. This prevents from leaving the ID
around as "used" on the monitor, which can cause confusion if expecting
sequential OSD IDs.
The usage of `destroy-new` allows this to be done without requiring the
admin keyring (otherwise needed for destroy and purge commands) | When the process of creating or preparing fails, the OSD needs to be
destroyed so that the ID can be reused. This prevents from leaving the ID
around as "used" on the monitor, which can cause confusion if expecting
sequential OSD IDs. | [
"When",
"the",
"process",
"of",
"creating",
"or",
"preparing",
"fails",
"the",
"OSD",
"needs",
"to",
"be",
"destroyed",
"so",
"that",
"the",
"ID",
"can",
"be",
"reused",
".",
"This",
"prevents",
"from",
"leaving",
"the",
"ID",
"around",
"as",
"used",
"on",
"the",
"monitor",
"which",
"can",
"cause",
"confusion",
"if",
"expecting",
"sequential",
"OSD",
"IDs",
"."
] | def rollback_osd(args, osd_id=None):
"""
When the process of creating or preparing fails, the OSD needs to be
destroyed so that the ID can be reused. This prevents from leaving the ID
around as "used" on the monitor, which can cause confusion if expecting
sequential OSD IDs.
The usage of `destroy-new` allows this to be done without requiring the
admin keyring (otherwise needed for destroy and purge commands)
"""
if not osd_id:
# it means that it wasn't generated, so there is nothing to rollback here
return
# once here, this is an error condition that needs to be rolled back
terminal.error('Was unable to complete a new OSD, will rollback changes')
osd_name = 'osd.%s'
bootstrap_keyring = '/var/lib/ceph/bootstrap-osd/%s.keyring' % conf.cluster
cmd = [
'ceph',
'--cluster', conf.cluster,
'--name', 'client.bootstrap-osd',
'--keyring', bootstrap_keyring,
'osd', 'purge-new', osd_name % osd_id,
'--yes-i-really-mean-it',
]
process.run(cmd)
Zap(['--destroy', '--osd-id', osd_id]).main() | [
"def",
"rollback_osd",
"(",
"args",
",",
"osd_id",
"=",
"None",
")",
":",
"if",
"not",
"osd_id",
":",
"# it means that it wasn't generated, so there is nothing to rollback here",
"return",
"# once here, this is an error condition that needs to be rolled back",
"terminal",
".",
"error",
"(",
"'Was unable to complete a new OSD, will rollback changes'",
")",
"osd_name",
"=",
"'osd.%s'",
"bootstrap_keyring",
"=",
"'/var/lib/ceph/bootstrap-osd/%s.keyring'",
"%",
"conf",
".",
"cluster",
"cmd",
"=",
"[",
"'ceph'",
",",
"'--cluster'",
",",
"conf",
".",
"cluster",
",",
"'--name'",
",",
"'client.bootstrap-osd'",
",",
"'--keyring'",
",",
"bootstrap_keyring",
",",
"'osd'",
",",
"'purge-new'",
",",
"osd_name",
"%",
"osd_id",
",",
"'--yes-i-really-mean-it'",
",",
"]",
"process",
".",
"run",
"(",
"cmd",
")",
"Zap",
"(",
"[",
"'--destroy'",
",",
"'--osd-id'",
",",
"osd_id",
"]",
")",
".",
"main",
"(",
")"
] | https://github.com/ceph/ceph/blob/959663007321a369c83218414a29bd9dbc8bda3a/src/ceph-volume/ceph_volume/devices/lvm/common.py#L8-L36 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/site-packages/pip/_vendor/ipaddress.py | python | _BaseNetwork.hosts | (self) | Generate Iterator over usable hosts in a network.
This is like __iter__ except it doesn't return the network
or broadcast addresses. | Generate Iterator over usable hosts in a network. | [
"Generate",
"Iterator",
"over",
"usable",
"hosts",
"in",
"a",
"network",
"."
] | def hosts(self):
"""Generate Iterator over usable hosts in a network.
This is like __iter__ except it doesn't return the network
or broadcast addresses.
"""
network = int(self.network_address)
broadcast = int(self.broadcast_address)
for x in _compat_range(network + 1, broadcast):
yield self._address_class(x) | [
"def",
"hosts",
"(",
"self",
")",
":",
"network",
"=",
"int",
"(",
"self",
".",
"network_address",
")",
"broadcast",
"=",
"int",
"(",
"self",
".",
"broadcast_address",
")",
"for",
"x",
"in",
"_compat_range",
"(",
"network",
"+",
"1",
",",
"broadcast",
")",
":",
"yield",
"self",
".",
"_address_class",
"(",
"x",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/pip/_vendor/ipaddress.py#L740-L750 | ||
gemrb/gemrb | 730206eed8d1dd358ca5e69a62f9e099aa22ffc6 | gemrb/GUIScripts/InventoryCommon.py | python | ConsumeItem | () | return | Drink the potion | Drink the potion | [
"Drink",
"the",
"potion"
] | def ConsumeItem ():
"""Drink the potion"""
pc = GemRB.GameGetSelectedPCSingle ()
slot = GemRB.GetVar ("ItemButton")
# the drink item header is always the first
# pst also requires forcing the target (eg. clot charms), which doesn't hurt elsewhere
GemRB.UseItem (pc, slot, 0, 5)
CloseItemInfoWindow ()
return | [
"def",
"ConsumeItem",
"(",
")",
":",
"pc",
"=",
"GemRB",
".",
"GameGetSelectedPCSingle",
"(",
")",
"slot",
"=",
"GemRB",
".",
"GetVar",
"(",
"\"ItemButton\"",
")",
"# the drink item header is always the first",
"# pst also requires forcing the target (eg. clot charms), which doesn't hurt elsewhere",
"GemRB",
".",
"UseItem",
"(",
"pc",
",",
"slot",
",",
"0",
",",
"5",
")",
"CloseItemInfoWindow",
"(",
")",
"return"
] | https://github.com/gemrb/gemrb/blob/730206eed8d1dd358ca5e69a62f9e099aa22ffc6/gemrb/GUIScripts/InventoryCommon.py#L804-L813 | |
windystrife/UnrealEngine_NVIDIAGameWorks | b50e6338a7c5b26374d66306ebc7807541ff815e | Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/mhlib.py | python | MH.listfolders | (self) | return folders | Return the names of the top-level folders. | Return the names of the top-level folders. | [
"Return",
"the",
"names",
"of",
"the",
"top",
"-",
"level",
"folders",
"."
] | def listfolders(self):
"""Return the names of the top-level folders."""
folders = []
path = self.getpath()
for name in os.listdir(path):
fullname = os.path.join(path, name)
if os.path.isdir(fullname):
folders.append(name)
folders.sort()
return folders | [
"def",
"listfolders",
"(",
"self",
")",
":",
"folders",
"=",
"[",
"]",
"path",
"=",
"self",
".",
"getpath",
"(",
")",
"for",
"name",
"in",
"os",
".",
"listdir",
"(",
"path",
")",
":",
"fullname",
"=",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"name",
")",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"fullname",
")",
":",
"folders",
".",
"append",
"(",
"name",
")",
"folders",
".",
"sort",
"(",
")",
"return",
"folders"
] | https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/mhlib.py#L144-L153 | |
lmb-freiburg/flownet2 | b92e198b56b0e52e1ba0a5a98dc0e39fa5ae70cc | tools/extra/resize_and_crop_images.py | python | OpenCVResizeCrop.resize_and_crop_image | (self, input_file, output_file, output_side_length = 256) | Takes an image name, resize it and crop the center square | Takes an image name, resize it and crop the center square | [
"Takes",
"an",
"image",
"name",
"resize",
"it",
"and",
"crop",
"the",
"center",
"square"
] | def resize_and_crop_image(self, input_file, output_file, output_side_length = 256):
'''Takes an image name, resize it and crop the center square
'''
img = cv2.imread(input_file)
height, width, depth = img.shape
new_height = output_side_length
new_width = output_side_length
if height > width:
new_height = output_side_length * height / width
else:
new_width = output_side_length * width / height
resized_img = cv2.resize(img, (new_width, new_height))
height_offset = (new_height - output_side_length) / 2
width_offset = (new_width - output_side_length) / 2
cropped_img = resized_img[height_offset:height_offset + output_side_length,
width_offset:width_offset + output_side_length]
cv2.imwrite(output_file, cropped_img) | [
"def",
"resize_and_crop_image",
"(",
"self",
",",
"input_file",
",",
"output_file",
",",
"output_side_length",
"=",
"256",
")",
":",
"img",
"=",
"cv2",
".",
"imread",
"(",
"input_file",
")",
"height",
",",
"width",
",",
"depth",
"=",
"img",
".",
"shape",
"new_height",
"=",
"output_side_length",
"new_width",
"=",
"output_side_length",
"if",
"height",
">",
"width",
":",
"new_height",
"=",
"output_side_length",
"*",
"height",
"/",
"width",
"else",
":",
"new_width",
"=",
"output_side_length",
"*",
"width",
"/",
"height",
"resized_img",
"=",
"cv2",
".",
"resize",
"(",
"img",
",",
"(",
"new_width",
",",
"new_height",
")",
")",
"height_offset",
"=",
"(",
"new_height",
"-",
"output_side_length",
")",
"/",
"2",
"width_offset",
"=",
"(",
"new_width",
"-",
"output_side_length",
")",
"/",
"2",
"cropped_img",
"=",
"resized_img",
"[",
"height_offset",
":",
"height_offset",
"+",
"output_side_length",
",",
"width_offset",
":",
"width_offset",
"+",
"output_side_length",
"]",
"cv2",
".",
"imwrite",
"(",
"output_file",
",",
"cropped_img",
")"
] | https://github.com/lmb-freiburg/flownet2/blob/b92e198b56b0e52e1ba0a5a98dc0e39fa5ae70cc/tools/extra/resize_and_crop_images.py#L20-L36 | ||
giuspen/cherrytree | 84712f206478fcf9acf30174009ad28c648c6344 | pygtk2/modules/machines.py | python | StateMachine.apply_object_justification | (self, iter_start, justification, text_buffer) | Apply the Proper Justification to an Image | Apply the Proper Justification to an Image | [
"Apply",
"the",
"Proper",
"Justification",
"to",
"an",
"Image"
] | def apply_object_justification(self, iter_start, justification, text_buffer):
"""Apply the Proper Justification to an Image"""
if justification == None: return
iter_end = iter_start.copy()
iter_end.forward_char()
self.dad.apply_tag(cons.TAG_JUSTIFICATION,
justification,
iter_sel_start=iter_start,
iter_sel_end=iter_end,
text_buffer=text_buffer) | [
"def",
"apply_object_justification",
"(",
"self",
",",
"iter_start",
",",
"justification",
",",
"text_buffer",
")",
":",
"if",
"justification",
"==",
"None",
":",
"return",
"iter_end",
"=",
"iter_start",
".",
"copy",
"(",
")",
"iter_end",
".",
"forward_char",
"(",
")",
"self",
".",
"dad",
".",
"apply_tag",
"(",
"cons",
".",
"TAG_JUSTIFICATION",
",",
"justification",
",",
"iter_sel_start",
"=",
"iter_start",
",",
"iter_sel_end",
"=",
"iter_end",
",",
"text_buffer",
"=",
"text_buffer",
")"
] | https://github.com/giuspen/cherrytree/blob/84712f206478fcf9acf30174009ad28c648c6344/pygtk2/modules/machines.py#L815-L824 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/ftplib.py | python | FTP.pwd | (self) | return parse257(resp) | Return current working directory. | Return current working directory. | [
"Return",
"current",
"working",
"directory",
"."
] | def pwd(self):
'''Return current working directory.'''
resp = self.voidcmd('PWD')
# fix around non-compliant implementations such as IIS shipped
# with Windows server 2003
if not resp.startswith('257'):
return ''
return parse257(resp) | [
"def",
"pwd",
"(",
"self",
")",
":",
"resp",
"=",
"self",
".",
"voidcmd",
"(",
"'PWD'",
")",
"# fix around non-compliant implementations such as IIS shipped",
"# with Windows server 2003",
"if",
"not",
"resp",
".",
"startswith",
"(",
"'257'",
")",
":",
"return",
"''",
"return",
"parse257",
"(",
"resp",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/ftplib.py#L654-L661 | |
LiquidPlayer/LiquidCore | 9405979363f2353ac9a71ad8ab59685dd7f919c9 | deps/boost_1_66_0/tools/build/src/build/property_set.py | python | PropertySet.base | (self) | return result | Returns properties that are neither incidental nor free. | Returns properties that are neither incidental nor free. | [
"Returns",
"properties",
"that",
"are",
"neither",
"incidental",
"nor",
"free",
"."
] | def base (self):
""" Returns properties that are neither incidental nor free.
"""
result = [p for p in self.lazy_properties
if not(p.feature.incidental or p.feature.free)]
result.extend(self.base_)
return result | [
"def",
"base",
"(",
"self",
")",
":",
"result",
"=",
"[",
"p",
"for",
"p",
"in",
"self",
".",
"lazy_properties",
"if",
"not",
"(",
"p",
".",
"feature",
".",
"incidental",
"or",
"p",
".",
"feature",
".",
"free",
")",
"]",
"result",
".",
"extend",
"(",
"self",
".",
"base_",
")",
"return",
"result"
] | https://github.com/LiquidPlayer/LiquidCore/blob/9405979363f2353ac9a71ad8ab59685dd7f919c9/deps/boost_1_66_0/tools/build/src/build/property_set.py#L264-L270 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/site-packages/pip/_internal/exceptions.py | python | HashError.body | (self) | return f' {self._requirement_name()}' | Return a summary of me for display under the heading.
This default implementation simply prints a description of the
triggering requirement.
:param req: The InstallRequirement that provoked this error, with
its link already populated by the resolver's _populate_link(). | Return a summary of me for display under the heading. | [
"Return",
"a",
"summary",
"of",
"me",
"for",
"display",
"under",
"the",
"heading",
"."
] | def body(self):
# type: () -> str
"""Return a summary of me for display under the heading.
This default implementation simply prints a description of the
triggering requirement.
:param req: The InstallRequirement that provoked this error, with
its link already populated by the resolver's _populate_link().
"""
return f' {self._requirement_name()}' | [
"def",
"body",
"(",
"self",
")",
":",
"# type: () -> str",
"return",
"f' {self._requirement_name()}'"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/pip/_internal/exceptions.py#L208-L219 | |
runtimejs/runtime | 0a6e84c30823d35a4548d6634166784260ae7b74 | deps/v8/PRESUBMIT.py | python | _CheckNoProductionCodeUsingTestOnlyFunctions | (input_api, output_api) | Attempts to prevent use of functions intended only for testing in
non-testing code. For now this is just a best-effort implementation
that ignores header files and may have some false positives. A
better implementation would probably need a proper C++ parser. | Attempts to prevent use of functions intended only for testing in
non-testing code. For now this is just a best-effort implementation
that ignores header files and may have some false positives. A
better implementation would probably need a proper C++ parser. | [
"Attempts",
"to",
"prevent",
"use",
"of",
"functions",
"intended",
"only",
"for",
"testing",
"in",
"non",
"-",
"testing",
"code",
".",
"For",
"now",
"this",
"is",
"just",
"a",
"best",
"-",
"effort",
"implementation",
"that",
"ignores",
"header",
"files",
"and",
"may",
"have",
"some",
"false",
"positives",
".",
"A",
"better",
"implementation",
"would",
"probably",
"need",
"a",
"proper",
"C",
"++",
"parser",
"."
] | def _CheckNoProductionCodeUsingTestOnlyFunctions(input_api, output_api):
"""Attempts to prevent use of functions intended only for testing in
non-testing code. For now this is just a best-effort implementation
that ignores header files and may have some false positives. A
better implementation would probably need a proper C++ parser.
"""
# We only scan .cc files, as the declaration of for-testing functions in
# header files are hard to distinguish from calls to such functions without a
# proper C++ parser.
file_inclusion_pattern = r'.+\.cc'
base_function_pattern = r'[ :]test::[^\s]+|ForTest(ing)?|for_test(ing)?'
inclusion_pattern = input_api.re.compile(r'(%s)\s*\(' % base_function_pattern)
comment_pattern = input_api.re.compile(r'//.*(%s)' % base_function_pattern)
exclusion_pattern = input_api.re.compile(
r'::[A-Za-z0-9_]+(%s)|(%s)[^;]+\{' % (
base_function_pattern, base_function_pattern))
def FilterFile(affected_file):
black_list = (_EXCLUDED_PATHS +
_TEST_CODE_EXCLUDED_PATHS +
input_api.DEFAULT_BLACK_LIST)
return input_api.FilterSourceFile(
affected_file,
white_list=(file_inclusion_pattern, ),
black_list=black_list)
problems = []
for f in input_api.AffectedSourceFiles(FilterFile):
local_path = f.LocalPath()
for line_number, line in f.ChangedContents():
if (inclusion_pattern.search(line) and
not comment_pattern.search(line) and
not exclusion_pattern.search(line)):
problems.append(
'%s:%d\n %s' % (local_path, line_number, line.strip()))
if problems:
return [output_api.PresubmitPromptOrNotify(_TEST_ONLY_WARNING, problems)]
else:
return [] | [
"def",
"_CheckNoProductionCodeUsingTestOnlyFunctions",
"(",
"input_api",
",",
"output_api",
")",
":",
"# We only scan .cc files, as the declaration of for-testing functions in",
"# header files are hard to distinguish from calls to such functions without a",
"# proper C++ parser.",
"file_inclusion_pattern",
"=",
"r'.+\\.cc'",
"base_function_pattern",
"=",
"r'[ :]test::[^\\s]+|ForTest(ing)?|for_test(ing)?'",
"inclusion_pattern",
"=",
"input_api",
".",
"re",
".",
"compile",
"(",
"r'(%s)\\s*\\('",
"%",
"base_function_pattern",
")",
"comment_pattern",
"=",
"input_api",
".",
"re",
".",
"compile",
"(",
"r'//.*(%s)'",
"%",
"base_function_pattern",
")",
"exclusion_pattern",
"=",
"input_api",
".",
"re",
".",
"compile",
"(",
"r'::[A-Za-z0-9_]+(%s)|(%s)[^;]+\\{'",
"%",
"(",
"base_function_pattern",
",",
"base_function_pattern",
")",
")",
"def",
"FilterFile",
"(",
"affected_file",
")",
":",
"black_list",
"=",
"(",
"_EXCLUDED_PATHS",
"+",
"_TEST_CODE_EXCLUDED_PATHS",
"+",
"input_api",
".",
"DEFAULT_BLACK_LIST",
")",
"return",
"input_api",
".",
"FilterSourceFile",
"(",
"affected_file",
",",
"white_list",
"=",
"(",
"file_inclusion_pattern",
",",
")",
",",
"black_list",
"=",
"black_list",
")",
"problems",
"=",
"[",
"]",
"for",
"f",
"in",
"input_api",
".",
"AffectedSourceFiles",
"(",
"FilterFile",
")",
":",
"local_path",
"=",
"f",
".",
"LocalPath",
"(",
")",
"for",
"line_number",
",",
"line",
"in",
"f",
".",
"ChangedContents",
"(",
")",
":",
"if",
"(",
"inclusion_pattern",
".",
"search",
"(",
"line",
")",
"and",
"not",
"comment_pattern",
".",
"search",
"(",
"line",
")",
"and",
"not",
"exclusion_pattern",
".",
"search",
"(",
"line",
")",
")",
":",
"problems",
".",
"append",
"(",
"'%s:%d\\n %s'",
"%",
"(",
"local_path",
",",
"line_number",
",",
"line",
".",
"strip",
"(",
")",
")",
")",
"if",
"problems",
":",
"return",
"[",
"output_api",
".",
"PresubmitPromptOrNotify",
"(",
"_TEST_ONLY_WARNING",
",",
"problems",
")",
"]",
"else",
":",
"return",
"[",
"]"
] | https://github.com/runtimejs/runtime/blob/0a6e84c30823d35a4548d6634166784260ae7b74/deps/v8/PRESUBMIT.py#L176-L216 | ||
rrwick/Unicycler | 96ffea71e3a78d63ade19d6124946773e65cf129 | unicycler/path_finding.py | python | cull_paths | (graph, paths, sequence, scoring_scheme, expected_scaled_score, cull_score_fraction) | return surviving_paths | Returns a reduced list of paths - the ones which best align to the given sequence. | Returns a reduced list of paths - the ones which best align to the given sequence. | [
"Returns",
"a",
"reduced",
"list",
"of",
"paths",
"-",
"the",
"ones",
"which",
"best",
"align",
"to",
"the",
"given",
"sequence",
"."
] | def cull_paths(graph, paths, sequence, scoring_scheme, expected_scaled_score, cull_score_fraction):
"""
Returns a reduced list of paths - the ones which best align to the given sequence.
"""
# It's possible that all of the working paths share quite a bit in common at their
# start. We can therefore find the common starting sequence and align to that once,
# and then only do separate alignments for the remainder of the paths, saving some time.
common_start = []
smallest_seg_count = min(len(x) for x in paths)
for i in range(smallest_seg_count):
potential_common_seg = paths[0][i]
for path in paths:
if path[i] != potential_common_seg:
break
else:
common_start.append(potential_common_seg)
continue
break
# Align the consensus sequence to the common start of the paths. We exclude the first segment
# (which is the start segment and not part of the consensus) and back up a little bit so our
# different alignments to follow won't start right at a difference. I.e. it's better to begin
# with a bit of common sequence.
common_path_seq = graph.get_path_sequence(common_start[1:])[:-100]
path_align_start = len(common_path_seq)
if common_path_seq:
alignment_result = path_alignment(common_path_seq, sequence, scoring_scheme, True, 1000)
seq_align_start = int(alignment_result.split(',', 6)[5])
else:
seq_align_start = 0
scored_paths = []
shortest_len = min(graph.get_path_length(x[1:]) for x in paths)
seq_after_common_path = sequence[seq_align_start:]
for path in paths:
path_seq_after_common_path = \
graph.get_path_sequence(path[1:])[path_align_start:shortest_len]
alignment_result = path_alignment(path_seq_after_common_path, seq_after_common_path,
scoring_scheme, True, 500)
if alignment_result:
scaled_score = float(alignment_result.split(',', 8)[7])
scored_paths.append((path, scaled_score))
scored_paths = sorted(scored_paths, key=lambda x: x[1], reverse=True)
if not scored_paths:
return []
# If our path finding has taken a wrong turn (i.e. all of the paths are wrong), then we want
# to give up to save time. To check for this we see if the best one falls well below our
# expectation and isn't that much better than the worst one.
best_score = scored_paths[0][1]
worst_score = scored_paths[-1][1]
if best_score < 0.9 * expected_scaled_score and best_score * 0.95 < worst_score:
return []
# Now that each path is scored we keep the ones that are closest in score to the best one.
surviving_paths = list(x for x in scored_paths
if x[1] >= best_score * cull_score_fraction)
# If any of the surviving paths end in the same segment but have different scores, only keep
# the ones with the top score. This is because the segments with a lower score will have the
# same future paths, and so will always be lower. Doing this also helps to ensure that future
# passes through this function will have a larger common start and will therefore go faster.
surviving_paths_by_terminal_seg = {}
for path in surviving_paths:
terminal_seg = path[0][-1]
score = path[1]
if terminal_seg not in surviving_paths_by_terminal_seg: # First
surviving_paths_by_terminal_seg[terminal_seg] = [path]
else: # We've seen this terminal segment already
current_best_score = surviving_paths_by_terminal_seg[terminal_seg][0][1]
if score > current_best_score:
surviving_paths_by_terminal_seg[terminal_seg] = [path] # Replace the list
elif score == current_best_score:
surviving_paths_by_terminal_seg[terminal_seg].append(path) # Add to the list
else: # score < current_best_score
pass
surviving_paths = []
for paths_with_same_terminal_seg in surviving_paths_by_terminal_seg.values():
surviving_paths += [x[0] for x in paths_with_same_terminal_seg]
return surviving_paths | [
"def",
"cull_paths",
"(",
"graph",
",",
"paths",
",",
"sequence",
",",
"scoring_scheme",
",",
"expected_scaled_score",
",",
"cull_score_fraction",
")",
":",
"# It's possible that all of the working paths share quite a bit in common at their",
"# start. We can therefore find the common starting sequence and align to that once,",
"# and then only do separate alignments for the remainder of the paths, saving some time.",
"common_start",
"=",
"[",
"]",
"smallest_seg_count",
"=",
"min",
"(",
"len",
"(",
"x",
")",
"for",
"x",
"in",
"paths",
")",
"for",
"i",
"in",
"range",
"(",
"smallest_seg_count",
")",
":",
"potential_common_seg",
"=",
"paths",
"[",
"0",
"]",
"[",
"i",
"]",
"for",
"path",
"in",
"paths",
":",
"if",
"path",
"[",
"i",
"]",
"!=",
"potential_common_seg",
":",
"break",
"else",
":",
"common_start",
".",
"append",
"(",
"potential_common_seg",
")",
"continue",
"break",
"# Align the consensus sequence to the common start of the paths. We exclude the first segment",
"# (which is the start segment and not part of the consensus) and back up a little bit so our",
"# different alignments to follow won't start right at a difference. I.e. it's better to begin",
"# with a bit of common sequence.",
"common_path_seq",
"=",
"graph",
".",
"get_path_sequence",
"(",
"common_start",
"[",
"1",
":",
"]",
")",
"[",
":",
"-",
"100",
"]",
"path_align_start",
"=",
"len",
"(",
"common_path_seq",
")",
"if",
"common_path_seq",
":",
"alignment_result",
"=",
"path_alignment",
"(",
"common_path_seq",
",",
"sequence",
",",
"scoring_scheme",
",",
"True",
",",
"1000",
")",
"seq_align_start",
"=",
"int",
"(",
"alignment_result",
".",
"split",
"(",
"','",
",",
"6",
")",
"[",
"5",
"]",
")",
"else",
":",
"seq_align_start",
"=",
"0",
"scored_paths",
"=",
"[",
"]",
"shortest_len",
"=",
"min",
"(",
"graph",
".",
"get_path_length",
"(",
"x",
"[",
"1",
":",
"]",
")",
"for",
"x",
"in",
"paths",
")",
"seq_after_common_path",
"=",
"sequence",
"[",
"seq_align_start",
":",
"]",
"for",
"path",
"in",
"paths",
":",
"path_seq_after_common_path",
"=",
"graph",
".",
"get_path_sequence",
"(",
"path",
"[",
"1",
":",
"]",
")",
"[",
"path_align_start",
":",
"shortest_len",
"]",
"alignment_result",
"=",
"path_alignment",
"(",
"path_seq_after_common_path",
",",
"seq_after_common_path",
",",
"scoring_scheme",
",",
"True",
",",
"500",
")",
"if",
"alignment_result",
":",
"scaled_score",
"=",
"float",
"(",
"alignment_result",
".",
"split",
"(",
"','",
",",
"8",
")",
"[",
"7",
"]",
")",
"scored_paths",
".",
"append",
"(",
"(",
"path",
",",
"scaled_score",
")",
")",
"scored_paths",
"=",
"sorted",
"(",
"scored_paths",
",",
"key",
"=",
"lambda",
"x",
":",
"x",
"[",
"1",
"]",
",",
"reverse",
"=",
"True",
")",
"if",
"not",
"scored_paths",
":",
"return",
"[",
"]",
"# If our path finding has taken a wrong turn (i.e. all of the paths are wrong), then we want",
"# to give up to save time. To check for this we see if the best one falls well below our",
"# expectation and isn't that much better than the worst one.",
"best_score",
"=",
"scored_paths",
"[",
"0",
"]",
"[",
"1",
"]",
"worst_score",
"=",
"scored_paths",
"[",
"-",
"1",
"]",
"[",
"1",
"]",
"if",
"best_score",
"<",
"0.9",
"*",
"expected_scaled_score",
"and",
"best_score",
"*",
"0.95",
"<",
"worst_score",
":",
"return",
"[",
"]",
"# Now that each path is scored we keep the ones that are closest in score to the best one.",
"surviving_paths",
"=",
"list",
"(",
"x",
"for",
"x",
"in",
"scored_paths",
"if",
"x",
"[",
"1",
"]",
">=",
"best_score",
"*",
"cull_score_fraction",
")",
"# If any of the surviving paths end in the same segment but have different scores, only keep",
"# the ones with the top score. This is because the segments with a lower score will have the",
"# same future paths, and so will always be lower. Doing this also helps to ensure that future",
"# passes through this function will have a larger common start and will therefore go faster.",
"surviving_paths_by_terminal_seg",
"=",
"{",
"}",
"for",
"path",
"in",
"surviving_paths",
":",
"terminal_seg",
"=",
"path",
"[",
"0",
"]",
"[",
"-",
"1",
"]",
"score",
"=",
"path",
"[",
"1",
"]",
"if",
"terminal_seg",
"not",
"in",
"surviving_paths_by_terminal_seg",
":",
"# First",
"surviving_paths_by_terminal_seg",
"[",
"terminal_seg",
"]",
"=",
"[",
"path",
"]",
"else",
":",
"# We've seen this terminal segment already",
"current_best_score",
"=",
"surviving_paths_by_terminal_seg",
"[",
"terminal_seg",
"]",
"[",
"0",
"]",
"[",
"1",
"]",
"if",
"score",
">",
"current_best_score",
":",
"surviving_paths_by_terminal_seg",
"[",
"terminal_seg",
"]",
"=",
"[",
"path",
"]",
"# Replace the list",
"elif",
"score",
"==",
"current_best_score",
":",
"surviving_paths_by_terminal_seg",
"[",
"terminal_seg",
"]",
".",
"append",
"(",
"path",
")",
"# Add to the list",
"else",
":",
"# score < current_best_score",
"pass",
"surviving_paths",
"=",
"[",
"]",
"for",
"paths_with_same_terminal_seg",
"in",
"surviving_paths_by_terminal_seg",
".",
"values",
"(",
")",
":",
"surviving_paths",
"+=",
"[",
"x",
"[",
"0",
"]",
"for",
"x",
"in",
"paths_with_same_terminal_seg",
"]",
"return",
"surviving_paths"
] | https://github.com/rrwick/Unicycler/blob/96ffea71e3a78d63ade19d6124946773e65cf129/unicycler/path_finding.py#L297-L378 | |
baidu/tera | dbcd28af792d879d961bf9fc7eb60de81b437646 | src/sdk/python/TeraSdk.py | python | RowReader.RowKey | (self) | return copy_string_to_user(value, long(vallen.value)) | Returns:
(string) 当前cell对应的rowkey | Returns:
(string) 当前cell对应的rowkey | [
"Returns",
":",
"(",
"string",
")",
"当前cell对应的rowkey"
] | def RowKey(self):
"""
Returns:
(string) 当前cell对应的rowkey
"""
value = POINTER(c_ubyte)()
vallen = c_uint64()
lib.tera_row_reader_rowkey(self.reader,
byref(value), byref(vallen))
return copy_string_to_user(value, long(vallen.value)) | [
"def",
"RowKey",
"(",
"self",
")",
":",
"value",
"=",
"POINTER",
"(",
"c_ubyte",
")",
"(",
")",
"vallen",
"=",
"c_uint64",
"(",
")",
"lib",
".",
"tera_row_reader_rowkey",
"(",
"self",
".",
"reader",
",",
"byref",
"(",
"value",
")",
",",
"byref",
"(",
"vallen",
")",
")",
"return",
"copy_string_to_user",
"(",
"value",
",",
"long",
"(",
"vallen",
".",
"value",
")",
")"
] | https://github.com/baidu/tera/blob/dbcd28af792d879d961bf9fc7eb60de81b437646/src/sdk/python/TeraSdk.py#L752-L761 | |
llvm/llvm-project | ffa6262cb4e2a335d26416fad39a581b4f98c5f4 | mlir/python/mlir/dialects/_pdl_ops_ext.py | python | RewriteOp.body | (self) | return self.regions[0].blocks[0] | Return the body (block) of the rewrite. | Return the body (block) of the rewrite. | [
"Return",
"the",
"body",
"(",
"block",
")",
"of",
"the",
"rewrite",
"."
] | def body(self):
"""Return the body (block) of the rewrite."""
return self.regions[0].blocks[0] | [
"def",
"body",
"(",
"self",
")",
":",
"return",
"self",
".",
"regions",
"[",
"0",
"]",
".",
"blocks",
"[",
"0",
"]"
] | https://github.com/llvm/llvm-project/blob/ffa6262cb4e2a335d26416fad39a581b4f98c5f4/mlir/python/mlir/dialects/_pdl_ops_ext.py#L255-L257 | |
apache/incubator-mxnet | f03fb23f1d103fec9541b5ae59ee06b1734a51d9 | python/mxnet/onnx/mx2onnx/_op_translations/_op_translations_opset12.py | python | convert_string_to_list | (string_val) | return result_list | Helper function to convert string to list.
Used to convert shape attribute string to list format. | Helper function to convert string to list.
Used to convert shape attribute string to list format. | [
"Helper",
"function",
"to",
"convert",
"string",
"to",
"list",
".",
"Used",
"to",
"convert",
"shape",
"attribute",
"string",
"to",
"list",
"format",
"."
] | def convert_string_to_list(string_val):
"""Helper function to convert string to list.
Used to convert shape attribute string to list format.
"""
result_list = []
list_string = string_val.split(',')
for val in list_string:
val = str(val.strip())
val = val.replace("(", "")
val = val.replace(")", "")
val = val.replace("L", "")
val = val.replace("[", "")
val = val.replace("]", "")
if val == "None":
result_list.append(None)
elif val != "":
result_list.append(int(val))
return result_list | [
"def",
"convert_string_to_list",
"(",
"string_val",
")",
":",
"result_list",
"=",
"[",
"]",
"list_string",
"=",
"string_val",
".",
"split",
"(",
"','",
")",
"for",
"val",
"in",
"list_string",
":",
"val",
"=",
"str",
"(",
"val",
".",
"strip",
"(",
")",
")",
"val",
"=",
"val",
".",
"replace",
"(",
"\"(\"",
",",
"\"\"",
")",
"val",
"=",
"val",
".",
"replace",
"(",
"\")\"",
",",
"\"\"",
")",
"val",
"=",
"val",
".",
"replace",
"(",
"\"L\"",
",",
"\"\"",
")",
"val",
"=",
"val",
".",
"replace",
"(",
"\"[\"",
",",
"\"\"",
")",
"val",
"=",
"val",
".",
"replace",
"(",
"\"]\"",
",",
"\"\"",
")",
"if",
"val",
"==",
"\"None\"",
":",
"result_list",
".",
"append",
"(",
"None",
")",
"elif",
"val",
"!=",
"\"\"",
":",
"result_list",
".",
"append",
"(",
"int",
"(",
"val",
")",
")",
"return",
"result_list"
] | https://github.com/apache/incubator-mxnet/blob/f03fb23f1d103fec9541b5ae59ee06b1734a51d9/python/mxnet/onnx/mx2onnx/_op_translations/_op_translations_opset12.py#L87-L106 | |
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/util/dispatch.py | python | binary_elementwise_apis | () | return tuple(_BINARY_ELEMENTWISE_APIS) | Returns a list of APIs that have been registered as binary elementwise. | Returns a list of APIs that have been registered as binary elementwise. | [
"Returns",
"a",
"list",
"of",
"APIs",
"that",
"have",
"been",
"registered",
"as",
"binary",
"elementwise",
"."
] | def binary_elementwise_apis():
"""Returns a list of APIs that have been registered as binary elementwise."""
return tuple(_BINARY_ELEMENTWISE_APIS) | [
"def",
"binary_elementwise_apis",
"(",
")",
":",
"return",
"tuple",
"(",
"_BINARY_ELEMENTWISE_APIS",
")"
] | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/util/dispatch.py#L872-L874 | |
snap-stanford/snap-python | d53c51b0a26aa7e3e7400b014cdf728948fde80a | setup/snap.py | python | TSOut.PutSep | (self, NextStrLen=0) | return _snap.TSOut_PutSep(self, NextStrLen) | PutSep(TSOut self, int const & NextStrLen=0) -> int
Parameters:
NextStrLen: int const &
PutSep(TSOut self) -> int
Parameters:
self: TSOut * | PutSep(TSOut self, int const & NextStrLen=0) -> int | [
"PutSep",
"(",
"TSOut",
"self",
"int",
"const",
"&",
"NextStrLen",
"=",
"0",
")",
"-",
">",
"int"
] | def PutSep(self, NextStrLen=0):
"""
PutSep(TSOut self, int const & NextStrLen=0) -> int
Parameters:
NextStrLen: int const &
PutSep(TSOut self) -> int
Parameters:
self: TSOut *
"""
return _snap.TSOut_PutSep(self, NextStrLen) | [
"def",
"PutSep",
"(",
"self",
",",
"NextStrLen",
"=",
"0",
")",
":",
"return",
"_snap",
".",
"TSOut_PutSep",
"(",
"self",
",",
"NextStrLen",
")"
] | https://github.com/snap-stanford/snap-python/blob/d53c51b0a26aa7e3e7400b014cdf728948fde80a/setup/snap.py#L2340-L2353 | |
openmm/openmm | cb293447c4fc8b03976dfe11399f107bab70f3d9 | wrappers/python/openmm/app/gromacstopfile.py | python | GromacsTopFile._processCmapType | (self, line) | Process a line in the [ cmaptypes ] category. | Process a line in the [ cmaptypes ] category. | [
"Process",
"a",
"line",
"in",
"the",
"[",
"cmaptypes",
"]",
"category",
"."
] | def _processCmapType(self, line):
"""Process a line in the [ cmaptypes ] category."""
fields = line.split()
if len(fields) < 8 or len(fields) < 8+int(fields[6])*int(fields[7]):
raise ValueError('Too few fields in [ cmaptypes ] line: '+line)
if fields[5] != '1':
raise ValueError('Unsupported function type in [ cmaptypes ] line: '+line)
self._cmapTypes[tuple(fields[:5])] = fields | [
"def",
"_processCmapType",
"(",
"self",
",",
"line",
")",
":",
"fields",
"=",
"line",
".",
"split",
"(",
")",
"if",
"len",
"(",
"fields",
")",
"<",
"8",
"or",
"len",
"(",
"fields",
")",
"<",
"8",
"+",
"int",
"(",
"fields",
"[",
"6",
"]",
")",
"*",
"int",
"(",
"fields",
"[",
"7",
"]",
")",
":",
"raise",
"ValueError",
"(",
"'Too few fields in [ cmaptypes ] line: '",
"+",
"line",
")",
"if",
"fields",
"[",
"5",
"]",
"!=",
"'1'",
":",
"raise",
"ValueError",
"(",
"'Unsupported function type in [ cmaptypes ] line: '",
"+",
"line",
")",
"self",
".",
"_cmapTypes",
"[",
"tuple",
"(",
"fields",
"[",
":",
"5",
"]",
")",
"]",
"=",
"fields"
] | https://github.com/openmm/openmm/blob/cb293447c4fc8b03976dfe11399f107bab70f3d9/wrappers/python/openmm/app/gromacstopfile.py#L448-L455 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/_core.py | python | Sizer.DeleteWindows | (*args, **kwargs) | return _core_.Sizer_DeleteWindows(*args, **kwargs) | DeleteWindows(self)
Destroy all windows managed by the sizer. | DeleteWindows(self) | [
"DeleteWindows",
"(",
"self",
")"
] | def DeleteWindows(*args, **kwargs):
"""
DeleteWindows(self)
Destroy all windows managed by the sizer.
"""
return _core_.Sizer_DeleteWindows(*args, **kwargs) | [
"def",
"DeleteWindows",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_core_",
".",
"Sizer_DeleteWindows",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_core.py#L14939-L14945 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/propgrid.py | python | PGProperty.SetCell | (*args, **kwargs) | return _propgrid.PGProperty_SetCell(*args, **kwargs) | SetCell(self, int column, PGCell cell) | SetCell(self, int column, PGCell cell) | [
"SetCell",
"(",
"self",
"int",
"column",
"PGCell",
"cell",
")"
] | def SetCell(*args, **kwargs):
"""SetCell(self, int column, PGCell cell)"""
return _propgrid.PGProperty_SetCell(*args, **kwargs) | [
"def",
"SetCell",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_propgrid",
".",
"PGProperty_SetCell",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/propgrid.py#L703-L705 | |
hfinkel/llvm-project-cxxjit | 91084ef018240bbb8e24235ff5cd8c355a9c1a1e | lldb/examples/python/gdbremote.py | python | TerminalColors.green | (self, fg=True) | return '' | Set the foreground or background color to green.
The foreground color will be set if "fg" tests True. The background color will be set if "fg" tests False. | Set the foreground or background color to green.
The foreground color will be set if "fg" tests True. The background color will be set if "fg" tests False. | [
"Set",
"the",
"foreground",
"or",
"background",
"color",
"to",
"green",
".",
"The",
"foreground",
"color",
"will",
"be",
"set",
"if",
"fg",
"tests",
"True",
".",
"The",
"background",
"color",
"will",
"be",
"set",
"if",
"fg",
"tests",
"False",
"."
] | def green(self, fg=True):
'''Set the foreground or background color to green.
The foreground color will be set if "fg" tests True. The background color will be set if "fg" tests False.'''
if self.enabled:
if fg:
return "\x1b[32m"
else:
return "\x1b[42m"
return '' | [
"def",
"green",
"(",
"self",
",",
"fg",
"=",
"True",
")",
":",
"if",
"self",
".",
"enabled",
":",
"if",
"fg",
":",
"return",
"\"\\x1b[32m\"",
"else",
":",
"return",
"\"\\x1b[42m\"",
"return",
"''"
] | https://github.com/hfinkel/llvm-project-cxxjit/blob/91084ef018240bbb8e24235ff5cd8c355a9c1a1e/lldb/examples/python/gdbremote.py#L120-L128 | |
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/framework/function.py | python | _from_definition | (fdef, grad_func=None) | return result | Creates a _DefinedFunction initialized from a FunctionDef proto.
Args:
fdef: a FunctionDef
grad_func: a _DefinedFunction or None
Returns:
A _DefinedFunction representing fdef | Creates a _DefinedFunction initialized from a FunctionDef proto. | [
"Creates",
"a",
"_DefinedFunction",
"initialized",
"from",
"a",
"FunctionDef",
"proto",
"."
] | def _from_definition(fdef, grad_func=None):
"""Creates a _DefinedFunction initialized from a FunctionDef proto.
Args:
fdef: a FunctionDef
grad_func: a _DefinedFunction or None
Returns:
A _DefinedFunction representing fdef
"""
# TODO(iga): This method does major surgery on _DefinedFunction.
# Make it a named constructor using @classmethod of _DefinedFunction.
# The Python callable is only needed to create a FunctionDef. Since we have
# the FunctionDef here, we don't need to set _DefinedFunction._func (nor do we
# have access to such a callable here).
func = None
argnames = [arg.name for arg in fdef.signature.input_arg]
input_types = tuple(
dtypes.as_dtype(arg.type) for arg in fdef.signature.input_arg)
func_name = fdef.signature.name
# Note: FunctionDefs do not include python gradient functions, so if the
# original _DefinedFunction included one it will not be reflected here.
python_grad_func = None
out_names = [arg.name for arg in fdef.signature.output_arg]
result = _DefinedFunction(func, argnames, input_types, func_name, grad_func,
python_grad_func, out_names)
# pylint: disable=protected-access
serialized = fdef.SerializeToString()
c_func = c_api.TF_FunctionImportFunctionDef(serialized)
result._c_func = c_api_util.ScopedTFFunction(c_func)
result._extra_inputs = []
result._op_def = fdef.signature
# pylint: enable=protected-access
return result | [
"def",
"_from_definition",
"(",
"fdef",
",",
"grad_func",
"=",
"None",
")",
":",
"# TODO(iga): This method does major surgery on _DefinedFunction.",
"# Make it a named constructor using @classmethod of _DefinedFunction.",
"# The Python callable is only needed to create a FunctionDef. Since we have",
"# the FunctionDef here, we don't need to set _DefinedFunction._func (nor do we",
"# have access to such a callable here).",
"func",
"=",
"None",
"argnames",
"=",
"[",
"arg",
".",
"name",
"for",
"arg",
"in",
"fdef",
".",
"signature",
".",
"input_arg",
"]",
"input_types",
"=",
"tuple",
"(",
"dtypes",
".",
"as_dtype",
"(",
"arg",
".",
"type",
")",
"for",
"arg",
"in",
"fdef",
".",
"signature",
".",
"input_arg",
")",
"func_name",
"=",
"fdef",
".",
"signature",
".",
"name",
"# Note: FunctionDefs do not include python gradient functions, so if the",
"# original _DefinedFunction included one it will not be reflected here.",
"python_grad_func",
"=",
"None",
"out_names",
"=",
"[",
"arg",
".",
"name",
"for",
"arg",
"in",
"fdef",
".",
"signature",
".",
"output_arg",
"]",
"result",
"=",
"_DefinedFunction",
"(",
"func",
",",
"argnames",
",",
"input_types",
",",
"func_name",
",",
"grad_func",
",",
"python_grad_func",
",",
"out_names",
")",
"# pylint: disable=protected-access",
"serialized",
"=",
"fdef",
".",
"SerializeToString",
"(",
")",
"c_func",
"=",
"c_api",
".",
"TF_FunctionImportFunctionDef",
"(",
"serialized",
")",
"result",
".",
"_c_func",
"=",
"c_api_util",
".",
"ScopedTFFunction",
"(",
"c_func",
")",
"result",
".",
"_extra_inputs",
"=",
"[",
"]",
"result",
".",
"_op_def",
"=",
"fdef",
".",
"signature",
"# pylint: enable=protected-access",
"return",
"result"
] | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/framework/function.py#L1073-L1108 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numpy/ma/timer_comparison.py | python | ModuleTester.test_6 | (self) | Tests inplace w/ array | Tests inplace w/ array | [
"Tests",
"inplace",
"w",
"/",
"array"
] | def test_6(self):
"""
Tests inplace w/ array
"""
x = self.arange(10, dtype=float_)
y = self.arange(10)
xm = self.arange(10, dtype=float_)
xm[2] = self.masked
m = xm.mask
a = self.arange(10, dtype=float_)
a[-1] = self.masked
x += a
xm += a
assert self.allequal(x, y+a)
assert self.allequal(xm, y+a)
assert self.allequal(xm.mask, self.mask_or(m, a.mask))
x = self.arange(10, dtype=float_)
xm = self.arange(10, dtype=float_)
xm[2] = self.masked
m = xm.mask
a = self.arange(10, dtype=float_)
a[-1] = self.masked
x -= a
xm -= a
assert self.allequal(x, y-a)
assert self.allequal(xm, y-a)
assert self.allequal(xm.mask, self.mask_or(m, a.mask))
x = self.arange(10, dtype=float_)
xm = self.arange(10, dtype=float_)
xm[2] = self.masked
m = xm.mask
a = self.arange(10, dtype=float_)
a[-1] = self.masked
x *= a
xm *= a
assert self.allequal(x, y*a)
assert self.allequal(xm, y*a)
assert self.allequal(xm.mask, self.mask_or(m, a.mask))
x = self.arange(10, dtype=float_)
xm = self.arange(10, dtype=float_)
xm[2] = self.masked
m = xm.mask
a = self.arange(10, dtype=float_)
a[-1] = self.masked
x /= a
xm /= a | [
"def",
"test_6",
"(",
"self",
")",
":",
"x",
"=",
"self",
".",
"arange",
"(",
"10",
",",
"dtype",
"=",
"float_",
")",
"y",
"=",
"self",
".",
"arange",
"(",
"10",
")",
"xm",
"=",
"self",
".",
"arange",
"(",
"10",
",",
"dtype",
"=",
"float_",
")",
"xm",
"[",
"2",
"]",
"=",
"self",
".",
"masked",
"m",
"=",
"xm",
".",
"mask",
"a",
"=",
"self",
".",
"arange",
"(",
"10",
",",
"dtype",
"=",
"float_",
")",
"a",
"[",
"-",
"1",
"]",
"=",
"self",
".",
"masked",
"x",
"+=",
"a",
"xm",
"+=",
"a",
"assert",
"self",
".",
"allequal",
"(",
"x",
",",
"y",
"+",
"a",
")",
"assert",
"self",
".",
"allequal",
"(",
"xm",
",",
"y",
"+",
"a",
")",
"assert",
"self",
".",
"allequal",
"(",
"xm",
".",
"mask",
",",
"self",
".",
"mask_or",
"(",
"m",
",",
"a",
".",
"mask",
")",
")",
"x",
"=",
"self",
".",
"arange",
"(",
"10",
",",
"dtype",
"=",
"float_",
")",
"xm",
"=",
"self",
".",
"arange",
"(",
"10",
",",
"dtype",
"=",
"float_",
")",
"xm",
"[",
"2",
"]",
"=",
"self",
".",
"masked",
"m",
"=",
"xm",
".",
"mask",
"a",
"=",
"self",
".",
"arange",
"(",
"10",
",",
"dtype",
"=",
"float_",
")",
"a",
"[",
"-",
"1",
"]",
"=",
"self",
".",
"masked",
"x",
"-=",
"a",
"xm",
"-=",
"a",
"assert",
"self",
".",
"allequal",
"(",
"x",
",",
"y",
"-",
"a",
")",
"assert",
"self",
".",
"allequal",
"(",
"xm",
",",
"y",
"-",
"a",
")",
"assert",
"self",
".",
"allequal",
"(",
"xm",
".",
"mask",
",",
"self",
".",
"mask_or",
"(",
"m",
",",
"a",
".",
"mask",
")",
")",
"x",
"=",
"self",
".",
"arange",
"(",
"10",
",",
"dtype",
"=",
"float_",
")",
"xm",
"=",
"self",
".",
"arange",
"(",
"10",
",",
"dtype",
"=",
"float_",
")",
"xm",
"[",
"2",
"]",
"=",
"self",
".",
"masked",
"m",
"=",
"xm",
".",
"mask",
"a",
"=",
"self",
".",
"arange",
"(",
"10",
",",
"dtype",
"=",
"float_",
")",
"a",
"[",
"-",
"1",
"]",
"=",
"self",
".",
"masked",
"x",
"*=",
"a",
"xm",
"*=",
"a",
"assert",
"self",
".",
"allequal",
"(",
"x",
",",
"y",
"*",
"a",
")",
"assert",
"self",
".",
"allequal",
"(",
"xm",
",",
"y",
"*",
"a",
")",
"assert",
"self",
".",
"allequal",
"(",
"xm",
".",
"mask",
",",
"self",
".",
"mask_or",
"(",
"m",
",",
"a",
".",
"mask",
")",
")",
"x",
"=",
"self",
".",
"arange",
"(",
"10",
",",
"dtype",
"=",
"float_",
")",
"xm",
"=",
"self",
".",
"arange",
"(",
"10",
",",
"dtype",
"=",
"float_",
")",
"xm",
"[",
"2",
"]",
"=",
"self",
".",
"masked",
"m",
"=",
"xm",
".",
"mask",
"a",
"=",
"self",
".",
"arange",
"(",
"10",
",",
"dtype",
"=",
"float_",
")",
"a",
"[",
"-",
"1",
"]",
"=",
"self",
".",
"masked",
"x",
"/=",
"a",
"xm",
"/=",
"a"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numpy/ma/timer_comparison.py#L290-L339 | ||
nasa/fprime | 595cf3682d8365943d86c1a6fe7c78f0a116acf0 | Autocoders/Python/src/fprime_ac/generators/writers/AbstractWriter.py | python | AbstractWriter.generateEmptyFile | (self) | return self.__generate_empty_file | Return flag indicating if a file should be created. | Return flag indicating if a file should be created. | [
"Return",
"flag",
"indicating",
"if",
"a",
"file",
"should",
"be",
"created",
"."
] | def generateEmptyFile(self):
"""
Return flag indicating if a file should be created.
"""
return self.__generate_empty_file | [
"def",
"generateEmptyFile",
"(",
"self",
")",
":",
"return",
"self",
".",
"__generate_empty_file"
] | https://github.com/nasa/fprime/blob/595cf3682d8365943d86c1a6fe7c78f0a116acf0/Autocoders/Python/src/fprime_ac/generators/writers/AbstractWriter.py#L52-L56 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/AWSPythonSDK/1.5.8/docutils/parsers/rst/states.py | python | Inliner.parse | (self, text, lineno, memo, parent) | return processed, messages | Return 2 lists: nodes (text and inline elements), and system_messages.
Using `self.patterns.initial`, a pattern which matches start-strings
(emphasis, strong, interpreted, phrase reference, literal,
substitution reference, and inline target) and complete constructs
(simple reference, footnote reference), search for a candidate. When
one is found, check for validity (e.g., not a quoted '*' character).
If valid, search for the corresponding end string if applicable, and
check it for validity. If not found or invalid, generate a warning
and ignore the start-string. Implicit inline markup (e.g. standalone
URIs) is found last. | Return 2 lists: nodes (text and inline elements), and system_messages. | [
"Return",
"2",
"lists",
":",
"nodes",
"(",
"text",
"and",
"inline",
"elements",
")",
"and",
"system_messages",
"."
] | def parse(self, text, lineno, memo, parent):
# Needs to be refactored for nested inline markup.
# Add nested_parse() method?
"""
Return 2 lists: nodes (text and inline elements), and system_messages.
Using `self.patterns.initial`, a pattern which matches start-strings
(emphasis, strong, interpreted, phrase reference, literal,
substitution reference, and inline target) and complete constructs
(simple reference, footnote reference), search for a candidate. When
one is found, check for validity (e.g., not a quoted '*' character).
If valid, search for the corresponding end string if applicable, and
check it for validity. If not found or invalid, generate a warning
and ignore the start-string. Implicit inline markup (e.g. standalone
URIs) is found last.
"""
self.reporter = memo.reporter
self.document = memo.document
self.language = memo.language
self.parent = parent
pattern_search = self.patterns.initial.search
dispatch = self.dispatch
remaining = escape2null(text)
processed = []
unprocessed = []
messages = []
while remaining:
match = pattern_search(remaining)
if match:
groups = match.groupdict()
method = dispatch[groups['start'] or groups['backquote']
or groups['refend'] or groups['fnend']]
before, inlines, remaining, sysmessages = method(self, match,
lineno)
unprocessed.append(before)
messages += sysmessages
if inlines:
processed += self.implicit_inline(''.join(unprocessed),
lineno)
processed += inlines
unprocessed = []
else:
break
remaining = ''.join(unprocessed) + remaining
if remaining:
processed += self.implicit_inline(remaining, lineno)
return processed, messages | [
"def",
"parse",
"(",
"self",
",",
"text",
",",
"lineno",
",",
"memo",
",",
"parent",
")",
":",
"# Needs to be refactored for nested inline markup.",
"# Add nested_parse() method?",
"self",
".",
"reporter",
"=",
"memo",
".",
"reporter",
"self",
".",
"document",
"=",
"memo",
".",
"document",
"self",
".",
"language",
"=",
"memo",
".",
"language",
"self",
".",
"parent",
"=",
"parent",
"pattern_search",
"=",
"self",
".",
"patterns",
".",
"initial",
".",
"search",
"dispatch",
"=",
"self",
".",
"dispatch",
"remaining",
"=",
"escape2null",
"(",
"text",
")",
"processed",
"=",
"[",
"]",
"unprocessed",
"=",
"[",
"]",
"messages",
"=",
"[",
"]",
"while",
"remaining",
":",
"match",
"=",
"pattern_search",
"(",
"remaining",
")",
"if",
"match",
":",
"groups",
"=",
"match",
".",
"groupdict",
"(",
")",
"method",
"=",
"dispatch",
"[",
"groups",
"[",
"'start'",
"]",
"or",
"groups",
"[",
"'backquote'",
"]",
"or",
"groups",
"[",
"'refend'",
"]",
"or",
"groups",
"[",
"'fnend'",
"]",
"]",
"before",
",",
"inlines",
",",
"remaining",
",",
"sysmessages",
"=",
"method",
"(",
"self",
",",
"match",
",",
"lineno",
")",
"unprocessed",
".",
"append",
"(",
"before",
")",
"messages",
"+=",
"sysmessages",
"if",
"inlines",
":",
"processed",
"+=",
"self",
".",
"implicit_inline",
"(",
"''",
".",
"join",
"(",
"unprocessed",
")",
",",
"lineno",
")",
"processed",
"+=",
"inlines",
"unprocessed",
"=",
"[",
"]",
"else",
":",
"break",
"remaining",
"=",
"''",
".",
"join",
"(",
"unprocessed",
")",
"+",
"remaining",
"if",
"remaining",
":",
"processed",
"+=",
"self",
".",
"implicit_inline",
"(",
"remaining",
",",
"lineno",
")",
"return",
"processed",
",",
"messages"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/AWSPythonSDK/1.5.8/docutils/parsers/rst/states.py#L612-L658 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scikit-learn/py2/sklearn/utils/bench.py | python | total_seconds | (delta) | return delta.seconds + delta.microseconds * mu_sec | helper function to emulate function total_seconds,
introduced in python2.7
http://docs.python.org/library/datetime.html\
#datetime.timedelta.total_seconds | helper function to emulate function total_seconds,
introduced in python2.7 | [
"helper",
"function",
"to",
"emulate",
"function",
"total_seconds",
"introduced",
"in",
"python2",
".",
"7"
] | def total_seconds(delta):
"""
helper function to emulate function total_seconds,
introduced in python2.7
http://docs.python.org/library/datetime.html\
#datetime.timedelta.total_seconds
"""
mu_sec = 1e-6 # number of seconds in one microseconds
return delta.seconds + delta.microseconds * mu_sec | [
"def",
"total_seconds",
"(",
"delta",
")",
":",
"mu_sec",
"=",
"1e-6",
"# number of seconds in one microseconds",
"return",
"delta",
".",
"seconds",
"+",
"delta",
".",
"microseconds",
"*",
"mu_sec"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py2/sklearn/utils/bench.py#L6-L17 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/lib/combotreebox.py | python | BaseComboTreeBox.GetTree | (self) | return self._popupFrame.GetTree() | Returns the tree control that is popped up. | Returns the tree control that is popped up. | [
"Returns",
"the",
"tree",
"control",
"that",
"is",
"popped",
"up",
"."
] | def GetTree(self):
"""Returns the tree control that is popped up."""
return self._popupFrame.GetTree() | [
"def",
"GetTree",
"(",
"self",
")",
":",
"return",
"self",
".",
"_popupFrame",
".",
"GetTree",
"(",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/combotreebox.py#L460-L462 | |
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | qt/python/mantidqt/mantidqt/widgets/superplot/presenter.py | python | SuperplotPresenter.on_add_button_clicked | (self) | Triggered when the add button is pressed. This function adds the
workspace to the selection list. | Triggered when the add button is pressed. This function adds the
workspace to the selection list. | [
"Triggered",
"when",
"the",
"add",
"button",
"is",
"pressed",
".",
"This",
"function",
"adds",
"the",
"workspace",
"to",
"the",
"selection",
"list",
"."
] | def on_add_button_clicked(self):
"""
Triggered when the add button is pressed. This function adds the
workspace to the selection list.
"""
selection = self._view.get_selection()
added_workspace = self._view.get_selected_workspace()
self._model.add_workspace(added_workspace)
self._update_list()
self._view.set_selection(selection)
self._update_plot() | [
"def",
"on_add_button_clicked",
"(",
"self",
")",
":",
"selection",
"=",
"self",
".",
"_view",
".",
"get_selection",
"(",
")",
"added_workspace",
"=",
"self",
".",
"_view",
".",
"get_selected_workspace",
"(",
")",
"self",
".",
"_model",
".",
"add_workspace",
"(",
"added_workspace",
")",
"self",
".",
"_update_list",
"(",
")",
"self",
".",
"_view",
".",
"set_selection",
"(",
"selection",
")",
"self",
".",
"_update_plot",
"(",
")"
] | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqt/mantidqt/widgets/superplot/presenter.py#L254-L264 | ||
kevinlin311tw/Caffe-DeepBinaryCode | 9eaa7662be47d49f475ecbeea2bd51be105270d2 | python/caffe/io.py | python | Transformer.set_channel_swap | (self, in_, order) | Set the input channel order for e.g. RGB to BGR conversion
as needed for the reference ImageNet model.
N.B. this assumes the channels are the first dimension AFTER transpose.
Parameters
----------
in_ : which input to assign this channel order
order : the order to take the channels.
(2,1,0) maps RGB to BGR for example. | Set the input channel order for e.g. RGB to BGR conversion
as needed for the reference ImageNet model.
N.B. this assumes the channels are the first dimension AFTER transpose. | [
"Set",
"the",
"input",
"channel",
"order",
"for",
"e",
".",
"g",
".",
"RGB",
"to",
"BGR",
"conversion",
"as",
"needed",
"for",
"the",
"reference",
"ImageNet",
"model",
".",
"N",
".",
"B",
".",
"this",
"assumes",
"the",
"channels",
"are",
"the",
"first",
"dimension",
"AFTER",
"transpose",
"."
] | def set_channel_swap(self, in_, order):
"""
Set the input channel order for e.g. RGB to BGR conversion
as needed for the reference ImageNet model.
N.B. this assumes the channels are the first dimension AFTER transpose.
Parameters
----------
in_ : which input to assign this channel order
order : the order to take the channels.
(2,1,0) maps RGB to BGR for example.
"""
self.__check_input(in_)
if len(order) != self.inputs[in_][1]:
raise Exception('Channel swap needs to have the same number of '
'dimensions as the input channels.')
self.channel_swap[in_] = order | [
"def",
"set_channel_swap",
"(",
"self",
",",
"in_",
",",
"order",
")",
":",
"self",
".",
"__check_input",
"(",
"in_",
")",
"if",
"len",
"(",
"order",
")",
"!=",
"self",
".",
"inputs",
"[",
"in_",
"]",
"[",
"1",
"]",
":",
"raise",
"Exception",
"(",
"'Channel swap needs to have the same number of '",
"'dimensions as the input channels.'",
")",
"self",
".",
"channel_swap",
"[",
"in_",
"]",
"=",
"order"
] | https://github.com/kevinlin311tw/Caffe-DeepBinaryCode/blob/9eaa7662be47d49f475ecbeea2bd51be105270d2/python/caffe/io.py#L199-L215 | ||
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/telemetry/third_party/web-page-replay/third_party/dns/set.py | python | Set.issubset | (self, other) | return True | Is I{self} a subset of I{other}?
@rtype: bool | Is I{self} a subset of I{other}? | [
"Is",
"I",
"{",
"self",
"}",
"a",
"subset",
"of",
"I",
"{",
"other",
"}",
"?"
] | def issubset(self, other):
"""Is I{self} a subset of I{other}?
@rtype: bool
"""
if not isinstance(other, Set):
raise ValueError('other must be a Set instance')
for item in self.items:
if not item in other.items:
return False
return True | [
"def",
"issubset",
"(",
"self",
",",
"other",
")",
":",
"if",
"not",
"isinstance",
"(",
"other",
",",
"Set",
")",
":",
"raise",
"ValueError",
"(",
"'other must be a Set instance'",
")",
"for",
"item",
"in",
"self",
".",
"items",
":",
"if",
"not",
"item",
"in",
"other",
".",
"items",
":",
"return",
"False",
"return",
"True"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/telemetry/third_party/web-page-replay/third_party/dns/set.py#L239-L250 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/httplib.py | python | HTTPConnection.send | (self, data) | Send `data' to the server. | Send `data' to the server. | [
"Send",
"data",
"to",
"the",
"server",
"."
] | def send(self, data):
"""Send `data' to the server."""
if self.sock is None:
if self.auto_open:
self.connect()
else:
raise NotConnected()
if self.debuglevel > 0:
print "send:", repr(data)
blocksize = 8192
if hasattr(data,'read') and not isinstance(data, array):
if self.debuglevel > 0: print "sendIng a read()able"
datablock = data.read(blocksize)
while datablock:
self.sock.sendall(datablock)
datablock = data.read(blocksize)
else:
self.sock.sendall(data) | [
"def",
"send",
"(",
"self",
",",
"data",
")",
":",
"if",
"self",
".",
"sock",
"is",
"None",
":",
"if",
"self",
".",
"auto_open",
":",
"self",
".",
"connect",
"(",
")",
"else",
":",
"raise",
"NotConnected",
"(",
")",
"if",
"self",
".",
"debuglevel",
">",
"0",
":",
"print",
"\"send:\"",
",",
"repr",
"(",
"data",
")",
"blocksize",
"=",
"8192",
"if",
"hasattr",
"(",
"data",
",",
"'read'",
")",
"and",
"not",
"isinstance",
"(",
"data",
",",
"array",
")",
":",
"if",
"self",
".",
"debuglevel",
">",
"0",
":",
"print",
"\"sendIng a read()able\"",
"datablock",
"=",
"data",
".",
"read",
"(",
"blocksize",
")",
"while",
"datablock",
":",
"self",
".",
"sock",
".",
"sendall",
"(",
"datablock",
")",
"datablock",
"=",
"data",
".",
"read",
"(",
"blocksize",
")",
"else",
":",
"self",
".",
"sock",
".",
"sendall",
"(",
"data",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/httplib.py#L787-L805 | ||
apache/incubator-weex | 5c25f0b59f7ac90703c363e7261f60bd06356dbe | weex_core/tools/cpplint.py | python | GetLineWidth | (line) | Determines the width of the line in column positions.
Args:
line: A string, which may be a Unicode string.
Returns:
The width of the line in column positions, accounting for Unicode
combining characters and wide characters. | Determines the width of the line in column positions. | [
"Determines",
"the",
"width",
"of",
"the",
"line",
"in",
"column",
"positions",
"."
] | def GetLineWidth(line):
"""Determines the width of the line in column positions.
Args:
line: A string, which may be a Unicode string.
Returns:
The width of the line in column positions, accounting for Unicode
combining characters and wide characters.
"""
if isinstance(line, unicode):
width = 0
for uc in unicodedata.normalize('NFC', line):
if unicodedata.east_asian_width(uc) in ('W', 'F'):
width += 2
elif not unicodedata.combining(uc):
# Issue 337
# https://mail.python.org/pipermail/python-list/2012-August/628809.html
if (sys.version_info.major, sys.version_info.minor) <= (3, 2):
# https://github.com/python/cpython/blob/2.7/Include/unicodeobject.h#L81
is_wide_build = sysconfig.get_config_var("Py_UNICODE_SIZE") >= 4
# https://github.com/python/cpython/blob/2.7/Objects/unicodeobject.c#L564
is_low_surrogate = 0xDC00 <= ord(uc) <= 0xDFFF
if not is_wide_build and is_low_surrogate:
width -= 1
width += 1
return width
else:
return len(line) | [
"def",
"GetLineWidth",
"(",
"line",
")",
":",
"if",
"isinstance",
"(",
"line",
",",
"unicode",
")",
":",
"width",
"=",
"0",
"for",
"uc",
"in",
"unicodedata",
".",
"normalize",
"(",
"'NFC'",
",",
"line",
")",
":",
"if",
"unicodedata",
".",
"east_asian_width",
"(",
"uc",
")",
"in",
"(",
"'W'",
",",
"'F'",
")",
":",
"width",
"+=",
"2",
"elif",
"not",
"unicodedata",
".",
"combining",
"(",
"uc",
")",
":",
"# Issue 337",
"# https://mail.python.org/pipermail/python-list/2012-August/628809.html",
"if",
"(",
"sys",
".",
"version_info",
".",
"major",
",",
"sys",
".",
"version_info",
".",
"minor",
")",
"<=",
"(",
"3",
",",
"2",
")",
":",
"# https://github.com/python/cpython/blob/2.7/Include/unicodeobject.h#L81",
"is_wide_build",
"=",
"sysconfig",
".",
"get_config_var",
"(",
"\"Py_UNICODE_SIZE\"",
")",
">=",
"4",
"# https://github.com/python/cpython/blob/2.7/Objects/unicodeobject.c#L564",
"is_low_surrogate",
"=",
"0xDC00",
"<=",
"ord",
"(",
"uc",
")",
"<=",
"0xDFFF",
"if",
"not",
"is_wide_build",
"and",
"is_low_surrogate",
":",
"width",
"-=",
"1",
"width",
"+=",
"1",
"return",
"width",
"else",
":",
"return",
"len",
"(",
"line",
")"
] | https://github.com/apache/incubator-weex/blob/5c25f0b59f7ac90703c363e7261f60bd06356dbe/weex_core/tools/cpplint.py#L4279-L4308 | ||
mingchen/protobuf-ios | 0958df34558cd54cb7b6e6ca5c8855bf3d475046 | compiler/python/google/protobuf/internal/encoder.py | python | Encoder.AppendUInt64NoTag | (self, unsigned_value) | Appends an unsigned 64-bit integer to our buffer, varint-encoded. | Appends an unsigned 64-bit integer to our buffer, varint-encoded. | [
"Appends",
"an",
"unsigned",
"64",
"-",
"bit",
"integer",
"to",
"our",
"buffer",
"varint",
"-",
"encoded",
"."
] | def AppendUInt64NoTag(self, unsigned_value):
"""Appends an unsigned 64-bit integer to our buffer, varint-encoded."""
self._stream.AppendVarUInt64(unsigned_value) | [
"def",
"AppendUInt64NoTag",
"(",
"self",
",",
"unsigned_value",
")",
":",
"self",
".",
"_stream",
".",
"AppendVarUInt64",
"(",
"unsigned_value",
")"
] | https://github.com/mingchen/protobuf-ios/blob/0958df34558cd54cb7b6e6ca5c8855bf3d475046/compiler/python/google/protobuf/internal/encoder.py#L76-L78 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/pandas/py2/pandas/tseries/holiday.py | python | next_workday | (dt) | return dt | returns next weekday used for observances | returns next weekday used for observances | [
"returns",
"next",
"weekday",
"used",
"for",
"observances"
] | def next_workday(dt):
"""
returns next weekday used for observances
"""
dt += timedelta(days=1)
while dt.weekday() > 4:
# Mon-Fri are 0-4
dt += timedelta(days=1)
return dt | [
"def",
"next_workday",
"(",
"dt",
")",
":",
"dt",
"+=",
"timedelta",
"(",
"days",
"=",
"1",
")",
"while",
"dt",
".",
"weekday",
"(",
")",
">",
"4",
":",
"# Mon-Fri are 0-4",
"dt",
"+=",
"timedelta",
"(",
"days",
"=",
"1",
")",
"return",
"dt"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py2/pandas/tseries/holiday.py#L87-L95 | |
krishauser/Klampt | 972cc83ea5befac3f653c1ba20f80155768ad519 | Python/python2_version/klampt/vis/glinterface.py | python | GLPluginInterface.add_action | (self,callback,short_name,key,description=None) | Defines a new generic GUI action. The action will be available in a menu in
Qt or as keyboard commands in GLUT. | Defines a new generic GUI action. The action will be available in a menu in
Qt or as keyboard commands in GLUT. | [
"Defines",
"a",
"new",
"generic",
"GUI",
"action",
".",
"The",
"action",
"will",
"be",
"available",
"in",
"a",
"menu",
"in",
"Qt",
"or",
"as",
"keyboard",
"commands",
"in",
"GLUT",
"."
] | def add_action(self,callback,short_name,key,description=None):
"""Defines a new generic GUI action. The action will be available in a menu in
Qt or as keyboard commands in GLUT."""
if not callable(callback):
raise ValueError("Invalid callback given to add_action(callback,short_name,key,description=None)")
self.actions.append((callback,short_name,key,description)) | [
"def",
"add_action",
"(",
"self",
",",
"callback",
",",
"short_name",
",",
"key",
",",
"description",
"=",
"None",
")",
":",
"if",
"not",
"callable",
"(",
"callback",
")",
":",
"raise",
"ValueError",
"(",
"\"Invalid callback given to add_action(callback,short_name,key,description=None)\"",
")",
"self",
".",
"actions",
".",
"append",
"(",
"(",
"callback",
",",
"short_name",
",",
"key",
",",
"description",
")",
")"
] | https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/python2_version/klampt/vis/glinterface.py#L41-L46 | ||
pirobot/rbx2 | 2a6544799fcf062e7b6bd5cf2981b2a84c0c7d2a | rbx2_utils/src/joint_utils.py | python | getServosFromURDF | () | Get servo parameters from URDF. | Get servo parameters from URDF. | [
"Get",
"servo",
"parameters",
"from",
"URDF",
"."
] | def getServosFromURDF():
""" Get servo parameters from URDF. """
try:
description = rospy.get_param("robot_description")
robot = xml.dom.minidom.parseString(description).getElementsByTagName('robot')[0]
joints = {}
# Find all non-fixed joints
for child in robot.childNodes:
if child.nodeType is child.TEXT_NODE:
continue
if child.localName == 'joint':
jtype = child.getAttribute('type')
if jtype == 'fixed':
continue
name = child.getAttribute('name')
if jtype == 'continuous':
minval = -pi
maxval = pi
else:
limit = child.getElementsByTagName('limit')[0]
minval = float(limit.getAttribute('lower'))
maxval = float(limit.getAttribute('upper'))
if minval > 0 or maxval < 0:
zeroval = (maxval + minval)/2
else:
zeroval = 0
joint = {'min':minval, 'max':maxval, 'zero':zeroval, 'value':zeroval }
joints[name] = joint
return joints
except:
rospy.loginfo('No URDF defined, proceeding with defaults')
return dict() | [
"def",
"getServosFromURDF",
"(",
")",
":",
"try",
":",
"description",
"=",
"rospy",
".",
"get_param",
"(",
"\"robot_description\"",
")",
"robot",
"=",
"xml",
".",
"dom",
".",
"minidom",
".",
"parseString",
"(",
"description",
")",
".",
"getElementsByTagName",
"(",
"'robot'",
")",
"[",
"0",
"]",
"joints",
"=",
"{",
"}",
"# Find all non-fixed joints",
"for",
"child",
"in",
"robot",
".",
"childNodes",
":",
"if",
"child",
".",
"nodeType",
"is",
"child",
".",
"TEXT_NODE",
":",
"continue",
"if",
"child",
".",
"localName",
"==",
"'joint'",
":",
"jtype",
"=",
"child",
".",
"getAttribute",
"(",
"'type'",
")",
"if",
"jtype",
"==",
"'fixed'",
":",
"continue",
"name",
"=",
"child",
".",
"getAttribute",
"(",
"'name'",
")",
"if",
"jtype",
"==",
"'continuous'",
":",
"minval",
"=",
"-",
"pi",
"maxval",
"=",
"pi",
"else",
":",
"limit",
"=",
"child",
".",
"getElementsByTagName",
"(",
"'limit'",
")",
"[",
"0",
"]",
"minval",
"=",
"float",
"(",
"limit",
".",
"getAttribute",
"(",
"'lower'",
")",
")",
"maxval",
"=",
"float",
"(",
"limit",
".",
"getAttribute",
"(",
"'upper'",
")",
")",
"if",
"minval",
">",
"0",
"or",
"maxval",
"<",
"0",
":",
"zeroval",
"=",
"(",
"maxval",
"+",
"minval",
")",
"/",
"2",
"else",
":",
"zeroval",
"=",
"0",
"joint",
"=",
"{",
"'min'",
":",
"minval",
",",
"'max'",
":",
"maxval",
",",
"'zero'",
":",
"zeroval",
",",
"'value'",
":",
"zeroval",
"}",
"joints",
"[",
"name",
"]",
"=",
"joint",
"return",
"joints",
"except",
":",
"rospy",
".",
"loginfo",
"(",
"'No URDF defined, proceeding with defaults'",
")",
"return",
"dict",
"(",
")"
] | https://github.com/pirobot/rbx2/blob/2a6544799fcf062e7b6bd5cf2981b2a84c0c7d2a/rbx2_utils/src/joint_utils.py#L35-L68 | ||
apache/qpid-proton | 6bcdfebb55ea3554bc29b1901422532db331a591 | python/proton/_events.py | python | Handler.on_unhandled | (self, method: str, *args) | The callback for handling events which are not handled by
any other handler.
:param method: The name of the intended handler method.
:param args: Arguments for the intended handler method. | The callback for handling events which are not handled by
any other handler. | [
"The",
"callback",
"for",
"handling",
"events",
"which",
"are",
"not",
"handled",
"by",
"any",
"other",
"handler",
"."
] | def on_unhandled(self, method: str, *args) -> None:
"""
The callback for handling events which are not handled by
any other handler.
:param method: The name of the intended handler method.
:param args: Arguments for the intended handler method.
"""
pass | [
"def",
"on_unhandled",
"(",
"self",
",",
"method",
":",
"str",
",",
"*",
"args",
")",
"->",
"None",
":",
"pass"
] | https://github.com/apache/qpid-proton/blob/6bcdfebb55ea3554bc29b1901422532db331a591/python/proton/_events.py#L635-L643 | ||
ptrkrysik/gr-gsm | 2de47e28ce1fb9a518337bfc0add36c8e3cff5eb | docs/doxygen/swig_doc.py | python | combine_descriptions | (obj) | return utoascii('\n\n'.join(description)).strip() | Combines the brief and detailed descriptions of an object together. | Combines the brief and detailed descriptions of an object together. | [
"Combines",
"the",
"brief",
"and",
"detailed",
"descriptions",
"of",
"an",
"object",
"together",
"."
] | def combine_descriptions(obj):
"""
Combines the brief and detailed descriptions of an object together.
"""
description = []
bd = obj.brief_description.strip()
dd = obj.detailed_description.strip()
if bd:
description.append(bd)
if dd:
description.append(dd)
return utoascii('\n\n'.join(description)).strip() | [
"def",
"combine_descriptions",
"(",
"obj",
")",
":",
"description",
"=",
"[",
"]",
"bd",
"=",
"obj",
".",
"brief_description",
".",
"strip",
"(",
")",
"dd",
"=",
"obj",
".",
"detailed_description",
".",
"strip",
"(",
")",
"if",
"bd",
":",
"description",
".",
"append",
"(",
"bd",
")",
"if",
"dd",
":",
"description",
".",
"append",
"(",
"dd",
")",
"return",
"utoascii",
"(",
"'\\n\\n'",
".",
"join",
"(",
"description",
")",
")",
".",
"strip",
"(",
")"
] | https://github.com/ptrkrysik/gr-gsm/blob/2de47e28ce1fb9a518337bfc0add36c8e3cff5eb/docs/doxygen/swig_doc.py#L95-L106 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python3/src/Lib/asyncio/futures.py | python | Future.add_done_callback | (self, fn, *, context=None) | Add a callback to be run when the future becomes done.
The callback is called with a single argument - the future object. If
the future is already done when this is called, the callback is
scheduled with call_soon. | Add a callback to be run when the future becomes done. | [
"Add",
"a",
"callback",
"to",
"be",
"run",
"when",
"the",
"future",
"becomes",
"done",
"."
] | def add_done_callback(self, fn, *, context=None):
"""Add a callback to be run when the future becomes done.
The callback is called with a single argument - the future object. If
the future is already done when this is called, the callback is
scheduled with call_soon.
"""
if self._state != _PENDING:
self._loop.call_soon(fn, self, context=context)
else:
if context is None:
context = contextvars.copy_context()
self._callbacks.append((fn, context)) | [
"def",
"add_done_callback",
"(",
"self",
",",
"fn",
",",
"*",
",",
"context",
"=",
"None",
")",
":",
"if",
"self",
".",
"_state",
"!=",
"_PENDING",
":",
"self",
".",
"_loop",
".",
"call_soon",
"(",
"fn",
",",
"self",
",",
"context",
"=",
"context",
")",
"else",
":",
"if",
"context",
"is",
"None",
":",
"context",
"=",
"contextvars",
".",
"copy_context",
"(",
")",
"self",
".",
"_callbacks",
".",
"append",
"(",
"(",
"fn",
",",
"context",
")",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/asyncio/futures.py#L220-L232 | ||
cocos-creator/engine-native | 984c4c9f5838253313b44ccd429bd8fac4ec8a6a | tools/bindings-generator/clang/cindex.py | python | Type.spelling | (self) | return conf.lib.clang_getTypeSpelling(self) | Retrieve the spelling of this Type. | Retrieve the spelling of this Type. | [
"Retrieve",
"the",
"spelling",
"of",
"this",
"Type",
"."
] | def spelling(self):
"""Retrieve the spelling of this Type."""
return conf.lib.clang_getTypeSpelling(self) | [
"def",
"spelling",
"(",
"self",
")",
":",
"return",
"conf",
".",
"lib",
".",
"clang_getTypeSpelling",
"(",
"self",
")"
] | https://github.com/cocos-creator/engine-native/blob/984c4c9f5838253313b44ccd429bd8fac4ec8a6a/tools/bindings-generator/clang/cindex.py#L2427-L2429 | |
stellar-deprecated/stellard | 67eabb2217bdfa9a6ea317f62338fb6bca458c90 | src/protobuf/python/google/protobuf/descriptor.py | python | DescriptorBase._SetOptions | (self, options, options_class_name) | Sets the descriptor's options
This function is used in generated proto2 files to update descriptor
options. It must not be used outside proto2. | Sets the descriptor's options | [
"Sets",
"the",
"descriptor",
"s",
"options"
] | def _SetOptions(self, options, options_class_name):
"""Sets the descriptor's options
This function is used in generated proto2 files to update descriptor
options. It must not be used outside proto2.
"""
self._options = options
self._options_class_name = options_class_name
# Does this descriptor have non-default options?
self.has_options = options is not None | [
"def",
"_SetOptions",
"(",
"self",
",",
"options",
",",
"options_class_name",
")",
":",
"self",
".",
"_options",
"=",
"options",
"self",
".",
"_options_class_name",
"=",
"options_class_name",
"# Does this descriptor have non-default options?",
"self",
".",
"has_options",
"=",
"options",
"is",
"not",
"None"
] | https://github.com/stellar-deprecated/stellard/blob/67eabb2217bdfa9a6ea317f62338fb6bca458c90/src/protobuf/python/google/protobuf/descriptor.py#L82-L92 | ||
albertz/openlierox | d316c14a8eb57848ef56e9bfa7b23a56f694a51b | tools/DedicatedServerVideo/gdata/health/__init__.py | python | Ccr.GetMedications | (self) | Helper for extracting Medication data from the CCR.
Returns:
A list of ExtensionElements (one for each medication found) or None if
no medications where found in this CCR. | Helper for extracting Medication data from the CCR. | [
"Helper",
"for",
"extracting",
"Medication",
"data",
"from",
"the",
"CCR",
"."
] | def GetMedications(self):
"""Helper for extracting Medication data from the CCR.
Returns:
A list of ExtensionElements (one for each medication found) or None if
no medications where found in this CCR.
"""
try:
body = self.FindExtensions('Body')[0]
return body.FindChildren('Medications')[0].FindChildren('Medication')
except:
return None | [
"def",
"GetMedications",
"(",
"self",
")",
":",
"try",
":",
"body",
"=",
"self",
".",
"FindExtensions",
"(",
"'Body'",
")",
"[",
"0",
"]",
"return",
"body",
".",
"FindChildren",
"(",
"'Medications'",
")",
"[",
"0",
"]",
".",
"FindChildren",
"(",
"'Medication'",
")",
"except",
":",
"return",
"None"
] | https://github.com/albertz/openlierox/blob/d316c14a8eb57848ef56e9bfa7b23a56f694a51b/tools/DedicatedServerVideo/gdata/health/__init__.py#L101-L112 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/_controls.py | python | ListCtrl.DeleteAllItems | (*args, **kwargs) | return _controls_.ListCtrl_DeleteAllItems(*args, **kwargs) | DeleteAllItems(self) -> bool | DeleteAllItems(self) -> bool | [
"DeleteAllItems",
"(",
"self",
")",
"-",
">",
"bool"
] | def DeleteAllItems(*args, **kwargs):
"""DeleteAllItems(self) -> bool"""
return _controls_.ListCtrl_DeleteAllItems(*args, **kwargs) | [
"def",
"DeleteAllItems",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_controls_",
".",
"ListCtrl_DeleteAllItems",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_controls.py#L4645-L4647 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/protobuf/py2/google/protobuf/internal/containers.py | python | RepeatedScalarFieldContainer.__delitem__ | (self, key) | Deletes the item at the specified position. | Deletes the item at the specified position. | [
"Deletes",
"the",
"item",
"at",
"the",
"specified",
"position",
"."
] | def __delitem__(self, key):
"""Deletes the item at the specified position."""
del self._values[key]
self._message_listener.Modified() | [
"def",
"__delitem__",
"(",
"self",
",",
"key",
")",
":",
"del",
"self",
".",
"_values",
"[",
"key",
"]",
"self",
".",
"_message_listener",
".",
"Modified",
"(",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/protobuf/py2/google/protobuf/internal/containers.py#L330-L333 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/richtext.py | python | RichTextBuffer.BeginItalic | (*args, **kwargs) | return _richtext.RichTextBuffer_BeginItalic(*args, **kwargs) | BeginItalic(self) -> bool | BeginItalic(self) -> bool | [
"BeginItalic",
"(",
"self",
")",
"-",
">",
"bool"
] | def BeginItalic(*args, **kwargs):
"""BeginItalic(self) -> bool"""
return _richtext.RichTextBuffer_BeginItalic(*args, **kwargs) | [
"def",
"BeginItalic",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_richtext",
".",
"RichTextBuffer_BeginItalic",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/richtext.py#L2341-L2343 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | tools/idl_parser/idl_ppapi_parser.py | python | IDLPPAPIParser.p_UnsignedIntegerType | (self, p) | UnsignedIntegerType : UINT8_T
| UINT16_T
| UINT32_T
| UINT64_T | UnsignedIntegerType : UINT8_T
| UINT16_T
| UINT32_T
| UINT64_T | [
"UnsignedIntegerType",
":",
"UINT8_T",
"|",
"UINT16_T",
"|",
"UINT32_T",
"|",
"UINT64_T"
] | def p_UnsignedIntegerType(self, p):
"""UnsignedIntegerType : UINT8_T
| UINT16_T
| UINT32_T
| UINT64_T"""
p[0] = p[1] | [
"def",
"p_UnsignedIntegerType",
"(",
"self",
",",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"p",
"[",
"1",
"]"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/tools/idl_parser/idl_ppapi_parser.py#L210-L215 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/email/message.py | python | Message.as_bytes | (self, unixfrom=False, policy=None) | return fp.getvalue() | Return the entire formatted message as a bytes object.
Optional 'unixfrom', when true, means include the Unix From_ envelope
header. 'policy' is passed to the BytesGenerator instance used to
serialize the message; if not specified the policy associated with
the message instance is used. | Return the entire formatted message as a bytes object. | [
"Return",
"the",
"entire",
"formatted",
"message",
"as",
"a",
"bytes",
"object",
"."
] | def as_bytes(self, unixfrom=False, policy=None):
"""Return the entire formatted message as a bytes object.
Optional 'unixfrom', when true, means include the Unix From_ envelope
header. 'policy' is passed to the BytesGenerator instance used to
serialize the message; if not specified the policy associated with
the message instance is used.
"""
from email.generator import BytesGenerator
policy = self.policy if policy is None else policy
fp = BytesIO()
g = BytesGenerator(fp, mangle_from_=False, policy=policy)
g.flatten(self, unixfrom=unixfrom)
return fp.getvalue() | [
"def",
"as_bytes",
"(",
"self",
",",
"unixfrom",
"=",
"False",
",",
"policy",
"=",
"None",
")",
":",
"from",
"email",
".",
"generator",
"import",
"BytesGenerator",
"policy",
"=",
"self",
".",
"policy",
"if",
"policy",
"is",
"None",
"else",
"policy",
"fp",
"=",
"BytesIO",
"(",
")",
"g",
"=",
"BytesGenerator",
"(",
"fp",
",",
"mangle_from_",
"=",
"False",
",",
"policy",
"=",
"policy",
")",
"g",
".",
"flatten",
"(",
"self",
",",
"unixfrom",
"=",
"unixfrom",
")",
"return",
"fp",
".",
"getvalue",
"(",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/email/message.py#L166-L179 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/aui.py | python | AuiTabArt.GetAdditionalBorderSpace | (*args, **kwargs) | return _aui.AuiTabArt_GetAdditionalBorderSpace(*args, **kwargs) | GetAdditionalBorderSpace(self, Window wnd) -> int | GetAdditionalBorderSpace(self, Window wnd) -> int | [
"GetAdditionalBorderSpace",
"(",
"self",
"Window",
"wnd",
")",
"-",
">",
"int"
] | def GetAdditionalBorderSpace(*args, **kwargs):
"""GetAdditionalBorderSpace(self, Window wnd) -> int"""
return _aui.AuiTabArt_GetAdditionalBorderSpace(*args, **kwargs) | [
"def",
"GetAdditionalBorderSpace",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_aui",
".",
"AuiTabArt_GetAdditionalBorderSpace",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/aui.py#L2334-L2336 | |
y123456yz/reading-and-annotate-mongodb-3.6 | 93280293672ca7586dc24af18132aa61e4ed7fcf | mongo/src/third_party/scons-2.5.0/scons-local-2.5.0/SCons/Tool/tex.py | python | TeXLaTeXStrFunction | (target = None, source= None, env=None) | return result | A strfunction for TeX and LaTeX that scans the source file to
decide the "flavor" of the source and then returns the appropriate
command string. | A strfunction for TeX and LaTeX that scans the source file to
decide the "flavor" of the source and then returns the appropriate
command string. | [
"A",
"strfunction",
"for",
"TeX",
"and",
"LaTeX",
"that",
"scans",
"the",
"source",
"file",
"to",
"decide",
"the",
"flavor",
"of",
"the",
"source",
"and",
"then",
"returns",
"the",
"appropriate",
"command",
"string",
"."
] | def TeXLaTeXStrFunction(target = None, source= None, env=None):
"""A strfunction for TeX and LaTeX that scans the source file to
decide the "flavor" of the source and then returns the appropriate
command string."""
if env.GetOption("no_exec"):
# find these paths for use in is_LaTeX to search for included files
basedir = os.path.split(str(source[0]))[0]
abspath = os.path.abspath(basedir)
if is_LaTeX(source,env,abspath):
result = env.subst('$LATEXCOM',0,target,source)+" ..."
else:
result = env.subst("$TEXCOM",0,target,source)+" ..."
else:
result = ''
return result | [
"def",
"TeXLaTeXStrFunction",
"(",
"target",
"=",
"None",
",",
"source",
"=",
"None",
",",
"env",
"=",
"None",
")",
":",
"if",
"env",
".",
"GetOption",
"(",
"\"no_exec\"",
")",
":",
"# find these paths for use in is_LaTeX to search for included files",
"basedir",
"=",
"os",
".",
"path",
".",
"split",
"(",
"str",
"(",
"source",
"[",
"0",
"]",
")",
")",
"[",
"0",
"]",
"abspath",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"basedir",
")",
"if",
"is_LaTeX",
"(",
"source",
",",
"env",
",",
"abspath",
")",
":",
"result",
"=",
"env",
".",
"subst",
"(",
"'$LATEXCOM'",
",",
"0",
",",
"target",
",",
"source",
")",
"+",
"\" ...\"",
"else",
":",
"result",
"=",
"env",
".",
"subst",
"(",
"\"$TEXCOM\"",
",",
"0",
",",
"target",
",",
"source",
")",
"+",
"\" ...\"",
"else",
":",
"result",
"=",
"''",
"return",
"result"
] | https://github.com/y123456yz/reading-and-annotate-mongodb-3.6/blob/93280293672ca7586dc24af18132aa61e4ed7fcf/mongo/src/third_party/scons-2.5.0/scons-local-2.5.0/SCons/Tool/tex.py#L581-L597 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/aui.py | python | AuiPaneInfo.IsResizable | (*args, **kwargs) | return _aui.AuiPaneInfo_IsResizable(*args, **kwargs) | IsResizable(self) -> bool | IsResizable(self) -> bool | [
"IsResizable",
"(",
"self",
")",
"-",
">",
"bool"
] | def IsResizable(*args, **kwargs):
"""IsResizable(self) -> bool"""
return _aui.AuiPaneInfo_IsResizable(*args, **kwargs) | [
"def",
"IsResizable",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_aui",
".",
"AuiPaneInfo_IsResizable",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/aui.py#L245-L247 | |
LiquidPlayer/LiquidCore | 9405979363f2353ac9a71ad8ab59685dd7f919c9 | deps/node-10.15.3/tools/jinja2/filters.py | python | do_first | (environment, seq) | Return the first item of a sequence. | Return the first item of a sequence. | [
"Return",
"the",
"first",
"item",
"of",
"a",
"sequence",
"."
] | def do_first(environment, seq):
"""Return the first item of a sequence."""
try:
return next(iter(seq))
except StopIteration:
return environment.undefined('No first item, sequence was empty.') | [
"def",
"do_first",
"(",
"environment",
",",
"seq",
")",
":",
"try",
":",
"return",
"next",
"(",
"iter",
"(",
"seq",
")",
")",
"except",
"StopIteration",
":",
"return",
"environment",
".",
"undefined",
"(",
"'No first item, sequence was empty.'",
")"
] | https://github.com/LiquidPlayer/LiquidCore/blob/9405979363f2353ac9a71ad8ab59685dd7f919c9/deps/node-10.15.3/tools/jinja2/filters.py#L433-L438 | ||
leanprover/lean | 72a965986fa5aeae54062e98efb3140b2c4e79fd | src/cmake/Modules/cpplint.py | python | FindEndOfExpressionInLine | (line, startpos, depth, startchar, endchar) | return -1 | Find the position just after the matching endchar.
Args:
line: a CleansedLines line.
startpos: start searching at this position.
depth: nesting level at startpos.
startchar: expression opening character.
endchar: expression closing character.
Returns:
Index just after endchar. | Find the position just after the matching endchar. | [
"Find",
"the",
"position",
"just",
"after",
"the",
"matching",
"endchar",
"."
] | def FindEndOfExpressionInLine(line, startpos, depth, startchar, endchar):
"""Find the position just after the matching endchar.
Args:
line: a CleansedLines line.
startpos: start searching at this position.
depth: nesting level at startpos.
startchar: expression opening character.
endchar: expression closing character.
Returns:
Index just after endchar.
"""
for i in xrange(startpos, len(line)):
if line[i] == startchar:
depth += 1
elif line[i] == endchar:
depth -= 1
if depth == 0:
return i + 1
return -1 | [
"def",
"FindEndOfExpressionInLine",
"(",
"line",
",",
"startpos",
",",
"depth",
",",
"startchar",
",",
"endchar",
")",
":",
"for",
"i",
"in",
"xrange",
"(",
"startpos",
",",
"len",
"(",
"line",
")",
")",
":",
"if",
"line",
"[",
"i",
"]",
"==",
"startchar",
":",
"depth",
"+=",
"1",
"elif",
"line",
"[",
"i",
"]",
"==",
"endchar",
":",
"depth",
"-=",
"1",
"if",
"depth",
"==",
"0",
":",
"return",
"i",
"+",
"1",
"return",
"-",
"1"
] | https://github.com/leanprover/lean/blob/72a965986fa5aeae54062e98efb3140b2c4e79fd/src/cmake/Modules/cpplint.py#L1102-L1122 | |
pmq20/node-packer | 12c46c6e44fbc14d9ee645ebd17d5296b324f7e0 | current/tools/gyp/pylib/gyp/xcodeproj_file.py | python | PBXGroup.TakeOverOnlyChild | (self, recurse=False) | If this PBXGroup has only one child and it's also a PBXGroup, take
it over by making all of its children this object's children.
This function will continue to take over only children when those children
are groups. If there are three PBXGroups representing a, b, and c, with
c inside b and b inside a, and a and b have no other children, this will
result in a taking over both b and c, forming a PBXGroup for a/b/c.
If recurse is True, this function will recurse into children and ask them
to collapse themselves by taking over only children as well. Assuming
an example hierarchy with files at a/b/c/d1, a/b/c/d2, and a/b/c/d3/e/f
(d1, d2, and f are files, the rest are groups), recursion will result in
a group for a/b/c containing a group for d3/e. | If this PBXGroup has only one child and it's also a PBXGroup, take
it over by making all of its children this object's children. | [
"If",
"this",
"PBXGroup",
"has",
"only",
"one",
"child",
"and",
"it",
"s",
"also",
"a",
"PBXGroup",
"take",
"it",
"over",
"by",
"making",
"all",
"of",
"its",
"children",
"this",
"object",
"s",
"children",
"."
] | def TakeOverOnlyChild(self, recurse=False):
"""If this PBXGroup has only one child and it's also a PBXGroup, take
it over by making all of its children this object's children.
This function will continue to take over only children when those children
are groups. If there are three PBXGroups representing a, b, and c, with
c inside b and b inside a, and a and b have no other children, this will
result in a taking over both b and c, forming a PBXGroup for a/b/c.
If recurse is True, this function will recurse into children and ask them
to collapse themselves by taking over only children as well. Assuming
an example hierarchy with files at a/b/c/d1, a/b/c/d2, and a/b/c/d3/e/f
(d1, d2, and f are files, the rest are groups), recursion will result in
a group for a/b/c containing a group for d3/e.
"""
# At this stage, check that child class types are PBXGroup exactly,
# instead of using isinstance. The only subclass of PBXGroup,
# PBXVariantGroup, should not participate in reparenting in the same way:
# reparenting by merging different object types would be wrong.
while len(self._properties['children']) == 1 and \
self._properties['children'][0].__class__ == PBXGroup:
# Loop to take over the innermost only-child group possible.
child = self._properties['children'][0]
# Assume the child's properties, including its children. Save a copy
# of this object's old properties, because they'll still be needed.
# This object retains its existing id and parent attributes.
old_properties = self._properties
self._properties = child._properties
self._children_by_path = child._children_by_path
if not 'sourceTree' in self._properties or \
self._properties['sourceTree'] == '<group>':
# The child was relative to its parent. Fix up the path. Note that
# children with a sourceTree other than "<group>" are not relative to
# their parents, so no path fix-up is needed in that case.
if 'path' in old_properties:
if 'path' in self._properties:
# Both the original parent and child have paths set.
self._properties['path'] = posixpath.join(old_properties['path'],
self._properties['path'])
else:
# Only the original parent has a path, use it.
self._properties['path'] = old_properties['path']
if 'sourceTree' in old_properties:
# The original parent had a sourceTree set, use it.
self._properties['sourceTree'] = old_properties['sourceTree']
# If the original parent had a name set, keep using it. If the original
# parent didn't have a name but the child did, let the child's name
# live on. If the name attribute seems unnecessary now, get rid of it.
if 'name' in old_properties and old_properties['name'] != None and \
old_properties['name'] != self.Name():
self._properties['name'] = old_properties['name']
if 'name' in self._properties and 'path' in self._properties and \
self._properties['name'] == self._properties['path']:
del self._properties['name']
# Notify all children of their new parent.
for child in self._properties['children']:
child.parent = self
# If asked to recurse, recurse.
if recurse:
for child in self._properties['children']:
if child.__class__ == PBXGroup:
child.TakeOverOnlyChild(recurse) | [
"def",
"TakeOverOnlyChild",
"(",
"self",
",",
"recurse",
"=",
"False",
")",
":",
"# At this stage, check that child class types are PBXGroup exactly,",
"# instead of using isinstance. The only subclass of PBXGroup,",
"# PBXVariantGroup, should not participate in reparenting in the same way:",
"# reparenting by merging different object types would be wrong.",
"while",
"len",
"(",
"self",
".",
"_properties",
"[",
"'children'",
"]",
")",
"==",
"1",
"and",
"self",
".",
"_properties",
"[",
"'children'",
"]",
"[",
"0",
"]",
".",
"__class__",
"==",
"PBXGroup",
":",
"# Loop to take over the innermost only-child group possible.",
"child",
"=",
"self",
".",
"_properties",
"[",
"'children'",
"]",
"[",
"0",
"]",
"# Assume the child's properties, including its children. Save a copy",
"# of this object's old properties, because they'll still be needed.",
"# This object retains its existing id and parent attributes.",
"old_properties",
"=",
"self",
".",
"_properties",
"self",
".",
"_properties",
"=",
"child",
".",
"_properties",
"self",
".",
"_children_by_path",
"=",
"child",
".",
"_children_by_path",
"if",
"not",
"'sourceTree'",
"in",
"self",
".",
"_properties",
"or",
"self",
".",
"_properties",
"[",
"'sourceTree'",
"]",
"==",
"'<group>'",
":",
"# The child was relative to its parent. Fix up the path. Note that",
"# children with a sourceTree other than \"<group>\" are not relative to",
"# their parents, so no path fix-up is needed in that case.",
"if",
"'path'",
"in",
"old_properties",
":",
"if",
"'path'",
"in",
"self",
".",
"_properties",
":",
"# Both the original parent and child have paths set.",
"self",
".",
"_properties",
"[",
"'path'",
"]",
"=",
"posixpath",
".",
"join",
"(",
"old_properties",
"[",
"'path'",
"]",
",",
"self",
".",
"_properties",
"[",
"'path'",
"]",
")",
"else",
":",
"# Only the original parent has a path, use it.",
"self",
".",
"_properties",
"[",
"'path'",
"]",
"=",
"old_properties",
"[",
"'path'",
"]",
"if",
"'sourceTree'",
"in",
"old_properties",
":",
"# The original parent had a sourceTree set, use it.",
"self",
".",
"_properties",
"[",
"'sourceTree'",
"]",
"=",
"old_properties",
"[",
"'sourceTree'",
"]",
"# If the original parent had a name set, keep using it. If the original",
"# parent didn't have a name but the child did, let the child's name",
"# live on. If the name attribute seems unnecessary now, get rid of it.",
"if",
"'name'",
"in",
"old_properties",
"and",
"old_properties",
"[",
"'name'",
"]",
"!=",
"None",
"and",
"old_properties",
"[",
"'name'",
"]",
"!=",
"self",
".",
"Name",
"(",
")",
":",
"self",
".",
"_properties",
"[",
"'name'",
"]",
"=",
"old_properties",
"[",
"'name'",
"]",
"if",
"'name'",
"in",
"self",
".",
"_properties",
"and",
"'path'",
"in",
"self",
".",
"_properties",
"and",
"self",
".",
"_properties",
"[",
"'name'",
"]",
"==",
"self",
".",
"_properties",
"[",
"'path'",
"]",
":",
"del",
"self",
".",
"_properties",
"[",
"'name'",
"]",
"# Notify all children of their new parent.",
"for",
"child",
"in",
"self",
".",
"_properties",
"[",
"'children'",
"]",
":",
"child",
".",
"parent",
"=",
"self",
"# If asked to recurse, recurse.",
"if",
"recurse",
":",
"for",
"child",
"in",
"self",
".",
"_properties",
"[",
"'children'",
"]",
":",
"if",
"child",
".",
"__class__",
"==",
"PBXGroup",
":",
"child",
".",
"TakeOverOnlyChild",
"(",
"recurse",
")"
] | https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/current/tools/gyp/pylib/gyp/xcodeproj_file.py#L1328-L1396 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/grid.py | python | Grid.DisableDragColSize | (*args, **kwargs) | return _grid.Grid_DisableDragColSize(*args, **kwargs) | DisableDragColSize(self) | DisableDragColSize(self) | [
"DisableDragColSize",
"(",
"self",
")"
] | def DisableDragColSize(*args, **kwargs):
"""DisableDragColSize(self)"""
return _grid.Grid_DisableDragColSize(*args, **kwargs) | [
"def",
"DisableDragColSize",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_grid",
".",
"Grid_DisableDragColSize",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/grid.py#L1610-L1612 | |
Polidea/SiriusObfuscator | b0e590d8130e97856afe578869b83a209e2b19be | SymbolExtractorAndRenamer/lldb/third_party/Python/module/pexpect-2.4/pexpect.py | python | spawn.write | (self, s) | This is similar to send() except that there is no return value. | This is similar to send() except that there is no return value. | [
"This",
"is",
"similar",
"to",
"send",
"()",
"except",
"that",
"there",
"is",
"no",
"return",
"value",
"."
] | def write(self, s): # File-like object.
"""This is similar to send() except that there is no return value.
"""
self.send(s) | [
"def",
"write",
"(",
"self",
",",
"s",
")",
":",
"# File-like object.",
"self",
".",
"send",
"(",
"s",
")"
] | https://github.com/Polidea/SiriusObfuscator/blob/b0e590d8130e97856afe578869b83a209e2b19be/SymbolExtractorAndRenamer/lldb/third_party/Python/module/pexpect-2.4/pexpect.py#L970-L974 | ||
echronos/echronos | c996f1d2c8af6c6536205eb319c1bf1d4d84569c | external_tools/ply_info/example/yply/yparse.py | python | p_namelist | (p) | namelist : namelist optcomma ID
| ID | namelist : namelist optcomma ID
| ID | [
"namelist",
":",
"namelist",
"optcomma",
"ID",
"|",
"ID"
] | def p_namelist(p):
'''namelist : namelist optcomma ID
| ID''' | [
"def",
"p_namelist",
"(",
"p",
")",
":"
] | https://github.com/echronos/echronos/blob/c996f1d2c8af6c6536205eb319c1bf1d4d84569c/external_tools/ply_info/example/yply/yparse.py#L99-L101 | ||
martinmoene/span-lite | 8f7935ff4e502ee023990d356d6578b8293eda74 | script/create-vcpkg.py | python | descriptionFrom | ( filename ) | return description if description else cfg_vcpkg_description | Obtain description from CMakeLists.txt | Obtain description from CMakeLists.txt | [
"Obtain",
"description",
"from",
"CMakeLists",
".",
"txt"
] | def descriptionFrom( filename ):
"""Obtain description from CMakeLists.txt"""
with open( filename, 'r' ) as f:
content = f.read()
description = re.search(r'DESCRIPTION\s"(.*)"', content).group(1)
return description if description else cfg_vcpkg_description | [
"def",
"descriptionFrom",
"(",
"filename",
")",
":",
"with",
"open",
"(",
"filename",
",",
"'r'",
")",
"as",
"f",
":",
"content",
"=",
"f",
".",
"read",
"(",
")",
"description",
"=",
"re",
".",
"search",
"(",
"r'DESCRIPTION\\s\"(.*)\"'",
",",
"content",
")",
".",
"group",
"(",
"1",
")",
"return",
"description",
"if",
"description",
"else",
"cfg_vcpkg_description"
] | https://github.com/martinmoene/span-lite/blob/8f7935ff4e502ee023990d356d6578b8293eda74/script/create-vcpkg.py#L100-L105 | |
NVIDIA/DALI | bf16cc86ba8f091b145f91962f21fe1b6aff243d | docs/examples/use_cases/tensorflow/efficientdet/pipeline/tf/preprocessor.py | python | random_horizontal_flip | (
image,
boxes=None,
masks=None,
keypoints=None,
keypoint_flip_permutation=None,
seed=None,
) | Randomly flips the image and detections horizontally.
The probability of flipping the image is 50%.
Args:
image: rank 3 float32 tensor with shape [height, width, channels].
boxes: (optional) rank 2 float32 tensor with shape [N, 4]
containing the bounding boxes.
Boxes are in normalized form meaning their coordinates vary
between [0, 1].
Each row is in the form of [ymin, xmin, ymax, xmax].
masks: (optional) rank 3 float32 tensor with shape
[num_instances, height, width] containing instance masks. The masks
are of the same height, width as the input `image`.
keypoints: (optional) rank 3 float32 tensor with shape
[num_instances, num_keypoints, 2]. The keypoints are in y-x
normalized coordinates.
keypoint_flip_permutation: rank 1 int32 tensor containing the keypoint flip
permutation.
seed: random seed
Returns:
image: image which is the same shape as input image.
If boxes, masks, keypoints, and keypoint_flip_permutation are not None,
the function also returns the following tensors.
boxes: rank 2 float32 tensor containing the bounding boxes -> [N, 4].
Boxes are in normalized form meaning their coordinates vary
between [0, 1].
masks: rank 3 float32 tensor with shape [num_instances, height, width]
containing instance masks.
keypoints: rank 3 float32 tensor with shape
[num_instances, num_keypoints, 2]
Raises:
ValueError: if keypoints are provided but keypoint_flip_permutation is not. | Randomly flips the image and detections horizontally. | [
"Randomly",
"flips",
"the",
"image",
"and",
"detections",
"horizontally",
"."
] | def random_horizontal_flip(
image,
boxes=None,
masks=None,
keypoints=None,
keypoint_flip_permutation=None,
seed=None,
):
"""Randomly flips the image and detections horizontally.
The probability of flipping the image is 50%.
Args:
image: rank 3 float32 tensor with shape [height, width, channels].
boxes: (optional) rank 2 float32 tensor with shape [N, 4]
containing the bounding boxes.
Boxes are in normalized form meaning their coordinates vary
between [0, 1].
Each row is in the form of [ymin, xmin, ymax, xmax].
masks: (optional) rank 3 float32 tensor with shape
[num_instances, height, width] containing instance masks. The masks
are of the same height, width as the input `image`.
keypoints: (optional) rank 3 float32 tensor with shape
[num_instances, num_keypoints, 2]. The keypoints are in y-x
normalized coordinates.
keypoint_flip_permutation: rank 1 int32 tensor containing the keypoint flip
permutation.
seed: random seed
Returns:
image: image which is the same shape as input image.
If boxes, masks, keypoints, and keypoint_flip_permutation are not None,
the function also returns the following tensors.
boxes: rank 2 float32 tensor containing the bounding boxes -> [N, 4].
Boxes are in normalized form meaning their coordinates vary
between [0, 1].
masks: rank 3 float32 tensor with shape [num_instances, height, width]
containing instance masks.
keypoints: rank 3 float32 tensor with shape
[num_instances, num_keypoints, 2]
Raises:
ValueError: if keypoints are provided but keypoint_flip_permutation is not.
"""
def _flip_image(image):
# flip image
image_flipped = tf.image.flip_left_right(image)
return image_flipped
if keypoints is not None and keypoint_flip_permutation is None:
raise ValueError(
"keypoints are provided but keypoints_flip_permutation is not provided"
)
with tf.name_scope("RandomHorizontalFlip", values=[image, boxes]):
result = []
# random variable defining whether to do flip or not
do_a_flip_random = tf.greater(tf.random_uniform([], seed=seed), 0.5)
# flip image
image = tf.cond(do_a_flip_random, lambda: _flip_image(image), lambda: image)
result.append(image)
# flip boxes
if boxes is not None:
boxes = tf.cond(
do_a_flip_random, lambda: _flip_boxes_left_right(boxes), lambda: boxes
)
result.append(boxes)
# flip masks
if masks is not None:
masks = tf.cond(
do_a_flip_random, lambda: _flip_masks_left_right(masks), lambda: masks
)
result.append(masks)
# flip keypoints
if keypoints is not None and keypoint_flip_permutation is not None:
permutation = keypoint_flip_permutation
keypoints = tf.cond(
do_a_flip_random,
lambda: keypoint_flip_horizontal(keypoints, 0.5, permutation),
lambda: keypoints,
)
result.append(keypoints)
return tuple(result) | [
"def",
"random_horizontal_flip",
"(",
"image",
",",
"boxes",
"=",
"None",
",",
"masks",
"=",
"None",
",",
"keypoints",
"=",
"None",
",",
"keypoint_flip_permutation",
"=",
"None",
",",
"seed",
"=",
"None",
",",
")",
":",
"def",
"_flip_image",
"(",
"image",
")",
":",
"# flip image",
"image_flipped",
"=",
"tf",
".",
"image",
".",
"flip_left_right",
"(",
"image",
")",
"return",
"image_flipped",
"if",
"keypoints",
"is",
"not",
"None",
"and",
"keypoint_flip_permutation",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"keypoints are provided but keypoints_flip_permutation is not provided\"",
")",
"with",
"tf",
".",
"name_scope",
"(",
"\"RandomHorizontalFlip\"",
",",
"values",
"=",
"[",
"image",
",",
"boxes",
"]",
")",
":",
"result",
"=",
"[",
"]",
"# random variable defining whether to do flip or not",
"do_a_flip_random",
"=",
"tf",
".",
"greater",
"(",
"tf",
".",
"random_uniform",
"(",
"[",
"]",
",",
"seed",
"=",
"seed",
")",
",",
"0.5",
")",
"# flip image",
"image",
"=",
"tf",
".",
"cond",
"(",
"do_a_flip_random",
",",
"lambda",
":",
"_flip_image",
"(",
"image",
")",
",",
"lambda",
":",
"image",
")",
"result",
".",
"append",
"(",
"image",
")",
"# flip boxes",
"if",
"boxes",
"is",
"not",
"None",
":",
"boxes",
"=",
"tf",
".",
"cond",
"(",
"do_a_flip_random",
",",
"lambda",
":",
"_flip_boxes_left_right",
"(",
"boxes",
")",
",",
"lambda",
":",
"boxes",
")",
"result",
".",
"append",
"(",
"boxes",
")",
"# flip masks",
"if",
"masks",
"is",
"not",
"None",
":",
"masks",
"=",
"tf",
".",
"cond",
"(",
"do_a_flip_random",
",",
"lambda",
":",
"_flip_masks_left_right",
"(",
"masks",
")",
",",
"lambda",
":",
"masks",
")",
"result",
".",
"append",
"(",
"masks",
")",
"# flip keypoints",
"if",
"keypoints",
"is",
"not",
"None",
"and",
"keypoint_flip_permutation",
"is",
"not",
"None",
":",
"permutation",
"=",
"keypoint_flip_permutation",
"keypoints",
"=",
"tf",
".",
"cond",
"(",
"do_a_flip_random",
",",
"lambda",
":",
"keypoint_flip_horizontal",
"(",
"keypoints",
",",
"0.5",
",",
"permutation",
")",
",",
"lambda",
":",
"keypoints",
",",
")",
"result",
".",
"append",
"(",
"keypoints",
")",
"return",
"tuple",
"(",
"result",
")"
] | https://github.com/NVIDIA/DALI/blob/bf16cc86ba8f091b145f91962f21fe1b6aff243d/docs/examples/use_cases/tensorflow/efficientdet/pipeline/tf/preprocessor.py#L112-L202 | ||
facebook/openr | ed38bdfd6bf290084bfab4821b59f83e7b59315d | openr/py/openr/cli/commands/fib.py | python | StreamSummaryCmd.get_subscriber_row | (self, stream_session_info) | return row | Takes StreamSubscriberInfo from thrift and returns list[str] (aka row)
representing the subscriber | Takes StreamSubscriberInfo from thrift and returns list[str] (aka row)
representing the subscriber | [
"Takes",
"StreamSubscriberInfo",
"from",
"thrift",
"and",
"returns",
"list",
"[",
"str",
"]",
"(",
"aka",
"row",
")",
"representing",
"the",
"subscriber"
] | def get_subscriber_row(self, stream_session_info):
"""
Takes StreamSubscriberInfo from thrift and returns list[str] (aka row)
representing the subscriber
"""
uptime = "unknown"
last_msg_time = "unknown"
if (
stream_session_info.uptime is not None
and stream_session_info.last_msg_sent_time is not None
):
uptime_str = str(
datetime.timedelta(milliseconds=stream_session_info.uptime)
)
last_msg_time_str = convertTime(stream_session_info.last_msg_sent_time)
uptime = uptime_str.split(".")[0]
last_msg_time = last_msg_time_str
# assert isinstance(stream_session_info, StreamSubscriberInfo)
row = [
stream_session_info.subscriber_id,
uptime,
stream_session_info.total_streamed_msgs,
last_msg_time,
]
return row | [
"def",
"get_subscriber_row",
"(",
"self",
",",
"stream_session_info",
")",
":",
"uptime",
"=",
"\"unknown\"",
"last_msg_time",
"=",
"\"unknown\"",
"if",
"(",
"stream_session_info",
".",
"uptime",
"is",
"not",
"None",
"and",
"stream_session_info",
".",
"last_msg_sent_time",
"is",
"not",
"None",
")",
":",
"uptime_str",
"=",
"str",
"(",
"datetime",
".",
"timedelta",
"(",
"milliseconds",
"=",
"stream_session_info",
".",
"uptime",
")",
")",
"last_msg_time_str",
"=",
"convertTime",
"(",
"stream_session_info",
".",
"last_msg_sent_time",
")",
"uptime",
"=",
"uptime_str",
".",
"split",
"(",
"\".\"",
")",
"[",
"0",
"]",
"last_msg_time",
"=",
"last_msg_time_str",
"# assert isinstance(stream_session_info, StreamSubscriberInfo)",
"row",
"=",
"[",
"stream_session_info",
".",
"subscriber_id",
",",
"uptime",
",",
"stream_session_info",
".",
"total_streamed_msgs",
",",
"last_msg_time",
",",
"]",
"return",
"row"
] | https://github.com/facebook/openr/blob/ed38bdfd6bf290084bfab4821b59f83e7b59315d/openr/py/openr/cli/commands/fib.py#L504-L530 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/third_party/pyfakefs/pyfakefs/fake_filesystem.py | python | FakeOsModule.mknod | (self, filename, mode=None, device=None) | Create a filesystem node named 'filename'.
Does not support device special files or named pipes as the real os
module does.
Args:
filename: (str) Name of the file to create
mode: (int) permissions to use and type of file to be created.
Default permissions are 0o666. Only the stat.S_IFREG file type
is supported by the fake implementation. The umask is applied
to this mode.
device: not supported in fake implementation
Raises:
OSError: if called with unsupported options or the file can not be
created. | Create a filesystem node named 'filename'. | [
"Create",
"a",
"filesystem",
"node",
"named",
"filename",
"."
] | def mknod(self, filename, mode=None, device=None):
"""Create a filesystem node named 'filename'.
Does not support device special files or named pipes as the real os
module does.
Args:
filename: (str) Name of the file to create
mode: (int) permissions to use and type of file to be created.
Default permissions are 0o666. Only the stat.S_IFREG file type
is supported by the fake implementation. The umask is applied
to this mode.
device: not supported in fake implementation
Raises:
OSError: if called with unsupported options or the file can not be
created.
"""
if mode is None:
mode = stat.S_IFREG | PERM_DEF_FILE
if device or not mode & stat.S_IFREG:
raise OSError(errno.EINVAL,
'Fake os mknod implementation only supports '
'regular files.')
head, tail = self.path.split(filename)
if not tail:
if self.filesystem.Exists(head):
raise OSError(errno.EEXIST, 'Fake filesystem: %s: %s' % (
os.strerror(errno.EEXIST), filename))
raise OSError(errno.ENOENT, 'Fake filesystem: %s: %s' % (
os.strerror(errno.ENOENT), filename))
if tail == '.' or tail == '..' or self.filesystem.Exists(filename):
raise OSError(errno.EEXIST, 'Fake fileystem: %s: %s' % (
os.strerror(errno.EEXIST), filename))
try:
self.filesystem.AddObject(head, FakeFile(tail,
mode & ~self.filesystem.umask))
except IOError:
raise OSError(errno.ENOTDIR, 'Fake filesystem: %s: %s' % (
os.strerror(errno.ENOTDIR), filename)) | [
"def",
"mknod",
"(",
"self",
",",
"filename",
",",
"mode",
"=",
"None",
",",
"device",
"=",
"None",
")",
":",
"if",
"mode",
"is",
"None",
":",
"mode",
"=",
"stat",
".",
"S_IFREG",
"|",
"PERM_DEF_FILE",
"if",
"device",
"or",
"not",
"mode",
"&",
"stat",
".",
"S_IFREG",
":",
"raise",
"OSError",
"(",
"errno",
".",
"EINVAL",
",",
"'Fake os mknod implementation only supports '",
"'regular files.'",
")",
"head",
",",
"tail",
"=",
"self",
".",
"path",
".",
"split",
"(",
"filename",
")",
"if",
"not",
"tail",
":",
"if",
"self",
".",
"filesystem",
".",
"Exists",
"(",
"head",
")",
":",
"raise",
"OSError",
"(",
"errno",
".",
"EEXIST",
",",
"'Fake filesystem: %s: %s'",
"%",
"(",
"os",
".",
"strerror",
"(",
"errno",
".",
"EEXIST",
")",
",",
"filename",
")",
")",
"raise",
"OSError",
"(",
"errno",
".",
"ENOENT",
",",
"'Fake filesystem: %s: %s'",
"%",
"(",
"os",
".",
"strerror",
"(",
"errno",
".",
"ENOENT",
")",
",",
"filename",
")",
")",
"if",
"tail",
"==",
"'.'",
"or",
"tail",
"==",
"'..'",
"or",
"self",
".",
"filesystem",
".",
"Exists",
"(",
"filename",
")",
":",
"raise",
"OSError",
"(",
"errno",
".",
"EEXIST",
",",
"'Fake fileystem: %s: %s'",
"%",
"(",
"os",
".",
"strerror",
"(",
"errno",
".",
"EEXIST",
")",
",",
"filename",
")",
")",
"try",
":",
"self",
".",
"filesystem",
".",
"AddObject",
"(",
"head",
",",
"FakeFile",
"(",
"tail",
",",
"mode",
"&",
"~",
"self",
".",
"filesystem",
".",
"umask",
")",
")",
"except",
"IOError",
":",
"raise",
"OSError",
"(",
"errno",
".",
"ENOTDIR",
",",
"'Fake filesystem: %s: %s'",
"%",
"(",
"os",
".",
"strerror",
"(",
"errno",
".",
"ENOTDIR",
")",
",",
"filename",
")",
")"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/pyfakefs/pyfakefs/fake_filesystem.py#L1810-L1850 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/_controls.py | python | ListItem.GetBackgroundColour | (*args, **kwargs) | return _controls_.ListItem_GetBackgroundColour(*args, **kwargs) | GetBackgroundColour(self) -> Colour | GetBackgroundColour(self) -> Colour | [
"GetBackgroundColour",
"(",
"self",
")",
"-",
">",
"Colour"
] | def GetBackgroundColour(*args, **kwargs):
"""GetBackgroundColour(self) -> Colour"""
return _controls_.ListItem_GetBackgroundColour(*args, **kwargs) | [
"def",
"GetBackgroundColour",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_controls_",
".",
"ListItem_GetBackgroundColour",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_controls.py#L4260-L4262 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scipy/py3/scipy/signal/spectral.py | python | _triage_segments | (window, nperseg, input_length) | return win, nperseg | Parses window and nperseg arguments for spectrogram and _spectral_helper.
This is a helper function, not meant to be called externally.
Parameters
----------
window : string, tuple, or ndarray
If window is specified by a string or tuple and nperseg is not
specified, nperseg is set to the default of 256 and returns a window of
that length.
If instead the window is array_like and nperseg is not specified, then
nperseg is set to the length of the window. A ValueError is raised if
the user supplies both an array_like window and a value for nperseg but
nperseg does not equal the length of the window.
nperseg : int
Length of each segment
input_length: int
Length of input signal, i.e. x.shape[-1]. Used to test for errors.
Returns
-------
win : ndarray
window. If function was called with string or tuple than this will hold
the actual array used as a window.
nperseg : int
Length of each segment. If window is str or tuple, nperseg is set to
256. If window is array_like, nperseg is set to the length of the
6
window. | Parses window and nperseg arguments for spectrogram and _spectral_helper.
This is a helper function, not meant to be called externally. | [
"Parses",
"window",
"and",
"nperseg",
"arguments",
"for",
"spectrogram",
"and",
"_spectral_helper",
".",
"This",
"is",
"a",
"helper",
"function",
"not",
"meant",
"to",
"be",
"called",
"externally",
"."
] | def _triage_segments(window, nperseg, input_length):
"""
Parses window and nperseg arguments for spectrogram and _spectral_helper.
This is a helper function, not meant to be called externally.
Parameters
----------
window : string, tuple, or ndarray
If window is specified by a string or tuple and nperseg is not
specified, nperseg is set to the default of 256 and returns a window of
that length.
If instead the window is array_like and nperseg is not specified, then
nperseg is set to the length of the window. A ValueError is raised if
the user supplies both an array_like window and a value for nperseg but
nperseg does not equal the length of the window.
nperseg : int
Length of each segment
input_length: int
Length of input signal, i.e. x.shape[-1]. Used to test for errors.
Returns
-------
win : ndarray
window. If function was called with string or tuple than this will hold
the actual array used as a window.
nperseg : int
Length of each segment. If window is str or tuple, nperseg is set to
256. If window is array_like, nperseg is set to the length of the
6
window.
"""
# parse window; if array like, then set nperseg = win.shape
if isinstance(window, string_types) or isinstance(window, tuple):
# if nperseg not specified
if nperseg is None:
nperseg = 256 # then change to default
if nperseg > input_length:
warnings.warn('nperseg = {0:d} is greater than input length '
' = {1:d}, using nperseg = {1:d}'
.format(nperseg, input_length))
nperseg = input_length
win = get_window(window, nperseg)
else:
win = np.asarray(window)
if len(win.shape) != 1:
raise ValueError('window must be 1-D')
if input_length < win.shape[-1]:
raise ValueError('window is longer than input signal')
if nperseg is None:
nperseg = win.shape[0]
elif nperseg is not None:
if nperseg != win.shape[0]:
raise ValueError("value specified for nperseg is different"
" from length of window")
return win, nperseg | [
"def",
"_triage_segments",
"(",
"window",
",",
"nperseg",
",",
"input_length",
")",
":",
"# parse window; if array like, then set nperseg = win.shape",
"if",
"isinstance",
"(",
"window",
",",
"string_types",
")",
"or",
"isinstance",
"(",
"window",
",",
"tuple",
")",
":",
"# if nperseg not specified",
"if",
"nperseg",
"is",
"None",
":",
"nperseg",
"=",
"256",
"# then change to default",
"if",
"nperseg",
">",
"input_length",
":",
"warnings",
".",
"warn",
"(",
"'nperseg = {0:d} is greater than input length '",
"' = {1:d}, using nperseg = {1:d}'",
".",
"format",
"(",
"nperseg",
",",
"input_length",
")",
")",
"nperseg",
"=",
"input_length",
"win",
"=",
"get_window",
"(",
"window",
",",
"nperseg",
")",
"else",
":",
"win",
"=",
"np",
".",
"asarray",
"(",
"window",
")",
"if",
"len",
"(",
"win",
".",
"shape",
")",
"!=",
"1",
":",
"raise",
"ValueError",
"(",
"'window must be 1-D'",
")",
"if",
"input_length",
"<",
"win",
".",
"shape",
"[",
"-",
"1",
"]",
":",
"raise",
"ValueError",
"(",
"'window is longer than input signal'",
")",
"if",
"nperseg",
"is",
"None",
":",
"nperseg",
"=",
"win",
".",
"shape",
"[",
"0",
"]",
"elif",
"nperseg",
"is",
"not",
"None",
":",
"if",
"nperseg",
"!=",
"win",
".",
"shape",
"[",
"0",
"]",
":",
"raise",
"ValueError",
"(",
"\"value specified for nperseg is different\"",
"\" from length of window\"",
")",
"return",
"win",
",",
"nperseg"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py3/scipy/signal/spectral.py#L1927-L1985 | |
pmq20/node-packer | 12c46c6e44fbc14d9ee645ebd17d5296b324f7e0 | lts/tools/gyp/pylib/gyp/xcode_emulation.py | python | XcodeSettings._GetIOSPostbuilds | (self, configname, output_binary) | return postbuilds | Return a shell command to codesign the iOS output binary so it can
be deployed to a device. This should be run as the very last step of the
build. | Return a shell command to codesign the iOS output binary so it can
be deployed to a device. This should be run as the very last step of the
build. | [
"Return",
"a",
"shell",
"command",
"to",
"codesign",
"the",
"iOS",
"output",
"binary",
"so",
"it",
"can",
"be",
"deployed",
"to",
"a",
"device",
".",
"This",
"should",
"be",
"run",
"as",
"the",
"very",
"last",
"step",
"of",
"the",
"build",
"."
] | def _GetIOSPostbuilds(self, configname, output_binary):
"""Return a shell command to codesign the iOS output binary so it can
be deployed to a device. This should be run as the very last step of the
build."""
if not (self.isIOS and
(self.spec['type'] == 'executable' or self._IsXCTest()) or
self.IsIosFramework()):
return []
postbuilds = []
product_name = self.GetFullProductName()
settings = self.xcode_settings[configname]
# Xcode expects XCTests to be copied into the TEST_HOST dir.
if self._IsXCTest():
source = os.path.join("${BUILT_PRODUCTS_DIR}", product_name)
test_host = os.path.dirname(settings.get('TEST_HOST'))
xctest_destination = os.path.join(test_host, 'PlugIns', product_name)
postbuilds.extend(['ditto %s %s' % (source, xctest_destination)])
key = self._GetIOSCodeSignIdentityKey(settings)
if not key:
return postbuilds
# Warn for any unimplemented signing xcode keys.
unimpl = ['OTHER_CODE_SIGN_FLAGS']
unimpl = set(unimpl) & set(self.xcode_settings[configname].keys())
if unimpl:
print('Warning: Some codesign keys not implemented, ignoring: %s' %
', '.join(sorted(unimpl)))
if self._IsXCTest():
# For device xctests, Xcode copies two extra frameworks into $TEST_HOST.
test_host = os.path.dirname(settings.get('TEST_HOST'))
frameworks_dir = os.path.join(test_host, 'Frameworks')
platform_root = self._XcodePlatformPath(configname)
frameworks = \
['Developer/Library/PrivateFrameworks/IDEBundleInjection.framework',
'Developer/Library/Frameworks/XCTest.framework']
for framework in frameworks:
source = os.path.join(platform_root, framework)
destination = os.path.join(frameworks_dir, os.path.basename(framework))
postbuilds.extend(['ditto %s %s' % (source, destination)])
# Then re-sign everything with 'preserve=True'
postbuilds.extend(['%s code-sign-bundle "%s" "%s" "%s" "%s" %s' % (
os.path.join('${TARGET_BUILD_DIR}', 'gyp-mac-tool'), key,
settings.get('CODE_SIGN_ENTITLEMENTS', ''),
settings.get('PROVISIONING_PROFILE', ''), destination, True)
])
plugin_dir = os.path.join(test_host, 'PlugIns')
targets = [os.path.join(plugin_dir, product_name), test_host]
for target in targets:
postbuilds.extend(['%s code-sign-bundle "%s" "%s" "%s" "%s" %s' % (
os.path.join('${TARGET_BUILD_DIR}', 'gyp-mac-tool'), key,
settings.get('CODE_SIGN_ENTITLEMENTS', ''),
settings.get('PROVISIONING_PROFILE', ''), target, True)
])
postbuilds.extend(['%s code-sign-bundle "%s" "%s" "%s" "%s" %s' % (
os.path.join('${TARGET_BUILD_DIR}', 'gyp-mac-tool'), key,
settings.get('CODE_SIGN_ENTITLEMENTS', ''),
settings.get('PROVISIONING_PROFILE', ''),
os.path.join("${BUILT_PRODUCTS_DIR}", product_name), False)
])
return postbuilds | [
"def",
"_GetIOSPostbuilds",
"(",
"self",
",",
"configname",
",",
"output_binary",
")",
":",
"if",
"not",
"(",
"self",
".",
"isIOS",
"and",
"(",
"self",
".",
"spec",
"[",
"'type'",
"]",
"==",
"'executable'",
"or",
"self",
".",
"_IsXCTest",
"(",
")",
")",
"or",
"self",
".",
"IsIosFramework",
"(",
")",
")",
":",
"return",
"[",
"]",
"postbuilds",
"=",
"[",
"]",
"product_name",
"=",
"self",
".",
"GetFullProductName",
"(",
")",
"settings",
"=",
"self",
".",
"xcode_settings",
"[",
"configname",
"]",
"# Xcode expects XCTests to be copied into the TEST_HOST dir.",
"if",
"self",
".",
"_IsXCTest",
"(",
")",
":",
"source",
"=",
"os",
".",
"path",
".",
"join",
"(",
"\"${BUILT_PRODUCTS_DIR}\"",
",",
"product_name",
")",
"test_host",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"settings",
".",
"get",
"(",
"'TEST_HOST'",
")",
")",
"xctest_destination",
"=",
"os",
".",
"path",
".",
"join",
"(",
"test_host",
",",
"'PlugIns'",
",",
"product_name",
")",
"postbuilds",
".",
"extend",
"(",
"[",
"'ditto %s %s'",
"%",
"(",
"source",
",",
"xctest_destination",
")",
"]",
")",
"key",
"=",
"self",
".",
"_GetIOSCodeSignIdentityKey",
"(",
"settings",
")",
"if",
"not",
"key",
":",
"return",
"postbuilds",
"# Warn for any unimplemented signing xcode keys.",
"unimpl",
"=",
"[",
"'OTHER_CODE_SIGN_FLAGS'",
"]",
"unimpl",
"=",
"set",
"(",
"unimpl",
")",
"&",
"set",
"(",
"self",
".",
"xcode_settings",
"[",
"configname",
"]",
".",
"keys",
"(",
")",
")",
"if",
"unimpl",
":",
"print",
"(",
"'Warning: Some codesign keys not implemented, ignoring: %s'",
"%",
"', '",
".",
"join",
"(",
"sorted",
"(",
"unimpl",
")",
")",
")",
"if",
"self",
".",
"_IsXCTest",
"(",
")",
":",
"# For device xctests, Xcode copies two extra frameworks into $TEST_HOST.",
"test_host",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"settings",
".",
"get",
"(",
"'TEST_HOST'",
")",
")",
"frameworks_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"test_host",
",",
"'Frameworks'",
")",
"platform_root",
"=",
"self",
".",
"_XcodePlatformPath",
"(",
"configname",
")",
"frameworks",
"=",
"[",
"'Developer/Library/PrivateFrameworks/IDEBundleInjection.framework'",
",",
"'Developer/Library/Frameworks/XCTest.framework'",
"]",
"for",
"framework",
"in",
"frameworks",
":",
"source",
"=",
"os",
".",
"path",
".",
"join",
"(",
"platform_root",
",",
"framework",
")",
"destination",
"=",
"os",
".",
"path",
".",
"join",
"(",
"frameworks_dir",
",",
"os",
".",
"path",
".",
"basename",
"(",
"framework",
")",
")",
"postbuilds",
".",
"extend",
"(",
"[",
"'ditto %s %s'",
"%",
"(",
"source",
",",
"destination",
")",
"]",
")",
"# Then re-sign everything with 'preserve=True'",
"postbuilds",
".",
"extend",
"(",
"[",
"'%s code-sign-bundle \"%s\" \"%s\" \"%s\" \"%s\" %s'",
"%",
"(",
"os",
".",
"path",
".",
"join",
"(",
"'${TARGET_BUILD_DIR}'",
",",
"'gyp-mac-tool'",
")",
",",
"key",
",",
"settings",
".",
"get",
"(",
"'CODE_SIGN_ENTITLEMENTS'",
",",
"''",
")",
",",
"settings",
".",
"get",
"(",
"'PROVISIONING_PROFILE'",
",",
"''",
")",
",",
"destination",
",",
"True",
")",
"]",
")",
"plugin_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"test_host",
",",
"'PlugIns'",
")",
"targets",
"=",
"[",
"os",
".",
"path",
".",
"join",
"(",
"plugin_dir",
",",
"product_name",
")",
",",
"test_host",
"]",
"for",
"target",
"in",
"targets",
":",
"postbuilds",
".",
"extend",
"(",
"[",
"'%s code-sign-bundle \"%s\" \"%s\" \"%s\" \"%s\" %s'",
"%",
"(",
"os",
".",
"path",
".",
"join",
"(",
"'${TARGET_BUILD_DIR}'",
",",
"'gyp-mac-tool'",
")",
",",
"key",
",",
"settings",
".",
"get",
"(",
"'CODE_SIGN_ENTITLEMENTS'",
",",
"''",
")",
",",
"settings",
".",
"get",
"(",
"'PROVISIONING_PROFILE'",
",",
"''",
")",
",",
"target",
",",
"True",
")",
"]",
")",
"postbuilds",
".",
"extend",
"(",
"[",
"'%s code-sign-bundle \"%s\" \"%s\" \"%s\" \"%s\" %s'",
"%",
"(",
"os",
".",
"path",
".",
"join",
"(",
"'${TARGET_BUILD_DIR}'",
",",
"'gyp-mac-tool'",
")",
",",
"key",
",",
"settings",
".",
"get",
"(",
"'CODE_SIGN_ENTITLEMENTS'",
",",
"''",
")",
",",
"settings",
".",
"get",
"(",
"'PROVISIONING_PROFILE'",
",",
"''",
")",
",",
"os",
".",
"path",
".",
"join",
"(",
"\"${BUILT_PRODUCTS_DIR}\"",
",",
"product_name",
")",
",",
"False",
")",
"]",
")",
"return",
"postbuilds"
] | https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/lts/tools/gyp/pylib/gyp/xcode_emulation.py#L1066-L1131 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.