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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
intel/caffe | 3f494b442ee3f9d17a07b09ecbd5fa2bbda00836 | examples/rfcn/lib/datasets/coco.py | python | _filter_crowd_proposals | (roidb, crowd_thresh) | return roidb | Finds proposals that are inside crowd regions and marks them with
overlap = -1 (for all gt rois), which means they will be excluded from
training. | Finds proposals that are inside crowd regions and marks them with
overlap = -1 (for all gt rois), which means they will be excluded from
training. | [
"Finds",
"proposals",
"that",
"are",
"inside",
"crowd",
"regions",
"and",
"marks",
"them",
"with",
"overlap",
"=",
"-",
"1",
"(",
"for",
"all",
"gt",
"rois",
")",
"which",
"means",
"they",
"will",
"be",
"excluded",
"from",
"training",
"."
] | def _filter_crowd_proposals(roidb, crowd_thresh):
"""
Finds proposals that are inside crowd regions and marks them with
overlap = -1 (for all gt rois), which means they will be excluded from
training.
"""
for ix, entry in enumerate(roidb):
overlaps = entry['gt_overlaps'].toarray()
crowd_inds = np.where(overlaps.max(axis=1) == -1)[0]
non_gt_inds = np.where(entry['gt_classes'] == 0)[0]
if len(crowd_inds) == 0 or len(non_gt_inds) == 0:
continue
iscrowd = [int(True) for _ in xrange(len(crowd_inds))]
crowd_boxes = ds_utils.xyxy_to_xywh(entry['boxes'][crowd_inds, :])
non_gt_boxes = ds_utils.xyxy_to_xywh(entry['boxes'][non_gt_inds, :])
ious = COCOmask.iou(non_gt_boxes, crowd_boxes, iscrowd)
bad_inds = np.where(ious.max(axis=1) > crowd_thresh)[0]
overlaps[non_gt_inds[bad_inds], :] = -1
roidb[ix]['gt_overlaps'] = scipy.sparse.csr_matrix(overlaps)
return roidb | [
"def",
"_filter_crowd_proposals",
"(",
"roidb",
",",
"crowd_thresh",
")",
":",
"for",
"ix",
",",
"entry",
"in",
"enumerate",
"(",
"roidb",
")",
":",
"overlaps",
"=",
"entry",
"[",
"'gt_overlaps'",
"]",
".",
"toarray",
"(",
")",
"crowd_inds",
"=",
"np",
".",
"where",
"(",
"overlaps",
".",
"max",
"(",
"axis",
"=",
"1",
")",
"==",
"-",
"1",
")",
"[",
"0",
"]",
"non_gt_inds",
"=",
"np",
".",
"where",
"(",
"entry",
"[",
"'gt_classes'",
"]",
"==",
"0",
")",
"[",
"0",
"]",
"if",
"len",
"(",
"crowd_inds",
")",
"==",
"0",
"or",
"len",
"(",
"non_gt_inds",
")",
"==",
"0",
":",
"continue",
"iscrowd",
"=",
"[",
"int",
"(",
"True",
")",
"for",
"_",
"in",
"xrange",
"(",
"len",
"(",
"crowd_inds",
")",
")",
"]",
"crowd_boxes",
"=",
"ds_utils",
".",
"xyxy_to_xywh",
"(",
"entry",
"[",
"'boxes'",
"]",
"[",
"crowd_inds",
",",
":",
"]",
")",
"non_gt_boxes",
"=",
"ds_utils",
".",
"xyxy_to_xywh",
"(",
"entry",
"[",
"'boxes'",
"]",
"[",
"non_gt_inds",
",",
":",
"]",
")",
"ious",
"=",
"COCOmask",
".",
"iou",
"(",
"non_gt_boxes",
",",
"crowd_boxes",
",",
"iscrowd",
")",
"bad_inds",
"=",
"np",
".",
"where",
"(",
"ious",
".",
"max",
"(",
"axis",
"=",
"1",
")",
">",
"crowd_thresh",
")",
"[",
"0",
"]",
"overlaps",
"[",
"non_gt_inds",
"[",
"bad_inds",
"]",
",",
":",
"]",
"=",
"-",
"1",
"roidb",
"[",
"ix",
"]",
"[",
"'gt_overlaps'",
"]",
"=",
"scipy",
".",
"sparse",
".",
"csr_matrix",
"(",
"overlaps",
")",
"return",
"roidb"
] | https://github.com/intel/caffe/blob/3f494b442ee3f9d17a07b09ecbd5fa2bbda00836/examples/rfcn/lib/datasets/coco.py#L24-L43 | |
jackaudio/jack2 | 21b293dbc37d42446141a08922cdec0d2550c6a0 | waflib/Tools/ccroot.py | python | set_full_paths_hpux | (self) | On hp-ux, extend the libpaths and static library paths to absolute paths | On hp-ux, extend the libpaths and static library paths to absolute paths | [
"On",
"hp",
"-",
"ux",
"extend",
"the",
"libpaths",
"and",
"static",
"library",
"paths",
"to",
"absolute",
"paths"
] | def set_full_paths_hpux(self):
"""
On hp-ux, extend the libpaths and static library paths to absolute paths
"""
if self.env.DEST_OS != 'hp-ux':
return
base = self.bld.bldnode.abspath()
for var in ['LIBPATH', 'STLIBPATH']:
lst = []
for x in self.env[var]:
if x.startswith('/'):
lst.append(x)
else:
lst.append(os.path.normpath(os.path.join(base, x)))
self.env[var] = lst | [
"def",
"set_full_paths_hpux",
"(",
"self",
")",
":",
"if",
"self",
".",
"env",
".",
"DEST_OS",
"!=",
"'hp-ux'",
":",
"return",
"base",
"=",
"self",
".",
"bld",
".",
"bldnode",
".",
"abspath",
"(",
")",
"for",
"var",
"in",
"[",
"'LIBPATH'",
",",
"'STLIBPATH'",
"]",
":",
"lst",
"=",
"[",
"]",
"for",
"x",
"in",
"self",
".",
"env",
"[",
"var",
"]",
":",
"if",
"x",
".",
"startswith",
"(",
"'/'",
")",
":",
"lst",
".",
"append",
"(",
"x",
")",
"else",
":",
"lst",
".",
"append",
"(",
"os",
".",
"path",
".",
"normpath",
"(",
"os",
".",
"path",
".",
"join",
"(",
"base",
",",
"x",
")",
")",
")",
"self",
".",
"env",
"[",
"var",
"]",
"=",
"lst"
] | https://github.com/jackaudio/jack2/blob/21b293dbc37d42446141a08922cdec0d2550c6a0/waflib/Tools/ccroot.py#L759-L773 | ||
kamyu104/LeetCode-Solutions | 77605708a927ea3b85aee5a479db733938c7c211 | Python/nested-list-weight-sum-ii.py | python | Solution.depthSumInverse | (self, nestedList) | return sum | :type nestedList: List[NestedInteger]
:rtype: int | :type nestedList: List[NestedInteger]
:rtype: int | [
":",
"type",
"nestedList",
":",
"List",
"[",
"NestedInteger",
"]",
":",
"rtype",
":",
"int"
] | def depthSumInverse(self, nestedList):
"""
:type nestedList: List[NestedInteger]
:rtype: int
"""
def depthSumInverseHelper(list, depth, result):
if len(result) < depth + 1:
result.append(0)
if list.isInteger():
result[depth] += list.getInteger()
else:
for l in list.getList():
depthSumInverseHelper(l, depth + 1, result)
result = []
for list in nestedList:
depthSumInverseHelper(list, 0, result)
sum = 0
for i in reversed(xrange(len(result))):
sum += result[i] * (len(result) - i)
return sum | [
"def",
"depthSumInverse",
"(",
"self",
",",
"nestedList",
")",
":",
"def",
"depthSumInverseHelper",
"(",
"list",
",",
"depth",
",",
"result",
")",
":",
"if",
"len",
"(",
"result",
")",
"<",
"depth",
"+",
"1",
":",
"result",
".",
"append",
"(",
"0",
")",
"if",
"list",
".",
"isInteger",
"(",
")",
":",
"result",
"[",
"depth",
"]",
"+=",
"list",
".",
"getInteger",
"(",
")",
"else",
":",
"for",
"l",
"in",
"list",
".",
"getList",
"(",
")",
":",
"depthSumInverseHelper",
"(",
"l",
",",
"depth",
"+",
"1",
",",
"result",
")",
"result",
"=",
"[",
"]",
"for",
"list",
"in",
"nestedList",
":",
"depthSumInverseHelper",
"(",
"list",
",",
"0",
",",
"result",
")",
"sum",
"=",
"0",
"for",
"i",
"in",
"reversed",
"(",
"xrange",
"(",
"len",
"(",
"result",
")",
")",
")",
":",
"sum",
"+=",
"result",
"[",
"i",
"]",
"*",
"(",
"len",
"(",
"result",
")",
"-",
"i",
")",
"return",
"sum"
] | https://github.com/kamyu104/LeetCode-Solutions/blob/77605708a927ea3b85aee5a479db733938c7c211/Python/nested-list-weight-sum-ii.py#L5-L26 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/x86/toolchain/lib/python2.7/plat-mac/lib-scriptpackages/_builtinSuites/builtin_Suite.py | python | builtin_Suite_Events.open | (self, _object, _attributes={}, **_arguments) | open: Open the specified object(s)
Required argument: list of objects to open
Keyword argument _attributes: AppleEvent attribute dictionary | open: Open the specified object(s)
Required argument: list of objects to open
Keyword argument _attributes: AppleEvent attribute dictionary | [
"open",
":",
"Open",
"the",
"specified",
"object",
"(",
"s",
")",
"Required",
"argument",
":",
"list",
"of",
"objects",
"to",
"open",
"Keyword",
"argument",
"_attributes",
":",
"AppleEvent",
"attribute",
"dictionary"
] | def open(self, _object, _attributes={}, **_arguments):
"""open: Open the specified object(s)
Required argument: list of objects to open
Keyword argument _attributes: AppleEvent attribute dictionary
"""
_code = 'aevt'
_subcode = 'odoc'
if _arguments: raise TypeError, 'No optional args expected'
_arguments['----'] = _object
_reply, _arguments, _attributes = self.send(_code, _subcode,
_arguments, _attributes)
if _arguments.get('errn', 0):
raise aetools.Error, aetools.decodeerror(_arguments)
# XXXX Optionally decode result
if _arguments.has_key('----'):
return _arguments['----'] | [
"def",
"open",
"(",
"self",
",",
"_object",
",",
"_attributes",
"=",
"{",
"}",
",",
"*",
"*",
"_arguments",
")",
":",
"_code",
"=",
"'aevt'",
"_subcode",
"=",
"'odoc'",
"if",
"_arguments",
":",
"raise",
"TypeError",
",",
"'No optional args expected'",
"_arguments",
"[",
"'----'",
"]",
"=",
"_object",
"_reply",
",",
"_arguments",
",",
"_attributes",
"=",
"self",
".",
"send",
"(",
"_code",
",",
"_subcode",
",",
"_arguments",
",",
"_attributes",
")",
"if",
"_arguments",
".",
"get",
"(",
"'errn'",
",",
"0",
")",
":",
"raise",
"aetools",
".",
"Error",
",",
"aetools",
".",
"decodeerror",
"(",
"_arguments",
")",
"# XXXX Optionally decode result",
"if",
"_arguments",
".",
"has_key",
"(",
"'----'",
")",
":",
"return",
"_arguments",
"[",
"'----'",
"]"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/plat-mac/lib-scriptpackages/_builtinSuites/builtin_Suite.py#L12-L30 | ||
FreeCAD/FreeCAD | ba42231b9c6889b89e064d6d563448ed81e376ec | src/Mod/TemplatePyMod/FeaturePython.py | python | ViewProviderMolecule.__init__ | (self, obj) | Set this object to the proxy object of the actual view provider | Set this object to the proxy object of the actual view provider | [
"Set",
"this",
"object",
"to",
"the",
"proxy",
"object",
"of",
"the",
"actual",
"view",
"provider"
] | def __init__(self, obj):
''' Set this object to the proxy object of the actual view provider '''
sep1=coin.SoSeparator()
self.trl1=coin.SoTranslation()
sep1.addChild(self.trl1)
sep1.addChild(coin.SoSphere())
sep2=coin.SoSeparator()
self.trl2=coin.SoTranslation()
sep2.addChild(self.trl2)
sep2.addChild(coin.SoSphere())
obj.RootNode.addChild(sep1)
obj.RootNode.addChild(sep2)
# triggers an updateData call so the the assignment at the end
obj.Proxy = self | [
"def",
"__init__",
"(",
"self",
",",
"obj",
")",
":",
"sep1",
"=",
"coin",
".",
"SoSeparator",
"(",
")",
"self",
".",
"trl1",
"=",
"coin",
".",
"SoTranslation",
"(",
")",
"sep1",
".",
"addChild",
"(",
"self",
".",
"trl1",
")",
"sep1",
".",
"addChild",
"(",
"coin",
".",
"SoSphere",
"(",
")",
")",
"sep2",
"=",
"coin",
".",
"SoSeparator",
"(",
")",
"self",
".",
"trl2",
"=",
"coin",
".",
"SoTranslation",
"(",
")",
"sep2",
".",
"addChild",
"(",
"self",
".",
"trl2",
")",
"sep2",
".",
"addChild",
"(",
"coin",
".",
"SoSphere",
"(",
")",
")",
"obj",
".",
"RootNode",
".",
"addChild",
"(",
"sep1",
")",
"obj",
".",
"RootNode",
".",
"addChild",
"(",
"sep2",
")",
"# triggers an updateData call so the the assignment at the end",
"obj",
".",
"Proxy",
"=",
"self"
] | https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/TemplatePyMod/FeaturePython.py#L538-L551 | ||
ideawu/ssdb | f229ba277c7f7d0ca5a441c0c6fb3d1209af68e4 | deps/cpy/antlr3/tree.py | python | TreeAdaptor.rulePostProcessing | (self, root) | Given the root of the subtree created for this rule, post process
it to do any simplifications or whatever you want. A required
behavior is to convert ^(nil singleSubtree) to singleSubtree
as the setting of start/stop indexes relies on a single non-nil root
for non-flat trees.
Flat trees such as for lists like "idlist : ID+ ;" are left alone
unless there is only one ID. For a list, the start/stop indexes
are set in the nil node.
This method is executed after all rule tree construction and right
before setTokenBoundaries(). | Given the root of the subtree created for this rule, post process
it to do any simplifications or whatever you want. A required
behavior is to convert ^(nil singleSubtree) to singleSubtree
as the setting of start/stop indexes relies on a single non-nil root
for non-flat trees. | [
"Given",
"the",
"root",
"of",
"the",
"subtree",
"created",
"for",
"this",
"rule",
"post",
"process",
"it",
"to",
"do",
"any",
"simplifications",
"or",
"whatever",
"you",
"want",
".",
"A",
"required",
"behavior",
"is",
"to",
"convert",
"^",
"(",
"nil",
"singleSubtree",
")",
"to",
"singleSubtree",
"as",
"the",
"setting",
"of",
"start",
"/",
"stop",
"indexes",
"relies",
"on",
"a",
"single",
"non",
"-",
"nil",
"root",
"for",
"non",
"-",
"flat",
"trees",
"."
] | def rulePostProcessing(self, root):
"""
Given the root of the subtree created for this rule, post process
it to do any simplifications or whatever you want. A required
behavior is to convert ^(nil singleSubtree) to singleSubtree
as the setting of start/stop indexes relies on a single non-nil root
for non-flat trees.
Flat trees such as for lists like "idlist : ID+ ;" are left alone
unless there is only one ID. For a list, the start/stop indexes
are set in the nil node.
This method is executed after all rule tree construction and right
before setTokenBoundaries().
"""
raise NotImplementedError | [
"def",
"rulePostProcessing",
"(",
"self",
",",
"root",
")",
":",
"raise",
"NotImplementedError"
] | https://github.com/ideawu/ssdb/blob/f229ba277c7f7d0ca5a441c0c6fb3d1209af68e4/deps/cpy/antlr3/tree.py#L371-L387 | ||
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/third_party/gsutil/gslib/boto_translation.py | python | BotoTranslation.UploadObject | (self, upload_stream, object_metadata, canned_acl=None,
preconditions=None, size=None, progress_callback=None,
provider=None, fields=None) | See CloudApi class for function doc strings. | See CloudApi class for function doc strings. | [
"See",
"CloudApi",
"class",
"for",
"function",
"doc",
"strings",
"."
] | def UploadObject(self, upload_stream, object_metadata, canned_acl=None,
preconditions=None, size=None, progress_callback=None,
provider=None, fields=None):
"""See CloudApi class for function doc strings."""
headers, dst_uri = self._UploadSetup(object_metadata,
preconditions=preconditions)
try:
md5 = None
if object_metadata.md5Hash:
md5 = []
# boto expects hex at index 0, base64 at index 1
md5.append(Base64ToHexHash(object_metadata.md5Hash))
md5.append(object_metadata.md5Hash.strip('\n"\''))
self._PerformSimpleUpload(dst_uri, upload_stream, md5=md5,
canned_acl=canned_acl,
progress_callback=progress_callback,
headers=headers)
return self._HandleSuccessfulUpload(dst_uri, object_metadata,
fields=fields)
except TRANSLATABLE_BOTO_EXCEPTIONS, e:
not_found_exception = CreateNotFoundExceptionForObjectWrite(
self.provider, object_metadata.bucket)
self._TranslateExceptionAndRaise(e, bucket_name=object_metadata.bucket,
object_name=object_metadata.name,
not_found_exception=not_found_exception) | [
"def",
"UploadObject",
"(",
"self",
",",
"upload_stream",
",",
"object_metadata",
",",
"canned_acl",
"=",
"None",
",",
"preconditions",
"=",
"None",
",",
"size",
"=",
"None",
",",
"progress_callback",
"=",
"None",
",",
"provider",
"=",
"None",
",",
"fields",
"=",
"None",
")",
":",
"headers",
",",
"dst_uri",
"=",
"self",
".",
"_UploadSetup",
"(",
"object_metadata",
",",
"preconditions",
"=",
"preconditions",
")",
"try",
":",
"md5",
"=",
"None",
"if",
"object_metadata",
".",
"md5Hash",
":",
"md5",
"=",
"[",
"]",
"# boto expects hex at index 0, base64 at index 1",
"md5",
".",
"append",
"(",
"Base64ToHexHash",
"(",
"object_metadata",
".",
"md5Hash",
")",
")",
"md5",
".",
"append",
"(",
"object_metadata",
".",
"md5Hash",
".",
"strip",
"(",
"'\\n\"\\''",
")",
")",
"self",
".",
"_PerformSimpleUpload",
"(",
"dst_uri",
",",
"upload_stream",
",",
"md5",
"=",
"md5",
",",
"canned_acl",
"=",
"canned_acl",
",",
"progress_callback",
"=",
"progress_callback",
",",
"headers",
"=",
"headers",
")",
"return",
"self",
".",
"_HandleSuccessfulUpload",
"(",
"dst_uri",
",",
"object_metadata",
",",
"fields",
"=",
"fields",
")",
"except",
"TRANSLATABLE_BOTO_EXCEPTIONS",
",",
"e",
":",
"not_found_exception",
"=",
"CreateNotFoundExceptionForObjectWrite",
"(",
"self",
".",
"provider",
",",
"object_metadata",
".",
"bucket",
")",
"self",
".",
"_TranslateExceptionAndRaise",
"(",
"e",
",",
"bucket_name",
"=",
"object_metadata",
".",
"bucket",
",",
"object_name",
"=",
"object_metadata",
".",
"name",
",",
"not_found_exception",
"=",
"not_found_exception",
")"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/gslib/boto_translation.py#L866-L891 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/pandas/py2/pandas/tseries/holiday.py | python | before_nearest_workday | (dt) | return previous_workday(nearest_workday(dt)) | returns previous workday after nearest workday | returns previous workday after nearest workday | [
"returns",
"previous",
"workday",
"after",
"nearest",
"workday"
] | def before_nearest_workday(dt):
"""
returns previous workday after nearest workday
"""
return previous_workday(nearest_workday(dt)) | [
"def",
"before_nearest_workday",
"(",
"dt",
")",
":",
"return",
"previous_workday",
"(",
"nearest_workday",
"(",
"dt",
")",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py2/pandas/tseries/holiday.py#L109-L113 | |
neopenx/Dragon | 0e639a7319035ddc81918bd3df059230436ee0a1 | Dragon/python/dragon/vm/theano/tensor/basic.py | python | clip | (x, min=None, max=None) | return ops.Clip(x, low=min, high=max) | Clip the input to be between min and max.
Parameters
----------
x : Tensor
The input tensor.
min : basic numerical type or None
The min bound. Default is ``None`` (Ignore).
max : basic numerical type or None
The max bound. Default is ``None`` (Ignore).
Returns
-------
Tensor
The clip result. | Clip the input to be between min and max. | [
"Clip",
"the",
"input",
"to",
"be",
"between",
"min",
"and",
"max",
"."
] | def clip(x, min=None, max=None):
"""Clip the input to be between min and max.
Parameters
----------
x : Tensor
The input tensor.
min : basic numerical type or None
The min bound. Default is ``None`` (Ignore).
max : basic numerical type or None
The max bound. Default is ``None`` (Ignore).
Returns
-------
Tensor
The clip result.
"""
return ops.Clip(x, low=min, high=max) | [
"def",
"clip",
"(",
"x",
",",
"min",
"=",
"None",
",",
"max",
"=",
"None",
")",
":",
"return",
"ops",
".",
"Clip",
"(",
"x",
",",
"low",
"=",
"min",
",",
"high",
"=",
"max",
")"
] | https://github.com/neopenx/Dragon/blob/0e639a7319035ddc81918bd3df059230436ee0a1/Dragon/python/dragon/vm/theano/tensor/basic.py#L473-L491 | |
telefonicaid/fiware-orion | 27c3202b9ddcfb9e3635a0af8d373f76e89b1d24 | scripts/cpplint.py | python | _CppLintState.SetVerboseLevel | (self, level) | return last_verbose_level | Sets the module's verbosity, and returns the previous setting. | Sets the module's verbosity, and returns the previous setting. | [
"Sets",
"the",
"module",
"s",
"verbosity",
"and",
"returns",
"the",
"previous",
"setting",
"."
] | def SetVerboseLevel(self, level):
"""Sets the module's verbosity, and returns the previous setting."""
last_verbose_level = self.verbose_level
self.verbose_level = level
return last_verbose_level | [
"def",
"SetVerboseLevel",
"(",
"self",
",",
"level",
")",
":",
"last_verbose_level",
"=",
"self",
".",
"verbose_level",
"self",
".",
"verbose_level",
"=",
"level",
"return",
"last_verbose_level"
] | https://github.com/telefonicaid/fiware-orion/blob/27c3202b9ddcfb9e3635a0af8d373f76e89b1d24/scripts/cpplint.py#L511-L515 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/third_party/gsutil/third_party/boto/boto/sqs/queue.py | python | Queue.purge | (self) | return self.connection.purge_queue(self) | Purge all messages in the queue. | Purge all messages in the queue. | [
"Purge",
"all",
"messages",
"in",
"the",
"queue",
"."
] | def purge(self):
"""
Purge all messages in the queue.
"""
return self.connection.purge_queue(self) | [
"def",
"purge",
"(",
"self",
")",
":",
"return",
"self",
".",
"connection",
".",
"purge_queue",
"(",
"self",
")"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/third_party/boto/boto/sqs/queue.py#L343-L347 | |
pmq20/node-packer | 12c46c6e44fbc14d9ee645ebd17d5296b324f7e0 | lts/tools/gyp/pylib/gyp/xcodeproj_file.py | python | XCObject.Print | (self, file=sys.stdout) | Prints a reprentation of this object to file, adhering to Xcode output
formatting. | Prints a reprentation of this object to file, adhering to Xcode output
formatting. | [
"Prints",
"a",
"reprentation",
"of",
"this",
"object",
"to",
"file",
"adhering",
"to",
"Xcode",
"output",
"formatting",
"."
] | def Print(self, file=sys.stdout):
"""Prints a reprentation of this object to file, adhering to Xcode output
formatting.
"""
self.VerifyHasRequiredProperties()
if self._should_print_single_line:
# When printing an object in a single line, Xcode doesn't put any space
# between the beginning of a dictionary (or presumably a list) and the
# first contained item, so you wind up with snippets like
# ...CDEF = {isa = PBXFileReference; fileRef = 0123...
# If it were me, I would have put a space in there after the opening
# curly, but I guess this is just another one of those inconsistencies
# between how Xcode prints PBXFileReference and PBXBuildFile objects as
# compared to other objects. Mimic Xcode's behavior here by using an
# empty string for sep.
sep = ''
end_tabs = 0
else:
sep = '\n'
end_tabs = 2
# Start the object. For example, '\t\tPBXProject = {\n'.
self._XCPrint(file, 2, self._XCPrintableValue(2, self) + ' = {' + sep)
# "isa" isn't in the _properties dictionary, it's an intrinsic property
# of the class which the object belongs to. Xcode always outputs "isa"
# as the first element of an object dictionary.
self._XCKVPrint(file, 3, 'isa', self.__class__.__name__)
# The remaining elements of an object dictionary are sorted alphabetically.
for property, value in sorted(self._properties.items()):
self._XCKVPrint(file, 3, property, value)
# End the object.
self._XCPrint(file, end_tabs, '};\n') | [
"def",
"Print",
"(",
"self",
",",
"file",
"=",
"sys",
".",
"stdout",
")",
":",
"self",
".",
"VerifyHasRequiredProperties",
"(",
")",
"if",
"self",
".",
"_should_print_single_line",
":",
"# When printing an object in a single line, Xcode doesn't put any space",
"# between the beginning of a dictionary (or presumably a list) and the",
"# first contained item, so you wind up with snippets like",
"# ...CDEF = {isa = PBXFileReference; fileRef = 0123...",
"# If it were me, I would have put a space in there after the opening",
"# curly, but I guess this is just another one of those inconsistencies",
"# between how Xcode prints PBXFileReference and PBXBuildFile objects as",
"# compared to other objects. Mimic Xcode's behavior here by using an",
"# empty string for sep.",
"sep",
"=",
"''",
"end_tabs",
"=",
"0",
"else",
":",
"sep",
"=",
"'\\n'",
"end_tabs",
"=",
"2",
"# Start the object. For example, '\\t\\tPBXProject = {\\n'.",
"self",
".",
"_XCPrint",
"(",
"file",
",",
"2",
",",
"self",
".",
"_XCPrintableValue",
"(",
"2",
",",
"self",
")",
"+",
"' = {'",
"+",
"sep",
")",
"# \"isa\" isn't in the _properties dictionary, it's an intrinsic property",
"# of the class which the object belongs to. Xcode always outputs \"isa\"",
"# as the first element of an object dictionary.",
"self",
".",
"_XCKVPrint",
"(",
"file",
",",
"3",
",",
"'isa'",
",",
"self",
".",
"__class__",
".",
"__name__",
")",
"# The remaining elements of an object dictionary are sorted alphabetically.",
"for",
"property",
",",
"value",
"in",
"sorted",
"(",
"self",
".",
"_properties",
".",
"items",
"(",
")",
")",
":",
"self",
".",
"_XCKVPrint",
"(",
"file",
",",
"3",
",",
"property",
",",
"value",
")",
"# End the object.",
"self",
".",
"_XCPrint",
"(",
"file",
",",
"end_tabs",
",",
"'};\\n'",
")"
] | https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/lts/tools/gyp/pylib/gyp/xcodeproj_file.py#L697-L733 | ||
NREL/EnergyPlus | fadc5973b85c70e8cc923efb69c144e808a26078 | src/EnergyPlus/api/func.py | python | Psychrometrics.humidity_ratio_d | (self, state: c_void_p, dry_bulb_temp: float, wet_bulb_temp: float, barometric_pressure: float) | return self.api.psyWFnTdbTwbPb(state, dry_bulb_temp, wet_bulb_temp, barometric_pressure) | Returns the psychrometric humidity ratio at the specified conditions.
:param state: An active EnergyPlus "state" that is returned from a call to `api.state_manager.new_state()`.
:param dry_bulb_temp: Psychrometric dry bulb temperature, in C
:param wet_bulb_temp: Psychrometric wet bulb temperature, in C
:param barometric_pressure: Barometric pressure, in Pa
:return: | Returns the psychrometric humidity ratio at the specified conditions. | [
"Returns",
"the",
"psychrometric",
"humidity",
"ratio",
"at",
"the",
"specified",
"conditions",
"."
] | def humidity_ratio_d(self, state: c_void_p, dry_bulb_temp: float, wet_bulb_temp: float, barometric_pressure: float) -> float:
"""
Returns the psychrometric humidity ratio at the specified conditions.
:param state: An active EnergyPlus "state" that is returned from a call to `api.state_manager.new_state()`.
:param dry_bulb_temp: Psychrometric dry bulb temperature, in C
:param wet_bulb_temp: Psychrometric wet bulb temperature, in C
:param barometric_pressure: Barometric pressure, in Pa
:return:
"""
return self.api.psyWFnTdbTwbPb(state, dry_bulb_temp, wet_bulb_temp, barometric_pressure) | [
"def",
"humidity_ratio_d",
"(",
"self",
",",
"state",
":",
"c_void_p",
",",
"dry_bulb_temp",
":",
"float",
",",
"wet_bulb_temp",
":",
"float",
",",
"barometric_pressure",
":",
"float",
")",
"->",
"float",
":",
"return",
"self",
".",
"api",
".",
"psyWFnTdbTwbPb",
"(",
"state",
",",
"dry_bulb_temp",
",",
"wet_bulb_temp",
",",
"barometric_pressure",
")"
] | https://github.com/NREL/EnergyPlus/blob/fadc5973b85c70e8cc923efb69c144e808a26078/src/EnergyPlus/api/func.py#L515-L525 | |
sigmaai/self-driving-golf-cart | 8d891600af3d851add27a10ae45cf3c2108bb87c | ros/src/segmentation/scripts/BirdsEyeView.py | python | BevParams.convert_position_pixel2metric | (self, YXpointArrays) | return np.array(
np.append(allYconverted.reshape((len(allYconverted), 1)), allXconverted.reshape((len(allXconverted), 1)),
axis=1)) | :param YXpointArrays:
:return: | [] | def convert_position_pixel2metric(self, YXpointArrays):
"""
:param YXpointArrays:
:return:
"""
allY = YXpointArrays[:, 0]
allX = YXpointArrays[:, 1]
allYconverted = self.px2meter(self.bev_size[0] - allY) + self.bev_zLimits[0]
allXconverted = self.px2meter(allX) + self.bev_xLimits[0]
return np.array(
np.append(allYconverted.reshape((len(allYconverted), 1)), allXconverted.reshape((len(allXconverted), 1)),
axis=1)) | [
"def",
"convert_position_pixel2metric",
"(",
"self",
",",
"YXpointArrays",
")",
":",
"allY",
"=",
"YXpointArrays",
"[",
":",
",",
"0",
"]",
"allX",
"=",
"YXpointArrays",
"[",
":",
",",
"1",
"]",
"allYconverted",
"=",
"self",
".",
"px2meter",
"(",
"self",
".",
"bev_size",
"[",
"0",
"]",
"-",
"allY",
")",
"+",
"self",
".",
"bev_zLimits",
"[",
"0",
"]",
"allXconverted",
"=",
"self",
".",
"px2meter",
"(",
"allX",
")",
"+",
"self",
".",
"bev_xLimits",
"[",
"0",
"]",
"return",
"np",
".",
"array",
"(",
"np",
".",
"append",
"(",
"allYconverted",
".",
"reshape",
"(",
"(",
"len",
"(",
"allYconverted",
")",
",",
"1",
")",
")",
",",
"allXconverted",
".",
"reshape",
"(",
"(",
"len",
"(",
"allXconverted",
")",
",",
"1",
")",
")",
",",
"axis",
"=",
"1",
")",
")"
] | https://github.com/sigmaai/self-driving-golf-cart/blob/8d891600af3d851add27a10ae45cf3c2108bb87c/ros/src/segmentation/scripts/BirdsEyeView.py#L77-L89 | ||
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/lib-tk/Tix.py | python | Grid.anchor_get | (self) | return self._getints(self.tk.call(self, 'anchor', 'get')) | Get the (x,y) coordinate of the current anchor cell | Get the (x,y) coordinate of the current anchor cell | [
"Get",
"the",
"(",
"x",
"y",
")",
"coordinate",
"of",
"the",
"current",
"anchor",
"cell"
] | def anchor_get(self):
"Get the (x,y) coordinate of the current anchor cell"
return self._getints(self.tk.call(self, 'anchor', 'get')) | [
"def",
"anchor_get",
"(",
"self",
")",
":",
"return",
"self",
".",
"_getints",
"(",
"self",
".",
"tk",
".",
"call",
"(",
"self",
",",
"'anchor'",
",",
"'get'",
")",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/lib-tk/Tix.py#L1822-L1824 | |
hfinkel/llvm-project-cxxjit | 91084ef018240bbb8e24235ff5cd8c355a9c1a1e | llvm/utils/docker/scripts/llvm_checksum/project_tree.py | python | WalkProjectFiles | (checkout_root, all_projects, project, visitor) | Walk over all files inside a project without recursing into subprojects, '.git' and '.svn' subfolders.
checkout_root: root of the LLVM checkout.
all_projects: projects in the LLVM checkout.
project: a project to walk the files of. Must be inside all_projects.
visitor: a function called on each visited file. | Walk over all files inside a project without recursing into subprojects, '.git' and '.svn' subfolders. | [
"Walk",
"over",
"all",
"files",
"inside",
"a",
"project",
"without",
"recursing",
"into",
"subprojects",
".",
"git",
"and",
".",
"svn",
"subfolders",
"."
] | def WalkProjectFiles(checkout_root, all_projects, project, visitor):
""" Walk over all files inside a project without recursing into subprojects, '.git' and '.svn' subfolders.
checkout_root: root of the LLVM checkout.
all_projects: projects in the LLVM checkout.
project: a project to walk the files of. Must be inside all_projects.
visitor: a function called on each visited file.
"""
assert project in all_projects
ignored_paths = set()
for other_project in all_projects:
if other_project != project and other_project.is_subproject(project):
ignored_paths.add(os.path.join(checkout_root, other_project.relpath))
def raise_error(err):
raise err
project_root = os.path.join(checkout_root, project.relpath)
for root, dirs, files in os.walk(project_root, onerror=raise_error):
dirs[:] = [
d for d in dirs
if d != ".svn" and d != ".git" and
os.path.join(root, d) not in ignored_paths
]
for f in files:
visitor(os.path.join(root, f)) | [
"def",
"WalkProjectFiles",
"(",
"checkout_root",
",",
"all_projects",
",",
"project",
",",
"visitor",
")",
":",
"assert",
"project",
"in",
"all_projects",
"ignored_paths",
"=",
"set",
"(",
")",
"for",
"other_project",
"in",
"all_projects",
":",
"if",
"other_project",
"!=",
"project",
"and",
"other_project",
".",
"is_subproject",
"(",
"project",
")",
":",
"ignored_paths",
".",
"add",
"(",
"os",
".",
"path",
".",
"join",
"(",
"checkout_root",
",",
"other_project",
".",
"relpath",
")",
")",
"def",
"raise_error",
"(",
"err",
")",
":",
"raise",
"err",
"project_root",
"=",
"os",
".",
"path",
".",
"join",
"(",
"checkout_root",
",",
"project",
".",
"relpath",
")",
"for",
"root",
",",
"dirs",
",",
"files",
"in",
"os",
".",
"walk",
"(",
"project_root",
",",
"onerror",
"=",
"raise_error",
")",
":",
"dirs",
"[",
":",
"]",
"=",
"[",
"d",
"for",
"d",
"in",
"dirs",
"if",
"d",
"!=",
"\".svn\"",
"and",
"d",
"!=",
"\".git\"",
"and",
"os",
".",
"path",
".",
"join",
"(",
"root",
",",
"d",
")",
"not",
"in",
"ignored_paths",
"]",
"for",
"f",
"in",
"files",
":",
"visitor",
"(",
"os",
".",
"path",
".",
"join",
"(",
"root",
",",
"f",
")",
")"
] | https://github.com/hfinkel/llvm-project-cxxjit/blob/91084ef018240bbb8e24235ff5cd8c355a9c1a1e/llvm/utils/docker/scripts/llvm_checksum/project_tree.py#L27-L53 | ||
kamyu104/LeetCode-Solutions | 77605708a927ea3b85aee5a479db733938c7c211 | Python/incremental-memory-leak.py | python | Solution.memLeak | (self, memory1, memory2) | return [n+l+r+1, memory1, memory2] | :type memory1: int
:type memory2: int
:rtype: List[int] | :type memory1: int
:type memory2: int
:rtype: List[int] | [
":",
"type",
"memory1",
":",
"int",
":",
"type",
"memory2",
":",
"int",
":",
"rtype",
":",
"List",
"[",
"int",
"]"
] | def memLeak(self, memory1, memory2):
"""
:type memory1: int
:type memory2: int
:rtype: List[int]
"""
def s(a, d, n):
return (2*a + (n-1)*d)*n//2
def f(a, d, x):
r = int((-(2*a-d)+((2*a-d)**2+8*d*x)**0.5)/(2*d))
if s(a, d, r) > x: # adjust float accuracy
r -= 1
return r
is_swapped = False
if memory1 < memory2:
memory1, memory2 = memory2, memory1
is_swapped = True
n = f(1, 1, memory1-memory2)
memory1 -= s(1, 1, n)
if memory1 == memory2:
is_swapped = False
l = f(n+1, 2, memory1)
r = f(n+2, 2, memory2)
memory1 -= s(n+1, 2, l)
memory2 -= s(n+2, 2, r)
if is_swapped:
memory1, memory2 = memory2, memory1
return [n+l+r+1, memory1, memory2] | [
"def",
"memLeak",
"(",
"self",
",",
"memory1",
",",
"memory2",
")",
":",
"def",
"s",
"(",
"a",
",",
"d",
",",
"n",
")",
":",
"return",
"(",
"2",
"*",
"a",
"+",
"(",
"n",
"-",
"1",
")",
"*",
"d",
")",
"*",
"n",
"//",
"2",
"def",
"f",
"(",
"a",
",",
"d",
",",
"x",
")",
":",
"r",
"=",
"int",
"(",
"(",
"-",
"(",
"2",
"*",
"a",
"-",
"d",
")",
"+",
"(",
"(",
"2",
"*",
"a",
"-",
"d",
")",
"**",
"2",
"+",
"8",
"*",
"d",
"*",
"x",
")",
"**",
"0.5",
")",
"/",
"(",
"2",
"*",
"d",
")",
")",
"if",
"s",
"(",
"a",
",",
"d",
",",
"r",
")",
">",
"x",
":",
"# adjust float accuracy",
"r",
"-=",
"1",
"return",
"r",
"is_swapped",
"=",
"False",
"if",
"memory1",
"<",
"memory2",
":",
"memory1",
",",
"memory2",
"=",
"memory2",
",",
"memory1",
"is_swapped",
"=",
"True",
"n",
"=",
"f",
"(",
"1",
",",
"1",
",",
"memory1",
"-",
"memory2",
")",
"memory1",
"-=",
"s",
"(",
"1",
",",
"1",
",",
"n",
")",
"if",
"memory1",
"==",
"memory2",
":",
"is_swapped",
"=",
"False",
"l",
"=",
"f",
"(",
"n",
"+",
"1",
",",
"2",
",",
"memory1",
")",
"r",
"=",
"f",
"(",
"n",
"+",
"2",
",",
"2",
",",
"memory2",
")",
"memory1",
"-=",
"s",
"(",
"n",
"+",
"1",
",",
"2",
",",
"l",
")",
"memory2",
"-=",
"s",
"(",
"n",
"+",
"2",
",",
"2",
",",
"r",
")",
"if",
"is_swapped",
":",
"memory1",
",",
"memory2",
"=",
"memory2",
",",
"memory1",
"return",
"[",
"n",
"+",
"l",
"+",
"r",
"+",
"1",
",",
"memory1",
",",
"memory2",
"]"
] | https://github.com/kamyu104/LeetCode-Solutions/blob/77605708a927ea3b85aee5a479db733938c7c211/Python/incremental-memory-leak.py#L6-L35 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/x86/toolchain/lib/python2.7/lib-tk/turtle.py | python | _Screen.bye | (self) | Shut the turtlegraphics window.
Example (for a TurtleScreen instance named screen):
>>> screen.bye() | Shut the turtlegraphics window. | [
"Shut",
"the",
"turtlegraphics",
"window",
"."
] | def bye(self):
"""Shut the turtlegraphics window.
Example (for a TurtleScreen instance named screen):
>>> screen.bye()
"""
self._destroy() | [
"def",
"bye",
"(",
"self",
")",
":",
"self",
".",
"_destroy",
"(",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/lib-tk/turtle.py#L3650-L3656 | ||
amd/OpenCL-caffe | 638543108517265366c18ae5821f3096cf5cf34a | scripts/cpp_lint.py | python | CheckCheck | (filename, clean_lines, linenum, error) | Checks the use of CHECK and EXPECT macros.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found. | Checks the use of CHECK and EXPECT macros. | [
"Checks",
"the",
"use",
"of",
"CHECK",
"and",
"EXPECT",
"macros",
"."
] | def CheckCheck(filename, clean_lines, linenum, error):
"""Checks the use of CHECK and EXPECT macros.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found.
"""
# Decide the set of replacement macros that should be suggested
lines = clean_lines.elided
check_macro = None
start_pos = -1
for macro in _CHECK_MACROS:
i = lines[linenum].find(macro)
if i >= 0:
check_macro = macro
# Find opening parenthesis. Do a regular expression match here
# to make sure that we are matching the expected CHECK macro, as
# opposed to some other macro that happens to contain the CHECK
# substring.
matched = Match(r'^(.*\b' + check_macro + r'\s*)\(', lines[linenum])
if not matched:
continue
start_pos = len(matched.group(1))
break
if not check_macro or start_pos < 0:
# Don't waste time here if line doesn't contain 'CHECK' or 'EXPECT'
return
# Find end of the boolean expression by matching parentheses
(last_line, end_line, end_pos) = CloseExpression(
clean_lines, linenum, start_pos)
if end_pos < 0:
return
if linenum == end_line:
expression = lines[linenum][start_pos + 1:end_pos - 1]
else:
expression = lines[linenum][start_pos + 1:]
for i in xrange(linenum + 1, end_line):
expression += lines[i]
expression += last_line[0:end_pos - 1]
# Parse expression so that we can take parentheses into account.
# This avoids false positives for inputs like "CHECK((a < 4) == b)",
# which is not replaceable by CHECK_LE.
lhs = ''
rhs = ''
operator = None
while expression:
matched = Match(r'^\s*(<<|<<=|>>|>>=|->\*|->|&&|\|\||'
r'==|!=|>=|>|<=|<|\()(.*)$', expression)
if matched:
token = matched.group(1)
if token == '(':
# Parenthesized operand
expression = matched.group(2)
(end, _) = FindEndOfExpressionInLine(expression, 0, 1, '(', ')')
if end < 0:
return # Unmatched parenthesis
lhs += '(' + expression[0:end]
expression = expression[end:]
elif token in ('&&', '||'):
# Logical and/or operators. This means the expression
# contains more than one term, for example:
# CHECK(42 < a && a < b);
#
# These are not replaceable with CHECK_LE, so bail out early.
return
elif token in ('<<', '<<=', '>>', '>>=', '->*', '->'):
# Non-relational operator
lhs += token
expression = matched.group(2)
else:
# Relational operator
operator = token
rhs = matched.group(2)
break
else:
# Unparenthesized operand. Instead of appending to lhs one character
# at a time, we do another regular expression match to consume several
# characters at once if possible. Trivial benchmark shows that this
# is more efficient when the operands are longer than a single
# character, which is generally the case.
matched = Match(r'^([^-=!<>()&|]+)(.*)$', expression)
if not matched:
matched = Match(r'^(\s*\S)(.*)$', expression)
if not matched:
break
lhs += matched.group(1)
expression = matched.group(2)
# Only apply checks if we got all parts of the boolean expression
if not (lhs and operator and rhs):
return
# Check that rhs do not contain logical operators. We already know
# that lhs is fine since the loop above parses out && and ||.
if rhs.find('&&') > -1 or rhs.find('||') > -1:
return
# At least one of the operands must be a constant literal. This is
# to avoid suggesting replacements for unprintable things like
# CHECK(variable != iterator)
#
# The following pattern matches decimal, hex integers, strings, and
# characters (in that order).
lhs = lhs.strip()
rhs = rhs.strip()
match_constant = r'^([-+]?(\d+|0[xX][0-9a-fA-F]+)[lLuU]{0,3}|".*"|\'.*\')$'
if Match(match_constant, lhs) or Match(match_constant, rhs):
# Note: since we know both lhs and rhs, we can provide a more
# descriptive error message like:
# Consider using CHECK_EQ(x, 42) instead of CHECK(x == 42)
# Instead of:
# Consider using CHECK_EQ instead of CHECK(a == b)
#
# We are still keeping the less descriptive message because if lhs
# or rhs gets long, the error message might become unreadable.
error(filename, linenum, 'readability/check', 2,
'Consider using %s instead of %s(a %s b)' % (
_CHECK_REPLACEMENT[check_macro][operator],
check_macro, operator)) | [
"def",
"CheckCheck",
"(",
"filename",
",",
"clean_lines",
",",
"linenum",
",",
"error",
")",
":",
"# Decide the set of replacement macros that should be suggested",
"lines",
"=",
"clean_lines",
".",
"elided",
"check_macro",
"=",
"None",
"start_pos",
"=",
"-",
"1",
"for",
"macro",
"in",
"_CHECK_MACROS",
":",
"i",
"=",
"lines",
"[",
"linenum",
"]",
".",
"find",
"(",
"macro",
")",
"if",
"i",
">=",
"0",
":",
"check_macro",
"=",
"macro",
"# Find opening parenthesis. Do a regular expression match here",
"# to make sure that we are matching the expected CHECK macro, as",
"# opposed to some other macro that happens to contain the CHECK",
"# substring.",
"matched",
"=",
"Match",
"(",
"r'^(.*\\b'",
"+",
"check_macro",
"+",
"r'\\s*)\\('",
",",
"lines",
"[",
"linenum",
"]",
")",
"if",
"not",
"matched",
":",
"continue",
"start_pos",
"=",
"len",
"(",
"matched",
".",
"group",
"(",
"1",
")",
")",
"break",
"if",
"not",
"check_macro",
"or",
"start_pos",
"<",
"0",
":",
"# Don't waste time here if line doesn't contain 'CHECK' or 'EXPECT'",
"return",
"# Find end of the boolean expression by matching parentheses",
"(",
"last_line",
",",
"end_line",
",",
"end_pos",
")",
"=",
"CloseExpression",
"(",
"clean_lines",
",",
"linenum",
",",
"start_pos",
")",
"if",
"end_pos",
"<",
"0",
":",
"return",
"if",
"linenum",
"==",
"end_line",
":",
"expression",
"=",
"lines",
"[",
"linenum",
"]",
"[",
"start_pos",
"+",
"1",
":",
"end_pos",
"-",
"1",
"]",
"else",
":",
"expression",
"=",
"lines",
"[",
"linenum",
"]",
"[",
"start_pos",
"+",
"1",
":",
"]",
"for",
"i",
"in",
"xrange",
"(",
"linenum",
"+",
"1",
",",
"end_line",
")",
":",
"expression",
"+=",
"lines",
"[",
"i",
"]",
"expression",
"+=",
"last_line",
"[",
"0",
":",
"end_pos",
"-",
"1",
"]",
"# Parse expression so that we can take parentheses into account.",
"# This avoids false positives for inputs like \"CHECK((a < 4) == b)\",",
"# which is not replaceable by CHECK_LE.",
"lhs",
"=",
"''",
"rhs",
"=",
"''",
"operator",
"=",
"None",
"while",
"expression",
":",
"matched",
"=",
"Match",
"(",
"r'^\\s*(<<|<<=|>>|>>=|->\\*|->|&&|\\|\\||'",
"r'==|!=|>=|>|<=|<|\\()(.*)$'",
",",
"expression",
")",
"if",
"matched",
":",
"token",
"=",
"matched",
".",
"group",
"(",
"1",
")",
"if",
"token",
"==",
"'('",
":",
"# Parenthesized operand",
"expression",
"=",
"matched",
".",
"group",
"(",
"2",
")",
"(",
"end",
",",
"_",
")",
"=",
"FindEndOfExpressionInLine",
"(",
"expression",
",",
"0",
",",
"1",
",",
"'('",
",",
"')'",
")",
"if",
"end",
"<",
"0",
":",
"return",
"# Unmatched parenthesis",
"lhs",
"+=",
"'('",
"+",
"expression",
"[",
"0",
":",
"end",
"]",
"expression",
"=",
"expression",
"[",
"end",
":",
"]",
"elif",
"token",
"in",
"(",
"'&&'",
",",
"'||'",
")",
":",
"# Logical and/or operators. This means the expression",
"# contains more than one term, for example:",
"# CHECK(42 < a && a < b);",
"#",
"# These are not replaceable with CHECK_LE, so bail out early.",
"return",
"elif",
"token",
"in",
"(",
"'<<'",
",",
"'<<='",
",",
"'>>'",
",",
"'>>='",
",",
"'->*'",
",",
"'->'",
")",
":",
"# Non-relational operator",
"lhs",
"+=",
"token",
"expression",
"=",
"matched",
".",
"group",
"(",
"2",
")",
"else",
":",
"# Relational operator",
"operator",
"=",
"token",
"rhs",
"=",
"matched",
".",
"group",
"(",
"2",
")",
"break",
"else",
":",
"# Unparenthesized operand. Instead of appending to lhs one character",
"# at a time, we do another regular expression match to consume several",
"# characters at once if possible. Trivial benchmark shows that this",
"# is more efficient when the operands are longer than a single",
"# character, which is generally the case.",
"matched",
"=",
"Match",
"(",
"r'^([^-=!<>()&|]+)(.*)$'",
",",
"expression",
")",
"if",
"not",
"matched",
":",
"matched",
"=",
"Match",
"(",
"r'^(\\s*\\S)(.*)$'",
",",
"expression",
")",
"if",
"not",
"matched",
":",
"break",
"lhs",
"+=",
"matched",
".",
"group",
"(",
"1",
")",
"expression",
"=",
"matched",
".",
"group",
"(",
"2",
")",
"# Only apply checks if we got all parts of the boolean expression",
"if",
"not",
"(",
"lhs",
"and",
"operator",
"and",
"rhs",
")",
":",
"return",
"# Check that rhs do not contain logical operators. We already know",
"# that lhs is fine since the loop above parses out && and ||.",
"if",
"rhs",
".",
"find",
"(",
"'&&'",
")",
">",
"-",
"1",
"or",
"rhs",
".",
"find",
"(",
"'||'",
")",
">",
"-",
"1",
":",
"return",
"# At least one of the operands must be a constant literal. This is",
"# to avoid suggesting replacements for unprintable things like",
"# CHECK(variable != iterator)",
"#",
"# The following pattern matches decimal, hex integers, strings, and",
"# characters (in that order).",
"lhs",
"=",
"lhs",
".",
"strip",
"(",
")",
"rhs",
"=",
"rhs",
".",
"strip",
"(",
")",
"match_constant",
"=",
"r'^([-+]?(\\d+|0[xX][0-9a-fA-F]+)[lLuU]{0,3}|\".*\"|\\'.*\\')$'",
"if",
"Match",
"(",
"match_constant",
",",
"lhs",
")",
"or",
"Match",
"(",
"match_constant",
",",
"rhs",
")",
":",
"# Note: since we know both lhs and rhs, we can provide a more",
"# descriptive error message like:",
"# Consider using CHECK_EQ(x, 42) instead of CHECK(x == 42)",
"# Instead of:",
"# Consider using CHECK_EQ instead of CHECK(a == b)",
"#",
"# We are still keeping the less descriptive message because if lhs",
"# or rhs gets long, the error message might become unreadable.",
"error",
"(",
"filename",
",",
"linenum",
",",
"'readability/check'",
",",
"2",
",",
"'Consider using %s instead of %s(a %s b)'",
"%",
"(",
"_CHECK_REPLACEMENT",
"[",
"check_macro",
"]",
"[",
"operator",
"]",
",",
"check_macro",
",",
"operator",
")",
")"
] | https://github.com/amd/OpenCL-caffe/blob/638543108517265366c18ae5821f3096cf5cf34a/scripts/cpp_lint.py#L3278-L3402 | ||
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/lib-tk/Tkinter.py | python | Misc.focus_set | (self) | Direct input focus to this widget.
If the application currently does not have the focus
this widget will get the focus if the application gets
the focus through the window manager. | Direct input focus to this widget. | [
"Direct",
"input",
"focus",
"to",
"this",
"widget",
"."
] | def focus_set(self):
"""Direct input focus to this widget.
If the application currently does not have the focus
this widget will get the focus if the application gets
the focus through the window manager."""
self.tk.call('focus', self._w) | [
"def",
"focus_set",
"(",
"self",
")",
":",
"self",
".",
"tk",
".",
"call",
"(",
"'focus'",
",",
"self",
".",
"_w",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/lib-tk/Tkinter.py#L460-L466 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/core/dtypes/inference.py | python | is_iterator | (obj) | return hasattr(obj, "__next__") | Check if the object is an iterator.
For example, lists are considered iterators
but not strings or datetime objects.
Parameters
----------
obj : The object to check
Returns
-------
is_iter : bool
Whether `obj` is an iterator.
Examples
--------
>>> is_iterator([1, 2, 3])
True
>>> is_iterator(datetime(2017, 1, 1))
False
>>> is_iterator("foo")
False
>>> is_iterator(1)
False | Check if the object is an iterator. | [
"Check",
"if",
"the",
"object",
"is",
"an",
"iterator",
"."
] | def is_iterator(obj) -> bool:
"""
Check if the object is an iterator.
For example, lists are considered iterators
but not strings or datetime objects.
Parameters
----------
obj : The object to check
Returns
-------
is_iter : bool
Whether `obj` is an iterator.
Examples
--------
>>> is_iterator([1, 2, 3])
True
>>> is_iterator(datetime(2017, 1, 1))
False
>>> is_iterator("foo")
False
>>> is_iterator(1)
False
"""
if not hasattr(obj, "__iter__"):
return False
return hasattr(obj, "__next__") | [
"def",
"is_iterator",
"(",
"obj",
")",
"->",
"bool",
":",
"if",
"not",
"hasattr",
"(",
"obj",
",",
"\"__iter__\"",
")",
":",
"return",
"False",
"return",
"hasattr",
"(",
"obj",
",",
"\"__next__\"",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/core/dtypes/inference.py#L96-L127 | |
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/keras/backend.py | python | is_sparse | (tensor) | return isinstance(tensor, sparse_tensor.SparseTensor) | Returns whether a tensor is a sparse tensor.
Args:
tensor: A tensor instance.
Returns:
A boolean.
Example:
>>> a = tf.keras.backend.placeholder((2, 2), sparse=False)
>>> print(tf.keras.backend.is_sparse(a))
False
>>> b = tf.keras.backend.placeholder((2, 2), sparse=True)
>>> print(tf.keras.backend.is_sparse(b))
True | Returns whether a tensor is a sparse tensor. | [
"Returns",
"whether",
"a",
"tensor",
"is",
"a",
"sparse",
"tensor",
"."
] | def is_sparse(tensor):
"""Returns whether a tensor is a sparse tensor.
Args:
tensor: A tensor instance.
Returns:
A boolean.
Example:
>>> a = tf.keras.backend.placeholder((2, 2), sparse=False)
>>> print(tf.keras.backend.is_sparse(a))
False
>>> b = tf.keras.backend.placeholder((2, 2), sparse=True)
>>> print(tf.keras.backend.is_sparse(b))
True
"""
spec = getattr(tensor, '_type_spec', None)
if spec is not None:
return isinstance(spec, sparse_tensor.SparseTensorSpec)
return isinstance(tensor, sparse_tensor.SparseTensor) | [
"def",
"is_sparse",
"(",
"tensor",
")",
":",
"spec",
"=",
"getattr",
"(",
"tensor",
",",
"'_type_spec'",
",",
"None",
")",
"if",
"spec",
"is",
"not",
"None",
":",
"return",
"isinstance",
"(",
"spec",
",",
"sparse_tensor",
".",
"SparseTensorSpec",
")",
"return",
"isinstance",
"(",
"tensor",
",",
"sparse_tensor",
".",
"SparseTensor",
")"
] | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/keras/backend.py#L960-L983 | |
osquery/osquery | fd529718e48348853f708d56990720c3c84c7152 | tools/codegen/gentable.py | python | extended_schema | (check, schema_list) | define a comparator and a list of Columns objects. | define a comparator and a list of Columns objects. | [
"define",
"a",
"comparator",
"and",
"a",
"list",
"of",
"Columns",
"objects",
"."
] | def extended_schema(check, schema_list):
"""
define a comparator and a list of Columns objects.
"""
logging.debug("- extended schema")
for it in schema_list:
if isinstance(it, Column):
logging.debug(" - column: %s (%s)" % (it.name, it.type))
if not check():
it.options['hidden'] = True
table.schema.append(it) | [
"def",
"extended_schema",
"(",
"check",
",",
"schema_list",
")",
":",
"logging",
".",
"debug",
"(",
"\"- extended schema\"",
")",
"for",
"it",
"in",
"schema_list",
":",
"if",
"isinstance",
"(",
"it",
",",
"Column",
")",
":",
"logging",
".",
"debug",
"(",
"\" - column: %s (%s)\"",
"%",
"(",
"it",
".",
"name",
",",
"it",
".",
"type",
")",
")",
"if",
"not",
"check",
"(",
")",
":",
"it",
".",
"options",
"[",
"'hidden'",
"]",
"=",
"True",
"table",
".",
"schema",
".",
"append",
"(",
"it",
")"
] | https://github.com/osquery/osquery/blob/fd529718e48348853f708d56990720c3c84c7152/tools/codegen/gentable.py#L361-L371 | ||
windystrife/UnrealEngine_NVIDIAGameWorks | b50e6338a7c5b26374d66306ebc7807541ff815e | Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/site-packages/pip/vendor/distlib/database.py | python | get_required_dists | (dists, dist) | return req | Recursively generate a list of distributions from *dists* that are
required by *dist*.
:param dists: a list of distributions
:param dist: a distribution, member of *dists* for which we are interested | Recursively generate a list of distributions from *dists* that are
required by *dist*. | [
"Recursively",
"generate",
"a",
"list",
"of",
"distributions",
"from",
"*",
"dists",
"*",
"that",
"are",
"required",
"by",
"*",
"dist",
"*",
"."
] | def get_required_dists(dists, dist):
"""Recursively generate a list of distributions from *dists* that are
required by *dist*.
:param dists: a list of distributions
:param dist: a distribution, member of *dists* for which we are interested
"""
if dist not in dists:
raise DistlibException('given distribution %r is not a member '
'of the list' % dist.name)
graph = make_graph(dists)
req = [] # required distributions
todo = graph.adjacency_list[dist] # list of nodes we should inspect
while todo:
d = todo.pop()[0]
req.append(d)
for pred in graph.adjacency_list[d]:
if pred not in req:
todo.append(pred)
return req | [
"def",
"get_required_dists",
"(",
"dists",
",",
"dist",
")",
":",
"if",
"dist",
"not",
"in",
"dists",
":",
"raise",
"DistlibException",
"(",
"'given distribution %r is not a member '",
"'of the list'",
"%",
"dist",
".",
"name",
")",
"graph",
"=",
"make_graph",
"(",
"dists",
")",
"req",
"=",
"[",
"]",
"# required distributions",
"todo",
"=",
"graph",
".",
"adjacency_list",
"[",
"dist",
"]",
"# list of nodes we should inspect",
"while",
"todo",
":",
"d",
"=",
"todo",
".",
"pop",
"(",
")",
"[",
"0",
"]",
"req",
".",
"append",
"(",
"d",
")",
"for",
"pred",
"in",
"graph",
".",
"adjacency_list",
"[",
"d",
"]",
":",
"if",
"pred",
"not",
"in",
"req",
":",
"todo",
".",
"append",
"(",
"pred",
")",
"return",
"req"
] | https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/site-packages/pip/vendor/distlib/database.py#L1270-L1292 | |
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/ops/ragged/ragged_string_ops.py | python | string_format | (
template: str,
inputs: typing.Union[ragged_tensor.Ragged,
typing.List[ragged_tensor.RaggedOrDense]],
placeholder="{}",
summarize=3,
name=None) | Version of tf.strings.format that handles RaggedTensors. | Version of tf.strings.format that handles RaggedTensors. | [
"Version",
"of",
"tf",
".",
"strings",
".",
"format",
"that",
"handles",
"RaggedTensors",
"."
] | def string_format(
template: str,
inputs: typing.Union[ragged_tensor.Ragged,
typing.List[ragged_tensor.RaggedOrDense]],
placeholder="{}",
summarize=3,
name=None):
"""Version of tf.strings.format that handles RaggedTensors."""
if tensor_util.is_tf_type(inputs) or ragged_tensor.is_ragged(inputs):
inputs = [inputs]
split_template = template.split(placeholder)
if len(inputs) != len(split_template) - 1:
raise ValueError("num placeholders in template and num inputs must match"
": {} vs {}".format(len(split_template) - 1, len(inputs)))
with ops.name_scope(name, "StringFormat", [inputs]):
output_pieces = [constant_op.constant(split_template[0])]
for i, input in enumerate(inputs):
if ragged_tensor.is_ragged(input):
output_pieces.append(ragged_tensor_to_string(input, summarize))
else:
output_pieces.append(string_ops.string_format(
"{}", [input], summarize=summarize))
output_pieces.append(constant_op.constant(split_template[i + 1]))
if len(output_pieces) == 1:
return output_pieces[0]
else:
return string_ops.reduce_join(output_pieces) | [
"def",
"string_format",
"(",
"template",
":",
"str",
",",
"inputs",
":",
"typing",
".",
"Union",
"[",
"ragged_tensor",
".",
"Ragged",
",",
"typing",
".",
"List",
"[",
"ragged_tensor",
".",
"RaggedOrDense",
"]",
"]",
",",
"placeholder",
"=",
"\"{}\"",
",",
"summarize",
"=",
"3",
",",
"name",
"=",
"None",
")",
":",
"if",
"tensor_util",
".",
"is_tf_type",
"(",
"inputs",
")",
"or",
"ragged_tensor",
".",
"is_ragged",
"(",
"inputs",
")",
":",
"inputs",
"=",
"[",
"inputs",
"]",
"split_template",
"=",
"template",
".",
"split",
"(",
"placeholder",
")",
"if",
"len",
"(",
"inputs",
")",
"!=",
"len",
"(",
"split_template",
")",
"-",
"1",
":",
"raise",
"ValueError",
"(",
"\"num placeholders in template and num inputs must match\"",
"\": {} vs {}\"",
".",
"format",
"(",
"len",
"(",
"split_template",
")",
"-",
"1",
",",
"len",
"(",
"inputs",
")",
")",
")",
"with",
"ops",
".",
"name_scope",
"(",
"name",
",",
"\"StringFormat\"",
",",
"[",
"inputs",
"]",
")",
":",
"output_pieces",
"=",
"[",
"constant_op",
".",
"constant",
"(",
"split_template",
"[",
"0",
"]",
")",
"]",
"for",
"i",
",",
"input",
"in",
"enumerate",
"(",
"inputs",
")",
":",
"if",
"ragged_tensor",
".",
"is_ragged",
"(",
"input",
")",
":",
"output_pieces",
".",
"append",
"(",
"ragged_tensor_to_string",
"(",
"input",
",",
"summarize",
")",
")",
"else",
":",
"output_pieces",
".",
"append",
"(",
"string_ops",
".",
"string_format",
"(",
"\"{}\"",
",",
"[",
"input",
"]",
",",
"summarize",
"=",
"summarize",
")",
")",
"output_pieces",
".",
"append",
"(",
"constant_op",
".",
"constant",
"(",
"split_template",
"[",
"i",
"+",
"1",
"]",
")",
")",
"if",
"len",
"(",
"output_pieces",
")",
"==",
"1",
":",
"return",
"output_pieces",
"[",
"0",
"]",
"else",
":",
"return",
"string_ops",
".",
"reduce_join",
"(",
"output_pieces",
")"
] | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/ops/ragged/ragged_string_ops.py#L831-L859 | ||
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/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/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/mhlib.py#L144-L153 | |
adobe/chromium | cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7 | gpu/command_buffer/build_gles2_cmd_buffer.py | python | BoolArgument.GetValidGLArg | (self, func, offset, index) | return 'true' | Gets a valid GL value for this argument. | Gets a valid GL value for this argument. | [
"Gets",
"a",
"valid",
"GL",
"value",
"for",
"this",
"argument",
"."
] | def GetValidGLArg(self, func, offset, index):
"""Gets a valid GL value for this argument."""
return 'true' | [
"def",
"GetValidGLArg",
"(",
"self",
",",
"func",
",",
"offset",
",",
"index",
")",
":",
"return",
"'true'"
] | https://github.com/adobe/chromium/blob/cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7/gpu/command_buffer/build_gles2_cmd_buffer.py#L4656-L4658 | |
yyzybb537/libgo | 4af17b7c67643c4d54aa354dcc77963ea07847d0 | third_party/boost.context/tools/build/src/build/property_set.py | python | PropertySet.incidental | (self) | return self.incidental_ | Returns incidental properties. | Returns incidental properties. | [
"Returns",
"incidental",
"properties",
"."
] | def incidental (self):
""" Returns incidental properties.
"""
return self.incidental_ | [
"def",
"incidental",
"(",
"self",
")",
":",
"return",
"self",
".",
"incidental_"
] | https://github.com/yyzybb537/libgo/blob/4af17b7c67643c4d54aa354dcc77963ea07847d0/third_party/boost.context/tools/build/src/build/property_set.py#L288-L291 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/site-packages/pip/_vendor/html5lib/treewalkers/base.py | python | TreeWalker.startTag | (self, namespace, name, attrs) | return {"type": "StartTag",
"name": name,
"namespace": namespace,
"data": attrs} | Generates a StartTag token
:arg namespace: the namespace of the token--can be ``None``
:arg name: the name of the element
:arg attrs: the attributes of the element as a dict
:returns: StartTag token | Generates a StartTag token | [
"Generates",
"a",
"StartTag",
"token"
] | def startTag(self, namespace, name, attrs):
"""Generates a StartTag token
:arg namespace: the namespace of the token--can be ``None``
:arg name: the name of the element
:arg attrs: the attributes of the element as a dict
:returns: StartTag token
"""
return {"type": "StartTag",
"name": name,
"namespace": namespace,
"data": attrs} | [
"def",
"startTag",
"(",
"self",
",",
"namespace",
",",
"name",
",",
"attrs",
")",
":",
"return",
"{",
"\"type\"",
":",
"\"StartTag\"",
",",
"\"name\"",
":",
"name",
",",
"\"namespace\"",
":",
"namespace",
",",
"\"data\"",
":",
"attrs",
"}"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/pip/_vendor/html5lib/treewalkers/base.py#L69-L84 | |
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/keras/distribute/distributed_training_utils.py | python | is_dataset_shape_fully_defined | (dataset) | return not unknown_shapes | Returns whether a dataset contains a final partial batch. | Returns whether a dataset contains a final partial batch. | [
"Returns",
"whether",
"a",
"dataset",
"contains",
"a",
"final",
"partial",
"batch",
"."
] | def is_dataset_shape_fully_defined(dataset):
"""Returns whether a dataset contains a final partial batch."""
shapes = nest.flatten(dataset_ops.get_legacy_output_shapes(dataset))
unknown_shapes = [s for s in shapes if not s.is_fully_defined()]
return not unknown_shapes | [
"def",
"is_dataset_shape_fully_defined",
"(",
"dataset",
")",
":",
"shapes",
"=",
"nest",
".",
"flatten",
"(",
"dataset_ops",
".",
"get_legacy_output_shapes",
"(",
"dataset",
")",
")",
"unknown_shapes",
"=",
"[",
"s",
"for",
"s",
"in",
"shapes",
"if",
"not",
"s",
".",
"is_fully_defined",
"(",
")",
"]",
"return",
"not",
"unknown_shapes"
] | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/keras/distribute/distributed_training_utils.py#L446-L450 | |
Polidea/SiriusObfuscator | b0e590d8130e97856afe578869b83a209e2b19be | SymbolExtractorAndRenamer/lldb/scripts/Python/static-binding/lldb.py | python | SBPlatform.Get | (self, *args) | return _lldb.SBPlatform_Get(self, *args) | Get(self, SBFileSpec src, SBFileSpec dst) -> SBError | Get(self, SBFileSpec src, SBFileSpec dst) -> SBError | [
"Get",
"(",
"self",
"SBFileSpec",
"src",
"SBFileSpec",
"dst",
")",
"-",
">",
"SBError"
] | def Get(self, *args):
"""Get(self, SBFileSpec src, SBFileSpec dst) -> SBError"""
return _lldb.SBPlatform_Get(self, *args) | [
"def",
"Get",
"(",
"self",
",",
"*",
"args",
")",
":",
"return",
"_lldb",
".",
"SBPlatform_Get",
"(",
"self",
",",
"*",
"args",
")"
] | https://github.com/Polidea/SiriusObfuscator/blob/b0e590d8130e97856afe578869b83a209e2b19be/SymbolExtractorAndRenamer/lldb/scripts/Python/static-binding/lldb.py#L6855-L6857 | |
tensorflow/io | 92b44e180674a8af0e12e405530f7343e3e693e4 | tensorflow_io/python/experimental/color_ops.py | python | rgb_to_rgba | (input, name=None) | return tf.stack([r, g, b, a], axis=-1) | Convert a RGB image to RGBA.
Args:
input: A 3-D (`[H, W, 3]`) or 4-D (`[N, H, W, 3]`) Tensor.
name: A name for the operation (optional).
Returns:
A 3-D (`[H, W, 4]`) or 4-D (`[N, H, W, 4]`) Tensor. | Convert a RGB image to RGBA. | [
"Convert",
"a",
"RGB",
"image",
"to",
"RGBA",
"."
] | def rgb_to_rgba(input, name=None):
"""
Convert a RGB image to RGBA.
Args:
input: A 3-D (`[H, W, 3]`) or 4-D (`[N, H, W, 3]`) Tensor.
name: A name for the operation (optional).
Returns:
A 3-D (`[H, W, 4]`) or 4-D (`[N, H, W, 4]`) Tensor.
"""
rgb = tf.unstack(input, axis=-1)
r, g, b = rgb[0], rgb[1], rgb[2]
a = tf.zeros_like(r)
return tf.stack([r, g, b, a], axis=-1) | [
"def",
"rgb_to_rgba",
"(",
"input",
",",
"name",
"=",
"None",
")",
":",
"rgb",
"=",
"tf",
".",
"unstack",
"(",
"input",
",",
"axis",
"=",
"-",
"1",
")",
"r",
",",
"g",
",",
"b",
"=",
"rgb",
"[",
"0",
"]",
",",
"rgb",
"[",
"1",
"]",
",",
"rgb",
"[",
"2",
"]",
"a",
"=",
"tf",
".",
"zeros_like",
"(",
"r",
")",
"return",
"tf",
".",
"stack",
"(",
"[",
"r",
",",
"g",
",",
"b",
",",
"a",
"]",
",",
"axis",
"=",
"-",
"1",
")"
] | https://github.com/tensorflow/io/blob/92b44e180674a8af0e12e405530f7343e3e693e4/tensorflow_io/python/experimental/color_ops.py#L52-L66 | |
facebook/fbthrift | fb9c8562aba04c4fd9b17716eb5d970cc88a75bb | thrift/lib/py/util/remote.py | python | print_functions | (functions, service_names, out, local_only: bool=False) | Print all the functions available from this thrift service | Print all the functions available from this thrift service | [
"Print",
"all",
"the",
"functions",
"available",
"from",
"this",
"thrift",
"service"
] | def print_functions(functions, service_names, out, local_only: bool=False) -> None:
"""Print all the functions available from this thrift service"""
fns_by_service_name = {svc_name: {} for svc_name in service_names}
for fn in functions.values():
fns_by_service_name[fn.svc_name][fn.fn_name] = fn
svc_names = service_names[0:1] if local_only else \
reversed(service_names)
for svc_name in svc_names:
out.write('Functions in %s:\n' % (svc_name,))
for fn_name, fn in sorted(fns_by_service_name[svc_name].items()):
if fn.return_type is None:
out.write(' oneway void ')
else:
out.write(' %s ' % (fn.return_type,))
out.write(fn_name + '(')
out.write(', '.join('%s %s' % (type, name)
for type, name, true_type in fn.args))
out.write(')\n') | [
"def",
"print_functions",
"(",
"functions",
",",
"service_names",
",",
"out",
",",
"local_only",
":",
"bool",
"=",
"False",
")",
"->",
"None",
":",
"fns_by_service_name",
"=",
"{",
"svc_name",
":",
"{",
"}",
"for",
"svc_name",
"in",
"service_names",
"}",
"for",
"fn",
"in",
"functions",
".",
"values",
"(",
")",
":",
"fns_by_service_name",
"[",
"fn",
".",
"svc_name",
"]",
"[",
"fn",
".",
"fn_name",
"]",
"=",
"fn",
"svc_names",
"=",
"service_names",
"[",
"0",
":",
"1",
"]",
"if",
"local_only",
"else",
"reversed",
"(",
"service_names",
")",
"for",
"svc_name",
"in",
"svc_names",
":",
"out",
".",
"write",
"(",
"'Functions in %s:\\n'",
"%",
"(",
"svc_name",
",",
")",
")",
"for",
"fn_name",
",",
"fn",
"in",
"sorted",
"(",
"fns_by_service_name",
"[",
"svc_name",
"]",
".",
"items",
"(",
")",
")",
":",
"if",
"fn",
".",
"return_type",
"is",
"None",
":",
"out",
".",
"write",
"(",
"' oneway void '",
")",
"else",
":",
"out",
".",
"write",
"(",
"' %s '",
"%",
"(",
"fn",
".",
"return_type",
",",
")",
")",
"out",
".",
"write",
"(",
"fn_name",
"+",
"'('",
")",
"out",
".",
"write",
"(",
"', '",
".",
"join",
"(",
"'%s %s'",
"%",
"(",
"type",
",",
"name",
")",
"for",
"type",
",",
"name",
",",
"true_type",
"in",
"fn",
".",
"args",
")",
")",
"out",
".",
"write",
"(",
"')\\n'",
")"
] | https://github.com/facebook/fbthrift/blob/fb9c8562aba04c4fd9b17716eb5d970cc88a75bb/thrift/lib/py/util/remote.py#L67-L85 | ||
domino-team/openwrt-cc | 8b181297c34d14d3ca521cc9f31430d561dbc688 | package/gli-pub/openwrt-node-packages-master/node/node-v6.9.1/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/android.py | python | AndroidMkWriter.ComputeOutputParts | (self, spec) | return (target_stem, target_ext) | Return the 'output basename' of a gyp spec, split into filename + ext.
Android libraries must be named the same thing as their module name,
otherwise the linker can't find them, so product_name and so on must be
ignored if we are building a library, and the "lib" prepending is
not done for Android. | Return the 'output basename' of a gyp spec, split into filename + ext. | [
"Return",
"the",
"output",
"basename",
"of",
"a",
"gyp",
"spec",
"split",
"into",
"filename",
"+",
"ext",
"."
] | def ComputeOutputParts(self, spec):
"""Return the 'output basename' of a gyp spec, split into filename + ext.
Android libraries must be named the same thing as their module name,
otherwise the linker can't find them, so product_name and so on must be
ignored if we are building a library, and the "lib" prepending is
not done for Android.
"""
assert self.type != 'loadable_module' # TODO: not supported?
target = spec['target_name']
target_prefix = ''
target_ext = ''
if self.type == 'static_library':
target = self.ComputeAndroidModule(spec)
target_ext = '.a'
elif self.type == 'shared_library':
target = self.ComputeAndroidModule(spec)
target_ext = '.so'
elif self.type == 'none':
target_ext = '.stamp'
elif self.type != 'executable':
print ("ERROR: What output file should be generated?",
"type", self.type, "target", target)
if self.type != 'static_library' and self.type != 'shared_library':
target_prefix = spec.get('product_prefix', target_prefix)
target = spec.get('product_name', target)
product_ext = spec.get('product_extension')
if product_ext:
target_ext = '.' + product_ext
target_stem = target_prefix + target
return (target_stem, target_ext) | [
"def",
"ComputeOutputParts",
"(",
"self",
",",
"spec",
")",
":",
"assert",
"self",
".",
"type",
"!=",
"'loadable_module'",
"# TODO: not supported?",
"target",
"=",
"spec",
"[",
"'target_name'",
"]",
"target_prefix",
"=",
"''",
"target_ext",
"=",
"''",
"if",
"self",
".",
"type",
"==",
"'static_library'",
":",
"target",
"=",
"self",
".",
"ComputeAndroidModule",
"(",
"spec",
")",
"target_ext",
"=",
"'.a'",
"elif",
"self",
".",
"type",
"==",
"'shared_library'",
":",
"target",
"=",
"self",
".",
"ComputeAndroidModule",
"(",
"spec",
")",
"target_ext",
"=",
"'.so'",
"elif",
"self",
".",
"type",
"==",
"'none'",
":",
"target_ext",
"=",
"'.stamp'",
"elif",
"self",
".",
"type",
"!=",
"'executable'",
":",
"print",
"(",
"\"ERROR: What output file should be generated?\"",
",",
"\"type\"",
",",
"self",
".",
"type",
",",
"\"target\"",
",",
"target",
")",
"if",
"self",
".",
"type",
"!=",
"'static_library'",
"and",
"self",
".",
"type",
"!=",
"'shared_library'",
":",
"target_prefix",
"=",
"spec",
".",
"get",
"(",
"'product_prefix'",
",",
"target_prefix",
")",
"target",
"=",
"spec",
".",
"get",
"(",
"'product_name'",
",",
"target",
")",
"product_ext",
"=",
"spec",
".",
"get",
"(",
"'product_extension'",
")",
"if",
"product_ext",
":",
"target_ext",
"=",
"'.'",
"+",
"product_ext",
"target_stem",
"=",
"target_prefix",
"+",
"target",
"return",
"(",
"target_stem",
",",
"target_ext",
")"
] | https://github.com/domino-team/openwrt-cc/blob/8b181297c34d14d3ca521cc9f31430d561dbc688/package/gli-pub/openwrt-node-packages-master/node/node-v6.9.1/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/android.py#L617-L650 | |
bitconch/bitconch-core | 5537f3215b3e3b76f6720d6f908676a6c34bc5db | deploy-nightly.py | python | execute_shell | (command, silent=False, cwd=None, shell=True, env=None) | Execute a system command | Execute a system command | [
"Execute",
"a",
"system",
"command"
] | def execute_shell(command, silent=False, cwd=None, shell=True, env=None):
"""
Execute a system command
"""
if env is not None:
env = dict(**os.environ, **env)
if silent:
p = Popen(
command, shell=shell, stdout=PIPE, stderr=PIPE, cwd=cwd, env=env)
stdout, _ = p.communicate()
return stdout
else:
check_call(command, shell=shell, cwd=cwd, env=env) | [
"def",
"execute_shell",
"(",
"command",
",",
"silent",
"=",
"False",
",",
"cwd",
"=",
"None",
",",
"shell",
"=",
"True",
",",
"env",
"=",
"None",
")",
":",
"if",
"env",
"is",
"not",
"None",
":",
"env",
"=",
"dict",
"(",
"*",
"*",
"os",
".",
"environ",
",",
"*",
"*",
"env",
")",
"if",
"silent",
":",
"p",
"=",
"Popen",
"(",
"command",
",",
"shell",
"=",
"shell",
",",
"stdout",
"=",
"PIPE",
",",
"stderr",
"=",
"PIPE",
",",
"cwd",
"=",
"cwd",
",",
"env",
"=",
"env",
")",
"stdout",
",",
"_",
"=",
"p",
".",
"communicate",
"(",
")",
"return",
"stdout",
"else",
":",
"check_call",
"(",
"command",
",",
"shell",
"=",
"shell",
",",
"cwd",
"=",
"cwd",
",",
"env",
"=",
"env",
")"
] | https://github.com/bitconch/bitconch-core/blob/5537f3215b3e3b76f6720d6f908676a6c34bc5db/deploy-nightly.py#L37-L52 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/py/sliceshell.py | python | SlicesShell.processLine | (self) | Process the line of text at which the user hit Enter or Shift+RETURN. | Process the line of text at which the user hit Enter or Shift+RETURN. | [
"Process",
"the",
"line",
"of",
"text",
"at",
"which",
"the",
"user",
"hit",
"Enter",
"or",
"Shift",
"+",
"RETURN",
"."
] | def processLine(self):
"""Process the line of text at which the user hit Enter or Shift+RETURN."""
# The user hit ENTER (Shift+RETURN) (Shift+ENTER) and we need to
# decide what to do. They could be sitting on any line in the slices shell.
thepos = self.GetCurrentPos()
cur_line = self.GetCurrentLine()
marker=self.MarkerGet(cur_line)
if marker & INPUT_MASK:
pass
elif marker & OUTPUT_MASK:
return
else:
pass #print 'BLANK LINE!!'
startline,endline=self.GetIOSlice(cur_line)
if startline==0:
startpos=0
else:
startpos=self.PositionFromLine(startline)
endpos=self.GetLineEndPosition(endline)
# If they hit ENTER inside the current command, execute the command.
if self.CanEdit():
self.SetCurrentPos(endpos)
self.interp.more = False
command = self.GetTextRange(startpos, endpos)
lines = command.split(os.linesep)
lines = [line.rstrip() for line in lines]
command = '\n'.join(lines)
if self.reader.isreading:
if not command:
# Match the behavior of the standard Python shell
# when the user hits return without entering a value.
command = '\n'
self.reader.input = command
self.write(os.linesep,'Input')
self.MarkerSet(self.GetCurrentLine(),READLINE_BG)
self.MarkerSet(self.GetCurrentLine(),INPUT_READLINE)
else:
self.runningSlice = (startline,endline)
self.push(command,useMultiCommand=True)
#print 'command: ',command
wx.FutureCall(1, self.EnsureCaretVisible)
self.runningSlice=None
skip=self.BackspaceWMarkers(force=True)
if skip:
self.DeleteBack()
if self.GetCurrentLine()==self.GetLineCount()-1:
self.write(os.linesep,type='Input')
cpos=self.GetCurrentLine()
if self.MarkerGet(cpos-1) & OUTPUT_MASK:
self.MarkerAdd(cpos-1,OUTPUT_BG)
self.SplitSlice()
else:
cur_line=self.GetCurrentLine()
new_pos=self.GetLineEndPosition(cur_line+1)
self.SetSelection(new_pos,new_pos)
self.SetCurrentPos(new_pos)
self.EmptyUndoBuffer()
self.NeedsCheckForSave=True
if self.hasSyntaxError:
pos=self.GetLineEndPosition(self.syntaxErrorRealLine)
self.SetCurrentPos(pos)
self.SetSelection(pos,pos) | [
"def",
"processLine",
"(",
"self",
")",
":",
"# The user hit ENTER (Shift+RETURN) (Shift+ENTER) and we need to",
"# decide what to do. They could be sitting on any line in the slices shell.",
"thepos",
"=",
"self",
".",
"GetCurrentPos",
"(",
")",
"cur_line",
"=",
"self",
".",
"GetCurrentLine",
"(",
")",
"marker",
"=",
"self",
".",
"MarkerGet",
"(",
"cur_line",
")",
"if",
"marker",
"&",
"INPUT_MASK",
":",
"pass",
"elif",
"marker",
"&",
"OUTPUT_MASK",
":",
"return",
"else",
":",
"pass",
"#print 'BLANK LINE!!'",
"startline",
",",
"endline",
"=",
"self",
".",
"GetIOSlice",
"(",
"cur_line",
")",
"if",
"startline",
"==",
"0",
":",
"startpos",
"=",
"0",
"else",
":",
"startpos",
"=",
"self",
".",
"PositionFromLine",
"(",
"startline",
")",
"endpos",
"=",
"self",
".",
"GetLineEndPosition",
"(",
"endline",
")",
"# If they hit ENTER inside the current command, execute the command.",
"if",
"self",
".",
"CanEdit",
"(",
")",
":",
"self",
".",
"SetCurrentPos",
"(",
"endpos",
")",
"self",
".",
"interp",
".",
"more",
"=",
"False",
"command",
"=",
"self",
".",
"GetTextRange",
"(",
"startpos",
",",
"endpos",
")",
"lines",
"=",
"command",
".",
"split",
"(",
"os",
".",
"linesep",
")",
"lines",
"=",
"[",
"line",
".",
"rstrip",
"(",
")",
"for",
"line",
"in",
"lines",
"]",
"command",
"=",
"'\\n'",
".",
"join",
"(",
"lines",
")",
"if",
"self",
".",
"reader",
".",
"isreading",
":",
"if",
"not",
"command",
":",
"# Match the behavior of the standard Python shell",
"# when the user hits return without entering a value.",
"command",
"=",
"'\\n'",
"self",
".",
"reader",
".",
"input",
"=",
"command",
"self",
".",
"write",
"(",
"os",
".",
"linesep",
",",
"'Input'",
")",
"self",
".",
"MarkerSet",
"(",
"self",
".",
"GetCurrentLine",
"(",
")",
",",
"READLINE_BG",
")",
"self",
".",
"MarkerSet",
"(",
"self",
".",
"GetCurrentLine",
"(",
")",
",",
"INPUT_READLINE",
")",
"else",
":",
"self",
".",
"runningSlice",
"=",
"(",
"startline",
",",
"endline",
")",
"self",
".",
"push",
"(",
"command",
",",
"useMultiCommand",
"=",
"True",
")",
"#print 'command: ',command",
"wx",
".",
"FutureCall",
"(",
"1",
",",
"self",
".",
"EnsureCaretVisible",
")",
"self",
".",
"runningSlice",
"=",
"None",
"skip",
"=",
"self",
".",
"BackspaceWMarkers",
"(",
"force",
"=",
"True",
")",
"if",
"skip",
":",
"self",
".",
"DeleteBack",
"(",
")",
"if",
"self",
".",
"GetCurrentLine",
"(",
")",
"==",
"self",
".",
"GetLineCount",
"(",
")",
"-",
"1",
":",
"self",
".",
"write",
"(",
"os",
".",
"linesep",
",",
"type",
"=",
"'Input'",
")",
"cpos",
"=",
"self",
".",
"GetCurrentLine",
"(",
")",
"if",
"self",
".",
"MarkerGet",
"(",
"cpos",
"-",
"1",
")",
"&",
"OUTPUT_MASK",
":",
"self",
".",
"MarkerAdd",
"(",
"cpos",
"-",
"1",
",",
"OUTPUT_BG",
")",
"self",
".",
"SplitSlice",
"(",
")",
"else",
":",
"cur_line",
"=",
"self",
".",
"GetCurrentLine",
"(",
")",
"new_pos",
"=",
"self",
".",
"GetLineEndPosition",
"(",
"cur_line",
"+",
"1",
")",
"self",
".",
"SetSelection",
"(",
"new_pos",
",",
"new_pos",
")",
"self",
".",
"SetCurrentPos",
"(",
"new_pos",
")",
"self",
".",
"EmptyUndoBuffer",
"(",
")",
"self",
".",
"NeedsCheckForSave",
"=",
"True",
"if",
"self",
".",
"hasSyntaxError",
":",
"pos",
"=",
"self",
".",
"GetLineEndPosition",
"(",
"self",
".",
"syntaxErrorRealLine",
")",
"self",
".",
"SetCurrentPos",
"(",
"pos",
")",
"self",
".",
"SetSelection",
"(",
"pos",
",",
"pos",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/py/sliceshell.py#L2291-L2359 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/datetime.py | python | datetime.fromisoformat | (cls, date_string) | return cls(*(date_components + time_components)) | Construct a datetime from the output of datetime.isoformat(). | Construct a datetime from the output of datetime.isoformat(). | [
"Construct",
"a",
"datetime",
"from",
"the",
"output",
"of",
"datetime",
".",
"isoformat",
"()",
"."
] | def fromisoformat(cls, date_string):
"""Construct a datetime from the output of datetime.isoformat()."""
if not isinstance(date_string, str):
raise TypeError('fromisoformat: argument must be str')
# Split this at the separator
dstr = date_string[0:10]
tstr = date_string[11:]
try:
date_components = _parse_isoformat_date(dstr)
except ValueError:
raise ValueError(f'Invalid isoformat string: {date_string!r}')
if tstr:
try:
time_components = _parse_isoformat_time(tstr)
except ValueError:
raise ValueError(f'Invalid isoformat string: {date_string!r}')
else:
time_components = [0, 0, 0, 0, None]
return cls(*(date_components + time_components)) | [
"def",
"fromisoformat",
"(",
"cls",
",",
"date_string",
")",
":",
"if",
"not",
"isinstance",
"(",
"date_string",
",",
"str",
")",
":",
"raise",
"TypeError",
"(",
"'fromisoformat: argument must be str'",
")",
"# Split this at the separator",
"dstr",
"=",
"date_string",
"[",
"0",
":",
"10",
"]",
"tstr",
"=",
"date_string",
"[",
"11",
":",
"]",
"try",
":",
"date_components",
"=",
"_parse_isoformat_date",
"(",
"dstr",
")",
"except",
"ValueError",
":",
"raise",
"ValueError",
"(",
"f'Invalid isoformat string: {date_string!r}'",
")",
"if",
"tstr",
":",
"try",
":",
"time_components",
"=",
"_parse_isoformat_time",
"(",
"tstr",
")",
"except",
"ValueError",
":",
"raise",
"ValueError",
"(",
"f'Invalid isoformat string: {date_string!r}'",
")",
"else",
":",
"time_components",
"=",
"[",
"0",
",",
"0",
",",
"0",
",",
"0",
",",
"None",
"]",
"return",
"cls",
"(",
"*",
"(",
"date_components",
"+",
"time_components",
")",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/datetime.py#L1667-L1689 | |
koth/kcws | 88efbd36a7022de4e6e90f5a1fb880cf87cfae9f | third_party/setuptools/pkg_resources.py | python | Requirement.__init__ | (self, project_name, specs, extras) | DO NOT CALL THIS UNDOCUMENTED METHOD; use Requirement.parse()! | DO NOT CALL THIS UNDOCUMENTED METHOD; use Requirement.parse()! | [
"DO",
"NOT",
"CALL",
"THIS",
"UNDOCUMENTED",
"METHOD",
";",
"use",
"Requirement",
".",
"parse",
"()",
"!"
] | def __init__(self, project_name, specs, extras):
"""DO NOT CALL THIS UNDOCUMENTED METHOD; use Requirement.parse()!"""
self.unsafe_name, project_name = project_name, safe_name(project_name)
self.project_name, self.key = project_name, project_name.lower()
index = [
(parse_version(v), state_machine[op], op, v)
for op, v in specs
]
index.sort()
self.specs = [(op, ver) for parsed, trans, op, ver in index]
self.index, self.extras = index, tuple(map(safe_extra, extras))
self.hashCmp = (
self.key,
tuple((op, parsed) for parsed, trans, op, ver in index),
frozenset(self.extras),
)
self.__hash = hash(self.hashCmp) | [
"def",
"__init__",
"(",
"self",
",",
"project_name",
",",
"specs",
",",
"extras",
")",
":",
"self",
".",
"unsafe_name",
",",
"project_name",
"=",
"project_name",
",",
"safe_name",
"(",
"project_name",
")",
"self",
".",
"project_name",
",",
"self",
".",
"key",
"=",
"project_name",
",",
"project_name",
".",
"lower",
"(",
")",
"index",
"=",
"[",
"(",
"parse_version",
"(",
"v",
")",
",",
"state_machine",
"[",
"op",
"]",
",",
"op",
",",
"v",
")",
"for",
"op",
",",
"v",
"in",
"specs",
"]",
"index",
".",
"sort",
"(",
")",
"self",
".",
"specs",
"=",
"[",
"(",
"op",
",",
"ver",
")",
"for",
"parsed",
",",
"trans",
",",
"op",
",",
"ver",
"in",
"index",
"]",
"self",
".",
"index",
",",
"self",
".",
"extras",
"=",
"index",
",",
"tuple",
"(",
"map",
"(",
"safe_extra",
",",
"extras",
")",
")",
"self",
".",
"hashCmp",
"=",
"(",
"self",
".",
"key",
",",
"tuple",
"(",
"(",
"op",
",",
"parsed",
")",
"for",
"parsed",
",",
"trans",
",",
"op",
",",
"ver",
"in",
"index",
")",
",",
"frozenset",
"(",
"self",
".",
"extras",
")",
",",
")",
"self",
".",
"__hash",
"=",
"hash",
"(",
"self",
".",
"hashCmp",
")"
] | https://github.com/koth/kcws/blob/88efbd36a7022de4e6e90f5a1fb880cf87cfae9f/third_party/setuptools/pkg_resources.py#L2691-L2707 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/combo.py | python | ComboCtrl.GetBackgroundColour | (*args, **kwargs) | return _combo.ComboCtrl_GetBackgroundColour(*args, **kwargs) | GetBackgroundColour(self) -> Colour
Returns the background colour of the window. | GetBackgroundColour(self) -> Colour | [
"GetBackgroundColour",
"(",
"self",
")",
"-",
">",
"Colour"
] | def GetBackgroundColour(*args, **kwargs):
"""
GetBackgroundColour(self) -> Colour
Returns the background colour of the window.
"""
return _combo.ComboCtrl_GetBackgroundColour(*args, **kwargs) | [
"def",
"GetBackgroundColour",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_combo",
".",
"ComboCtrl_GetBackgroundColour",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/combo.py#L474-L480 | |
benoitsteiner/tensorflow-opencl | cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5 | tensorflow/python/framework/function.py | python | _parse_kwargs_as_attrs | (func_name, **kwargs) | return attrs | Parses **kwargs into a node's attributes. | Parses **kwargs into a node's attributes. | [
"Parses",
"**",
"kwargs",
"into",
"a",
"node",
"s",
"attributes",
"."
] | def _parse_kwargs_as_attrs(func_name, **kwargs):
"""Parses **kwargs into a node's attributes."""
attrs = {}
noinline = kwargs.pop("noinline", None)
if noinline is not None:
attrs["_noinline"] = attr_value_pb2.AttrValue(b=bool(noinline))
compiled = kwargs.pop("compiled", None)
separate_compiled_gradients = kwargs.pop("separate_compiled_gradients", None)
if compiled is not None:
attrs["_XlaCompile"] = attr_value_pb2.AttrValue(b=bool(compiled))
attrs["_XlaSeparateCompiledGradients"] = attr_value_pb2.AttrValue(
b=bool(separate_compiled_gradients))
# Forward _XlaScope from enclosing context (if set), otherwise create new.
# pylint: disable=protected-access
if "_XlaScope" in ops.get_default_graph()._attr_scope_map:
attrs["_XlaScope"] = ops.get_default_graph()._attr_scope_map["_XlaScope"]
else:
attrs["_XlaScope"] = attr_value_pb2.AttrValue(
s=("function_%s" % func_name).encode())
# pylint: enable=protected-access
if kwargs:
raise ValueError("Unknown keyword arguments: %s" % kwargs.keys())
return attrs | [
"def",
"_parse_kwargs_as_attrs",
"(",
"func_name",
",",
"*",
"*",
"kwargs",
")",
":",
"attrs",
"=",
"{",
"}",
"noinline",
"=",
"kwargs",
".",
"pop",
"(",
"\"noinline\"",
",",
"None",
")",
"if",
"noinline",
"is",
"not",
"None",
":",
"attrs",
"[",
"\"_noinline\"",
"]",
"=",
"attr_value_pb2",
".",
"AttrValue",
"(",
"b",
"=",
"bool",
"(",
"noinline",
")",
")",
"compiled",
"=",
"kwargs",
".",
"pop",
"(",
"\"compiled\"",
",",
"None",
")",
"separate_compiled_gradients",
"=",
"kwargs",
".",
"pop",
"(",
"\"separate_compiled_gradients\"",
",",
"None",
")",
"if",
"compiled",
"is",
"not",
"None",
":",
"attrs",
"[",
"\"_XlaCompile\"",
"]",
"=",
"attr_value_pb2",
".",
"AttrValue",
"(",
"b",
"=",
"bool",
"(",
"compiled",
")",
")",
"attrs",
"[",
"\"_XlaSeparateCompiledGradients\"",
"]",
"=",
"attr_value_pb2",
".",
"AttrValue",
"(",
"b",
"=",
"bool",
"(",
"separate_compiled_gradients",
")",
")",
"# Forward _XlaScope from enclosing context (if set), otherwise create new.",
"# pylint: disable=protected-access",
"if",
"\"_XlaScope\"",
"in",
"ops",
".",
"get_default_graph",
"(",
")",
".",
"_attr_scope_map",
":",
"attrs",
"[",
"\"_XlaScope\"",
"]",
"=",
"ops",
".",
"get_default_graph",
"(",
")",
".",
"_attr_scope_map",
"[",
"\"_XlaScope\"",
"]",
"else",
":",
"attrs",
"[",
"\"_XlaScope\"",
"]",
"=",
"attr_value_pb2",
".",
"AttrValue",
"(",
"s",
"=",
"(",
"\"function_%s\"",
"%",
"func_name",
")",
".",
"encode",
"(",
")",
")",
"# pylint: enable=protected-access",
"if",
"kwargs",
":",
"raise",
"ValueError",
"(",
"\"Unknown keyword arguments: %s\"",
"%",
"kwargs",
".",
"keys",
"(",
")",
")",
"return",
"attrs"
] | https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/framework/function.py#L903-L928 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/dashboard/dashboard/edit_bug_labels.py | python | EditBugLabelsHandler._RemoveBuglabelPattern | (self) | Removes a BugLabelPattern so that the label no longer applies.
Request parameters:
buglabel_to_remove: The bug label, which is the name of a
BugLabelPattern entity. | Removes a BugLabelPattern so that the label no longer applies. | [
"Removes",
"a",
"BugLabelPattern",
"so",
"that",
"the",
"label",
"no",
"longer",
"applies",
"."
] | def _RemoveBuglabelPattern(self):
"""Removes a BugLabelPattern so that the label no longer applies.
Request parameters:
buglabel_to_remove: The bug label, which is the name of a
BugLabelPattern entity.
"""
label = self.request.get('buglabel_to_remove')
bug_label_patterns.RemoveBugLabel(label)
self.RenderHtml('result.html', {
'headline': 'Deleted label %s' % label
}) | [
"def",
"_RemoveBuglabelPattern",
"(",
"self",
")",
":",
"label",
"=",
"self",
".",
"request",
".",
"get",
"(",
"'buglabel_to_remove'",
")",
"bug_label_patterns",
".",
"RemoveBugLabel",
"(",
"label",
")",
"self",
".",
"RenderHtml",
"(",
"'result.html'",
",",
"{",
"'headline'",
":",
"'Deleted label %s'",
"%",
"label",
"}",
")"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/dashboard/dashboard/edit_bug_labels.py#L54-L65 | ||
cms-sw/cmssw | fd9de012d503d3405420bcbeec0ec879baa57cf2 | Validation/RecoTrack/python/plotting/plotting.py | python | Plot._setStats | (self, histos, startingX, startingY) | Set stats box. | Set stats box. | [
"Set",
"stats",
"box",
"."
] | def _setStats(self, histos, startingX, startingY):
"""Set stats box."""
if not self._stat:
for h in histos:
if h is not None and hasattr(h, "SetStats"):
h.SetStats(0)
return
def _doStats(h, col, dy):
if h is None:
return
h.SetStats(True)
if self._fit and h.GetEntries() > 0.5:
h.Fit("gaus", "Q")
f = h.GetListOfFunctions().FindObject("gaus")
if f == None:
h.SetStats(0)
return
f.SetLineColor(col)
f.SetLineWidth(1)
h.Draw()
ROOT.gPad.Update()
st = h.GetListOfFunctions().FindObject("stats")
if self._fit:
st.SetOptFit(0o010)
st.SetOptStat(1001)
st.SetOptStat(1110)
st.SetX1NDC(startingX)
st.SetX2NDC(startingX+0.3)
st.SetY1NDC(startingY+dy)
st.SetY2NDC(startingY+dy+0.12)
st.SetTextColor(col)
dy = 0.0
for i, h in enumerate(histos):
if self._statyadjust is not None and i < len(self._statyadjust):
dy += self._statyadjust[i]
_doStats(h, _plotStylesColor[i], dy)
dy -= 0.16 | [
"def",
"_setStats",
"(",
"self",
",",
"histos",
",",
"startingX",
",",
"startingY",
")",
":",
"if",
"not",
"self",
".",
"_stat",
":",
"for",
"h",
"in",
"histos",
":",
"if",
"h",
"is",
"not",
"None",
"and",
"hasattr",
"(",
"h",
",",
"\"SetStats\"",
")",
":",
"h",
".",
"SetStats",
"(",
"0",
")",
"return",
"def",
"_doStats",
"(",
"h",
",",
"col",
",",
"dy",
")",
":",
"if",
"h",
"is",
"None",
":",
"return",
"h",
".",
"SetStats",
"(",
"True",
")",
"if",
"self",
".",
"_fit",
"and",
"h",
".",
"GetEntries",
"(",
")",
">",
"0.5",
":",
"h",
".",
"Fit",
"(",
"\"gaus\"",
",",
"\"Q\"",
")",
"f",
"=",
"h",
".",
"GetListOfFunctions",
"(",
")",
".",
"FindObject",
"(",
"\"gaus\"",
")",
"if",
"f",
"==",
"None",
":",
"h",
".",
"SetStats",
"(",
"0",
")",
"return",
"f",
".",
"SetLineColor",
"(",
"col",
")",
"f",
".",
"SetLineWidth",
"(",
"1",
")",
"h",
".",
"Draw",
"(",
")",
"ROOT",
".",
"gPad",
".",
"Update",
"(",
")",
"st",
"=",
"h",
".",
"GetListOfFunctions",
"(",
")",
".",
"FindObject",
"(",
"\"stats\"",
")",
"if",
"self",
".",
"_fit",
":",
"st",
".",
"SetOptFit",
"(",
"0o010",
")",
"st",
".",
"SetOptStat",
"(",
"1001",
")",
"st",
".",
"SetOptStat",
"(",
"1110",
")",
"st",
".",
"SetX1NDC",
"(",
"startingX",
")",
"st",
".",
"SetX2NDC",
"(",
"startingX",
"+",
"0.3",
")",
"st",
".",
"SetY1NDC",
"(",
"startingY",
"+",
"dy",
")",
"st",
".",
"SetY2NDC",
"(",
"startingY",
"+",
"dy",
"+",
"0.12",
")",
"st",
".",
"SetTextColor",
"(",
"col",
")",
"dy",
"=",
"0.0",
"for",
"i",
",",
"h",
"in",
"enumerate",
"(",
"histos",
")",
":",
"if",
"self",
".",
"_statyadjust",
"is",
"not",
"None",
"and",
"i",
"<",
"len",
"(",
"self",
".",
"_statyadjust",
")",
":",
"dy",
"+=",
"self",
".",
"_statyadjust",
"[",
"i",
"]",
"_doStats",
"(",
"h",
",",
"_plotStylesColor",
"[",
"i",
"]",
",",
"dy",
")",
"dy",
"-=",
"0.16"
] | https://github.com/cms-sw/cmssw/blob/fd9de012d503d3405420bcbeec0ec879baa57cf2/Validation/RecoTrack/python/plotting/plotting.py#L1942-L1982 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/site-packages/setuptools/command/easy_install.py | python | easy_install.install_script | (self, dist, script_name, script_text, dev_path=None) | Generate a legacy script wrapper and install it | Generate a legacy script wrapper and install it | [
"Generate",
"a",
"legacy",
"script",
"wrapper",
"and",
"install",
"it"
] | def install_script(self, dist, script_name, script_text, dev_path=None):
"""Generate a legacy script wrapper and install it"""
spec = str(dist.as_requirement())
is_script = is_python_script(script_text, script_name)
if is_script:
body = self._load_template(dev_path) % locals()
script_text = ScriptWriter.get_header(script_text) + body
self.write_script(script_name, _to_bytes(script_text), 'b') | [
"def",
"install_script",
"(",
"self",
",",
"dist",
",",
"script_name",
",",
"script_text",
",",
"dev_path",
"=",
"None",
")",
":",
"spec",
"=",
"str",
"(",
"dist",
".",
"as_requirement",
"(",
")",
")",
"is_script",
"=",
"is_python_script",
"(",
"script_text",
",",
"script_name",
")",
"if",
"is_script",
":",
"body",
"=",
"self",
".",
"_load_template",
"(",
"dev_path",
")",
"%",
"locals",
"(",
")",
"script_text",
"=",
"ScriptWriter",
".",
"get_header",
"(",
"script_text",
")",
"+",
"body",
"self",
".",
"write_script",
"(",
"script_name",
",",
"_to_bytes",
"(",
"script_text",
")",
",",
"'b'",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/setuptools/command/easy_install.py#L816-L824 | ||
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/distutils/config.py | python | PyPIRCCommand._store_pypirc | (self, username, password) | Creates a default .pypirc file. | Creates a default .pypirc file. | [
"Creates",
"a",
"default",
".",
"pypirc",
"file",
"."
] | def _store_pypirc(self, username, password):
"""Creates a default .pypirc file."""
rc = self._get_rc_file()
f = os.fdopen(os.open(rc, os.O_CREAT | os.O_WRONLY, 0600), 'w')
try:
f.write(DEFAULT_PYPIRC % (username, password))
finally:
f.close() | [
"def",
"_store_pypirc",
"(",
"self",
",",
"username",
",",
"password",
")",
":",
"rc",
"=",
"self",
".",
"_get_rc_file",
"(",
")",
"f",
"=",
"os",
".",
"fdopen",
"(",
"os",
".",
"open",
"(",
"rc",
",",
"os",
".",
"O_CREAT",
"|",
"os",
".",
"O_WRONLY",
",",
"0600",
")",
",",
"'w'",
")",
"try",
":",
"f",
".",
"write",
"(",
"DEFAULT_PYPIRC",
"%",
"(",
"username",
",",
"password",
")",
")",
"finally",
":",
"f",
".",
"close",
"(",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/distutils/config.py#L42-L49 | ||
crosslife/OpenBird | 9e0198a1a2295f03fa1e8676e216e22c9c7d380b | cocos2d/tools/bindings-generator/clang/cindex.py | python | Cursor.canonical | (self) | return self._canonical | Return the canonical Cursor corresponding to this Cursor.
The canonical cursor is the cursor which is representative for the
underlying entity. For example, if you have multiple forward
declarations for the same class, the canonical cursor for the forward
declarations will be identical. | Return the canonical Cursor corresponding to this Cursor. | [
"Return",
"the",
"canonical",
"Cursor",
"corresponding",
"to",
"this",
"Cursor",
"."
] | def canonical(self):
"""Return the canonical Cursor corresponding to this Cursor.
The canonical cursor is the cursor which is representative for the
underlying entity. For example, if you have multiple forward
declarations for the same class, the canonical cursor for the forward
declarations will be identical.
"""
if not hasattr(self, '_canonical'):
self._canonical = conf.lib.clang_getCanonicalCursor(self)
return self._canonical | [
"def",
"canonical",
"(",
"self",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'_canonical'",
")",
":",
"self",
".",
"_canonical",
"=",
"conf",
".",
"lib",
".",
"clang_getCanonicalCursor",
"(",
"self",
")",
"return",
"self",
".",
"_canonical"
] | https://github.com/crosslife/OpenBird/blob/9e0198a1a2295f03fa1e8676e216e22c9c7d380b/cocos2d/tools/bindings-generator/clang/cindex.py#L1309-L1320 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/setuptools/py2/pkg_resources/_vendor/pyparsing.py | python | dictOf | ( key, value ) | return Dict( ZeroOrMore( Group ( key + value ) ) ) | Helper to easily and clearly define a dictionary by specifying the respective patterns
for the key and value. Takes care of defining the C{L{Dict}}, C{L{ZeroOrMore}}, and C{L{Group}} tokens
in the proper order. The key pattern can include delimiting markers or punctuation,
as long as they are suppressed, thereby leaving the significant key text. The value
pattern can include named results, so that the C{Dict} results can include named token
fields.
Example::
text = "shape: SQUARE posn: upper left color: light blue texture: burlap"
attr_expr = (label + Suppress(':') + OneOrMore(data_word, stopOn=label).setParseAction(' '.join))
print(OneOrMore(attr_expr).parseString(text).dump())
attr_label = label
attr_value = Suppress(':') + OneOrMore(data_word, stopOn=label).setParseAction(' '.join)
# similar to Dict, but simpler call format
result = dictOf(attr_label, attr_value).parseString(text)
print(result.dump())
print(result['shape'])
print(result.shape) # object attribute access works too
print(result.asDict())
prints::
[['shape', 'SQUARE'], ['posn', 'upper left'], ['color', 'light blue'], ['texture', 'burlap']]
- color: light blue
- posn: upper left
- shape: SQUARE
- texture: burlap
SQUARE
SQUARE
{'color': 'light blue', 'shape': 'SQUARE', 'posn': 'upper left', 'texture': 'burlap'} | Helper to easily and clearly define a dictionary by specifying the respective patterns
for the key and value. Takes care of defining the C{L{Dict}}, C{L{ZeroOrMore}}, and C{L{Group}} tokens
in the proper order. The key pattern can include delimiting markers or punctuation,
as long as they are suppressed, thereby leaving the significant key text. The value
pattern can include named results, so that the C{Dict} results can include named token
fields. | [
"Helper",
"to",
"easily",
"and",
"clearly",
"define",
"a",
"dictionary",
"by",
"specifying",
"the",
"respective",
"patterns",
"for",
"the",
"key",
"and",
"value",
".",
"Takes",
"care",
"of",
"defining",
"the",
"C",
"{",
"L",
"{",
"Dict",
"}}",
"C",
"{",
"L",
"{",
"ZeroOrMore",
"}}",
"and",
"C",
"{",
"L",
"{",
"Group",
"}}",
"tokens",
"in",
"the",
"proper",
"order",
".",
"The",
"key",
"pattern",
"can",
"include",
"delimiting",
"markers",
"or",
"punctuation",
"as",
"long",
"as",
"they",
"are",
"suppressed",
"thereby",
"leaving",
"the",
"significant",
"key",
"text",
".",
"The",
"value",
"pattern",
"can",
"include",
"named",
"results",
"so",
"that",
"the",
"C",
"{",
"Dict",
"}",
"results",
"can",
"include",
"named",
"token",
"fields",
"."
] | def dictOf( key, value ):
"""
Helper to easily and clearly define a dictionary by specifying the respective patterns
for the key and value. Takes care of defining the C{L{Dict}}, C{L{ZeroOrMore}}, and C{L{Group}} tokens
in the proper order. The key pattern can include delimiting markers or punctuation,
as long as they are suppressed, thereby leaving the significant key text. The value
pattern can include named results, so that the C{Dict} results can include named token
fields.
Example::
text = "shape: SQUARE posn: upper left color: light blue texture: burlap"
attr_expr = (label + Suppress(':') + OneOrMore(data_word, stopOn=label).setParseAction(' '.join))
print(OneOrMore(attr_expr).parseString(text).dump())
attr_label = label
attr_value = Suppress(':') + OneOrMore(data_word, stopOn=label).setParseAction(' '.join)
# similar to Dict, but simpler call format
result = dictOf(attr_label, attr_value).parseString(text)
print(result.dump())
print(result['shape'])
print(result.shape) # object attribute access works too
print(result.asDict())
prints::
[['shape', 'SQUARE'], ['posn', 'upper left'], ['color', 'light blue'], ['texture', 'burlap']]
- color: light blue
- posn: upper left
- shape: SQUARE
- texture: burlap
SQUARE
SQUARE
{'color': 'light blue', 'shape': 'SQUARE', 'posn': 'upper left', 'texture': 'burlap'}
"""
return Dict( ZeroOrMore( Group ( key + value ) ) ) | [
"def",
"dictOf",
"(",
"key",
",",
"value",
")",
":",
"return",
"Dict",
"(",
"ZeroOrMore",
"(",
"Group",
"(",
"key",
"+",
"value",
")",
")",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/setuptools/py2/pkg_resources/_vendor/pyparsing.py#L4646-L4679 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/mailcap.py | python | parsefield | (line, i, n) | return line[start:i].strip(), i | Separate one key-value pair in a mailcap entry. | Separate one key-value pair in a mailcap entry. | [
"Separate",
"one",
"key",
"-",
"value",
"pair",
"in",
"a",
"mailcap",
"entry",
"."
] | def parsefield(line, i, n):
"""Separate one key-value pair in a mailcap entry."""
start = i
while i < n:
c = line[i]
if c == ';':
break
elif c == '\\':
i = i+2
else:
i = i+1
return line[start:i].strip(), i | [
"def",
"parsefield",
"(",
"line",
",",
"i",
",",
"n",
")",
":",
"start",
"=",
"i",
"while",
"i",
"<",
"n",
":",
"c",
"=",
"line",
"[",
"i",
"]",
"if",
"c",
"==",
"';'",
":",
"break",
"elif",
"c",
"==",
"'\\\\'",
":",
"i",
"=",
"i",
"+",
"2",
"else",
":",
"i",
"=",
"i",
"+",
"1",
"return",
"line",
"[",
"start",
":",
"i",
"]",
".",
"strip",
"(",
")",
",",
"i"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/mailcap.py#L143-L154 | |
happynear/caffe-windows | 967eedf25009e334b7f6f933bb5e17aaaff5bef6 | scripts/cpp_lint.py | python | _SetCountingStyle | (level) | Sets the module's counting options. | Sets the module's counting options. | [
"Sets",
"the",
"module",
"s",
"counting",
"options",
"."
] | def _SetCountingStyle(level):
"""Sets the module's counting options."""
_cpplint_state.SetCountingStyle(level) | [
"def",
"_SetCountingStyle",
"(",
"level",
")",
":",
"_cpplint_state",
".",
"SetCountingStyle",
"(",
"level",
")"
] | https://github.com/happynear/caffe-windows/blob/967eedf25009e334b7f6f933bb5e17aaaff5bef6/scripts/cpp_lint.py#L791-L793 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/_windows.py | python | SingleChoiceDialog.__init__ | (self, *args, **kwargs) | __init__(Window parent, String message, String caption,
List choices=EmptyList, long style=CHOICEDLG_STYLE,
Point pos=DefaultPosition) -> SingleChoiceDialog
Constructor. Use ShowModal method to show the dialog. | __init__(Window parent, String message, String caption,
List choices=EmptyList, long style=CHOICEDLG_STYLE,
Point pos=DefaultPosition) -> SingleChoiceDialog | [
"__init__",
"(",
"Window",
"parent",
"String",
"message",
"String",
"caption",
"List",
"choices",
"=",
"EmptyList",
"long",
"style",
"=",
"CHOICEDLG_STYLE",
"Point",
"pos",
"=",
"DefaultPosition",
")",
"-",
">",
"SingleChoiceDialog"
] | def __init__(self, *args, **kwargs):
"""
__init__(Window parent, String message, String caption,
List choices=EmptyList, long style=CHOICEDLG_STYLE,
Point pos=DefaultPosition) -> SingleChoiceDialog
Constructor. Use ShowModal method to show the dialog.
"""
_windows_.SingleChoiceDialog_swiginit(self,_windows_.new_SingleChoiceDialog(*args, **kwargs))
self._setOORInfo(self) | [
"def",
"__init__",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"_windows_",
".",
"SingleChoiceDialog_swiginit",
"(",
"self",
",",
"_windows_",
".",
"new_SingleChoiceDialog",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
")",
"self",
".",
"_setOORInfo",
"(",
"self",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_windows.py#L3329-L3338 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/_gdi.py | python | IconLocation.IsOk | (*args, **kwargs) | return _gdi_.IconLocation_IsOk(*args, **kwargs) | IsOk(self) -> bool | IsOk(self) -> bool | [
"IsOk",
"(",
"self",
")",
"-",
">",
"bool"
] | def IsOk(*args, **kwargs):
"""IsOk(self) -> bool"""
return _gdi_.IconLocation_IsOk(*args, **kwargs) | [
"def",
"IsOk",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_gdi_",
".",
"IconLocation_IsOk",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_gdi.py#L1351-L1353 | |
PaddlePaddle/Paddle | 1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c | python/paddle/fluid/framework.py | python | Operator.input | (self, name) | return self.desc.input(name) | r"""
Get the input arguments according to the input parameter name.
Args:
name(str): The input parameter name.
Returns:
list: return the list of argument names that associated with \
the specific parameter name. | r"""
Get the input arguments according to the input parameter name. | [
"r",
"Get",
"the",
"input",
"arguments",
"according",
"to",
"the",
"input",
"parameter",
"name",
"."
] | def input(self, name):
r"""
Get the input arguments according to the input parameter name.
Args:
name(str): The input parameter name.
Returns:
list: return the list of argument names that associated with \
the specific parameter name.
"""
return self.desc.input(name) | [
"def",
"input",
"(",
"self",
",",
"name",
")",
":",
"return",
"self",
".",
"desc",
".",
"input",
"(",
"name",
")"
] | https://github.com/PaddlePaddle/Paddle/blob/1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c/python/paddle/fluid/framework.py#L2783-L2794 | |
weolar/miniblink49 | 1c4678db0594a4abde23d3ebbcc7cd13c3170777 | third_party/WebKit/Tools/Scripts/webkitpy/thirdparty/pep8.py | python | tabs_obsolete | (physical_line) | r"""For new projects, spaces-only are strongly recommended over tabs.
Okay: if True:\n return
W191: if True:\n\treturn | r"""For new projects, spaces-only are strongly recommended over tabs. | [
"r",
"For",
"new",
"projects",
"spaces",
"-",
"only",
"are",
"strongly",
"recommended",
"over",
"tabs",
"."
] | def tabs_obsolete(physical_line):
r"""For new projects, spaces-only are strongly recommended over tabs.
Okay: if True:\n return
W191: if True:\n\treturn
"""
indent = INDENT_REGEX.match(physical_line).group(1)
if '\t' in indent:
return indent.index('\t'), "W191 indentation contains tabs" | [
"def",
"tabs_obsolete",
"(",
"physical_line",
")",
":",
"indent",
"=",
"INDENT_REGEX",
".",
"match",
"(",
"physical_line",
")",
".",
"group",
"(",
"1",
")",
"if",
"'\\t'",
"in",
"indent",
":",
"return",
"indent",
".",
"index",
"(",
"'\\t'",
")",
",",
"\"W191 indentation contains tabs\""
] | https://github.com/weolar/miniblink49/blob/1c4678db0594a4abde23d3ebbcc7cd13c3170777/third_party/WebKit/Tools/Scripts/webkitpy/thirdparty/pep8.py#L142-L150 | ||
natanielruiz/android-yolo | 1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f | jni-build/jni/include/tensorflow/contrib/graph_editor/reroute.py | python | reroute_b2a_outputs | (sgv0, sgv1) | return _reroute_sgv_outputs(sgv0, sgv1, _RerouteMode.b2a) | Re-route all the outputs of sgv1 to sgv0 (see _reroute_outputs). | Re-route all the outputs of sgv1 to sgv0 (see _reroute_outputs). | [
"Re",
"-",
"route",
"all",
"the",
"outputs",
"of",
"sgv1",
"to",
"sgv0",
"(",
"see",
"_reroute_outputs",
")",
"."
] | def reroute_b2a_outputs(sgv0, sgv1):
"""Re-route all the outputs of sgv1 to sgv0 (see _reroute_outputs)."""
return _reroute_sgv_outputs(sgv0, sgv1, _RerouteMode.b2a) | [
"def",
"reroute_b2a_outputs",
"(",
"sgv0",
",",
"sgv1",
")",
":",
"return",
"_reroute_sgv_outputs",
"(",
"sgv0",
",",
"sgv1",
",",
"_RerouteMode",
".",
"b2a",
")"
] | https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/tensorflow/contrib/graph_editor/reroute.py#L423-L425 | |
VelsonWang/HmiFuncDesigner | 439265da17bd3424e678932cbfbc0237b52630f3 | HmiFuncDesigner/libs/qscintilla/Python/configure.py | python | ModuleConfiguration.apply_options | (target_configuration, options) | Apply the module specific command line options to the target
configuration. target_configuration is the target configuration.
options are the parsed options. | Apply the module specific command line options to the target
configuration. target_configuration is the target configuration.
options are the parsed options. | [
"Apply",
"the",
"module",
"specific",
"command",
"line",
"options",
"to",
"the",
"target",
"configuration",
".",
"target_configuration",
"is",
"the",
"target",
"configuration",
".",
"options",
"are",
"the",
"parsed",
"options",
"."
] | def apply_options(target_configuration, options):
""" Apply the module specific command line options to the target
configuration. target_configuration is the target configuration.
options are the parsed options.
"""
if options.qsci_features_dir is not None:
target_configuration.qsci_features_dir = options.qsci_features_dir
if options.qsci_inc_dir is not None:
target_configuration.qsci_inc_dir = options.qsci_inc_dir
if options.qsci_lib_dir is not None:
target_configuration.qsci_lib_dir = options.qsci_lib_dir
if options.qsci_sip_dir is not None:
target_configuration.qsci_sip_dir = options.qsci_sip_dir
else:
target_configuration.qsci_sip_dir = target_configuration.pyqt_sip_dir
if options.qsci_no_sip_files:
target_configuration.qsci_sip_dir = '' | [
"def",
"apply_options",
"(",
"target_configuration",
",",
"options",
")",
":",
"if",
"options",
".",
"qsci_features_dir",
"is",
"not",
"None",
":",
"target_configuration",
".",
"qsci_features_dir",
"=",
"options",
".",
"qsci_features_dir",
"if",
"options",
".",
"qsci_inc_dir",
"is",
"not",
"None",
":",
"target_configuration",
".",
"qsci_inc_dir",
"=",
"options",
".",
"qsci_inc_dir",
"if",
"options",
".",
"qsci_lib_dir",
"is",
"not",
"None",
":",
"target_configuration",
".",
"qsci_lib_dir",
"=",
"options",
".",
"qsci_lib_dir",
"if",
"options",
".",
"qsci_sip_dir",
"is",
"not",
"None",
":",
"target_configuration",
".",
"qsci_sip_dir",
"=",
"options",
".",
"qsci_sip_dir",
"else",
":",
"target_configuration",
".",
"qsci_sip_dir",
"=",
"target_configuration",
".",
"pyqt_sip_dir",
"if",
"options",
".",
"qsci_no_sip_files",
":",
"target_configuration",
".",
"qsci_sip_dir",
"=",
"''"
] | https://github.com/VelsonWang/HmiFuncDesigner/blob/439265da17bd3424e678932cbfbc0237b52630f3/HmiFuncDesigner/libs/qscintilla/Python/configure.py#L170-L191 | ||
larroy/clearskies_core | 3574ddf0edc8555454c7044126e786a6c29444dc | tools/gyp/pylib/gyp/xcodeproj_file.py | python | XCObject.Children | (self) | return children | Returns a list of all of this object's owned (strong) children. | Returns a list of all of this object's owned (strong) children. | [
"Returns",
"a",
"list",
"of",
"all",
"of",
"this",
"object",
"s",
"owned",
"(",
"strong",
")",
"children",
"."
] | def Children(self):
"""Returns a list of all of this object's owned (strong) children."""
children = []
for property, attributes in self._schema.iteritems():
(is_list, property_type, is_strong) = attributes[0:3]
if is_strong and property in self._properties:
if not is_list:
children.append(self._properties[property])
else:
children.extend(self._properties[property])
return children | [
"def",
"Children",
"(",
"self",
")",
":",
"children",
"=",
"[",
"]",
"for",
"property",
",",
"attributes",
"in",
"self",
".",
"_schema",
".",
"iteritems",
"(",
")",
":",
"(",
"is_list",
",",
"property_type",
",",
"is_strong",
")",
"=",
"attributes",
"[",
"0",
":",
"3",
"]",
"if",
"is_strong",
"and",
"property",
"in",
"self",
".",
"_properties",
":",
"if",
"not",
"is_list",
":",
"children",
".",
"append",
"(",
"self",
".",
"_properties",
"[",
"property",
"]",
")",
"else",
":",
"children",
".",
"extend",
"(",
"self",
".",
"_properties",
"[",
"property",
"]",
")",
"return",
"children"
] | https://github.com/larroy/clearskies_core/blob/3574ddf0edc8555454c7044126e786a6c29444dc/tools/gyp/pylib/gyp/xcodeproj_file.py#L475-L486 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/x86/toolchain/lib/python2.7/mailbox.py | python | Mailbox.keys | (self) | return list(self.iterkeys()) | Return a list of keys. | Return a list of keys. | [
"Return",
"a",
"list",
"of",
"keys",
"."
] | def keys(self):
"""Return a list of keys."""
return list(self.iterkeys()) | [
"def",
"keys",
"(",
"self",
")",
":",
"return",
"list",
"(",
"self",
".",
"iterkeys",
"(",
")",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/mailbox.py#L102-L104 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numpy/random/_examples/cffi/parse.py | python | parse_distributions_h | (ffi, inc_dir) | Parse distributions.h located in inc_dir for CFFI, filling in the ffi.cdef
Read the function declarations without the "#define ..." macros that will
be filled in when loading the library. | Parse distributions.h located in inc_dir for CFFI, filling in the ffi.cdef | [
"Parse",
"distributions",
".",
"h",
"located",
"in",
"inc_dir",
"for",
"CFFI",
"filling",
"in",
"the",
"ffi",
".",
"cdef"
] | def parse_distributions_h(ffi, inc_dir):
"""
Parse distributions.h located in inc_dir for CFFI, filling in the ffi.cdef
Read the function declarations without the "#define ..." macros that will
be filled in when loading the library.
"""
with open(os.path.join(inc_dir, 'random', 'bitgen.h')) as fid:
s = []
for line in fid:
# massage the include file
if line.strip().startswith('#'):
continue
s.append(line)
ffi.cdef('\n'.join(s))
with open(os.path.join(inc_dir, 'random', 'distributions.h')) as fid:
s = []
in_skip = 0
for line in fid:
# massage the include file
if line.strip().startswith('#'):
continue
# skip any inlined function definition
# which starts with 'static NPY_INLINE xxx(...) {'
# and ends with a closing '}'
if line.strip().startswith('static NPY_INLINE'):
in_skip += line.count('{')
continue
elif in_skip > 0:
in_skip += line.count('{')
in_skip -= line.count('}')
continue
# replace defines with their value or remove them
line = line.replace('DECLDIR', '')
line = line.replace('NPY_INLINE', '')
line = line.replace('RAND_INT_TYPE', 'int64_t')
s.append(line)
ffi.cdef('\n'.join(s)) | [
"def",
"parse_distributions_h",
"(",
"ffi",
",",
"inc_dir",
")",
":",
"with",
"open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"inc_dir",
",",
"'random'",
",",
"'bitgen.h'",
")",
")",
"as",
"fid",
":",
"s",
"=",
"[",
"]",
"for",
"line",
"in",
"fid",
":",
"# massage the include file",
"if",
"line",
".",
"strip",
"(",
")",
".",
"startswith",
"(",
"'#'",
")",
":",
"continue",
"s",
".",
"append",
"(",
"line",
")",
"ffi",
".",
"cdef",
"(",
"'\\n'",
".",
"join",
"(",
"s",
")",
")",
"with",
"open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"inc_dir",
",",
"'random'",
",",
"'distributions.h'",
")",
")",
"as",
"fid",
":",
"s",
"=",
"[",
"]",
"in_skip",
"=",
"0",
"for",
"line",
"in",
"fid",
":",
"# massage the include file",
"if",
"line",
".",
"strip",
"(",
")",
".",
"startswith",
"(",
"'#'",
")",
":",
"continue",
"# skip any inlined function definition",
"# which starts with 'static NPY_INLINE xxx(...) {'",
"# and ends with a closing '}'",
"if",
"line",
".",
"strip",
"(",
")",
".",
"startswith",
"(",
"'static NPY_INLINE'",
")",
":",
"in_skip",
"+=",
"line",
".",
"count",
"(",
"'{'",
")",
"continue",
"elif",
"in_skip",
">",
"0",
":",
"in_skip",
"+=",
"line",
".",
"count",
"(",
"'{'",
")",
"in_skip",
"-=",
"line",
".",
"count",
"(",
"'}'",
")",
"continue",
"# replace defines with their value or remove them",
"line",
"=",
"line",
".",
"replace",
"(",
"'DECLDIR'",
",",
"''",
")",
"line",
"=",
"line",
".",
"replace",
"(",
"'NPY_INLINE'",
",",
"''",
")",
"line",
"=",
"line",
".",
"replace",
"(",
"'RAND_INT_TYPE'",
",",
"'int64_t'",
")",
"s",
".",
"append",
"(",
"line",
")",
"ffi",
".",
"cdef",
"(",
"'\\n'",
".",
"join",
"(",
"s",
")",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numpy/random/_examples/cffi/parse.py#L4-L45 | ||
cmu-sei/pharos | af54b6ada58d50c046fa899452addce80e9ce8da | tools/ooanalyzer/ida/OOAnalyzer.py | python | PyOOAnalyzer.__parse_members | (self, cls, members) | return | Add each member specified | Add each member specified | [
"Add",
"each",
"member",
"specified"
] | def __parse_members(self, cls, members):
'''
Add each member specified
'''
print("Parsing %d members for class %s ..." %
(len(members), cls.ida_name))
for m in members.values ():
offset = int(m['offset'], 16)
if offset > 0x7FFFFFFF:
offset -= 0x100000000
if offset < 0:
print("WARNING: Negative member offset (%d) found - discarding" % offset)
continue
# valid member - create it
mem = PyClassMember(cls, m['type'], m['size'])
mem.cls = cls
mem.base = m['base']
mem.member_name = m['name']
self.__parse_member_usages (cls, m['usages'])
if mem.member_type == ida_bytes.FF_STRUCT:
mem.class_member_name = m['struc'] # This could be mangled
# Search for the parsed class information
cls_mem = None
for c in self.__classes:
if mem.class_member_name == c.name:
cls_mem = c
break
assert cls_mem is not None, "Unable to find class member struct %s" % mem.class_member_name
mem.class_member = cls_mem
if m['parent']:
# this is a parent
mem.is_parent = True
cls.add_parent(cls_mem, offset)
print(" - Found class parent, name: '%s', type: %s" %
(mem.member_name, mem.class_member.ida_name))
else:
print(" - Found class member, name: '%s', type: %s" %
(mem.member_name, mem.class_member.ida_name))
else:
mem.class_member = None
print(" - Found member '%s' @ offset 0x%x" %
(mem.member_name, offset))
# offset of this member
mem.offset = offset
# add the new member if it is not from the base class
if not mem.base:
cls.add_member(mem, offset)
if cls.id != idaapi.BADADDR:
mid = idc.get_member_id(cls.id, offset)
if mid != -1:
mem.id = mid
print("Members parsed")
return | [
"def",
"__parse_members",
"(",
"self",
",",
"cls",
",",
"members",
")",
":",
"print",
"(",
"\"Parsing %d members for class %s ...\"",
"%",
"(",
"len",
"(",
"members",
")",
",",
"cls",
".",
"ida_name",
")",
")",
"for",
"m",
"in",
"members",
".",
"values",
"(",
")",
":",
"offset",
"=",
"int",
"(",
"m",
"[",
"'offset'",
"]",
",",
"16",
")",
"if",
"offset",
">",
"0x7FFFFFFF",
":",
"offset",
"-=",
"0x100000000",
"if",
"offset",
"<",
"0",
":",
"print",
"(",
"\"WARNING: Negative member offset (%d) found - discarding\"",
"%",
"offset",
")",
"continue",
"# valid member - create it",
"mem",
"=",
"PyClassMember",
"(",
"cls",
",",
"m",
"[",
"'type'",
"]",
",",
"m",
"[",
"'size'",
"]",
")",
"mem",
".",
"cls",
"=",
"cls",
"mem",
".",
"base",
"=",
"m",
"[",
"'base'",
"]",
"mem",
".",
"member_name",
"=",
"m",
"[",
"'name'",
"]",
"self",
".",
"__parse_member_usages",
"(",
"cls",
",",
"m",
"[",
"'usages'",
"]",
")",
"if",
"mem",
".",
"member_type",
"==",
"ida_bytes",
".",
"FF_STRUCT",
":",
"mem",
".",
"class_member_name",
"=",
"m",
"[",
"'struc'",
"]",
"# This could be mangled",
"# Search for the parsed class information",
"cls_mem",
"=",
"None",
"for",
"c",
"in",
"self",
".",
"__classes",
":",
"if",
"mem",
".",
"class_member_name",
"==",
"c",
".",
"name",
":",
"cls_mem",
"=",
"c",
"break",
"assert",
"cls_mem",
"is",
"not",
"None",
",",
"\"Unable to find class member struct %s\"",
"%",
"mem",
".",
"class_member_name",
"mem",
".",
"class_member",
"=",
"cls_mem",
"if",
"m",
"[",
"'parent'",
"]",
":",
"# this is a parent",
"mem",
".",
"is_parent",
"=",
"True",
"cls",
".",
"add_parent",
"(",
"cls_mem",
",",
"offset",
")",
"print",
"(",
"\" - Found class parent, name: '%s', type: %s\"",
"%",
"(",
"mem",
".",
"member_name",
",",
"mem",
".",
"class_member",
".",
"ida_name",
")",
")",
"else",
":",
"print",
"(",
"\" - Found class member, name: '%s', type: %s\"",
"%",
"(",
"mem",
".",
"member_name",
",",
"mem",
".",
"class_member",
".",
"ida_name",
")",
")",
"else",
":",
"mem",
".",
"class_member",
"=",
"None",
"print",
"(",
"\" - Found member '%s' @ offset 0x%x\"",
"%",
"(",
"mem",
".",
"member_name",
",",
"offset",
")",
")",
"# offset of this member",
"mem",
".",
"offset",
"=",
"offset",
"# add the new member if it is not from the base class",
"if",
"not",
"mem",
".",
"base",
":",
"cls",
".",
"add_member",
"(",
"mem",
",",
"offset",
")",
"if",
"cls",
".",
"id",
"!=",
"idaapi",
".",
"BADADDR",
":",
"mid",
"=",
"idc",
".",
"get_member_id",
"(",
"cls",
".",
"id",
",",
"offset",
")",
"if",
"mid",
"!=",
"-",
"1",
":",
"mem",
".",
"id",
"=",
"mid",
"print",
"(",
"\"Members parsed\"",
")",
"return"
] | https://github.com/cmu-sei/pharos/blob/af54b6ada58d50c046fa899452addce80e9ce8da/tools/ooanalyzer/ida/OOAnalyzer.py#L351-L420 | |
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/keras/engine/training_utils.py | python | prepare_loss_functions | (loss, output_names) | return loss_functions | Converts loss to a list of loss functions.
Arguments:
loss: String (name of objective function), objective function or
`tf.losses.Loss` instance. See `tf.losses`. If the model has multiple
outputs, you can use a different loss on each output by passing a
dictionary or a list of losses. The loss value that will be minimized by
the model will then be the sum of all individual losses.
output_names: List of model output names.
Returns:
A list of loss objective functions.
Raises:
ValueError: If loss is a dict with keys not in model output names,
or if loss is a list with len not equal to model outputs. | Converts loss to a list of loss functions. | [
"Converts",
"loss",
"to",
"a",
"list",
"of",
"loss",
"functions",
"."
] | def prepare_loss_functions(loss, output_names):
"""Converts loss to a list of loss functions.
Arguments:
loss: String (name of objective function), objective function or
`tf.losses.Loss` instance. See `tf.losses`. If the model has multiple
outputs, you can use a different loss on each output by passing a
dictionary or a list of losses. The loss value that will be minimized by
the model will then be the sum of all individual losses.
output_names: List of model output names.
Returns:
A list of loss objective functions.
Raises:
ValueError: If loss is a dict with keys not in model output names,
or if loss is a list with len not equal to model outputs.
"""
if isinstance(loss, collections_abc.Mapping):
generic_utils.check_for_unexpected_keys('loss', loss, output_names)
loss_functions = []
for name in output_names:
if name not in loss:
logging.warning(
'Output {0} missing from loss dictionary. We assume '
'this was done on purpose. The fit and evaluate APIs will not be '
'expecting any data to be passed to {0}.'.format(name))
loss_functions.append(get_loss_function(loss.get(name, None)))
elif isinstance(loss, six.string_types):
loss_functions = [get_loss_function(loss) for _ in output_names]
elif isinstance(loss, collections_abc.Sequence):
if len(loss) != len(output_names):
raise ValueError('When passing a list as loss, it should have one entry '
'per model outputs. The model has {} outputs, but you '
'passed loss={}'.format(len(output_names), loss))
loss_functions = nest.map_structure(get_loss_function, loss)
else:
loss_functions = [get_loss_function(loss) for _ in range(len(output_names))]
return loss_functions | [
"def",
"prepare_loss_functions",
"(",
"loss",
",",
"output_names",
")",
":",
"if",
"isinstance",
"(",
"loss",
",",
"collections_abc",
".",
"Mapping",
")",
":",
"generic_utils",
".",
"check_for_unexpected_keys",
"(",
"'loss'",
",",
"loss",
",",
"output_names",
")",
"loss_functions",
"=",
"[",
"]",
"for",
"name",
"in",
"output_names",
":",
"if",
"name",
"not",
"in",
"loss",
":",
"logging",
".",
"warning",
"(",
"'Output {0} missing from loss dictionary. We assume '",
"'this was done on purpose. The fit and evaluate APIs will not be '",
"'expecting any data to be passed to {0}.'",
".",
"format",
"(",
"name",
")",
")",
"loss_functions",
".",
"append",
"(",
"get_loss_function",
"(",
"loss",
".",
"get",
"(",
"name",
",",
"None",
")",
")",
")",
"elif",
"isinstance",
"(",
"loss",
",",
"six",
".",
"string_types",
")",
":",
"loss_functions",
"=",
"[",
"get_loss_function",
"(",
"loss",
")",
"for",
"_",
"in",
"output_names",
"]",
"elif",
"isinstance",
"(",
"loss",
",",
"collections_abc",
".",
"Sequence",
")",
":",
"if",
"len",
"(",
"loss",
")",
"!=",
"len",
"(",
"output_names",
")",
":",
"raise",
"ValueError",
"(",
"'When passing a list as loss, it should have one entry '",
"'per model outputs. The model has {} outputs, but you '",
"'passed loss={}'",
".",
"format",
"(",
"len",
"(",
"output_names",
")",
",",
"loss",
")",
")",
"loss_functions",
"=",
"nest",
".",
"map_structure",
"(",
"get_loss_function",
",",
"loss",
")",
"else",
":",
"loss_functions",
"=",
"[",
"get_loss_function",
"(",
"loss",
")",
"for",
"_",
"in",
"range",
"(",
"len",
"(",
"output_names",
")",
")",
"]",
"return",
"loss_functions"
] | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/keras/engine/training_utils.py#L1320-L1359 | |
apple/swift-clang | d7403439fc6641751840b723e7165fb02f52db95 | utils/check_cfc/check_cfc.py | python | is_output_specified | (args) | return get_output_file(args) is not None | Return true is output file is specified in args. | Return true is output file is specified in args. | [
"Return",
"true",
"is",
"output",
"file",
"is",
"specified",
"in",
"args",
"."
] | def is_output_specified(args):
"""Return true is output file is specified in args."""
return get_output_file(args) is not None | [
"def",
"is_output_specified",
"(",
"args",
")",
":",
"return",
"get_output_file",
"(",
"args",
")",
"is",
"not",
"None"
] | https://github.com/apple/swift-clang/blob/d7403439fc6641751840b723e7165fb02f52db95/utils/check_cfc/check_cfc.py#L147-L149 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_vendor/requests/utils.py | python | dict_from_cookiejar | (cj) | return cookie_dict | Returns a key/value dictionary from a CookieJar.
:param cj: CookieJar object to extract cookies from.
:rtype: dict | Returns a key/value dictionary from a CookieJar. | [
"Returns",
"a",
"key",
"/",
"value",
"dictionary",
"from",
"a",
"CookieJar",
"."
] | def dict_from_cookiejar(cj):
"""Returns a key/value dictionary from a CookieJar.
:param cj: CookieJar object to extract cookies from.
:rtype: dict
"""
cookie_dict = {}
for cookie in cj:
cookie_dict[cookie.name] = cookie.value
return cookie_dict | [
"def",
"dict_from_cookiejar",
"(",
"cj",
")",
":",
"cookie_dict",
"=",
"{",
"}",
"for",
"cookie",
"in",
"cj",
":",
"cookie_dict",
"[",
"cookie",
".",
"name",
"]",
"=",
"cookie",
".",
"value",
"return",
"cookie_dict"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_vendor/requests/utils.py#L415-L427 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/pdb.py | python | Pdb.do_commands | (self, arg) | Defines a list of commands associated to a breakpoint.
Those commands will be executed whenever the breakpoint causes
the program to stop execution. | Defines a list of commands associated to a breakpoint. | [
"Defines",
"a",
"list",
"of",
"commands",
"associated",
"to",
"a",
"breakpoint",
"."
] | def do_commands(self, arg):
"""Defines a list of commands associated to a breakpoint.
Those commands will be executed whenever the breakpoint causes
the program to stop execution."""
if not arg:
bnum = len(bdb.Breakpoint.bpbynumber)-1
else:
try:
bnum = int(arg)
except:
print >>self.stdout, "Usage : commands [bnum]\n ..." \
"\n end"
return
self.commands_bnum = bnum
self.commands[bnum] = []
self.commands_doprompt[bnum] = True
self.commands_silent[bnum] = False
prompt_back = self.prompt
self.prompt = '(com) '
self.commands_defining = True
try:
self.cmdloop()
finally:
self.commands_defining = False
self.prompt = prompt_back | [
"def",
"do_commands",
"(",
"self",
",",
"arg",
")",
":",
"if",
"not",
"arg",
":",
"bnum",
"=",
"len",
"(",
"bdb",
".",
"Breakpoint",
".",
"bpbynumber",
")",
"-",
"1",
"else",
":",
"try",
":",
"bnum",
"=",
"int",
"(",
"arg",
")",
"except",
":",
"print",
">>",
"self",
".",
"stdout",
",",
"\"Usage : commands [bnum]\\n ...\"",
"\"\\n end\"",
"return",
"self",
".",
"commands_bnum",
"=",
"bnum",
"self",
".",
"commands",
"[",
"bnum",
"]",
"=",
"[",
"]",
"self",
".",
"commands_doprompt",
"[",
"bnum",
"]",
"=",
"True",
"self",
".",
"commands_silent",
"[",
"bnum",
"]",
"=",
"False",
"prompt_back",
"=",
"self",
".",
"prompt",
"self",
".",
"prompt",
"=",
"'(com) '",
"self",
".",
"commands_defining",
"=",
"True",
"try",
":",
"self",
".",
"cmdloop",
"(",
")",
"finally",
":",
"self",
".",
"commands_defining",
"=",
"False",
"self",
".",
"prompt",
"=",
"prompt_back"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/pdb.py#L317-L342 | ||
microsoft/CNTK | e9396480025b9ca457d26b6f33dd07c474c6aa04 | Examples/Image/Detection/FastRCNN/BrainScript/selectivesearch/selectivesearch.py | python | _sim_texture | (r1, r2) | return sum([min(a, b) for a, b in zip(r1["hist_t"], r2["hist_t"])]) | calculate the sum of histogram intersection of texture | calculate the sum of histogram intersection of texture | [
"calculate",
"the",
"sum",
"of",
"histogram",
"intersection",
"of",
"texture"
] | def _sim_texture(r1, r2):
"""
calculate the sum of histogram intersection of texture
"""
return sum([min(a, b) for a, b in zip(r1["hist_t"], r2["hist_t"])]) | [
"def",
"_sim_texture",
"(",
"r1",
",",
"r2",
")",
":",
"return",
"sum",
"(",
"[",
"min",
"(",
"a",
",",
"b",
")",
"for",
"a",
",",
"b",
"in",
"zip",
"(",
"r1",
"[",
"\"hist_t\"",
"]",
",",
"r2",
"[",
"\"hist_t\"",
"]",
")",
"]",
")"
] | https://github.com/microsoft/CNTK/blob/e9396480025b9ca457d26b6f33dd07c474c6aa04/Examples/Image/Detection/FastRCNN/BrainScript/selectivesearch/selectivesearch.py#L44-L48 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/protobuf/py3/google/protobuf/json_format.py | python | _Parser._ConvertValueMessage | (self, value, message) | Convert a JSON representation into Value message. | Convert a JSON representation into Value message. | [
"Convert",
"a",
"JSON",
"representation",
"into",
"Value",
"message",
"."
] | def _ConvertValueMessage(self, value, message):
"""Convert a JSON representation into Value message."""
if isinstance(value, dict):
self._ConvertStructMessage(value, message.struct_value)
elif isinstance(value, list):
self. _ConvertListValueMessage(value, message.list_value)
elif value is None:
message.null_value = 0
elif isinstance(value, bool):
message.bool_value = value
elif isinstance(value, six.string_types):
message.string_value = value
elif isinstance(value, _INT_OR_FLOAT):
message.number_value = value
else:
raise ParseError('Value {0} has unexpected type {1}.'.format(
value, type(value))) | [
"def",
"_ConvertValueMessage",
"(",
"self",
",",
"value",
",",
"message",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"dict",
")",
":",
"self",
".",
"_ConvertStructMessage",
"(",
"value",
",",
"message",
".",
"struct_value",
")",
"elif",
"isinstance",
"(",
"value",
",",
"list",
")",
":",
"self",
".",
"_ConvertListValueMessage",
"(",
"value",
",",
"message",
".",
"list_value",
")",
"elif",
"value",
"is",
"None",
":",
"message",
".",
"null_value",
"=",
"0",
"elif",
"isinstance",
"(",
"value",
",",
"bool",
")",
":",
"message",
".",
"bool_value",
"=",
"value",
"elif",
"isinstance",
"(",
"value",
",",
"six",
".",
"string_types",
")",
":",
"message",
".",
"string_value",
"=",
"value",
"elif",
"isinstance",
"(",
"value",
",",
"_INT_OR_FLOAT",
")",
":",
"message",
".",
"number_value",
"=",
"value",
"else",
":",
"raise",
"ParseError",
"(",
"'Value {0} has unexpected type {1}.'",
".",
"format",
"(",
"value",
",",
"type",
"(",
"value",
")",
")",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/protobuf/py3/google/protobuf/json_format.py#L639-L655 | ||
windystrife/UnrealEngine_NVIDIAGameWorks | b50e6338a7c5b26374d66306ebc7807541ff815e | Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/site-packages/setuptools/dist.py | python | Distribution.get_cmdline_options | (self) | return d | Return a '{cmd: {opt:val}}' map of all command-line options
Option names are all long, but do not include the leading '--', and
contain dashes rather than underscores. If the option doesn't take
an argument (e.g. '--quiet'), the 'val' is 'None'.
Note that options provided by config files are intentionally excluded. | Return a '{cmd: {opt:val}}' map of all command-line options | [
"Return",
"a",
"{",
"cmd",
":",
"{",
"opt",
":",
"val",
"}}",
"map",
"of",
"all",
"command",
"-",
"line",
"options"
] | def get_cmdline_options(self):
"""Return a '{cmd: {opt:val}}' map of all command-line options
Option names are all long, but do not include the leading '--', and
contain dashes rather than underscores. If the option doesn't take
an argument (e.g. '--quiet'), the 'val' is 'None'.
Note that options provided by config files are intentionally excluded.
"""
d = {}
for cmd,opts in self.command_options.items():
for opt,(src,val) in opts.items():
if src != "command line":
continue
opt = opt.replace('_','-')
if val==0:
cmdobj = self.get_command_obj(cmd)
neg_opt = self.negative_opt.copy()
neg_opt.update(getattr(cmdobj,'negative_opt',{}))
for neg,pos in neg_opt.items():
if pos==opt:
opt=neg
val=None
break
else:
raise AssertionError("Shouldn't be able to get here")
elif val==1:
val = None
d.setdefault(cmd,{})[opt] = val
return d | [
"def",
"get_cmdline_options",
"(",
"self",
")",
":",
"d",
"=",
"{",
"}",
"for",
"cmd",
",",
"opts",
"in",
"self",
".",
"command_options",
".",
"items",
"(",
")",
":",
"for",
"opt",
",",
"(",
"src",
",",
"val",
")",
"in",
"opts",
".",
"items",
"(",
")",
":",
"if",
"src",
"!=",
"\"command line\"",
":",
"continue",
"opt",
"=",
"opt",
".",
"replace",
"(",
"'_'",
",",
"'-'",
")",
"if",
"val",
"==",
"0",
":",
"cmdobj",
"=",
"self",
".",
"get_command_obj",
"(",
"cmd",
")",
"neg_opt",
"=",
"self",
".",
"negative_opt",
".",
"copy",
"(",
")",
"neg_opt",
".",
"update",
"(",
"getattr",
"(",
"cmdobj",
",",
"'negative_opt'",
",",
"{",
"}",
")",
")",
"for",
"neg",
",",
"pos",
"in",
"neg_opt",
".",
"items",
"(",
")",
":",
"if",
"pos",
"==",
"opt",
":",
"opt",
"=",
"neg",
"val",
"=",
"None",
"break",
"else",
":",
"raise",
"AssertionError",
"(",
"\"Shouldn't be able to get here\"",
")",
"elif",
"val",
"==",
"1",
":",
"val",
"=",
"None",
"d",
".",
"setdefault",
"(",
"cmd",
",",
"{",
"}",
")",
"[",
"opt",
"]",
"=",
"val",
"return",
"d"
] | https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/site-packages/setuptools/dist.py#L633-L671 | |
windystrife/UnrealEngine_NVIDIAGameWorks | b50e6338a7c5b26374d66306ebc7807541ff815e | Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/numbers.py | python | Real.__floordiv__ | (self, other) | self // other: The floor() of self/other. | self // other: The floor() of self/other. | [
"self",
"//",
"other",
":",
"The",
"floor",
"()",
"of",
"self",
"/",
"other",
"."
] | def __floordiv__(self, other):
"""self // other: The floor() of self/other."""
raise NotImplementedError | [
"def",
"__floordiv__",
"(",
"self",
",",
"other",
")",
":",
"raise",
"NotImplementedError"
] | https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/numbers.py#L217-L219 | ||
ricardoquesada/Spidermonkey | 4a75ea2543408bd1b2c515aa95901523eeef7858 | config/configobj.py | python | Section.rename | (self, oldkey, newkey) | Change a keyname to another, without changing position in sequence.
Implemented so that transformations can be made on keys,
as well as on values. (used by encode and decode)
Also renames comments. | Change a keyname to another, without changing position in sequence.
Implemented so that transformations can be made on keys,
as well as on values. (used by encode and decode)
Also renames comments. | [
"Change",
"a",
"keyname",
"to",
"another",
"without",
"changing",
"position",
"in",
"sequence",
".",
"Implemented",
"so",
"that",
"transformations",
"can",
"be",
"made",
"on",
"keys",
"as",
"well",
"as",
"on",
"values",
".",
"(",
"used",
"by",
"encode",
"and",
"decode",
")",
"Also",
"renames",
"comments",
"."
] | def rename(self, oldkey, newkey):
"""
Change a keyname to another, without changing position in sequence.
Implemented so that transformations can be made on keys,
as well as on values. (used by encode and decode)
Also renames comments.
"""
if oldkey in self.scalars:
the_list = self.scalars
elif oldkey in self.sections:
the_list = self.sections
else:
raise KeyError, 'Key "%s" not found.' % oldkey
pos = the_list.index(oldkey)
#
val = self[oldkey]
dict.__delitem__(self, oldkey)
dict.__setitem__(self, newkey, val)
the_list.remove(oldkey)
the_list.insert(pos, newkey)
comm = self.comments[oldkey]
inline_comment = self.inline_comments[oldkey]
del self.comments[oldkey]
del self.inline_comments[oldkey]
self.comments[newkey] = comm
self.inline_comments[newkey] = inline_comment | [
"def",
"rename",
"(",
"self",
",",
"oldkey",
",",
"newkey",
")",
":",
"if",
"oldkey",
"in",
"self",
".",
"scalars",
":",
"the_list",
"=",
"self",
".",
"scalars",
"elif",
"oldkey",
"in",
"self",
".",
"sections",
":",
"the_list",
"=",
"self",
".",
"sections",
"else",
":",
"raise",
"KeyError",
",",
"'Key \"%s\" not found.'",
"%",
"oldkey",
"pos",
"=",
"the_list",
".",
"index",
"(",
"oldkey",
")",
"#",
"val",
"=",
"self",
"[",
"oldkey",
"]",
"dict",
".",
"__delitem__",
"(",
"self",
",",
"oldkey",
")",
"dict",
".",
"__setitem__",
"(",
"self",
",",
"newkey",
",",
"val",
")",
"the_list",
".",
"remove",
"(",
"oldkey",
")",
"the_list",
".",
"insert",
"(",
"pos",
",",
"newkey",
")",
"comm",
"=",
"self",
".",
"comments",
"[",
"oldkey",
"]",
"inline_comment",
"=",
"self",
".",
"inline_comments",
"[",
"oldkey",
"]",
"del",
"self",
".",
"comments",
"[",
"oldkey",
"]",
"del",
"self",
".",
"inline_comments",
"[",
"oldkey",
"]",
"self",
".",
"comments",
"[",
"newkey",
"]",
"=",
"comm",
"self",
".",
"inline_comments",
"[",
"newkey",
"]",
"=",
"inline_comment"
] | https://github.com/ricardoquesada/Spidermonkey/blob/4a75ea2543408bd1b2c515aa95901523eeef7858/config/configobj.py#L754-L781 | ||
cmu-db/noisepage | 79276e68fe83322f1249e8a8be96bd63c583ae56 | script/self_driving/model_server.py | python | AbstractModel.infer | (self, data: Dict) | Do inference on the model, give the data file, and the model_map_path
:param data: data used for inference
:return: {List of predictions, if inference succeeds, error message} | Do inference on the model, give the data file, and the model_map_path
:param data: data used for inference
:return: {List of predictions, if inference succeeds, error message} | [
"Do",
"inference",
"on",
"the",
"model",
"give",
"the",
"data",
"file",
"and",
"the",
"model_map_path",
":",
"param",
"data",
":",
"data",
"used",
"for",
"inference",
":",
"return",
":",
"{",
"List",
"of",
"predictions",
"if",
"inference",
"succeeds",
"error",
"message",
"}"
] | def infer(self, data: Dict) -> Tuple[Any, bool, str]:
"""
Do inference on the model, give the data file, and the model_map_path
:param data: data used for inference
:return: {List of predictions, if inference succeeds, error message}
"""
raise NotImplementedError("Should be implemented by child classes") | [
"def",
"infer",
"(",
"self",
",",
"data",
":",
"Dict",
")",
"->",
"Tuple",
"[",
"Any",
",",
"bool",
",",
"str",
"]",
":",
"raise",
"NotImplementedError",
"(",
"\"Should be implemented by child classes\"",
")"
] | https://github.com/cmu-db/noisepage/blob/79276e68fe83322f1249e8a8be96bd63c583ae56/script/self_driving/model_server.py#L158-L164 | ||
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/distribute/cluster_resolver/tpu/tpu_cluster_resolver.py | python | TPUClusterResolver.get_tpu_system_metadata | (self) | return tpu_system_metadata | Returns the metadata of the TPU system.
Users can call this method to get some facts of the TPU system, like
total number of cores, number of TPU workers and the devices. E.g.
```python
resolver = tf.distribute.cluster_resolver.TPUClusterResolver(tpu='')
tpu_system_metadata = resolver.get_tpu_system_metadata()
num_hosts = tpu_system_metadata.num_hosts
```
Returns:
A `tf.tpu.experimental.TPUSystemMetadata` object. | Returns the metadata of the TPU system. | [
"Returns",
"the",
"metadata",
"of",
"the",
"TPU",
"system",
"."
] | def get_tpu_system_metadata(self):
"""Returns the metadata of the TPU system.
Users can call this method to get some facts of the TPU system, like
total number of cores, number of TPU workers and the devices. E.g.
```python
resolver = tf.distribute.cluster_resolver.TPUClusterResolver(tpu='')
tpu_system_metadata = resolver.get_tpu_system_metadata()
num_hosts = tpu_system_metadata.num_hosts
```
Returns:
A `tf.tpu.experimental.TPUSystemMetadata` object.
"""
cluster_spec = self.cluster_spec()
cluster_def = cluster_spec.as_cluster_def() if cluster_spec else None
tpu_system_metadata = (
tpu_system_metadata_lib._query_tpu_system_metadata( # pylint: disable=protected-access
self.master(),
cluster_def=cluster_def,
query_topology=False))
return tpu_system_metadata | [
"def",
"get_tpu_system_metadata",
"(",
"self",
")",
":",
"cluster_spec",
"=",
"self",
".",
"cluster_spec",
"(",
")",
"cluster_def",
"=",
"cluster_spec",
".",
"as_cluster_def",
"(",
")",
"if",
"cluster_spec",
"else",
"None",
"tpu_system_metadata",
"=",
"(",
"tpu_system_metadata_lib",
".",
"_query_tpu_system_metadata",
"(",
"# pylint: disable=protected-access",
"self",
".",
"master",
"(",
")",
",",
"cluster_def",
"=",
"cluster_def",
",",
"query_topology",
"=",
"False",
")",
")",
"return",
"tpu_system_metadata"
] | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/distribute/cluster_resolver/tpu/tpu_cluster_resolver.py#L276-L299 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/third_party/closure_linter/closure_linter/gjslint.py | python | main | (argv=None) | Main function.
Args:
argv: Sequence of command line arguments. | Main function. | [
"Main",
"function",
"."
] | def main(argv=None):
"""Main function.
Args:
argv: Sequence of command line arguments.
"""
if argv is None:
argv = flags.FLAGS(sys.argv)
if FLAGS.time:
start_time = time.time()
# Emacs sets the environment variable INSIDE_EMACS in the subshell.
# Request Unix mode as emacs will expect output to be in Unix format
# for integration.
# See https://www.gnu.org/software/emacs/manual/html_node/emacs/
# Interactive-Shell.html
if 'INSIDE_EMACS' in os.environ:
FLAGS.unix_mode = True
suffixes = ['.js']
if FLAGS.additional_extensions:
suffixes += ['.%s' % ext for ext in FLAGS.additional_extensions]
if FLAGS.check_html:
suffixes += ['.html', '.htm']
paths = fileflags.GetFileList(argv, 'JavaScript', suffixes)
if FLAGS.multiprocess:
records_iter = _MultiprocessCheckPaths(paths)
else:
records_iter = _CheckPaths(paths)
records_iter, records_iter_copy = itertools.tee(records_iter, 2)
_PrintErrorRecords(records_iter_copy)
error_records = list(records_iter)
_PrintSummary(paths, error_records)
exit_code = 0
# If there are any errors
if error_records:
exit_code += 1
# If there are any new errors
if [r for r in error_records if r.new_error]:
exit_code += 2
if exit_code:
if FLAGS.summary:
_PrintFileSummary(paths, error_records)
if FLAGS.beep:
# Make a beep noise.
sys.stdout.write(chr(7))
# Write out instructions for using fixjsstyle script to fix some of the
# reported errors.
fix_args = []
for flag in sys.argv[1:]:
for f in GJSLINT_ONLY_FLAGS:
if flag.startswith(f):
break
else:
fix_args.append(flag)
if not FLAGS.quiet:
print """
Some of the errors reported by GJsLint may be auto-fixable using the script
fixjsstyle. Please double check any changes it makes and report any bugs. The
script can be run by executing:
fixjsstyle %s """ % ' '.join(fix_args)
if FLAGS.time:
print 'Done in %s.' % _FormatTime(time.time() - start_time)
sys.exit(exit_code) | [
"def",
"main",
"(",
"argv",
"=",
"None",
")",
":",
"if",
"argv",
"is",
"None",
":",
"argv",
"=",
"flags",
".",
"FLAGS",
"(",
"sys",
".",
"argv",
")",
"if",
"FLAGS",
".",
"time",
":",
"start_time",
"=",
"time",
".",
"time",
"(",
")",
"# Emacs sets the environment variable INSIDE_EMACS in the subshell.",
"# Request Unix mode as emacs will expect output to be in Unix format",
"# for integration.",
"# See https://www.gnu.org/software/emacs/manual/html_node/emacs/",
"# Interactive-Shell.html",
"if",
"'INSIDE_EMACS'",
"in",
"os",
".",
"environ",
":",
"FLAGS",
".",
"unix_mode",
"=",
"True",
"suffixes",
"=",
"[",
"'.js'",
"]",
"if",
"FLAGS",
".",
"additional_extensions",
":",
"suffixes",
"+=",
"[",
"'.%s'",
"%",
"ext",
"for",
"ext",
"in",
"FLAGS",
".",
"additional_extensions",
"]",
"if",
"FLAGS",
".",
"check_html",
":",
"suffixes",
"+=",
"[",
"'.html'",
",",
"'.htm'",
"]",
"paths",
"=",
"fileflags",
".",
"GetFileList",
"(",
"argv",
",",
"'JavaScript'",
",",
"suffixes",
")",
"if",
"FLAGS",
".",
"multiprocess",
":",
"records_iter",
"=",
"_MultiprocessCheckPaths",
"(",
"paths",
")",
"else",
":",
"records_iter",
"=",
"_CheckPaths",
"(",
"paths",
")",
"records_iter",
",",
"records_iter_copy",
"=",
"itertools",
".",
"tee",
"(",
"records_iter",
",",
"2",
")",
"_PrintErrorRecords",
"(",
"records_iter_copy",
")",
"error_records",
"=",
"list",
"(",
"records_iter",
")",
"_PrintSummary",
"(",
"paths",
",",
"error_records",
")",
"exit_code",
"=",
"0",
"# If there are any errors",
"if",
"error_records",
":",
"exit_code",
"+=",
"1",
"# If there are any new errors",
"if",
"[",
"r",
"for",
"r",
"in",
"error_records",
"if",
"r",
".",
"new_error",
"]",
":",
"exit_code",
"+=",
"2",
"if",
"exit_code",
":",
"if",
"FLAGS",
".",
"summary",
":",
"_PrintFileSummary",
"(",
"paths",
",",
"error_records",
")",
"if",
"FLAGS",
".",
"beep",
":",
"# Make a beep noise.",
"sys",
".",
"stdout",
".",
"write",
"(",
"chr",
"(",
"7",
")",
")",
"# Write out instructions for using fixjsstyle script to fix some of the",
"# reported errors.",
"fix_args",
"=",
"[",
"]",
"for",
"flag",
"in",
"sys",
".",
"argv",
"[",
"1",
":",
"]",
":",
"for",
"f",
"in",
"GJSLINT_ONLY_FLAGS",
":",
"if",
"flag",
".",
"startswith",
"(",
"f",
")",
":",
"break",
"else",
":",
"fix_args",
".",
"append",
"(",
"flag",
")",
"if",
"not",
"FLAGS",
".",
"quiet",
":",
"print",
"\"\"\"\nSome of the errors reported by GJsLint may be auto-fixable using the script\nfixjsstyle. Please double check any changes it makes and report any bugs. The\nscript can be run by executing:\n\nfixjsstyle %s \"\"\"",
"%",
"' '",
".",
"join",
"(",
"fix_args",
")",
"if",
"FLAGS",
".",
"time",
":",
"print",
"'Done in %s.'",
"%",
"_FormatTime",
"(",
"time",
".",
"time",
"(",
")",
"-",
"start_time",
")",
"sys",
".",
"exit",
"(",
"exit_code",
")"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/closure_linter/closure_linter/gjslint.py#L246-L323 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/setuptools/py3/setuptools/_vendor/more_itertools/more.py | python | only | (iterable, default=None, too_long=None) | return first_value | If *iterable* has only one item, return it.
If it has zero items, return *default*.
If it has more than one item, raise the exception given by *too_long*,
which is ``ValueError`` by default.
>>> only([], default='missing')
'missing'
>>> only([1])
1
>>> only([1, 2]) # doctest: +IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
...
ValueError: Expected exactly one item in iterable, but got 1, 2,
and perhaps more.'
>>> only([1, 2], too_long=TypeError) # doctest: +IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
...
TypeError
Note that :func:`only` attempts to advance *iterable* twice to ensure there
is only one item. See :func:`spy` or :func:`peekable` to check
iterable contents less destructively. | If *iterable* has only one item, return it.
If it has zero items, return *default*.
If it has more than one item, raise the exception given by *too_long*,
which is ``ValueError`` by default. | [
"If",
"*",
"iterable",
"*",
"has",
"only",
"one",
"item",
"return",
"it",
".",
"If",
"it",
"has",
"zero",
"items",
"return",
"*",
"default",
"*",
".",
"If",
"it",
"has",
"more",
"than",
"one",
"item",
"raise",
"the",
"exception",
"given",
"by",
"*",
"too_long",
"*",
"which",
"is",
"ValueError",
"by",
"default",
"."
] | def only(iterable, default=None, too_long=None):
"""If *iterable* has only one item, return it.
If it has zero items, return *default*.
If it has more than one item, raise the exception given by *too_long*,
which is ``ValueError`` by default.
>>> only([], default='missing')
'missing'
>>> only([1])
1
>>> only([1, 2]) # doctest: +IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
...
ValueError: Expected exactly one item in iterable, but got 1, 2,
and perhaps more.'
>>> only([1, 2], too_long=TypeError) # doctest: +IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
...
TypeError
Note that :func:`only` attempts to advance *iterable* twice to ensure there
is only one item. See :func:`spy` or :func:`peekable` to check
iterable contents less destructively.
"""
it = iter(iterable)
first_value = next(it, default)
try:
second_value = next(it)
except StopIteration:
pass
else:
msg = (
'Expected exactly one item in iterable, but got {!r}, {!r}, '
'and perhaps more.'.format(first_value, second_value)
)
raise too_long or ValueError(msg)
return first_value | [
"def",
"only",
"(",
"iterable",
",",
"default",
"=",
"None",
",",
"too_long",
"=",
"None",
")",
":",
"it",
"=",
"iter",
"(",
"iterable",
")",
"first_value",
"=",
"next",
"(",
"it",
",",
"default",
")",
"try",
":",
"second_value",
"=",
"next",
"(",
"it",
")",
"except",
"StopIteration",
":",
"pass",
"else",
":",
"msg",
"=",
"(",
"'Expected exactly one item in iterable, but got {!r}, {!r}, '",
"'and perhaps more.'",
".",
"format",
"(",
"first_value",
",",
"second_value",
")",
")",
"raise",
"too_long",
"or",
"ValueError",
"(",
"msg",
")",
"return",
"first_value"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/setuptools/py3/setuptools/_vendor/more_itertools/more.py#L3117-L3155 | |
microsoft/TSS.MSR | 0f2516fca2cd9929c31d5450e39301c9bde43688 | TSS.Py/src/TpmTypes.py | python | TPM2B_SENSITIVE_DATA.initFromTpm | (self, buf) | TpmMarshaller method | TpmMarshaller method | [
"TpmMarshaller",
"method"
] | def initFromTpm(self, buf):
""" TpmMarshaller method """
self.buffer = buf.readSizedByteBuf() | [
"def",
"initFromTpm",
"(",
"self",
",",
"buf",
")",
":",
"self",
".",
"buffer",
"=",
"buf",
".",
"readSizedByteBuf",
"(",
")"
] | https://github.com/microsoft/TSS.MSR/blob/0f2516fca2cd9929c31d5450e39301c9bde43688/TSS.Py/src/TpmTypes.py#L6091-L6093 | ||
ChromiumWebApps/chromium | c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7 | third_party/google_appengine_cloudstorage/cloudstorage/storage_api.py | python | _StorageApi.delete_object_async | (self, path, **kwds) | return self.do_request_async(self.api_url + path, 'DELETE', **kwds) | DELETE an object.
Note: No payload argument is supported. | DELETE an object. | [
"DELETE",
"an",
"object",
"."
] | def delete_object_async(self, path, **kwds):
"""DELETE an object.
Note: No payload argument is supported.
"""
return self.do_request_async(self.api_url + path, 'DELETE', **kwds) | [
"def",
"delete_object_async",
"(",
"self",
",",
"path",
",",
"*",
"*",
"kwds",
")",
":",
"return",
"self",
".",
"do_request_async",
"(",
"self",
".",
"api_url",
"+",
"path",
",",
"'DELETE'",
",",
"*",
"*",
"kwds",
")"
] | https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/third_party/google_appengine_cloudstorage/cloudstorage/storage_api.py#L152-L157 | |
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/framework/ops.py | python | add_to_collection | (name, value) | Wrapper for `Graph.add_to_collection()` using the default graph.
See `tf.Graph.add_to_collection`
for more details.
Args:
name: The key for the collection. For example, the `GraphKeys` class
contains many standard names for collections.
value: The value to add to the collection. @compatibility(eager)
Collections are only supported in eager when variables are created inside
an EagerVariableStore (e.g. as part of a layer or template).
@end_compatibility | Wrapper for `Graph.add_to_collection()` using the default graph. | [
"Wrapper",
"for",
"Graph",
".",
"add_to_collection",
"()",
"using",
"the",
"default",
"graph",
"."
] | def add_to_collection(name, value):
"""Wrapper for `Graph.add_to_collection()` using the default graph.
See `tf.Graph.add_to_collection`
for more details.
Args:
name: The key for the collection. For example, the `GraphKeys` class
contains many standard names for collections.
value: The value to add to the collection. @compatibility(eager)
Collections are only supported in eager when variables are created inside
an EagerVariableStore (e.g. as part of a layer or template).
@end_compatibility
"""
get_default_graph().add_to_collection(name, value) | [
"def",
"add_to_collection",
"(",
"name",
",",
"value",
")",
":",
"get_default_graph",
"(",
")",
".",
"add_to_collection",
"(",
"name",
",",
"value",
")"
] | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/framework/ops.py#L6154-L6168 | ||
neoml-lib/neoml | a0d370fba05269a1b2258cef126f77bbd2054a3e | NeoML/Python/neoml/Dnn/FullyConnected.py | python | FullyConnected.weights | (self, blob) | Sets the trained weights as a blob of the dimensions:
- **BatchLength** * **BatchWidth** * **ListSize** equal to element_count
- **Height**, **Width**, **Depth**, **Channels** the same as for the first input | Sets the trained weights as a blob of the dimensions: | [
"Sets",
"the",
"trained",
"weights",
"as",
"a",
"blob",
"of",
"the",
"dimensions",
":"
] | def weights(self, blob):
"""Sets the trained weights as a blob of the dimensions:
- **BatchLength** * **BatchWidth** * **ListSize** equal to element_count
- **Height**, **Width**, **Depth**, **Channels** the same as for the first input
"""
if not type(blob) is Blob.Blob:
raise ValueError('The `blob` must be neoml.Blob.')
self._internal.set_weights(blob._internal) | [
"def",
"weights",
"(",
"self",
",",
"blob",
")",
":",
"if",
"not",
"type",
"(",
"blob",
")",
"is",
"Blob",
".",
"Blob",
":",
"raise",
"ValueError",
"(",
"'The `blob` must be neoml.Blob.'",
")",
"self",
".",
"_internal",
".",
"set_weights",
"(",
"blob",
".",
"_internal",
")"
] | https://github.com/neoml-lib/neoml/blob/a0d370fba05269a1b2258cef126f77bbd2054a3e/NeoML/Python/neoml/Dnn/FullyConnected.py#L113-L122 | ||
benoitsteiner/tensorflow-opencl | cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5 | tensorflow/contrib/tensor_forest/client/random_forest.py | python | get_model_fn | (params,
graph_builder_class,
device_assigner,
feature_columns=None,
weights_name=None,
model_head=None,
keys_name=None,
early_stopping_rounds=100,
early_stopping_loss_threshold=0.001,
num_trainers=1,
trainer_id=0,
report_feature_importances=False,
local_eval=False,
head_scope=None) | return _model_fn | Return a model function given a way to construct a graph builder. | Return a model function given a way to construct a graph builder. | [
"Return",
"a",
"model",
"function",
"given",
"a",
"way",
"to",
"construct",
"a",
"graph",
"builder",
"."
] | def get_model_fn(params,
graph_builder_class,
device_assigner,
feature_columns=None,
weights_name=None,
model_head=None,
keys_name=None,
early_stopping_rounds=100,
early_stopping_loss_threshold=0.001,
num_trainers=1,
trainer_id=0,
report_feature_importances=False,
local_eval=False,
head_scope=None):
"""Return a model function given a way to construct a graph builder."""
if model_head is None:
model_head = get_default_head(params, weights_name)
def _model_fn(features, labels, mode):
"""Function that returns predictions, training loss, and training op."""
if (isinstance(features, ops.Tensor) or
isinstance(features, sparse_tensor.SparseTensor)):
features = {'features': features}
if feature_columns:
features = features.copy()
features.update(layers.transform_features(features, feature_columns))
weights = None
if weights_name and weights_name in features:
weights = features.pop(weights_name)
keys = None
if keys_name and keys_name in features:
keys = features.pop(keys_name)
# If we're doing eval, optionally ignore device_assigner.
# Also ignore device assigner if we're exporting (mode == INFER)
dev_assn = device_assigner
if (mode == model_fn_lib.ModeKeys.INFER or
(local_eval and mode == model_fn_lib.ModeKeys.EVAL)):
dev_assn = None
graph_builder = graph_builder_class(params,
device_assigner=dev_assn)
logits, tree_paths, regression_variance = graph_builder.inference_graph(
features)
summary.scalar('average_tree_size', graph_builder.average_size())
# For binary classification problems, convert probabilities to logits.
# Includes hack to get around the fact that a probability might be 0 or 1.
if not params.regression and params.num_classes == 2:
class_1_probs = array_ops.slice(logits, [0, 1], [-1, 1])
logits = math_ops.log(
math_ops.maximum(class_1_probs / math_ops.maximum(
1.0 - class_1_probs, EPSILON), EPSILON))
# labels might be None if we're doing prediction (which brings up the
# question of why we force everything to adhere to a single model_fn).
training_graph = None
training_hooks = []
if labels is not None and mode == model_fn_lib.ModeKeys.TRAIN:
with ops.control_dependencies([logits.op]):
training_graph = control_flow_ops.group(
graph_builder.training_graph(
features, labels, input_weights=weights,
num_trainers=num_trainers,
trainer_id=trainer_id),
state_ops.assign_add(contrib_framework.get_global_step(), 1))
# Put weights back in
if weights is not None:
features[weights_name] = weights
# TensorForest's training graph isn't calculated directly from the loss
# like many other models.
def _train_fn(unused_loss):
return training_graph
model_ops = model_head.create_model_fn_ops(
features=features,
labels=labels,
mode=mode,
train_op_fn=_train_fn,
logits=logits,
scope=head_scope)
# Ops are run in lexigraphical order of their keys. Run the resource
# clean-up op last.
all_handles = graph_builder.get_all_resource_handles()
ops_at_end = {
'9: clean up resources': control_flow_ops.group(
*[resource_variable_ops.destroy_resource_op(handle)
for handle in all_handles])}
if report_feature_importances:
ops_at_end['1: feature_importances'] = (
graph_builder.feature_importances())
training_hooks.append(TensorForestRunOpAtEndHook(ops_at_end))
if early_stopping_rounds:
training_hooks.append(
TensorForestLossHook(
early_stopping_rounds,
early_stopping_loss_threshold=early_stopping_loss_threshold,
loss_op=model_ops.loss))
model_ops.training_hooks.extend(training_hooks)
if keys is not None:
model_ops.predictions[keys_name] = keys
if params.inference_tree_paths:
model_ops.predictions[TREE_PATHS_PREDICTION_KEY] = tree_paths
if params.regression:
model_ops.predictions[VARIANCE_PREDICTION_KEY] = regression_variance
return model_ops
return _model_fn | [
"def",
"get_model_fn",
"(",
"params",
",",
"graph_builder_class",
",",
"device_assigner",
",",
"feature_columns",
"=",
"None",
",",
"weights_name",
"=",
"None",
",",
"model_head",
"=",
"None",
",",
"keys_name",
"=",
"None",
",",
"early_stopping_rounds",
"=",
"100",
",",
"early_stopping_loss_threshold",
"=",
"0.001",
",",
"num_trainers",
"=",
"1",
",",
"trainer_id",
"=",
"0",
",",
"report_feature_importances",
"=",
"False",
",",
"local_eval",
"=",
"False",
",",
"head_scope",
"=",
"None",
")",
":",
"if",
"model_head",
"is",
"None",
":",
"model_head",
"=",
"get_default_head",
"(",
"params",
",",
"weights_name",
")",
"def",
"_model_fn",
"(",
"features",
",",
"labels",
",",
"mode",
")",
":",
"\"\"\"Function that returns predictions, training loss, and training op.\"\"\"",
"if",
"(",
"isinstance",
"(",
"features",
",",
"ops",
".",
"Tensor",
")",
"or",
"isinstance",
"(",
"features",
",",
"sparse_tensor",
".",
"SparseTensor",
")",
")",
":",
"features",
"=",
"{",
"'features'",
":",
"features",
"}",
"if",
"feature_columns",
":",
"features",
"=",
"features",
".",
"copy",
"(",
")",
"features",
".",
"update",
"(",
"layers",
".",
"transform_features",
"(",
"features",
",",
"feature_columns",
")",
")",
"weights",
"=",
"None",
"if",
"weights_name",
"and",
"weights_name",
"in",
"features",
":",
"weights",
"=",
"features",
".",
"pop",
"(",
"weights_name",
")",
"keys",
"=",
"None",
"if",
"keys_name",
"and",
"keys_name",
"in",
"features",
":",
"keys",
"=",
"features",
".",
"pop",
"(",
"keys_name",
")",
"# If we're doing eval, optionally ignore device_assigner.",
"# Also ignore device assigner if we're exporting (mode == INFER)",
"dev_assn",
"=",
"device_assigner",
"if",
"(",
"mode",
"==",
"model_fn_lib",
".",
"ModeKeys",
".",
"INFER",
"or",
"(",
"local_eval",
"and",
"mode",
"==",
"model_fn_lib",
".",
"ModeKeys",
".",
"EVAL",
")",
")",
":",
"dev_assn",
"=",
"None",
"graph_builder",
"=",
"graph_builder_class",
"(",
"params",
",",
"device_assigner",
"=",
"dev_assn",
")",
"logits",
",",
"tree_paths",
",",
"regression_variance",
"=",
"graph_builder",
".",
"inference_graph",
"(",
"features",
")",
"summary",
".",
"scalar",
"(",
"'average_tree_size'",
",",
"graph_builder",
".",
"average_size",
"(",
")",
")",
"# For binary classification problems, convert probabilities to logits.",
"# Includes hack to get around the fact that a probability might be 0 or 1.",
"if",
"not",
"params",
".",
"regression",
"and",
"params",
".",
"num_classes",
"==",
"2",
":",
"class_1_probs",
"=",
"array_ops",
".",
"slice",
"(",
"logits",
",",
"[",
"0",
",",
"1",
"]",
",",
"[",
"-",
"1",
",",
"1",
"]",
")",
"logits",
"=",
"math_ops",
".",
"log",
"(",
"math_ops",
".",
"maximum",
"(",
"class_1_probs",
"/",
"math_ops",
".",
"maximum",
"(",
"1.0",
"-",
"class_1_probs",
",",
"EPSILON",
")",
",",
"EPSILON",
")",
")",
"# labels might be None if we're doing prediction (which brings up the",
"# question of why we force everything to adhere to a single model_fn).",
"training_graph",
"=",
"None",
"training_hooks",
"=",
"[",
"]",
"if",
"labels",
"is",
"not",
"None",
"and",
"mode",
"==",
"model_fn_lib",
".",
"ModeKeys",
".",
"TRAIN",
":",
"with",
"ops",
".",
"control_dependencies",
"(",
"[",
"logits",
".",
"op",
"]",
")",
":",
"training_graph",
"=",
"control_flow_ops",
".",
"group",
"(",
"graph_builder",
".",
"training_graph",
"(",
"features",
",",
"labels",
",",
"input_weights",
"=",
"weights",
",",
"num_trainers",
"=",
"num_trainers",
",",
"trainer_id",
"=",
"trainer_id",
")",
",",
"state_ops",
".",
"assign_add",
"(",
"contrib_framework",
".",
"get_global_step",
"(",
")",
",",
"1",
")",
")",
"# Put weights back in",
"if",
"weights",
"is",
"not",
"None",
":",
"features",
"[",
"weights_name",
"]",
"=",
"weights",
"# TensorForest's training graph isn't calculated directly from the loss",
"# like many other models.",
"def",
"_train_fn",
"(",
"unused_loss",
")",
":",
"return",
"training_graph",
"model_ops",
"=",
"model_head",
".",
"create_model_fn_ops",
"(",
"features",
"=",
"features",
",",
"labels",
"=",
"labels",
",",
"mode",
"=",
"mode",
",",
"train_op_fn",
"=",
"_train_fn",
",",
"logits",
"=",
"logits",
",",
"scope",
"=",
"head_scope",
")",
"# Ops are run in lexigraphical order of their keys. Run the resource",
"# clean-up op last.",
"all_handles",
"=",
"graph_builder",
".",
"get_all_resource_handles",
"(",
")",
"ops_at_end",
"=",
"{",
"'9: clean up resources'",
":",
"control_flow_ops",
".",
"group",
"(",
"*",
"[",
"resource_variable_ops",
".",
"destroy_resource_op",
"(",
"handle",
")",
"for",
"handle",
"in",
"all_handles",
"]",
")",
"}",
"if",
"report_feature_importances",
":",
"ops_at_end",
"[",
"'1: feature_importances'",
"]",
"=",
"(",
"graph_builder",
".",
"feature_importances",
"(",
")",
")",
"training_hooks",
".",
"append",
"(",
"TensorForestRunOpAtEndHook",
"(",
"ops_at_end",
")",
")",
"if",
"early_stopping_rounds",
":",
"training_hooks",
".",
"append",
"(",
"TensorForestLossHook",
"(",
"early_stopping_rounds",
",",
"early_stopping_loss_threshold",
"=",
"early_stopping_loss_threshold",
",",
"loss_op",
"=",
"model_ops",
".",
"loss",
")",
")",
"model_ops",
".",
"training_hooks",
".",
"extend",
"(",
"training_hooks",
")",
"if",
"keys",
"is",
"not",
"None",
":",
"model_ops",
".",
"predictions",
"[",
"keys_name",
"]",
"=",
"keys",
"if",
"params",
".",
"inference_tree_paths",
":",
"model_ops",
".",
"predictions",
"[",
"TREE_PATHS_PREDICTION_KEY",
"]",
"=",
"tree_paths",
"if",
"params",
".",
"regression",
":",
"model_ops",
".",
"predictions",
"[",
"VARIANCE_PREDICTION_KEY",
"]",
"=",
"regression_variance",
"return",
"model_ops",
"return",
"_model_fn"
] | https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/contrib/tensor_forest/client/random_forest.py#L125-L246 | |
y123456yz/reading-and-annotate-mongodb-3.6 | 93280293672ca7586dc24af18132aa61e4ed7fcf | mongo/buildscripts/cpplint.py | python | _CppLintState.PrintErrorCounts | (self) | Print a summary of errors by category, and the total. | Print a summary of errors by category, and the total. | [
"Print",
"a",
"summary",
"of",
"errors",
"by",
"category",
"and",
"the",
"total",
"."
] | def PrintErrorCounts(self):
"""Print a summary of errors by category, and the total."""
for category, count in self.errors_by_category.iteritems():
sys.stderr.write('Category \'%s\' errors found: %d\n' %
(category, count))
sys.stderr.write('Total errors found: %d\n' % self.error_count) | [
"def",
"PrintErrorCounts",
"(",
"self",
")",
":",
"for",
"category",
",",
"count",
"in",
"self",
".",
"errors_by_category",
".",
"iteritems",
"(",
")",
":",
"sys",
".",
"stderr",
".",
"write",
"(",
"'Category \\'%s\\' errors found: %d\\n'",
"%",
"(",
"category",
",",
"count",
")",
")",
"sys",
".",
"stderr",
".",
"write",
"(",
"'Total errors found: %d\\n'",
"%",
"self",
".",
"error_count",
")"
] | https://github.com/y123456yz/reading-and-annotate-mongodb-3.6/blob/93280293672ca7586dc24af18132aa61e4ed7fcf/mongo/buildscripts/cpplint.py#L836-L841 | ||
Samsung/veles | 95ed733c2e49bc011ad98ccf2416ecec23fbf352 | veles/loader/ensemble.py | python | IEnsembleLoader.load_winners | () | :return: tuple (list of winning labels, <labels are indices>) | :return: tuple (list of winning labels, <labels are indices>) | [
":",
"return",
":",
"tuple",
"(",
"list",
"of",
"winning",
"labels",
"<labels",
"are",
"indices",
">",
")"
] | def load_winners():
"""
:return: tuple (list of winning labels, <labels are indices>)
""" | [
"def",
"load_winners",
"(",
")",
":"
] | https://github.com/Samsung/veles/blob/95ed733c2e49bc011ad98ccf2416ecec23fbf352/veles/loader/ensemble.py#L47-L50 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/protobuf/py2/google/protobuf/message.py | python | Message.SerializeToString | (self, **kwargs) | Serializes the protocol message to a binary string.
Keyword Args:
deterministic (bool): If true, requests deterministic serialization
of the protobuf, with predictable ordering of map keys.
Returns:
A binary string representation of the message if all of the required
fields in the message are set (i.e. the message is initialized).
Raises:
EncodeError: if the message isn't initialized (see :func:`IsInitialized`). | Serializes the protocol message to a binary string. | [
"Serializes",
"the",
"protocol",
"message",
"to",
"a",
"binary",
"string",
"."
] | def SerializeToString(self, **kwargs):
"""Serializes the protocol message to a binary string.
Keyword Args:
deterministic (bool): If true, requests deterministic serialization
of the protobuf, with predictable ordering of map keys.
Returns:
A binary string representation of the message if all of the required
fields in the message are set (i.e. the message is initialized).
Raises:
EncodeError: if the message isn't initialized (see :func:`IsInitialized`).
"""
raise NotImplementedError | [
"def",
"SerializeToString",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"raise",
"NotImplementedError"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/protobuf/py2/google/protobuf/message.py#L201-L215 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/email/message.py | python | Message.get_content_type | (self) | return ctype | Return the message's content type.
The returned string is coerced to lower case of the form
`maintype/subtype'. If there was no Content-Type header in the
message, the default type as given by get_default_type() will be
returned. Since according to RFC 2045, messages always have a default
type this will always return a value.
RFC 2045 defines a message's default type to be text/plain unless it
appears inside a multipart/digest container, in which case it would be
message/rfc822. | Return the message's content type. | [
"Return",
"the",
"message",
"s",
"content",
"type",
"."
] | def get_content_type(self):
"""Return the message's content type.
The returned string is coerced to lower case of the form
`maintype/subtype'. If there was no Content-Type header in the
message, the default type as given by get_default_type() will be
returned. Since according to RFC 2045, messages always have a default
type this will always return a value.
RFC 2045 defines a message's default type to be text/plain unless it
appears inside a multipart/digest container, in which case it would be
message/rfc822.
"""
missing = object()
value = self.get('content-type', missing)
if value is missing:
# This should have no parameters
return self.get_default_type()
ctype = _splitparam(value)[0].lower()
# RFC 2045, section 5.2 says if its invalid, use text/plain
if ctype.count('/') != 1:
return 'text/plain'
return ctype | [
"def",
"get_content_type",
"(",
"self",
")",
":",
"missing",
"=",
"object",
"(",
")",
"value",
"=",
"self",
".",
"get",
"(",
"'content-type'",
",",
"missing",
")",
"if",
"value",
"is",
"missing",
":",
"# This should have no parameters",
"return",
"self",
".",
"get_default_type",
"(",
")",
"ctype",
"=",
"_splitparam",
"(",
"value",
")",
"[",
"0",
"]",
".",
"lower",
"(",
")",
"# RFC 2045, section 5.2 says if its invalid, use text/plain",
"if",
"ctype",
".",
"count",
"(",
"'/'",
")",
"!=",
"1",
":",
"return",
"'text/plain'",
"return",
"ctype"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/email/message.py#L564-L586 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python/src/Lib/telnetlib.py | python | Telnet.rawq_getchar | (self) | return c | Get next char from raw queue.
Block if no data is immediately available. Raise EOFError
when connection is closed. | Get next char from raw queue. | [
"Get",
"next",
"char",
"from",
"raw",
"queue",
"."
] | def rawq_getchar(self):
"""Get next char from raw queue.
Block if no data is immediately available. Raise EOFError
when connection is closed.
"""
if not self.rawq:
self.fill_rawq()
if self.eof:
raise EOFError
c = self.rawq[self.irawq]
self.irawq = self.irawq + 1
if self.irawq >= len(self.rawq):
self.rawq = ''
self.irawq = 0
return c | [
"def",
"rawq_getchar",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"rawq",
":",
"self",
".",
"fill_rawq",
"(",
")",
"if",
"self",
".",
"eof",
":",
"raise",
"EOFError",
"c",
"=",
"self",
".",
"rawq",
"[",
"self",
".",
"irawq",
"]",
"self",
".",
"irawq",
"=",
"self",
".",
"irawq",
"+",
"1",
"if",
"self",
".",
"irawq",
">=",
"len",
"(",
"self",
".",
"rawq",
")",
":",
"self",
".",
"rawq",
"=",
"''",
"self",
".",
"irawq",
"=",
"0",
"return",
"c"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/telnetlib.py#L546-L562 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numpy/core/fromnumeric.py | python | product | (*args, **kwargs) | return prod(*args, **kwargs) | Return the product of array elements over a given axis.
See Also
--------
prod : equivalent function; see for details. | Return the product of array elements over a given axis. | [
"Return",
"the",
"product",
"of",
"array",
"elements",
"over",
"a",
"given",
"axis",
"."
] | def product(*args, **kwargs):
"""
Return the product of array elements over a given axis.
See Also
--------
prod : equivalent function; see for details.
"""
return prod(*args, **kwargs) | [
"def",
"product",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"prod",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numpy/core/fromnumeric.py#L3603-L3611 | |
microsoft/onnxruntime | f92e47e95b13a240e37caf7b36577983544f98fc | onnxruntime/python/onnxruntime_inference_collection.py | python | IOBinding.copy_outputs_to_cpu | (self) | return self._iobinding.copy_outputs_to_cpu() | Copy output contents to CPU (if on another device). No-op if already on the CPU. | Copy output contents to CPU (if on another device). No-op if already on the CPU. | [
"Copy",
"output",
"contents",
"to",
"CPU",
"(",
"if",
"on",
"another",
"device",
")",
".",
"No",
"-",
"op",
"if",
"already",
"on",
"the",
"CPU",
"."
] | def copy_outputs_to_cpu(self):
'''Copy output contents to CPU (if on another device). No-op if already on the CPU.'''
return self._iobinding.copy_outputs_to_cpu() | [
"def",
"copy_outputs_to_cpu",
"(",
"self",
")",
":",
"return",
"self",
".",
"_iobinding",
".",
"copy_outputs_to_cpu",
"(",
")"
] | https://github.com/microsoft/onnxruntime/blob/f92e47e95b13a240e37caf7b36577983544f98fc/onnxruntime/python/onnxruntime_inference_collection.py#L506-L508 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/x86/toolchain/lib/python2.7/inspect.py | python | classify_class_attrs | (cls) | return result | Return list of attribute-descriptor tuples.
For each name in dir(cls), the return list contains a 4-tuple
with these elements:
0. The name (a string).
1. The kind of attribute this is, one of these strings:
'class method' created via classmethod()
'static method' created via staticmethod()
'property' created via property()
'method' any other flavor of method
'data' not a method
2. The class which defined this attribute (a class).
3. The object as obtained directly from the defining class's
__dict__, not via getattr. This is especially important for
data attributes: C.data is just a data object, but
C.__dict__['data'] may be a data descriptor with additional
info, like a __doc__ string. | Return list of attribute-descriptor tuples. | [
"Return",
"list",
"of",
"attribute",
"-",
"descriptor",
"tuples",
"."
] | def classify_class_attrs(cls):
"""Return list of attribute-descriptor tuples.
For each name in dir(cls), the return list contains a 4-tuple
with these elements:
0. The name (a string).
1. The kind of attribute this is, one of these strings:
'class method' created via classmethod()
'static method' created via staticmethod()
'property' created via property()
'method' any other flavor of method
'data' not a method
2. The class which defined this attribute (a class).
3. The object as obtained directly from the defining class's
__dict__, not via getattr. This is especially important for
data attributes: C.data is just a data object, but
C.__dict__['data'] may be a data descriptor with additional
info, like a __doc__ string.
"""
mro = getmro(cls)
names = dir(cls)
result = []
for name in names:
# Get the object associated with the name, and where it was defined.
# Getting an obj from the __dict__ sometimes reveals more than
# using getattr. Static and class methods are dramatic examples.
# Furthermore, some objects may raise an Exception when fetched with
# getattr(). This is the case with some descriptors (bug #1785).
# Thus, we only use getattr() as a last resort.
homecls = None
for base in (cls,) + mro:
if name in base.__dict__:
obj = base.__dict__[name]
homecls = base
break
else:
obj = getattr(cls, name)
homecls = getattr(obj, "__objclass__", homecls)
# Classify the object.
if isinstance(obj, staticmethod):
kind = "static method"
elif isinstance(obj, classmethod):
kind = "class method"
elif isinstance(obj, property):
kind = "property"
elif ismethoddescriptor(obj):
kind = "method"
elif isdatadescriptor(obj):
kind = "data"
else:
obj_via_getattr = getattr(cls, name)
if (ismethod(obj_via_getattr) or
ismethoddescriptor(obj_via_getattr)):
kind = "method"
else:
kind = "data"
obj = obj_via_getattr
result.append(Attribute(name, kind, homecls, obj))
return result | [
"def",
"classify_class_attrs",
"(",
"cls",
")",
":",
"mro",
"=",
"getmro",
"(",
"cls",
")",
"names",
"=",
"dir",
"(",
"cls",
")",
"result",
"=",
"[",
"]",
"for",
"name",
"in",
"names",
":",
"# Get the object associated with the name, and where it was defined.",
"# Getting an obj from the __dict__ sometimes reveals more than",
"# using getattr. Static and class methods are dramatic examples.",
"# Furthermore, some objects may raise an Exception when fetched with",
"# getattr(). This is the case with some descriptors (bug #1785).",
"# Thus, we only use getattr() as a last resort.",
"homecls",
"=",
"None",
"for",
"base",
"in",
"(",
"cls",
",",
")",
"+",
"mro",
":",
"if",
"name",
"in",
"base",
".",
"__dict__",
":",
"obj",
"=",
"base",
".",
"__dict__",
"[",
"name",
"]",
"homecls",
"=",
"base",
"break",
"else",
":",
"obj",
"=",
"getattr",
"(",
"cls",
",",
"name",
")",
"homecls",
"=",
"getattr",
"(",
"obj",
",",
"\"__objclass__\"",
",",
"homecls",
")",
"# Classify the object.",
"if",
"isinstance",
"(",
"obj",
",",
"staticmethod",
")",
":",
"kind",
"=",
"\"static method\"",
"elif",
"isinstance",
"(",
"obj",
",",
"classmethod",
")",
":",
"kind",
"=",
"\"class method\"",
"elif",
"isinstance",
"(",
"obj",
",",
"property",
")",
":",
"kind",
"=",
"\"property\"",
"elif",
"ismethoddescriptor",
"(",
"obj",
")",
":",
"kind",
"=",
"\"method\"",
"elif",
"isdatadescriptor",
"(",
"obj",
")",
":",
"kind",
"=",
"\"data\"",
"else",
":",
"obj_via_getattr",
"=",
"getattr",
"(",
"cls",
",",
"name",
")",
"if",
"(",
"ismethod",
"(",
"obj_via_getattr",
")",
"or",
"ismethoddescriptor",
"(",
"obj_via_getattr",
")",
")",
":",
"kind",
"=",
"\"method\"",
"else",
":",
"kind",
"=",
"\"data\"",
"obj",
"=",
"obj_via_getattr",
"result",
".",
"append",
"(",
"Attribute",
"(",
"name",
",",
"kind",
",",
"homecls",
",",
"obj",
")",
")",
"return",
"result"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/inspect.py#L263-L329 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | tools/auto_bisect/math_utils.py | python | StandardDeviation | (values) | return math.sqrt(Variance(values)) | Calculates the sample standard deviation of the given list of values. | Calculates the sample standard deviation of the given list of values. | [
"Calculates",
"the",
"sample",
"standard",
"deviation",
"of",
"the",
"given",
"list",
"of",
"values",
"."
] | def StandardDeviation(values):
"""Calculates the sample standard deviation of the given list of values."""
return math.sqrt(Variance(values)) | [
"def",
"StandardDeviation",
"(",
"values",
")",
":",
"return",
"math",
".",
"sqrt",
"(",
"Variance",
"(",
"values",
")",
")"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/tools/auto_bisect/math_utils.py#L75-L77 | |
rrwick/Unicycler | 96ffea71e3a78d63ade19d6124946773e65cf129 | unicycler/assembly_graph.py | python | AssemblyGraph.renumber_segments | (self) | This function gives the longest segment the number 1, the second-longest the number 2, etc. | This function gives the longest segment the number 1, the second-longest the number 2, etc. | [
"This",
"function",
"gives",
"the",
"longest",
"segment",
"the",
"number",
"1",
"the",
"second",
"-",
"longest",
"the",
"number",
"2",
"etc",
"."
] | def renumber_segments(self):
"""
This function gives the longest segment the number 1, the second-longest the number 2, etc.
"""
old_nums = [x.number for x in sorted(self.segments.values(), reverse=True,
key=lambda x: x.get_length())]
new_nums = list(range(1, len(old_nums) + 1))
old_nums += [-x for x in old_nums]
new_nums += [-x for x in new_nums]
changes = dict(zip(old_nums, new_nums))
new_segments = {}
for seg_num, seg in self.segments.items():
new_num = changes[seg_num]
seg.number = new_num
new_segments[new_num] = seg
self.segments = new_segments
new_forward_links = {}
for seg_num, link_nums in self.forward_links.items():
if link_nums:
new_forward_links[changes[seg_num]] = [changes[x] for x in link_nums]
self.forward_links = new_forward_links
new_reverse_links = {}
for seg_num, link_nums in self.reverse_links.items():
if link_nums:
new_reverse_links[changes[seg_num]] = [changes[x] for x in link_nums]
self.reverse_links = new_reverse_links
self.copy_depths = {changes[x]: y for x, y in self.copy_depths.items()}
new_paths = {}
for name, path_nums in self.paths.items():
new_paths[name] = [changes[x] for x in path_nums]
self.paths = new_paths | [
"def",
"renumber_segments",
"(",
"self",
")",
":",
"old_nums",
"=",
"[",
"x",
".",
"number",
"for",
"x",
"in",
"sorted",
"(",
"self",
".",
"segments",
".",
"values",
"(",
")",
",",
"reverse",
"=",
"True",
",",
"key",
"=",
"lambda",
"x",
":",
"x",
".",
"get_length",
"(",
")",
")",
"]",
"new_nums",
"=",
"list",
"(",
"range",
"(",
"1",
",",
"len",
"(",
"old_nums",
")",
"+",
"1",
")",
")",
"old_nums",
"+=",
"[",
"-",
"x",
"for",
"x",
"in",
"old_nums",
"]",
"new_nums",
"+=",
"[",
"-",
"x",
"for",
"x",
"in",
"new_nums",
"]",
"changes",
"=",
"dict",
"(",
"zip",
"(",
"old_nums",
",",
"new_nums",
")",
")",
"new_segments",
"=",
"{",
"}",
"for",
"seg_num",
",",
"seg",
"in",
"self",
".",
"segments",
".",
"items",
"(",
")",
":",
"new_num",
"=",
"changes",
"[",
"seg_num",
"]",
"seg",
".",
"number",
"=",
"new_num",
"new_segments",
"[",
"new_num",
"]",
"=",
"seg",
"self",
".",
"segments",
"=",
"new_segments",
"new_forward_links",
"=",
"{",
"}",
"for",
"seg_num",
",",
"link_nums",
"in",
"self",
".",
"forward_links",
".",
"items",
"(",
")",
":",
"if",
"link_nums",
":",
"new_forward_links",
"[",
"changes",
"[",
"seg_num",
"]",
"]",
"=",
"[",
"changes",
"[",
"x",
"]",
"for",
"x",
"in",
"link_nums",
"]",
"self",
".",
"forward_links",
"=",
"new_forward_links",
"new_reverse_links",
"=",
"{",
"}",
"for",
"seg_num",
",",
"link_nums",
"in",
"self",
".",
"reverse_links",
".",
"items",
"(",
")",
":",
"if",
"link_nums",
":",
"new_reverse_links",
"[",
"changes",
"[",
"seg_num",
"]",
"]",
"=",
"[",
"changes",
"[",
"x",
"]",
"for",
"x",
"in",
"link_nums",
"]",
"self",
".",
"reverse_links",
"=",
"new_reverse_links",
"self",
".",
"copy_depths",
"=",
"{",
"changes",
"[",
"x",
"]",
":",
"y",
"for",
"x",
",",
"y",
"in",
"self",
".",
"copy_depths",
".",
"items",
"(",
")",
"}",
"new_paths",
"=",
"{",
"}",
"for",
"name",
",",
"path_nums",
"in",
"self",
".",
"paths",
".",
"items",
"(",
")",
":",
"new_paths",
"[",
"name",
"]",
"=",
"[",
"changes",
"[",
"x",
"]",
"for",
"x",
"in",
"path_nums",
"]",
"self",
".",
"paths",
"=",
"new_paths"
] | https://github.com/rrwick/Unicycler/blob/96ffea71e3a78d63ade19d6124946773e65cf129/unicycler/assembly_graph.py#L1646-L1681 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python/src/Lib/cookielib.py | python | request_path | (request) | return path | Path component of request-URI, as defined by RFC 2965. | Path component of request-URI, as defined by RFC 2965. | [
"Path",
"component",
"of",
"request",
"-",
"URI",
"as",
"defined",
"by",
"RFC",
"2965",
"."
] | def request_path(request):
"""Path component of request-URI, as defined by RFC 2965."""
url = request.get_full_url()
parts = urlparse.urlsplit(url)
path = escape_path(parts.path)
if not path.startswith("/"):
# fix bad RFC 2396 absoluteURI
path = "/" + path
return path | [
"def",
"request_path",
"(",
"request",
")",
":",
"url",
"=",
"request",
".",
"get_full_url",
"(",
")",
"parts",
"=",
"urlparse",
".",
"urlsplit",
"(",
"url",
")",
"path",
"=",
"escape_path",
"(",
"parts",
".",
"path",
")",
"if",
"not",
"path",
".",
"startswith",
"(",
"\"/\"",
")",
":",
"# fix bad RFC 2396 absoluteURI",
"path",
"=",
"\"/\"",
"+",
"path",
"return",
"path"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/cookielib.py#L625-L633 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/_core.py | python | IndividualLayoutConstraint.Above | (*args, **kwargs) | return _core_.IndividualLayoutConstraint_Above(*args, **kwargs) | Above(self, Window sibling, int marg=0)
Constrains this edge to be above the given window, with an optional
margin. Implicitly, this is relative to the top edge of the other
window. | Above(self, Window sibling, int marg=0) | [
"Above",
"(",
"self",
"Window",
"sibling",
"int",
"marg",
"=",
"0",
")"
] | def Above(*args, **kwargs):
"""
Above(self, Window sibling, int marg=0)
Constrains this edge to be above the given window, with an optional
margin. Implicitly, this is relative to the top edge of the other
window.
"""
return _core_.IndividualLayoutConstraint_Above(*args, **kwargs) | [
"def",
"Above",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_core_",
".",
"IndividualLayoutConstraint_Above",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_core.py#L16156-L16164 | |
adobe/chromium | cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7 | tools/find_depot_tools.py | python | add_depot_tools_to_path | () | return None | Search for depot_tools and add it to sys.path. | Search for depot_tools and add it to sys.path. | [
"Search",
"for",
"depot_tools",
"and",
"add",
"it",
"to",
"sys",
".",
"path",
"."
] | def add_depot_tools_to_path():
"""Search for depot_tools and add it to sys.path."""
# First look if depot_tools is already in PYTHONPATH.
for i in sys.path:
if i.rstrip(os.sep).endswith('depot_tools'):
return i
# Then look if depot_tools is in PATH, common case.
for i in os.environ['PATH'].split(os.pathsep):
if i.rstrip(os.sep).endswith('depot_tools'):
sys.path.append(i.rstrip(os.sep))
return i
# Rare case, it's not even in PATH, look upward up to root.
root_dir = os.path.dirname(os.path.abspath(__file__))
previous_dir = os.path.abspath(__file__)
while root_dir and root_dir != previous_dir:
if os.path.isfile(os.path.join(root_dir, 'depot_tools', 'breakpad.py')):
i = os.path.join(root_dir, 'depot_tools')
sys.path.append(i)
return i
previous_dir = root_dir
root_dir = os.path.dirname(root_dir)
print >> sys.stderr, 'Failed to find depot_tools'
return None | [
"def",
"add_depot_tools_to_path",
"(",
")",
":",
"# First look if depot_tools is already in PYTHONPATH.",
"for",
"i",
"in",
"sys",
".",
"path",
":",
"if",
"i",
".",
"rstrip",
"(",
"os",
".",
"sep",
")",
".",
"endswith",
"(",
"'depot_tools'",
")",
":",
"return",
"i",
"# Then look if depot_tools is in PATH, common case.",
"for",
"i",
"in",
"os",
".",
"environ",
"[",
"'PATH'",
"]",
".",
"split",
"(",
"os",
".",
"pathsep",
")",
":",
"if",
"i",
".",
"rstrip",
"(",
"os",
".",
"sep",
")",
".",
"endswith",
"(",
"'depot_tools'",
")",
":",
"sys",
".",
"path",
".",
"append",
"(",
"i",
".",
"rstrip",
"(",
"os",
".",
"sep",
")",
")",
"return",
"i",
"# Rare case, it's not even in PATH, look upward up to root.",
"root_dir",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"os",
".",
"path",
".",
"abspath",
"(",
"__file__",
")",
")",
"previous_dir",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"__file__",
")",
"while",
"root_dir",
"and",
"root_dir",
"!=",
"previous_dir",
":",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"os",
".",
"path",
".",
"join",
"(",
"root_dir",
",",
"'depot_tools'",
",",
"'breakpad.py'",
")",
")",
":",
"i",
"=",
"os",
".",
"path",
".",
"join",
"(",
"root_dir",
",",
"'depot_tools'",
")",
"sys",
".",
"path",
".",
"append",
"(",
"i",
")",
"return",
"i",
"previous_dir",
"=",
"root_dir",
"root_dir",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"root_dir",
")",
"print",
">>",
"sys",
".",
"stderr",
",",
"'Failed to find depot_tools'",
"return",
"None"
] | https://github.com/adobe/chromium/blob/cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7/tools/find_depot_tools.py#L13-L35 | |
facebook/hermes | b1b1a00ab468ec1b397b31b71587110044830970 | tools/hbc-read-trace/hbc_sections.py | python | raw_sections | (hbcdump, bytecode) | Sequence of sections identified in bytecode.
hbcdump -- Path to the hbcdump binary to use to read the bytecode file.
bytecode -- Path to the bytecode file to extract sections from.
Returns the sequence of sections in the order they are output by hbcdump. | Sequence of sections identified in bytecode. | [
"Sequence",
"of",
"sections",
"identified",
"in",
"bytecode",
"."
] | def raw_sections(hbcdump, bytecode):
"""Sequence of sections identified in bytecode.
hbcdump -- Path to the hbcdump binary to use to read the bytecode file.
bytecode -- Path to the bytecode file to extract sections from.
Returns the sequence of sections in the order they are output by hbcdump.
"""
ranges = subprocess.check_output([hbcdump, "-show-section-ranges", bytecode])
for line in ranges.decode().split("\n"):
sect = parse_section(line)
if sect:
yield sect | [
"def",
"raw_sections",
"(",
"hbcdump",
",",
"bytecode",
")",
":",
"ranges",
"=",
"subprocess",
".",
"check_output",
"(",
"[",
"hbcdump",
",",
"\"-show-section-ranges\"",
",",
"bytecode",
"]",
")",
"for",
"line",
"in",
"ranges",
".",
"decode",
"(",
")",
".",
"split",
"(",
"\"\\n\"",
")",
":",
"sect",
"=",
"parse_section",
"(",
"line",
")",
"if",
"sect",
":",
"yield",
"sect"
] | https://github.com/facebook/hermes/blob/b1b1a00ab468ec1b397b31b71587110044830970/tools/hbc-read-trace/hbc_sections.py#L81-L94 | ||
evpo/EncryptPad | 156904860aaba8e7e8729b44e269b2992f9fe9f4 | deps/botan/src/scripts/build_docs.py | python | get_concurrency | () | Get default concurrency level of build | Get default concurrency level of build | [
"Get",
"default",
"concurrency",
"level",
"of",
"build"
] | def get_concurrency():
"""
Get default concurrency level of build
"""
def_concurrency = 2
try:
import multiprocessing
return max(def_concurrency, multiprocessing.cpu_count())
except ImportError:
return def_concurrency | [
"def",
"get_concurrency",
"(",
")",
":",
"def_concurrency",
"=",
"2",
"try",
":",
"import",
"multiprocessing",
"return",
"max",
"(",
"def_concurrency",
",",
"multiprocessing",
".",
"cpu_count",
"(",
")",
")",
"except",
"ImportError",
":",
"return",
"def_concurrency"
] | https://github.com/evpo/EncryptPad/blob/156904860aaba8e7e8729b44e269b2992f9fe9f4/deps/botan/src/scripts/build_docs.py#L21-L31 | ||
NVIDIA/TensorRT | 42805f078052daad1a98bc5965974fcffaad0960 | samples/python/yolov3_onnx/yolov3_to_onnx.py | python | MajorNodeSpecs.__init__ | (self, name, channels) | Initialize a MajorNodeSpecs object.
Keyword arguments:
name -- name of the ONNX node
channels -- number of output channels of this node | Initialize a MajorNodeSpecs object. | [
"Initialize",
"a",
"MajorNodeSpecs",
"object",
"."
] | def __init__(self, name, channels):
""" Initialize a MajorNodeSpecs object.
Keyword arguments:
name -- name of the ONNX node
channels -- number of output channels of this node
"""
self.name = name
self.channels = channels
self.created_onnx_node = False
if name is not None and isinstance(channels, int) and channels > 0:
self.created_onnx_node = True | [
"def",
"__init__",
"(",
"self",
",",
"name",
",",
"channels",
")",
":",
"self",
".",
"name",
"=",
"name",
"self",
".",
"channels",
"=",
"channels",
"self",
".",
"created_onnx_node",
"=",
"False",
"if",
"name",
"is",
"not",
"None",
"and",
"isinstance",
"(",
"channels",
",",
"int",
")",
"and",
"channels",
">",
"0",
":",
"self",
".",
"created_onnx_node",
"=",
"True"
] | https://github.com/NVIDIA/TensorRT/blob/42805f078052daad1a98bc5965974fcffaad0960/samples/python/yolov3_onnx/yolov3_to_onnx.py#L148-L159 | ||
zerollzeng/tiny-tensorrt | e7bdb8f82934342a0f22ce68dfefdb8e15eb72b2 | third_party/pybind11/tools/clang/cindex.py | python | Cursor.get_template_argument_value | (self, num) | return conf.lib.clang_Cursor_getTemplateArgumentValue(self, num) | Returns the value of the indicated arg as a signed 64b integer. | Returns the value of the indicated arg as a signed 64b integer. | [
"Returns",
"the",
"value",
"of",
"the",
"indicated",
"arg",
"as",
"a",
"signed",
"64b",
"integer",
"."
] | def get_template_argument_value(self, num):
"""Returns the value of the indicated arg as a signed 64b integer."""
return conf.lib.clang_Cursor_getTemplateArgumentValue(self, num) | [
"def",
"get_template_argument_value",
"(",
"self",
",",
"num",
")",
":",
"return",
"conf",
".",
"lib",
".",
"clang_Cursor_getTemplateArgumentValue",
"(",
"self",
",",
"num",
")"
] | https://github.com/zerollzeng/tiny-tensorrt/blob/e7bdb8f82934342a0f22ce68dfefdb8e15eb72b2/third_party/pybind11/tools/clang/cindex.py#L1635-L1637 | |
microsoft/TSS.MSR | 0f2516fca2cd9929c31d5450e39301c9bde43688 | TSS.Py/src/TpmTypes.py | python | TPM2B_ECC_PARAMETER.GetUnionSelector | (self) | return TPM_ALG_ID.ECC | TpmUnion method | TpmUnion method | [
"TpmUnion",
"method"
] | def GetUnionSelector(self): # TPM_ALG_ID
""" TpmUnion method """
return TPM_ALG_ID.ECC | [
"def",
"GetUnionSelector",
"(",
"self",
")",
":",
"# TPM_ALG_ID",
"return",
"TPM_ALG_ID",
".",
"ECC"
] | https://github.com/microsoft/TSS.MSR/blob/0f2516fca2cd9929c31d5450e39301c9bde43688/TSS.Py/src/TpmTypes.py#L7217-L7219 | |
rrwick/Porechop | 109e437280436d1ec27e5a5b7a34ffb752176390 | ez_setup.py | python | archive_context | (filename) | Unzip filename to a temporary directory, set to the cwd.
The unzipped target is cleaned up after. | Unzip filename to a temporary directory, set to the cwd. | [
"Unzip",
"filename",
"to",
"a",
"temporary",
"directory",
"set",
"to",
"the",
"cwd",
"."
] | def archive_context(filename):
"""
Unzip filename to a temporary directory, set to the cwd.
The unzipped target is cleaned up after.
"""
tmpdir = tempfile.mkdtemp()
log.warn('Extracting in %s', tmpdir)
old_wd = os.getcwd()
try:
os.chdir(tmpdir)
try:
with ContextualZipFile(filename) as archive:
archive.extractall()
except zipfile.BadZipfile as err:
if not err.args:
err.args = ('', )
err.args = err.args + (
MEANINGFUL_INVALID_ZIP_ERR_MSG.format(filename),
)
raise
# going in the directory
subdir = os.path.join(tmpdir, os.listdir(tmpdir)[0])
os.chdir(subdir)
log.warn('Now working in %s', subdir)
yield
finally:
os.chdir(old_wd)
shutil.rmtree(tmpdir) | [
"def",
"archive_context",
"(",
"filename",
")",
":",
"tmpdir",
"=",
"tempfile",
".",
"mkdtemp",
"(",
")",
"log",
".",
"warn",
"(",
"'Extracting in %s'",
",",
"tmpdir",
")",
"old_wd",
"=",
"os",
".",
"getcwd",
"(",
")",
"try",
":",
"os",
".",
"chdir",
"(",
"tmpdir",
")",
"try",
":",
"with",
"ContextualZipFile",
"(",
"filename",
")",
"as",
"archive",
":",
"archive",
".",
"extractall",
"(",
")",
"except",
"zipfile",
".",
"BadZipfile",
"as",
"err",
":",
"if",
"not",
"err",
".",
"args",
":",
"err",
".",
"args",
"=",
"(",
"''",
",",
")",
"err",
".",
"args",
"=",
"err",
".",
"args",
"+",
"(",
"MEANINGFUL_INVALID_ZIP_ERR_MSG",
".",
"format",
"(",
"filename",
")",
",",
")",
"raise",
"# going in the directory",
"subdir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"tmpdir",
",",
"os",
".",
"listdir",
"(",
"tmpdir",
")",
"[",
"0",
"]",
")",
"os",
".",
"chdir",
"(",
"subdir",
")",
"log",
".",
"warn",
"(",
"'Now working in %s'",
",",
"subdir",
")",
"yield",
"finally",
":",
"os",
".",
"chdir",
"(",
"old_wd",
")",
"shutil",
".",
"rmtree",
"(",
"tmpdir",
")"
] | https://github.com/rrwick/Porechop/blob/109e437280436d1ec27e5a5b7a34ffb752176390/ez_setup.py#L99-L129 | ||
nasa/fprime | 595cf3682d8365943d86c1a6fe7c78f0a116acf0 | Autocoders/Python/src/fprime_ac/generators/writers/InstChannelWriter.py | python | InstChannelWriter.DictBodyWrite | (self, obj, topology_model) | Defined to generate the body of the Python channel class
@param obj: the instance of the channel model to operation on. | Defined to generate the body of the Python channel class | [
"Defined",
"to",
"generate",
"the",
"body",
"of",
"the",
"Python",
"channel",
"class"
] | def DictBodyWrite(self, obj, topology_model):
"""
Defined to generate the body of the Python channel class
@param obj: the instance of the channel model to operation on.
"""
try:
instance_obj_list = topology_model.get_base_id_dict()[
obj.get_component_base_name()
]
except Exception:
PRINT.info(
"ERROR: Could not find instance object for component "
+ obj.get_component_base_name()
+ ". Check topology model to see if the component was instanced."
)
raise
for instance_obj in instance_obj_list:
c = ChannelBody.ChannelBody()
if instance_obj[3].get_dict_short_name() is not None:
fname = "{}_{}".format(
instance_obj[3].get_dict_short_name(), obj.get_name()
)
elif (
not topology_model.get_prepend_instance_name()
and len(instance_obj_list) == 1
):
fname = obj.get_name()
else:
fname = "{}_{}".format(instance_obj[0], obj.get_name())
c.name = fname
if len(obj.get_ids()) > 1:
raise Exception(
"There is more than one event id when creating dictionaries. Check xml of {} or see if multiple explicit IDs exist in the AcConstants.ini file".format(
fname
)
)
try:
c.id = hex(instance_obj[1] + int(float(obj.get_ids()[0])))
except (ValueError, TypeError):
c.id = hex(instance_obj[1] + int(obj.get_ids()[0], 16))
c.description = obj.get_comment()
c.format_string = obj.get_format_string()
c.component = obj.get_component_name()
(
c.low_red,
c.low_orange,
c.low_yellow,
c.high_yellow,
c.high_orange,
c.high_red,
) = obj.get_limits()
c.ser_import = None
(
c.type,
c.ser_import,
type_name,
dontcare,
) = DictTypeConverter.DictTypeConverter().convert(
obj.get_type(), obj.get_size()
)
# special case for enums and Gse GUI. Needs to convert %d to %s
if type_name == "enum":
c.format_string = "%s"
self._writeTmpl(c, self.__fp[fname], "channelBodyWrite")
self.__fp[fname].close() | [
"def",
"DictBodyWrite",
"(",
"self",
",",
"obj",
",",
"topology_model",
")",
":",
"try",
":",
"instance_obj_list",
"=",
"topology_model",
".",
"get_base_id_dict",
"(",
")",
"[",
"obj",
".",
"get_component_base_name",
"(",
")",
"]",
"except",
"Exception",
":",
"PRINT",
".",
"info",
"(",
"\"ERROR: Could not find instance object for component \"",
"+",
"obj",
".",
"get_component_base_name",
"(",
")",
"+",
"\". Check topology model to see if the component was instanced.\"",
")",
"raise",
"for",
"instance_obj",
"in",
"instance_obj_list",
":",
"c",
"=",
"ChannelBody",
".",
"ChannelBody",
"(",
")",
"if",
"instance_obj",
"[",
"3",
"]",
".",
"get_dict_short_name",
"(",
")",
"is",
"not",
"None",
":",
"fname",
"=",
"\"{}_{}\"",
".",
"format",
"(",
"instance_obj",
"[",
"3",
"]",
".",
"get_dict_short_name",
"(",
")",
",",
"obj",
".",
"get_name",
"(",
")",
")",
"elif",
"(",
"not",
"topology_model",
".",
"get_prepend_instance_name",
"(",
")",
"and",
"len",
"(",
"instance_obj_list",
")",
"==",
"1",
")",
":",
"fname",
"=",
"obj",
".",
"get_name",
"(",
")",
"else",
":",
"fname",
"=",
"\"{}_{}\"",
".",
"format",
"(",
"instance_obj",
"[",
"0",
"]",
",",
"obj",
".",
"get_name",
"(",
")",
")",
"c",
".",
"name",
"=",
"fname",
"if",
"len",
"(",
"obj",
".",
"get_ids",
"(",
")",
")",
">",
"1",
":",
"raise",
"Exception",
"(",
"\"There is more than one event id when creating dictionaries. Check xml of {} or see if multiple explicit IDs exist in the AcConstants.ini file\"",
".",
"format",
"(",
"fname",
")",
")",
"try",
":",
"c",
".",
"id",
"=",
"hex",
"(",
"instance_obj",
"[",
"1",
"]",
"+",
"int",
"(",
"float",
"(",
"obj",
".",
"get_ids",
"(",
")",
"[",
"0",
"]",
")",
")",
")",
"except",
"(",
"ValueError",
",",
"TypeError",
")",
":",
"c",
".",
"id",
"=",
"hex",
"(",
"instance_obj",
"[",
"1",
"]",
"+",
"int",
"(",
"obj",
".",
"get_ids",
"(",
")",
"[",
"0",
"]",
",",
"16",
")",
")",
"c",
".",
"description",
"=",
"obj",
".",
"get_comment",
"(",
")",
"c",
".",
"format_string",
"=",
"obj",
".",
"get_format_string",
"(",
")",
"c",
".",
"component",
"=",
"obj",
".",
"get_component_name",
"(",
")",
"(",
"c",
".",
"low_red",
",",
"c",
".",
"low_orange",
",",
"c",
".",
"low_yellow",
",",
"c",
".",
"high_yellow",
",",
"c",
".",
"high_orange",
",",
"c",
".",
"high_red",
",",
")",
"=",
"obj",
".",
"get_limits",
"(",
")",
"c",
".",
"ser_import",
"=",
"None",
"(",
"c",
".",
"type",
",",
"c",
".",
"ser_import",
",",
"type_name",
",",
"dontcare",
",",
")",
"=",
"DictTypeConverter",
".",
"DictTypeConverter",
"(",
")",
".",
"convert",
"(",
"obj",
".",
"get_type",
"(",
")",
",",
"obj",
".",
"get_size",
"(",
")",
")",
"# special case for enums and Gse GUI. Needs to convert %d to %s",
"if",
"type_name",
"==",
"\"enum\"",
":",
"c",
".",
"format_string",
"=",
"\"%s\"",
"self",
".",
"_writeTmpl",
"(",
"c",
",",
"self",
".",
"__fp",
"[",
"fname",
"]",
",",
"\"channelBodyWrite\"",
")",
"self",
".",
"__fp",
"[",
"fname",
"]",
".",
"close",
"(",
")"
] | https://github.com/nasa/fprime/blob/595cf3682d8365943d86c1a6fe7c78f0a116acf0/Autocoders/Python/src/fprime_ac/generators/writers/InstChannelWriter.py#L147-L217 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/tools/Editra/src/ebmlib/_dirmon.py | python | DirectoryMonitor.Suspend | (self, pause=True) | Suspend background processing
@keyword pause: True (suspend) False (resume) | Suspend background processing
@keyword pause: True (suspend) False (resume) | [
"Suspend",
"background",
"processing",
"@keyword",
"pause",
":",
"True",
"(",
"suspend",
")",
"False",
"(",
"resume",
")"
] | def Suspend(self, pause=True):
"""Suspend background processing
@keyword pause: True (suspend) False (resume)
"""
if pause:
self._watcher.Suspend()
else:
self._watcher.Continue() | [
"def",
"Suspend",
"(",
"self",
",",
"pause",
"=",
"True",
")",
":",
"if",
"pause",
":",
"self",
".",
"_watcher",
".",
"Suspend",
"(",
")",
"else",
":",
"self",
".",
"_watcher",
".",
"Continue",
"(",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/ebmlib/_dirmon.py#L109-L117 | ||
Polidea/SiriusObfuscator | b0e590d8130e97856afe578869b83a209e2b19be | SymbolExtractorAndRenamer/lldb/utils/vim-lldb/python-vim-lldb/vim_panes.py | python | PaneLayout.contains | (self, bufferName=None) | return False | Returns True if window with name bufferName is contained in the layout, False otherwise.
If bufferName is None, the currently selected window is checked. | Returns True if window with name bufferName is contained in the layout, False otherwise.
If bufferName is None, the currently selected window is checked. | [
"Returns",
"True",
"if",
"window",
"with",
"name",
"bufferName",
"is",
"contained",
"in",
"the",
"layout",
"False",
"otherwise",
".",
"If",
"bufferName",
"is",
"None",
"the",
"currently",
"selected",
"window",
"is",
"checked",
"."
] | def contains(self, bufferName=None):
""" Returns True if window with name bufferName is contained in the layout, False otherwise.
If bufferName is None, the currently selected window is checked.
"""
if not bufferName:
bufferName = vim.current.buffer.name
for p in self.panes:
if bufferName is not None and bufferName.endswith(p):
return True
return False | [
"def",
"contains",
"(",
"self",
",",
"bufferName",
"=",
"None",
")",
":",
"if",
"not",
"bufferName",
":",
"bufferName",
"=",
"vim",
".",
"current",
".",
"buffer",
".",
"name",
"for",
"p",
"in",
"self",
".",
"panes",
":",
"if",
"bufferName",
"is",
"not",
"None",
"and",
"bufferName",
".",
"endswith",
"(",
"p",
")",
":",
"return",
"True",
"return",
"False"
] | https://github.com/Polidea/SiriusObfuscator/blob/b0e590d8130e97856afe578869b83a209e2b19be/SymbolExtractorAndRenamer/lldb/utils/vim-lldb/python-vim-lldb/vim_panes.py#L180-L190 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/traitlets/py2/traitlets/traitlets.py | python | HasTraits.has_trait | (self, name) | return isinstance(getattr(self.__class__, name, None), TraitType) | Returns True if the object has a trait with the specified name. | Returns True if the object has a trait with the specified name. | [
"Returns",
"True",
"if",
"the",
"object",
"has",
"a",
"trait",
"with",
"the",
"specified",
"name",
"."
] | def has_trait(self, name):
"""Returns True if the object has a trait with the specified name."""
return isinstance(getattr(self.__class__, name, None), TraitType) | [
"def",
"has_trait",
"(",
"self",
",",
"name",
")",
":",
"return",
"isinstance",
"(",
"getattr",
"(",
"self",
".",
"__class__",
",",
"name",
",",
"None",
")",
",",
"TraitType",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/traitlets/py2/traitlets/traitlets.py#L1399-L1401 | |
ChromiumWebApps/chromium | c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7 | tools/python/google/process_utils.py | python | RunCommandsInParallel | (commands, verbose=True, collect_output=False,
print_output=True) | return [(procs[i].returncode, outputs[i]) for i in xrange(command_num)] | Runs a list of commands in parallel, waits for all commands to terminate
and returns their status. If specified, the ouput of commands can be
returned and/or printed.
Args:
commands: the list of commands to run, each as a list of one or more
strings.
verbose: if True, combines stdout and stderr into stdout.
Otherwise, prints only the command's stderr to stdout.
collect_output: if True, collects the output of the each command as a list
of lines and returns it.
print_output: if True, prints the output of each command.
Returns:
A list of tuples consisting of each command's exit status and output. If
collect_output is False, the output will be [].
Raises:
CommandNotFound if any of the command executables could not be found. | Runs a list of commands in parallel, waits for all commands to terminate
and returns their status. If specified, the ouput of commands can be
returned and/or printed. | [
"Runs",
"a",
"list",
"of",
"commands",
"in",
"parallel",
"waits",
"for",
"all",
"commands",
"to",
"terminate",
"and",
"returns",
"their",
"status",
".",
"If",
"specified",
"the",
"ouput",
"of",
"commands",
"can",
"be",
"returned",
"and",
"/",
"or",
"printed",
"."
] | def RunCommandsInParallel(commands, verbose=True, collect_output=False,
print_output=True):
"""Runs a list of commands in parallel, waits for all commands to terminate
and returns their status. If specified, the ouput of commands can be
returned and/or printed.
Args:
commands: the list of commands to run, each as a list of one or more
strings.
verbose: if True, combines stdout and stderr into stdout.
Otherwise, prints only the command's stderr to stdout.
collect_output: if True, collects the output of the each command as a list
of lines and returns it.
print_output: if True, prints the output of each command.
Returns:
A list of tuples consisting of each command's exit status and output. If
collect_output is False, the output will be [].
Raises:
CommandNotFound if any of the command executables could not be found.
"""
command_num = len(commands)
outputs = [[] for i in xrange(command_num)]
procs = [None for i in xrange(command_num)]
eofs = [False for i in xrange(command_num)]
for command in commands:
print '\n' + subprocess.list2cmdline(command).replace('\\', '/') + '\n',
if verbose:
out = subprocess.PIPE
err = subprocess.STDOUT
else:
out = file(os.devnull, 'w')
err = subprocess.PIPE
for i in xrange(command_num):
try:
command = commands[i]
procs[i] = subprocess.Popen(command, stdout=out, stderr=err, bufsize=1)
except OSError, e:
if e.errno == errno.ENOENT:
raise CommandNotFound('Unable to find "%s"' % command[0])
raise
# We could consider terminating the processes already started.
# But Popen.kill() is only available in version 2.6.
# For now the clean up is done by KillAll.
while True:
eof_all = True
for i in xrange(command_num):
if eofs[i]:
continue
if verbose:
read_from = procs[i].stdout
else:
read_from = procs[i].stderr
line = read_from.readline()
if line:
eof_all = False
line = line.rstrip()
outputs[i].append(line)
if print_output:
# Windows Python converts \n to \r\n automatically whenever it
# encounters it written to a text file (including stdout). The only
# way around it is to write to a binary file, which isn't feasible
# for stdout. So we end up with \r\n here even though we explicitly
# write \n. (We could write \r instead, which doesn't get converted
# to \r\n, but that's probably more troublesome for people trying to
# read the files.)
print line + '\n',
else:
eofs[i] = True
if eof_all:
break
# Make sure the process terminates.
for i in xrange(command_num):
procs[i].wait()
if not verbose:
out.close()
return [(procs[i].returncode, outputs[i]) for i in xrange(command_num)] | [
"def",
"RunCommandsInParallel",
"(",
"commands",
",",
"verbose",
"=",
"True",
",",
"collect_output",
"=",
"False",
",",
"print_output",
"=",
"True",
")",
":",
"command_num",
"=",
"len",
"(",
"commands",
")",
"outputs",
"=",
"[",
"[",
"]",
"for",
"i",
"in",
"xrange",
"(",
"command_num",
")",
"]",
"procs",
"=",
"[",
"None",
"for",
"i",
"in",
"xrange",
"(",
"command_num",
")",
"]",
"eofs",
"=",
"[",
"False",
"for",
"i",
"in",
"xrange",
"(",
"command_num",
")",
"]",
"for",
"command",
"in",
"commands",
":",
"print",
"'\\n'",
"+",
"subprocess",
".",
"list2cmdline",
"(",
"command",
")",
".",
"replace",
"(",
"'\\\\'",
",",
"'/'",
")",
"+",
"'\\n'",
",",
"if",
"verbose",
":",
"out",
"=",
"subprocess",
".",
"PIPE",
"err",
"=",
"subprocess",
".",
"STDOUT",
"else",
":",
"out",
"=",
"file",
"(",
"os",
".",
"devnull",
",",
"'w'",
")",
"err",
"=",
"subprocess",
".",
"PIPE",
"for",
"i",
"in",
"xrange",
"(",
"command_num",
")",
":",
"try",
":",
"command",
"=",
"commands",
"[",
"i",
"]",
"procs",
"[",
"i",
"]",
"=",
"subprocess",
".",
"Popen",
"(",
"command",
",",
"stdout",
"=",
"out",
",",
"stderr",
"=",
"err",
",",
"bufsize",
"=",
"1",
")",
"except",
"OSError",
",",
"e",
":",
"if",
"e",
".",
"errno",
"==",
"errno",
".",
"ENOENT",
":",
"raise",
"CommandNotFound",
"(",
"'Unable to find \"%s\"'",
"%",
"command",
"[",
"0",
"]",
")",
"raise",
"# We could consider terminating the processes already started.",
"# But Popen.kill() is only available in version 2.6.",
"# For now the clean up is done by KillAll.",
"while",
"True",
":",
"eof_all",
"=",
"True",
"for",
"i",
"in",
"xrange",
"(",
"command_num",
")",
":",
"if",
"eofs",
"[",
"i",
"]",
":",
"continue",
"if",
"verbose",
":",
"read_from",
"=",
"procs",
"[",
"i",
"]",
".",
"stdout",
"else",
":",
"read_from",
"=",
"procs",
"[",
"i",
"]",
".",
"stderr",
"line",
"=",
"read_from",
".",
"readline",
"(",
")",
"if",
"line",
":",
"eof_all",
"=",
"False",
"line",
"=",
"line",
".",
"rstrip",
"(",
")",
"outputs",
"[",
"i",
"]",
".",
"append",
"(",
"line",
")",
"if",
"print_output",
":",
"# Windows Python converts \\n to \\r\\n automatically whenever it",
"# encounters it written to a text file (including stdout). The only",
"# way around it is to write to a binary file, which isn't feasible",
"# for stdout. So we end up with \\r\\n here even though we explicitly",
"# write \\n. (We could write \\r instead, which doesn't get converted",
"# to \\r\\n, but that's probably more troublesome for people trying to",
"# read the files.)",
"print",
"line",
"+",
"'\\n'",
",",
"else",
":",
"eofs",
"[",
"i",
"]",
"=",
"True",
"if",
"eof_all",
":",
"break",
"# Make sure the process terminates.",
"for",
"i",
"in",
"xrange",
"(",
"command_num",
")",
":",
"procs",
"[",
"i",
"]",
".",
"wait",
"(",
")",
"if",
"not",
"verbose",
":",
"out",
".",
"close",
"(",
")",
"return",
"[",
"(",
"procs",
"[",
"i",
"]",
".",
"returncode",
",",
"outputs",
"[",
"i",
"]",
")",
"for",
"i",
"in",
"xrange",
"(",
"command_num",
")",
"]"
] | https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/tools/python/google/process_utils.py#L136-L221 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.