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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
thalium/icebox | 99d147d5b9269222225443ce171b4fd46d8985d4 | third_party/virtualbox/src/libs/libxml2-2.9.4/python/libxml2class.py | python | relaxNgSchema.relaxNGNewValidCtxt | (self) | return __tmp | Create an XML RelaxNGs validation context based on the
given schema | Create an XML RelaxNGs validation context based on the
given schema | [
"Create",
"an",
"XML",
"RelaxNGs",
"validation",
"context",
"based",
"on",
"the",
"given",
"schema"
] | def relaxNGNewValidCtxt(self):
"""Create an XML RelaxNGs validation context based on the
given schema """
ret = libxml2mod.xmlRelaxNGNewValidCtxt(self._o)
if ret is None:raise treeError('xmlRelaxNGNewValidCtxt() failed')
__tmp = relaxNgValidCtxt(_obj=ret)
__tmp.schema = self
return __tmp | [
"def",
"relaxNGNewValidCtxt",
"(",
"self",
")",
":",
"ret",
"=",
"libxml2mod",
".",
"xmlRelaxNGNewValidCtxt",
"(",
"self",
".",
"_o",
")",
"if",
"ret",
"is",
"None",
":",
"raise",
"treeError",
"(",
"'xmlRelaxNGNewValidCtxt() failed'",
")",
"__tmp",
"=",
"relax... | https://github.com/thalium/icebox/blob/99d147d5b9269222225443ce171b4fd46d8985d4/third_party/virtualbox/src/libs/libxml2-2.9.4/python/libxml2class.py#L5476-L5483 | |
kamyu104/LeetCode-Solutions | 77605708a927ea3b85aee5a479db733938c7c211 | Python/ransom-note.py | python | Solution2.canConstruct | (self, ransomNote, magazine) | return not collections.Counter(ransomNote) - collections.Counter(magazine) | :type ransomNote: str
:type magazine: str
:rtype: bool | :type ransomNote: str
:type magazine: str
:rtype: bool | [
":",
"type",
"ransomNote",
":",
"str",
":",
"type",
"magazine",
":",
"str",
":",
"rtype",
":",
"bool"
] | def canConstruct(self, ransomNote, magazine):
"""
:type ransomNote: str
:type magazine: str
:rtype: bool
"""
return not collections.Counter(ransomNote) - collections.Counter(magazine) | [
"def",
"canConstruct",
"(",
"self",
",",
"ransomNote",
",",
"magazine",
")",
":",
"return",
"not",
"collections",
".",
"Counter",
"(",
"ransomNote",
")",
"-",
"collections",
".",
"Counter",
"(",
"magazine",
")"
] | https://github.com/kamyu104/LeetCode-Solutions/blob/77605708a927ea3b85aee5a479db733938c7c211/Python/ransom-note.py#L33-L39 | |
mindspore-ai/mindspore | fb8fd3338605bb34fa5cea054e535a8b1d753fab | mindspore/python/mindspore/numpy/math_ops.py | python | _handle_prepend_append | (combined, tensor, additional_tensor, axis) | return combined | Concatenates prepend or append to tensor. | Concatenates prepend or append to tensor. | [
"Concatenates",
"prepend",
"or",
"append",
"to",
"tensor",
"."
] | def _handle_prepend_append(combined, tensor, additional_tensor, axis):
"""Concatenates prepend or append to tensor."""
if isinstance(additional_tensor, (int, float, bool)):
additional_tensor = asarray_const(additional_tensor)
elif not isinstance(additional_tensor, Tensor):
_raise_type_error("prepend must be scalar or Tensor, but got ", additional_tensor)
additional_shape = tensor.shape
additional_shape = _tuple_setitem(additional_shape, axis, 1)
additional_tensor = _broadcast_to_shape(additional_tensor, additional_shape)
combined += (additional_tensor,)
return combined | [
"def",
"_handle_prepend_append",
"(",
"combined",
",",
"tensor",
",",
"additional_tensor",
",",
"axis",
")",
":",
"if",
"isinstance",
"(",
"additional_tensor",
",",
"(",
"int",
",",
"float",
",",
"bool",
")",
")",
":",
"additional_tensor",
"=",
"asarray_const"... | https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/numpy/math_ops.py#L1882-L1892 | |
eerolanguage/clang | 91360bee004a1cbdb95fe5eb605ef243152da41b | docs/tools/dump_ast_matchers.py | python | act_on_decl | (declaration, comment, allowed_types) | Parse the matcher out of the given declaration and comment.
If 'allowed_types' is set, it contains a list of node types the matcher
can match on, as extracted from the static type asserts in the matcher
definition. | Parse the matcher out of the given declaration and comment. | [
"Parse",
"the",
"matcher",
"out",
"of",
"the",
"given",
"declaration",
"and",
"comment",
"."
] | def act_on_decl(declaration, comment, allowed_types):
"""Parse the matcher out of the given declaration and comment.
If 'allowed_types' is set, it contains a list of node types the matcher
can match on, as extracted from the static type asserts in the matcher
definition.
"""
if declaration.strip():
# Node matchers are defined by writing:
# VariadicDynCastAllOfMatcher<ResultType, ArgumentType> name;
m = re.match(r""".*Variadic(?:DynCast)?AllOfMatcher\s*<
\s*([^\s,]+)\s*(?:,
\s*([^\s>]+)\s*)?>
\s*([^\s;]+)\s*;\s*$""", declaration, flags=re.X)
if m:
result, inner, name = m.groups()
if not inner:
inner = result
add_matcher(result, name, 'Matcher<%s>...' % inner,
comment, is_dyncast=True)
return
# Parse the various matcher definition macros.
m = re.match(""".*AST_TYPE_MATCHER\(
\s*([^\s,]+\s*),
\s*([^\s,]+\s*)
\)\s*;\s*$""", declaration, flags=re.X)
if m:
inner, name = m.groups()
add_matcher('Type', name, 'Matcher<%s>...' % inner,
comment, is_dyncast=True)
# FIXME: re-enable once we have implemented casting on the TypeLoc
# hierarchy.
# add_matcher('TypeLoc', '%sLoc' % name, 'Matcher<%sLoc>...' % inner,
# comment, is_dyncast=True)
return
m = re.match(""".*AST_TYPE(LOC)?_TRAVERSE_MATCHER\(
\s*([^\s,]+\s*),
\s*(?:[^\s,]+\s*),
\s*AST_POLYMORPHIC_SUPPORTED_TYPES_([^(]*)\(([^)]*)\)
\)\s*;\s*$""", declaration, flags=re.X)
if m:
loc, name, n_results, results = m.groups()[0:4]
result_types = [r.strip() for r in results.split(',')]
comment_result_types = extract_result_types(comment)
if (comment_result_types and
sorted(result_types) != sorted(comment_result_types)):
raise Exception('Inconsistent documentation for: %s' % name)
for result_type in result_types:
add_matcher(result_type, name, 'Matcher<Type>', comment)
if loc:
add_matcher('%sLoc' % result_type, '%sLoc' % name, 'Matcher<TypeLoc>',
comment)
return
m = re.match(r"""^\s*AST_POLYMORPHIC_MATCHER(_P)?(.?)(?:_OVERLOAD)?\(
\s*([^\s,]+)\s*,
\s*AST_POLYMORPHIC_SUPPORTED_TYPES_([^(]*)\(([^)]*)\)
(?:,\s*([^\s,]+)\s*
,\s*([^\s,]+)\s*)?
(?:,\s*([^\s,]+)\s*
,\s*([^\s,]+)\s*)?
(?:,\s*\d+\s*)?
\)\s*{\s*$""", declaration, flags=re.X)
if m:
p, n, name, n_results, results = m.groups()[0:5]
args = m.groups()[5:]
result_types = [r.strip() for r in results.split(',')]
if allowed_types and allowed_types != result_types:
raise Exception('Inconsistent documentation for: %s' % name)
if n not in ['', '2']:
raise Exception('Cannot parse "%s"' % declaration)
args = ', '.join('%s %s' % (args[i], args[i+1])
for i in range(0, len(args), 2) if args[i])
for result_type in result_types:
add_matcher(result_type, name, args, comment)
return
m = re.match(r"""^\s*AST_MATCHER(_P)?(.?)(?:_OVERLOAD)?\(
(?:\s*([^\s,]+)\s*,)?
\s*([^\s,]+)\s*
(?:,\s*([^\s,]+)\s*
,\s*([^\s,]+)\s*)?
(?:,\s*([^\s,]+)\s*
,\s*([^\s,]+)\s*)?
(?:,\s*\d+\s*)?
\)\s*{\s*$""", declaration, flags=re.X)
if m:
p, n, result, name = m.groups()[0:4]
args = m.groups()[4:]
if not result:
if not allowed_types:
raise Exception('Did not find allowed result types for: %s' % name)
result_types = allowed_types
else:
result_types = [result]
if n not in ['', '2']:
raise Exception('Cannot parse "%s"' % declaration)
args = ', '.join('%s %s' % (args[i], args[i+1])
for i in range(0, len(args), 2) if args[i])
for result_type in result_types:
add_matcher(result_type, name, args, comment)
return
# Parse ArgumentAdapting matchers.
m = re.match(
r"""^.*ArgumentAdaptingMatcherFunc<.*>\s*(?:LLVM_ATTRIBUTE_UNUSED\s*)
([a-zA-Z]*)\s*=\s*{};$""",
declaration, flags=re.X)
if m:
name = m.groups()[0]
add_matcher('*', name, 'Matcher<*>', comment)
return
# Parse Variadic operator matchers.
m = re.match(
r"""^.*VariadicOperatorMatcherFunc\s*([a-zA-Z]*)\s*=\s*{.*};$""",
declaration, flags=re.X)
if m:
name = m.groups()[0]
add_matcher('*', name, 'Matcher<*>, ..., Matcher<*>', comment)
return
# Parse free standing matcher functions, like:
# Matcher<ResultType> Name(Matcher<ArgumentType> InnerMatcher) {
m = re.match(r"""^\s*(.*)\s+
([^\s\(]+)\s*\(
(.*)
\)\s*{""", declaration, re.X)
if m:
result, name, args = m.groups()
args = ', '.join(p.strip() for p in args.split(','))
m = re.match(r'.*\s+internal::(Bindable)?Matcher<([^>]+)>$', result)
if m:
result_types = [m.group(2)]
else:
result_types = extract_result_types(comment)
if not result_types:
if not comment:
# Only overloads don't have their own doxygen comments; ignore those.
print 'Ignoring "%s"' % name
else:
print 'Cannot determine result type for "%s"' % name
else:
for result_type in result_types:
add_matcher(result_type, name, args, comment)
else:
print '*** Unparsable: "' + declaration + '" ***' | [
"def",
"act_on_decl",
"(",
"declaration",
",",
"comment",
",",
"allowed_types",
")",
":",
"if",
"declaration",
".",
"strip",
"(",
")",
":",
"# Node matchers are defined by writing:",
"# VariadicDynCastAllOfMatcher<ResultType, ArgumentType> name;",
"m",
"=",
"re",
".",
... | https://github.com/eerolanguage/clang/blob/91360bee004a1cbdb95fe5eb605ef243152da41b/docs/tools/dump_ast_matchers.py#L126-L277 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/propgrid.py | python | PropertyGrid.SetVirtualWidth | (*args, **kwargs) | return _propgrid.PropertyGrid_SetVirtualWidth(*args, **kwargs) | SetVirtualWidth(self, int width) | SetVirtualWidth(self, int width) | [
"SetVirtualWidth",
"(",
"self",
"int",
"width",
")"
] | def SetVirtualWidth(*args, **kwargs):
"""SetVirtualWidth(self, int width)"""
return _propgrid.PropertyGrid_SetVirtualWidth(*args, **kwargs) | [
"def",
"SetVirtualWidth",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_propgrid",
".",
"PropertyGrid_SetVirtualWidth",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/propgrid.py#L2299-L2301 | |
intel/caffe | 3f494b442ee3f9d17a07b09ecbd5fa2bbda00836 | examples/rfcn/lib/pycocotools/coco.py | python | COCO.loadRes | (self, resFile) | return res | Load result file and return a result api object.
:param resFile (str) : file name of result file
:return: res (obj) : result api object | Load result file and return a result api object.
:param resFile (str) : file name of result file
:return: res (obj) : result api object | [
"Load",
"result",
"file",
"and",
"return",
"a",
"result",
"api",
"object",
".",
":",
"param",
"resFile",
"(",
"str",
")",
":",
"file",
"name",
"of",
"result",
"file",
":",
"return",
":",
"res",
"(",
"obj",
")",
":",
"result",
"api",
"object"
] | def loadRes(self, resFile):
"""
Load result file and return a result api object.
:param resFile (str) : file name of result file
:return: res (obj) : result api object
"""
res = COCO()
res.dataset['images'] = [img for img in self.dataset['images']]
# res.dataset['info'] = copy.deepcopy(self.dataset['info'])
# res.dataset['licenses'] = copy.deepcopy(self.dataset['licenses'])
print 'Loading and preparing results... '
tic = time.time()
anns = json.load(open(resFile))
assert type(anns) == list, 'results in not an array of objects'
annsImgIds = [ann['image_id'] for ann in anns]
assert set(annsImgIds) == (set(annsImgIds) & set(self.getImgIds())), \
'Results do not correspond to current coco set'
if 'caption' in anns[0]:
imgIds = set([img['id'] for img in res.dataset['images']]) & set([ann['image_id'] for ann in anns])
res.dataset['images'] = [img for img in res.dataset['images'] if img['id'] in imgIds]
for id, ann in enumerate(anns):
ann['id'] = id+1
elif 'bbox' in anns[0] and not anns[0]['bbox'] == []:
res.dataset['categories'] = copy.deepcopy(self.dataset['categories'])
for id, ann in enumerate(anns):
bb = ann['bbox']
x1, x2, y1, y2 = [bb[0], bb[0]+bb[2], bb[1], bb[1]+bb[3]]
if not 'segmentation' in ann:
ann['segmentation'] = [[x1, y1, x1, y2, x2, y2, x2, y1]]
ann['area'] = bb[2]*bb[3]
ann['id'] = id+1
ann['iscrowd'] = 0
elif 'segmentation' in anns[0]:
res.dataset['categories'] = copy.deepcopy(self.dataset['categories'])
for id, ann in enumerate(anns):
# now only support compressed RLE format as segmentation results
ann['area'] = mask.area([ann['segmentation']])[0]
if not 'bbox' in ann:
ann['bbox'] = mask.toBbox([ann['segmentation']])[0]
ann['id'] = id+1
ann['iscrowd'] = 0
print 'DONE (t=%0.2fs)'%(time.time()- tic)
res.dataset['annotations'] = anns
res.createIndex()
return res | [
"def",
"loadRes",
"(",
"self",
",",
"resFile",
")",
":",
"res",
"=",
"COCO",
"(",
")",
"res",
".",
"dataset",
"[",
"'images'",
"]",
"=",
"[",
"img",
"for",
"img",
"in",
"self",
".",
"dataset",
"[",
"'images'",
"]",
"]",
"# res.dataset['info'] = copy.de... | https://github.com/intel/caffe/blob/3f494b442ee3f9d17a07b09ecbd5fa2bbda00836/examples/rfcn/lib/pycocotools/coco.py#L281-L327 | |
epiqc/ScaffCC | 66a79944ee4cd116b27bc1a69137276885461db8 | llvm/utils/lit/lit/run.py | python | Run.execute | (self) | Execute the tests in the run using up to the specified number of
parallel tasks, and inform the caller of each individual result. The
provided tests should be a subset of the tests available in this run
object.
The progress_callback will be invoked for each completed test.
If timeout is non-None, it should be a time in seconds after which to
stop executing tests.
Returns the elapsed testing time.
Upon completion, each test in the run will have its result
computed. Tests which were not actually executed (for any reason) will
be given an UNRESOLVED result. | Execute the tests in the run using up to the specified number of
parallel tasks, and inform the caller of each individual result. The
provided tests should be a subset of the tests available in this run
object. | [
"Execute",
"the",
"tests",
"in",
"the",
"run",
"using",
"up",
"to",
"the",
"specified",
"number",
"of",
"parallel",
"tasks",
"and",
"inform",
"the",
"caller",
"of",
"each",
"individual",
"result",
".",
"The",
"provided",
"tests",
"should",
"be",
"a",
"subs... | def execute(self):
"""
Execute the tests in the run using up to the specified number of
parallel tasks, and inform the caller of each individual result. The
provided tests should be a subset of the tests available in this run
object.
The progress_callback will be invoked for each completed test.
If timeout is non-None, it should be a time in seconds after which to
stop executing tests.
Returns the elapsed testing time.
Upon completion, each test in the run will have its result
computed. Tests which were not actually executed (for any reason) will
be given an UNRESOLVED result.
"""
self.failure_count = 0
self.hit_max_failures = False
# Larger timeouts (one year, positive infinity) don't work on Windows.
one_week = 7 * 24 * 60 * 60 # days * hours * minutes * seconds
timeout = self.timeout or one_week
deadline = time.time() + timeout
self._execute(deadline)
# Mark any tests that weren't run as UNRESOLVED.
for test in self.tests:
if test.result is None:
test.setResult(lit.Test.Result(lit.Test.UNRESOLVED, '', 0.0)) | [
"def",
"execute",
"(",
"self",
")",
":",
"self",
".",
"failure_count",
"=",
"0",
"self",
".",
"hit_max_failures",
"=",
"False",
"# Larger timeouts (one year, positive infinity) don't work on Windows.",
"one_week",
"=",
"7",
"*",
"24",
"*",
"60",
"*",
"60",
"# days... | https://github.com/epiqc/ScaffCC/blob/66a79944ee4cd116b27bc1a69137276885461db8/llvm/utils/lit/lit/run.py#L35-L66 | ||
gnuradio/gnuradio | 09c3c4fa4bfb1a02caac74cb5334dfe065391e3b | gr-channels/python/channels/impairments.py | python | impairments.set_i_ofs | (self, i_ofs) | Set inphase part of DC offset | Set inphase part of DC offset | [
"Set",
"inphase",
"part",
"of",
"DC",
"offset"
] | def set_i_ofs(self, i_ofs):
"""Set inphase part of DC offset"""
self.i_ofs = i_ofs
self.dc_offset.set_k((self.i_ofs + self.q_ofs * 1j, )) | [
"def",
"set_i_ofs",
"(",
"self",
",",
"i_ofs",
")",
":",
"self",
".",
"i_ofs",
"=",
"i_ofs",
"self",
".",
"dc_offset",
".",
"set_k",
"(",
"(",
"self",
".",
"i_ofs",
"+",
"self",
".",
"q_ofs",
"*",
"1j",
",",
")",
")"
] | https://github.com/gnuradio/gnuradio/blob/09c3c4fa4bfb1a02caac74cb5334dfe065391e3b/gr-channels/python/channels/impairments.py#L116-L119 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/psutil/__init__.py | python | Process.num_ctx_switches | (self) | return self._proc.num_ctx_switches() | Return the number of voluntary and involuntary context
switches performed by this process. | Return the number of voluntary and involuntary context
switches performed by this process. | [
"Return",
"the",
"number",
"of",
"voluntary",
"and",
"involuntary",
"context",
"switches",
"performed",
"by",
"this",
"process",
"."
] | def num_ctx_switches(self):
"""Return the number of voluntary and involuntary context
switches performed by this process.
"""
return self._proc.num_ctx_switches() | [
"def",
"num_ctx_switches",
"(",
"self",
")",
":",
"return",
"self",
".",
"_proc",
".",
"num_ctx_switches",
"(",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/psutil/__init__.py#L868-L872 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/dataview.py | python | DataViewListCtrl.SetValue | (*args, **kwargs) | return _dataview.DataViewListCtrl_SetValue(*args, **kwargs) | SetValue(self, wxVariant value, unsigned int row, unsigned int col) | SetValue(self, wxVariant value, unsigned int row, unsigned int col) | [
"SetValue",
"(",
"self",
"wxVariant",
"value",
"unsigned",
"int",
"row",
"unsigned",
"int",
"col",
")"
] | def SetValue(*args, **kwargs):
"""SetValue(self, wxVariant value, unsigned int row, unsigned int col)"""
return _dataview.DataViewListCtrl_SetValue(*args, **kwargs) | [
"def",
"SetValue",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_dataview",
".",
"DataViewListCtrl_SetValue",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/dataview.py#L2176-L2178 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/x86/toolchain/lib/python2.7/email/_parseaddr.py | python | AddrlistClass.__init__ | (self, field) | Initialize a new instance.
`field' is an unparsed address header field, containing
one or more addresses. | Initialize a new instance. | [
"Initialize",
"a",
"new",
"instance",
"."
] | def __init__(self, field):
"""Initialize a new instance.
`field' is an unparsed address header field, containing
one or more addresses.
"""
self.specials = '()<>@,:;.\"[]'
self.pos = 0
self.LWS = ' \t'
self.CR = '\r\n'
self.FWS = self.LWS + self.CR
self.atomends = self.specials + self.LWS + self.CR
# Note that RFC 2822 now specifies `.' as obs-phrase, meaning that it
# is obsolete syntax. RFC 2822 requires that we recognize obsolete
# syntax, so allow dots in phrases.
self.phraseends = self.atomends.replace('.', '')
self.field = field
self.commentlist = [] | [
"def",
"__init__",
"(",
"self",
",",
"field",
")",
":",
"self",
".",
"specials",
"=",
"'()<>@,:;.\\\"[]'",
"self",
".",
"pos",
"=",
"0",
"self",
".",
"LWS",
"=",
"' \\t'",
"self",
".",
"CR",
"=",
"'\\r\\n'",
"self",
".",
"FWS",
"=",
"self",
".",
"L... | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/email/_parseaddr.py#L182-L199 | ||
mongodb/mongo | d8ff665343ad29cf286ee2cf4a1960d29371937b | buildscripts/idl/idl/generator.py | python | _CppHeaderFileWriter.gen_template_declaration | (self) | Generate a template declaration for a command's base class. | Generate a template declaration for a command's base class. | [
"Generate",
"a",
"template",
"declaration",
"for",
"a",
"command",
"s",
"base",
"class",
"."
] | def gen_template_declaration(self):
# type: () -> None
"""Generate a template declaration for a command's base class."""
self._writer.write_line('template <typename Derived>') | [
"def",
"gen_template_declaration",
"(",
"self",
")",
":",
"# type: () -> None",
"self",
".",
"_writer",
".",
"write_line",
"(",
"'template <typename Derived>'",
")"
] | https://github.com/mongodb/mongo/blob/d8ff665343ad29cf286ee2cf4a1960d29371937b/buildscripts/idl/idl/generator.py#L853-L856 | ||
facebook/openr | ed38bdfd6bf290084bfab4821b59f83e7b59315d | openr/py/openr/cli/commands/kvstore.py | python | StreamSummaryCmd.get_subscriber_row | (self, stream_session_info) | return row | Takes StreamSubscriberInfo from thrift and returns list[str] (aka row)
representing the subscriber | Takes StreamSubscriberInfo from thrift and returns list[str] (aka row)
representing the subscriber | [
"Takes",
"StreamSubscriberInfo",
"from",
"thrift",
"and",
"returns",
"list",
"[",
"str",
"]",
"(",
"aka",
"row",
")",
"representing",
"the",
"subscriber"
] | def get_subscriber_row(self, stream_session_info):
"""
Takes StreamSubscriberInfo from thrift and returns list[str] (aka row)
representing the subscriber
"""
uptime = "unknown"
last_msg_time = "unknown"
if (
stream_session_info.uptime is not None
and stream_session_info.last_msg_sent_time is not None
):
uptime_str = str(
datetime.timedelta(milliseconds=stream_session_info.uptime)
)
last_msg_time_str = convertTime(stream_session_info.last_msg_sent_time)
uptime = uptime_str.split(".")[0]
last_msg_time = last_msg_time_str
row = [
stream_session_info.subscriber_id,
uptime,
stream_session_info.total_streamed_msgs,
last_msg_time,
]
return row | [
"def",
"get_subscriber_row",
"(",
"self",
",",
"stream_session_info",
")",
":",
"uptime",
"=",
"\"unknown\"",
"last_msg_time",
"=",
"\"unknown\"",
"if",
"(",
"stream_session_info",
".",
"uptime",
"is",
"not",
"None",
"and",
"stream_session_info",
".",
"last_msg_sent... | https://github.com/facebook/openr/blob/ed38bdfd6bf290084bfab4821b59f83e7b59315d/openr/py/openr/cli/commands/kvstore.py#L1417-L1442 | |
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/debug/wrappers/framework.py | python | NonInteractiveDebugWrapperSession.__init__ | (self, sess, watch_fn=None, thread_name_filter=None,
pass_through_operrors=False) | Constructor of NonInteractiveDebugWrapperSession.
Args:
sess: The TensorFlow `Session` object being wrapped.
watch_fn: (`Callable`) A Callable that maps the fetches and feeds of a
debugged `Session.run()` call to `WatchOptions.`
* Args:
* `fetches`: the fetches to the `Session.run()` call.
* `feeds`: the feeds to the `Session.run()` call.
* Returns:
(`tf_debug.WatchOptions`) An object containing debug options including
the debug ops to use, the node names, op types and/or tensor data
types to watch, etc. See the documentation of `tf_debug.WatchOptions`
for more details.
thread_name_filter: Regular-expression white list for threads on which the
wrapper session will be active. See doc of `BaseDebugWrapperSession` for
more details.
pass_through_operrors: If true, all captured OpErrors will be
propagated. By default this captures all OpErrors.
Raises:
TypeError: If a non-None `watch_fn` is specified and it is not callable. | Constructor of NonInteractiveDebugWrapperSession. | [
"Constructor",
"of",
"NonInteractiveDebugWrapperSession",
"."
] | def __init__(self, sess, watch_fn=None, thread_name_filter=None,
pass_through_operrors=False):
"""Constructor of NonInteractiveDebugWrapperSession.
Args:
sess: The TensorFlow `Session` object being wrapped.
watch_fn: (`Callable`) A Callable that maps the fetches and feeds of a
debugged `Session.run()` call to `WatchOptions.`
* Args:
* `fetches`: the fetches to the `Session.run()` call.
* `feeds`: the feeds to the `Session.run()` call.
* Returns:
(`tf_debug.WatchOptions`) An object containing debug options including
the debug ops to use, the node names, op types and/or tensor data
types to watch, etc. See the documentation of `tf_debug.WatchOptions`
for more details.
thread_name_filter: Regular-expression white list for threads on which the
wrapper session will be active. See doc of `BaseDebugWrapperSession` for
more details.
pass_through_operrors: If true, all captured OpErrors will be
propagated. By default this captures all OpErrors.
Raises:
TypeError: If a non-None `watch_fn` is specified and it is not callable.
"""
BaseDebugWrapperSession.__init__(
self, sess, thread_name_filter=thread_name_filter,
pass_through_operrors=pass_through_operrors)
self._watch_fn = None
if watch_fn is not None:
if not callable(watch_fn):
raise TypeError("watch_fn is not callable")
self._watch_fn = watch_fn | [
"def",
"__init__",
"(",
"self",
",",
"sess",
",",
"watch_fn",
"=",
"None",
",",
"thread_name_filter",
"=",
"None",
",",
"pass_through_operrors",
"=",
"False",
")",
":",
"BaseDebugWrapperSession",
".",
"__init__",
"(",
"self",
",",
"sess",
",",
"thread_name_fil... | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/debug/wrappers/framework.py#L889-L923 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/numpy/py3/numpy/lib/utils.py | python | _median_nancheck | (data, result, axis, out) | return result | Utility function to check median result from data for NaN values at the end
and return NaN in that case. Input result can also be a MaskedArray.
Parameters
----------
data : array
Input data to median function
result : Array or MaskedArray
Result of median function
axis : int
Axis along which the median was computed.
out : ndarray, optional
Output array in which to place the result.
Returns
-------
median : scalar or ndarray
Median or NaN in axes which contained NaN in the input. | Utility function to check median result from data for NaN values at the end
and return NaN in that case. Input result can also be a MaskedArray. | [
"Utility",
"function",
"to",
"check",
"median",
"result",
"from",
"data",
"for",
"NaN",
"values",
"at",
"the",
"end",
"and",
"return",
"NaN",
"in",
"that",
"case",
".",
"Input",
"result",
"can",
"also",
"be",
"a",
"MaskedArray",
"."
] | def _median_nancheck(data, result, axis, out):
"""
Utility function to check median result from data for NaN values at the end
and return NaN in that case. Input result can also be a MaskedArray.
Parameters
----------
data : array
Input data to median function
result : Array or MaskedArray
Result of median function
axis : int
Axis along which the median was computed.
out : ndarray, optional
Output array in which to place the result.
Returns
-------
median : scalar or ndarray
Median or NaN in axes which contained NaN in the input.
"""
if data.size == 0:
return result
n = np.isnan(data.take(-1, axis=axis))
# masked NaN values are ok
if np.ma.isMaskedArray(n):
n = n.filled(False)
if result.ndim == 0:
if n == True:
if out is not None:
out[...] = data.dtype.type(np.nan)
result = out
else:
result = data.dtype.type(np.nan)
elif np.count_nonzero(n.ravel()) > 0:
result[n] = np.nan
return result | [
"def",
"_median_nancheck",
"(",
"data",
",",
"result",
",",
"axis",
",",
"out",
")",
":",
"if",
"data",
".",
"size",
"==",
"0",
":",
"return",
"result",
"n",
"=",
"np",
".",
"isnan",
"(",
"data",
".",
"take",
"(",
"-",
"1",
",",
"axis",
"=",
"a... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/numpy/py3/numpy/lib/utils.py#L1007-L1043 | |
microsoft/ivy | 9f3c7ecc0b2383129fdd0953e10890d98d09a82d | ivy/ivy_parser.py | python | p_paramval_false | (p) | paramval : FALSE | paramval : FALSE | [
"paramval",
":",
"FALSE"
] | def p_paramval_false(p):
'paramval : FALSE'
p[0] = Atom('false')
p[0].lineno = get_lineno(p,1) | [
"def",
"p_paramval_false",
"(",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"Atom",
"(",
"'false'",
")",
"p",
"[",
"0",
"]",
".",
"lineno",
"=",
"get_lineno",
"(",
"p",
",",
"1",
")"
] | https://github.com/microsoft/ivy/blob/9f3c7ecc0b2383129fdd0953e10890d98d09a82d/ivy/ivy_parser.py#L774-L777 | ||
BitMEX/api-connectors | 37a3a5b806ad5d0e0fc975ab86d9ed43c3bcd812 | auto-generated/python/swagger_client/models/trade_bin.py | python | TradeBin.open | (self, open) | Sets the open of this TradeBin.
:param open: The open of this TradeBin. # noqa: E501
:type: float | Sets the open of this TradeBin. | [
"Sets",
"the",
"open",
"of",
"this",
"TradeBin",
"."
] | def open(self, open):
"""Sets the open of this TradeBin.
:param open: The open of this TradeBin. # noqa: E501
:type: float
"""
self._open = open | [
"def",
"open",
"(",
"self",
",",
"open",
")",
":",
"self",
".",
"_open",
"=",
"open"
] | https://github.com/BitMEX/api-connectors/blob/37a3a5b806ad5d0e0fc975ab86d9ed43c3bcd812/auto-generated/python/swagger_client/models/trade_bin.py#L165-L173 | ||
forkineye/ESPixelStick | 22926f1c0d1131f1369fc7cad405689a095ae3cb | dist/bin/esptool/esptool.py | python | BaseFirmwareImage.save_segment | (self, f, segment, checksum=None) | Save the next segment to the image file, return next checksum value if provided | Save the next segment to the image file, return next checksum value if provided | [
"Save",
"the",
"next",
"segment",
"to",
"the",
"image",
"file",
"return",
"next",
"checksum",
"value",
"if",
"provided"
] | def save_segment(self, f, segment, checksum=None):
""" Save the next segment to the image file, return next checksum value if provided """
segment_data = self.maybe_patch_segment_data(f, segment.data)
f.write(struct.pack('<II', segment.addr, len(segment_data)))
f.write(segment_data)
if checksum is not None:
return ESPLoader.checksum(segment_data, checksum) | [
"def",
"save_segment",
"(",
"self",
",",
"f",
",",
"segment",
",",
"checksum",
"=",
"None",
")",
":",
"segment_data",
"=",
"self",
".",
"maybe_patch_segment_data",
"(",
"f",
",",
"segment",
".",
"data",
")",
"f",
".",
"write",
"(",
"struct",
".",
"pack... | https://github.com/forkineye/ESPixelStick/blob/22926f1c0d1131f1369fc7cad405689a095ae3cb/dist/bin/esptool/esptool.py#L1501-L1507 | ||
Samsung/veles | 95ed733c2e49bc011ad98ccf2416ecec23fbf352 | veles/external/progressbar/widgets.py | python | AdaptiveETA.update | (self, pbar) | Updates the widget to show the ETA or total time when finished. | Updates the widget to show the ETA or total time when finished. | [
"Updates",
"the",
"widget",
"to",
"show",
"the",
"ETA",
"or",
"total",
"time",
"when",
"finished",
"."
] | def update(self, pbar):
"""Updates the widget to show the ETA or total time when finished."""
if pbar.currval == 0:
return 'ETA: --:--:--'
elif pbar.finished:
return 'Time: %s' % self.format_time(pbar.seconds_elapsed)
else:
elapsed = pbar.seconds_elapsed
currval1, elapsed1 = self._update_samples(pbar.currval, elapsed)
eta = self._eta(pbar.maxval, pbar.currval, elapsed)
if pbar.currval > currval1:
etasamp = self._eta(pbar.maxval - currval1,
pbar.currval - currval1,
elapsed - elapsed1)
weight = (pbar.currval / float(pbar.maxval)) ** 0.5
eta = (1 - weight) * eta + weight * etasamp
return 'ETA: %s' % self.format_time(eta) | [
"def",
"update",
"(",
"self",
",",
"pbar",
")",
":",
"if",
"pbar",
".",
"currval",
"==",
"0",
":",
"return",
"'ETA: --:--:--'",
"elif",
"pbar",
".",
"finished",
":",
"return",
"'Time: %s'",
"%",
"self",
".",
"format_time",
"(",
"pbar",
".",
"seconds_ela... | https://github.com/Samsung/veles/blob/95ed733c2e49bc011ad98ccf2416ecec23fbf352/veles/external/progressbar/widgets.py#L150-L166 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/_core.py | python | FileSystemHandler.GetRightLocation | (*args, **kwargs) | return _core_.FileSystemHandler_GetRightLocation(*args, **kwargs) | GetRightLocation(String location) -> String | GetRightLocation(String location) -> String | [
"GetRightLocation",
"(",
"String",
"location",
")",
"-",
">",
"String"
] | def GetRightLocation(*args, **kwargs):
"""GetRightLocation(String location) -> String"""
return _core_.FileSystemHandler_GetRightLocation(*args, **kwargs) | [
"def",
"GetRightLocation",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_core_",
".",
"FileSystemHandler_GetRightLocation",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_core.py#L2375-L2377 | |
GoSSIP-SJTU/TripleDoggy | 03648d6b19c812504b14e8b98c8c7b3f443f4e54 | tools/clang/bindings/python/clang/cindex.py | python | Cursor.extent | (self) | return self._extent | Return the source range (the range of text) occupied by the entity
pointed at by the cursor. | Return the source range (the range of text) occupied by the entity
pointed at by the cursor. | [
"Return",
"the",
"source",
"range",
"(",
"the",
"range",
"of",
"text",
")",
"occupied",
"by",
"the",
"entity",
"pointed",
"at",
"by",
"the",
"cursor",
"."
] | def extent(self):
"""
Return the source range (the range of text) occupied by the entity
pointed at by the cursor.
"""
if not hasattr(self, '_extent'):
self._extent = conf.lib.clang_getCursorExtent(self)
return self._extent | [
"def",
"extent",
"(",
"self",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'_extent'",
")",
":",
"self",
".",
"_extent",
"=",
"conf",
".",
"lib",
".",
"clang_getCursorExtent",
"(",
"self",
")",
"return",
"self",
".",
"_extent"
] | https://github.com/GoSSIP-SJTU/TripleDoggy/blob/03648d6b19c812504b14e8b98c8c7b3f443f4e54/tools/clang/bindings/python/clang/cindex.py#L1577-L1585 | |
DLR-SC/tigl | d1c5901e948e33d10b1f9659ff3e22c4717b455f | bindings/python_internal/tigl3/occ_helpers/containers.py | python | int_array | (int_list) | return result | Creates an OpenCASCADE TColStd_HArray1OfInteger from
a list of integers
:param int_list: List of integer values
:return: TColStd_HArray1OfInteger | Creates an OpenCASCADE TColStd_HArray1OfInteger from
a list of integers
:param int_list: List of integer values
:return: TColStd_HArray1OfInteger | [
"Creates",
"an",
"OpenCASCADE",
"TColStd_HArray1OfInteger",
"from",
"a",
"list",
"of",
"integers",
":",
"param",
"int_list",
":",
"List",
"of",
"integer",
"values",
":",
"return",
":",
"TColStd_HArray1OfInteger"
] | def int_array(int_list):
"""
Creates an OpenCASCADE TColStd_HArray1OfInteger from
a list of integers
:param int_list: List of integer values
:return: TColStd_HArray1OfInteger
"""
result = TColStd_HArray1OfInteger(1, len(int_list))
for i, value in enumerate(int_list):
result.SetValue(i+1, value)
return result | [
"def",
"int_array",
"(",
"int_list",
")",
":",
"result",
"=",
"TColStd_HArray1OfInteger",
"(",
"1",
",",
"len",
"(",
"int_list",
")",
")",
"for",
"i",
",",
"value",
"in",
"enumerate",
"(",
"int_list",
")",
":",
"result",
".",
"SetValue",
"(",
"i",
"+",... | https://github.com/DLR-SC/tigl/blob/d1c5901e948e33d10b1f9659ff3e22c4717b455f/bindings/python_internal/tigl3/occ_helpers/containers.py#L22-L32 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/pandas/py2/pandas/core/frame.py | python | DataFrame.query | (self, expr, inplace=False, **kwargs) | Query the columns of a DataFrame with a boolean expression.
Parameters
----------
expr : string
The query string to evaluate. You can refer to variables
in the environment by prefixing them with an '@' character like
``@a + b``.
inplace : bool
Whether the query should modify the data in place or return
a modified copy
.. versionadded:: 0.18.0
kwargs : dict
See the documentation for :func:`pandas.eval` for complete details
on the keyword arguments accepted by :meth:`DataFrame.query`.
Returns
-------
q : DataFrame
See Also
--------
pandas.eval
DataFrame.eval
Notes
-----
The result of the evaluation of this expression is first passed to
:attr:`DataFrame.loc` and if that fails because of a
multidimensional key (e.g., a DataFrame) then the result will be passed
to :meth:`DataFrame.__getitem__`.
This method uses the top-level :func:`pandas.eval` function to
evaluate the passed query.
The :meth:`~pandas.DataFrame.query` method uses a slightly
modified Python syntax by default. For example, the ``&`` and ``|``
(bitwise) operators have the precedence of their boolean cousins,
:keyword:`and` and :keyword:`or`. This *is* syntactically valid Python,
however the semantics are different.
You can change the semantics of the expression by passing the keyword
argument ``parser='python'``. This enforces the same semantics as
evaluation in Python space. Likewise, you can pass ``engine='python'``
to evaluate an expression using Python itself as a backend. This is not
recommended as it is inefficient compared to using ``numexpr`` as the
engine.
The :attr:`DataFrame.index` and
:attr:`DataFrame.columns` attributes of the
:class:`~pandas.DataFrame` instance are placed in the query namespace
by default, which allows you to treat both the index and columns of the
frame as a column in the frame.
The identifier ``index`` is used for the frame index; you can also
use the name of the index to identify it in a query. Please note that
Python keywords may not be used as identifiers.
For further details and examples see the ``query`` documentation in
:ref:`indexing <indexing.query>`.
Examples
--------
>>> df = pd.DataFrame(np.random.randn(10, 2), columns=list('ab'))
>>> df.query('a > b')
>>> df[df.a > df.b] # same result as the previous expression | Query the columns of a DataFrame with a boolean expression. | [
"Query",
"the",
"columns",
"of",
"a",
"DataFrame",
"with",
"a",
"boolean",
"expression",
"."
] | def query(self, expr, inplace=False, **kwargs):
"""
Query the columns of a DataFrame with a boolean expression.
Parameters
----------
expr : string
The query string to evaluate. You can refer to variables
in the environment by prefixing them with an '@' character like
``@a + b``.
inplace : bool
Whether the query should modify the data in place or return
a modified copy
.. versionadded:: 0.18.0
kwargs : dict
See the documentation for :func:`pandas.eval` for complete details
on the keyword arguments accepted by :meth:`DataFrame.query`.
Returns
-------
q : DataFrame
See Also
--------
pandas.eval
DataFrame.eval
Notes
-----
The result of the evaluation of this expression is first passed to
:attr:`DataFrame.loc` and if that fails because of a
multidimensional key (e.g., a DataFrame) then the result will be passed
to :meth:`DataFrame.__getitem__`.
This method uses the top-level :func:`pandas.eval` function to
evaluate the passed query.
The :meth:`~pandas.DataFrame.query` method uses a slightly
modified Python syntax by default. For example, the ``&`` and ``|``
(bitwise) operators have the precedence of their boolean cousins,
:keyword:`and` and :keyword:`or`. This *is* syntactically valid Python,
however the semantics are different.
You can change the semantics of the expression by passing the keyword
argument ``parser='python'``. This enforces the same semantics as
evaluation in Python space. Likewise, you can pass ``engine='python'``
to evaluate an expression using Python itself as a backend. This is not
recommended as it is inefficient compared to using ``numexpr`` as the
engine.
The :attr:`DataFrame.index` and
:attr:`DataFrame.columns` attributes of the
:class:`~pandas.DataFrame` instance are placed in the query namespace
by default, which allows you to treat both the index and columns of the
frame as a column in the frame.
The identifier ``index`` is used for the frame index; you can also
use the name of the index to identify it in a query. Please note that
Python keywords may not be used as identifiers.
For further details and examples see the ``query`` documentation in
:ref:`indexing <indexing.query>`.
Examples
--------
>>> df = pd.DataFrame(np.random.randn(10, 2), columns=list('ab'))
>>> df.query('a > b')
>>> df[df.a > df.b] # same result as the previous expression
"""
inplace = validate_bool_kwarg(inplace, 'inplace')
if not isinstance(expr, compat.string_types):
msg = "expr must be a string to be evaluated, {0} given"
raise ValueError(msg.format(type(expr)))
kwargs['level'] = kwargs.pop('level', 0) + 1
kwargs['target'] = None
res = self.eval(expr, **kwargs)
try:
new_data = self.loc[res]
except ValueError:
# when res is multi-dimensional loc raises, but this is sometimes a
# valid query
new_data = self[res]
if inplace:
self._update_inplace(new_data)
else:
return new_data | [
"def",
"query",
"(",
"self",
",",
"expr",
",",
"inplace",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"inplace",
"=",
"validate_bool_kwarg",
"(",
"inplace",
",",
"'inplace'",
")",
"if",
"not",
"isinstance",
"(",
"expr",
",",
"compat",
".",
"string... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py2/pandas/core/frame.py#L3012-L3100 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemFramework/v1/ResourceManager/lib/Crypto/IO/PEM.py | python | decode | (pem_data, passphrase=None) | return (data, marker, enc_flag) | Decode a PEM block into binary.
Args:
pem_data (string):
The PEM block.
passphrase (byte string):
If given and the PEM block is encrypted,
the key will be derived from the passphrase.
Returns:
A tuple with the binary data, the marker string, and a boolean to
indicate if decryption was performed.
Raises:
ValueError: if decoding fails, if the PEM file is encrypted and no passphrase has
been provided or if the passphrase is incorrect. | Decode a PEM block into binary. | [
"Decode",
"a",
"PEM",
"block",
"into",
"binary",
"."
] | def decode(pem_data, passphrase=None):
"""Decode a PEM block into binary.
Args:
pem_data (string):
The PEM block.
passphrase (byte string):
If given and the PEM block is encrypted,
the key will be derived from the passphrase.
Returns:
A tuple with the binary data, the marker string, and a boolean to
indicate if decryption was performed.
Raises:
ValueError: if decoding fails, if the PEM file is encrypted and no passphrase has
been provided or if the passphrase is incorrect.
"""
# Verify Pre-Encapsulation Boundary
r = re.compile(r"\s*-----BEGIN (.*)-----\s+")
m = r.match(pem_data)
if not m:
raise ValueError("Not a valid PEM pre boundary")
marker = m.group(1)
# Verify Post-Encapsulation Boundary
r = re.compile(r"-----END (.*)-----\s*$")
m = r.search(pem_data)
if not m or m.group(1) != marker:
raise ValueError("Not a valid PEM post boundary")
# Removes spaces and slit on lines
lines = pem_data.replace(" ", '').split()
# Decrypts, if necessary
if lines[1].startswith('Proc-Type:4,ENCRYPTED'):
if not passphrase:
raise ValueError("PEM is encrypted, but no passphrase available")
DEK = lines[2].split(':')
if len(DEK) != 2 or DEK[0] != 'DEK-Info':
raise ValueError("PEM encryption format not supported.")
algo, salt = DEK[1].split(',')
salt = unhexlify(tobytes(salt))
padding = True
if algo == "DES-CBC":
key = _EVP_BytesToKey(passphrase, salt, 8)
objdec = DES.new(key, DES.MODE_CBC, salt)
elif algo == "DES-EDE3-CBC":
key = _EVP_BytesToKey(passphrase, salt, 24)
objdec = DES3.new(key, DES3.MODE_CBC, salt)
elif algo == "AES-128-CBC":
key = _EVP_BytesToKey(passphrase, salt[:8], 16)
objdec = AES.new(key, AES.MODE_CBC, salt)
elif algo == "AES-192-CBC":
key = _EVP_BytesToKey(passphrase, salt[:8], 24)
objdec = AES.new(key, AES.MODE_CBC, salt)
elif algo == "AES-256-CBC":
key = _EVP_BytesToKey(passphrase, salt[:8], 32)
objdec = AES.new(key, AES.MODE_CBC, salt)
elif algo.lower() == "id-aes256-gcm":
key = _EVP_BytesToKey(passphrase, salt[:8], 32)
objdec = AES.new(key, AES.MODE_GCM, nonce=salt)
padding = False
else:
raise ValueError("Unsupport PEM encryption algorithm (%s)." % algo)
lines = lines[2:]
else:
objdec = None
# Decode body
data = a2b_base64(''.join(lines[1:-1]))
enc_flag = False
if objdec:
if padding:
data = unpad(objdec.decrypt(data), objdec.block_size)
else:
# There is no tag, so we don't use decrypt_and_verify
data = objdec.decrypt(data)
enc_flag = True
return (data, marker, enc_flag) | [
"def",
"decode",
"(",
"pem_data",
",",
"passphrase",
"=",
"None",
")",
":",
"# Verify Pre-Encapsulation Boundary",
"r",
"=",
"re",
".",
"compile",
"(",
"r\"\\s*-----BEGIN (.*)-----\\s+\"",
")",
"m",
"=",
"r",
".",
"match",
"(",
"pem_data",
")",
"if",
"not",
... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemFramework/v1/ResourceManager/lib/Crypto/IO/PEM.py#L106-L189 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/targets/listobj.py | python | get_list_payload | (context, builder, list_type, value) | return context.make_data_helper(builder, payload_type, ref=payload) | Given a list value and type, get its payload structure (as a
reference, so that mutations are seen by all). | Given a list value and type, get its payload structure (as a
reference, so that mutations are seen by all). | [
"Given",
"a",
"list",
"value",
"and",
"type",
"get",
"its",
"payload",
"structure",
"(",
"as",
"a",
"reference",
"so",
"that",
"mutations",
"are",
"seen",
"by",
"all",
")",
"."
] | def get_list_payload(context, builder, list_type, value):
"""
Given a list value and type, get its payload structure (as a
reference, so that mutations are seen by all).
"""
payload_type = types.ListPayload(list_type)
payload = context.nrt.meminfo_data(builder, value.meminfo)
ptrty = context.get_data_type(payload_type).as_pointer()
payload = builder.bitcast(payload, ptrty)
return context.make_data_helper(builder, payload_type, ref=payload) | [
"def",
"get_list_payload",
"(",
"context",
",",
"builder",
",",
"list_type",
",",
"value",
")",
":",
"payload_type",
"=",
"types",
".",
"ListPayload",
"(",
"list_type",
")",
"payload",
"=",
"context",
".",
"nrt",
".",
"meminfo_data",
"(",
"builder",
",",
"... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/targets/listobj.py#L21-L30 | |
gklz1982/caffe-yolov2 | ebb27029db4ddc0d40e520634633b0fa9cdcc10d | scripts/cpp_lint.py | python | FindPreviousMatchingAngleBracket | (clean_lines, linenum, init_prefix) | return False | Find the corresponding < that started a template.
Args:
clean_lines: A CleansedLines instance containing the file.
linenum: Current line number.
init_prefix: Part of the current line before the initial >.
Returns:
True if a matching bracket exists. | Find the corresponding < that started a template. | [
"Find",
"the",
"corresponding",
"<",
"that",
"started",
"a",
"template",
"."
] | def FindPreviousMatchingAngleBracket(clean_lines, linenum, init_prefix):
"""Find the corresponding < that started a template.
Args:
clean_lines: A CleansedLines instance containing the file.
linenum: Current line number.
init_prefix: Part of the current line before the initial >.
Returns:
True if a matching bracket exists.
"""
line = init_prefix
nesting_stack = ['>']
while True:
# Find the previous operator
match = Search(r'^(.*)([<>(),;\[\]])[^<>(),;\[\]]*$', line)
if match:
# Found an operator, update nesting stack
operator = match.group(2)
line = match.group(1)
if nesting_stack[-1] == '>':
# Expecting opening angle bracket
if operator in ('>', ')', ']'):
nesting_stack.append(operator)
elif operator == '<':
nesting_stack.pop()
if not nesting_stack:
# Found matching angle bracket
return True
elif operator == ',':
# Got a comma before a bracket, this is most likely a
# template argument. The opening angle bracket is probably
# there if we look for it, so just return early here.
return True
else:
# Got some other operator.
return False
else:
# Expecting opening parenthesis or opening bracket
if operator in ('>', ')', ']'):
nesting_stack.append(operator)
elif operator in ('(', '['):
nesting_stack.pop()
else:
# Scan the previous line
linenum -= 1
if linenum < 0:
break
line = clean_lines.elided[linenum]
# Exhausted all earlier lines and still no matching angle bracket.
return False | [
"def",
"FindPreviousMatchingAngleBracket",
"(",
"clean_lines",
",",
"linenum",
",",
"init_prefix",
")",
":",
"line",
"=",
"init_prefix",
"nesting_stack",
"=",
"[",
"'>'",
"]",
"while",
"True",
":",
"# Find the previous operator",
"match",
"=",
"Search",
"(",
"r'^(... | https://github.com/gklz1982/caffe-yolov2/blob/ebb27029db4ddc0d40e520634633b0fa9cdcc10d/scripts/cpp_lint.py#L2586-L2640 | |
microsoft/ivy | 9f3c7ecc0b2383129fdd0953e10890d98d09a82d | ivy/ivy_interp.py | python | diagram | (state,clauses,implied=false_clauses(),extra_axioms=None,weaken=True) | return under | Return the diagram of a single model of clauses in state or
None if clauses are unsat. | Return the diagram of a single model of clauses in state or
None if clauses are unsat. | [
"Return",
"the",
"diagram",
"of",
"a",
"single",
"model",
"of",
"clauses",
"in",
"state",
"or",
"None",
"if",
"clauses",
"are",
"unsat",
"."
] | def diagram(state,clauses,implied=false_clauses(),extra_axioms=None,weaken=True):
""" Return the diagram of a single model of clauses in state or
None if clauses are unsat.
"""
axioms = state.domain.background_theory(state.in_scope)
if extra_axioms:
axioms = and_clauses(axioms,extra_axioms)
under = clauses_model_to_diagram(clauses,is_skolem,implied,axioms=axioms,weaken=weaken)
return under | [
"def",
"diagram",
"(",
"state",
",",
"clauses",
",",
"implied",
"=",
"false_clauses",
"(",
")",
",",
"extra_axioms",
"=",
"None",
",",
"weaken",
"=",
"True",
")",
":",
"axioms",
"=",
"state",
".",
"domain",
".",
"background_theory",
"(",
"state",
".",
... | https://github.com/microsoft/ivy/blob/9f3c7ecc0b2383129fdd0953e10890d98d09a82d/ivy/ivy_interp.py#L337-L345 | |
psnonis/FinBERT | c0c555d833a14e2316a3701e59c0b5156f804b4e | bert-gpu/tensorrt-inference-server/src/clients/python/__init__.py | python | ServerStatusContext.close | (self) | Close the context. Any future calls to get_server_status() will
result in an Error. | Close the context. Any future calls to get_server_status() will
result in an Error. | [
"Close",
"the",
"context",
".",
"Any",
"future",
"calls",
"to",
"get_server_status",
"()",
"will",
"result",
"in",
"an",
"Error",
"."
] | def close(self):
"""Close the context. Any future calls to get_server_status() will
result in an Error.
"""
_crequest_status_ctx_del(self._ctx)
self._ctx = None | [
"def",
"close",
"(",
"self",
")",
":",
"_crequest_status_ctx_del",
"(",
"self",
".",
"_ctx",
")",
"self",
".",
"_ctx",
"=",
"None"
] | https://github.com/psnonis/FinBERT/blob/c0c555d833a14e2316a3701e59c0b5156f804b4e/bert-gpu/tensorrt-inference-server/src/clients/python/__init__.py#L439-L445 | ||
ianmaclarty/amulet | 3d1363e0a0dde5e4c346409cefab66c2dc91b237 | third_party/freetype-2.5.5/src/tools/docmaker/tohtml.py | python | HtmlFormatter.make_html_code | ( self, lines ) | return line + code_footer | Convert a code sequence to HTML. | Convert a code sequence to HTML. | [
"Convert",
"a",
"code",
"sequence",
"to",
"HTML",
"."
] | def make_html_code( self, lines ):
"""Convert a code sequence to HTML."""
line = code_header + '\n'
for l in lines:
line = line + html_quote( l ) + '\n'
return line + code_footer | [
"def",
"make_html_code",
"(",
"self",
",",
"lines",
")",
":",
"line",
"=",
"code_header",
"+",
"'\\n'",
"for",
"l",
"in",
"lines",
":",
"line",
"=",
"line",
"+",
"html_quote",
"(",
"l",
")",
"+",
"'\\n'",
"return",
"line",
"+",
"code_footer"
] | https://github.com/ianmaclarty/amulet/blob/3d1363e0a0dde5e4c346409cefab66c2dc91b237/third_party/freetype-2.5.5/src/tools/docmaker/tohtml.py#L365-L371 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/prompt-toolkit/py3/prompt_toolkit/layout/layout.py | python | Layout.focus_previous | (self) | Focus the previous visible/focusable Window. | Focus the previous visible/focusable Window. | [
"Focus",
"the",
"previous",
"visible",
"/",
"focusable",
"Window",
"."
] | def focus_previous(self) -> None:
"""
Focus the previous visible/focusable Window.
"""
windows = self.get_visible_focusable_windows()
if len(windows) > 0:
try:
index = windows.index(self.current_window)
except ValueError:
index = 0
else:
index = (index - 1) % len(windows)
self.focus(windows[index]) | [
"def",
"focus_previous",
"(",
"self",
")",
"->",
"None",
":",
"windows",
"=",
"self",
".",
"get_visible_focusable_windows",
"(",
")",
"if",
"len",
"(",
"windows",
")",
">",
"0",
":",
"try",
":",
"index",
"=",
"windows",
".",
"index",
"(",
"self",
".",
... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/prompt-toolkit/py3/prompt_toolkit/layout/layout.py#L325-L339 | ||
indutny/candor | 48e7260618f5091c80a3416828e2808cad3ea22e | tools/gyp/pylib/gyp/win_tool.py | python | WinTool._CommandifyName | (self, name_string) | return name_string.title().replace('-', '') | Transforms a tool name like recursive-mirror to RecursiveMirror. | Transforms a tool name like recursive-mirror to RecursiveMirror. | [
"Transforms",
"a",
"tool",
"name",
"like",
"recursive",
"-",
"mirror",
"to",
"RecursiveMirror",
"."
] | def _CommandifyName(self, name_string):
"""Transforms a tool name like recursive-mirror to RecursiveMirror."""
return name_string.title().replace('-', '') | [
"def",
"_CommandifyName",
"(",
"self",
",",
"name_string",
")",
":",
"return",
"name_string",
".",
"title",
"(",
")",
".",
"replace",
"(",
"'-'",
",",
"''",
")"
] | https://github.com/indutny/candor/blob/48e7260618f5091c80a3416828e2808cad3ea22e/tools/gyp/pylib/gyp/win_tool.py#L56-L58 | |
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/ops/distributions/util.py | python | prefer_static_value | (x) | return x | Return static value of tensor `x` if available, else `x`.
Args:
x: `Tensor` (already converted).
Returns:
Numpy array (if static value is obtainable), else `Tensor`. | Return static value of tensor `x` if available, else `x`. | [
"Return",
"static",
"value",
"of",
"tensor",
"x",
"if",
"available",
"else",
"x",
"."
] | def prefer_static_value(x):
"""Return static value of tensor `x` if available, else `x`.
Args:
x: `Tensor` (already converted).
Returns:
Numpy array (if static value is obtainable), else `Tensor`.
"""
static_x = tensor_util.constant_value(x)
if static_x is not None:
return static_x
return x | [
"def",
"prefer_static_value",
"(",
"x",
")",
":",
"static_x",
"=",
"tensor_util",
".",
"constant_value",
"(",
"x",
")",
"if",
"static_x",
"is",
"not",
"None",
":",
"return",
"static_x",
"return",
"x"
] | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/ops/distributions/util.py#L772-L784 | |
MhLiao/TextBoxes_plusplus | 39d4898de1504c53a2ed3d67966a57b3595836d0 | python/caffe/io.py | python | arraylist_to_blobprotovector_str | (arraylist) | return vec.SerializeToString() | Converts a list of arrays to a serialized blobprotovec, which could be
then passed to a network for processing. | Converts a list of arrays to a serialized blobprotovec, which could be
then passed to a network for processing. | [
"Converts",
"a",
"list",
"of",
"arrays",
"to",
"a",
"serialized",
"blobprotovec",
"which",
"could",
"be",
"then",
"passed",
"to",
"a",
"network",
"for",
"processing",
"."
] | def arraylist_to_blobprotovector_str(arraylist):
"""Converts a list of arrays to a serialized blobprotovec, which could be
then passed to a network for processing.
"""
vec = caffe_pb2.BlobProtoVector()
vec.blobs.extend([array_to_blobproto(arr) for arr in arraylist])
return vec.SerializeToString() | [
"def",
"arraylist_to_blobprotovector_str",
"(",
"arraylist",
")",
":",
"vec",
"=",
"caffe_pb2",
".",
"BlobProtoVector",
"(",
")",
"vec",
".",
"blobs",
".",
"extend",
"(",
"[",
"array_to_blobproto",
"(",
"arr",
")",
"for",
"arr",
"in",
"arraylist",
"]",
")",
... | https://github.com/MhLiao/TextBoxes_plusplus/blob/39d4898de1504c53a2ed3d67966a57b3595836d0/python/caffe/io.py#L49-L55 | |
natanielruiz/android-yolo | 1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f | jni-build/jni/include/tensorflow/models/image/cifar10/cifar10.py | python | _activation_summary | (x) | Helper to create summaries for activations.
Creates a summary that provides a histogram of activations.
Creates a summary that measure the sparsity of activations.
Args:
x: Tensor
Returns:
nothing | Helper to create summaries for activations. | [
"Helper",
"to",
"create",
"summaries",
"for",
"activations",
"."
] | def _activation_summary(x):
"""Helper to create summaries for activations.
Creates a summary that provides a histogram of activations.
Creates a summary that measure the sparsity of activations.
Args:
x: Tensor
Returns:
nothing
"""
# Remove 'tower_[0-9]/' from the name in case this is a multi-GPU training
# session. This helps the clarity of presentation on tensorboard.
tensor_name = re.sub('%s_[0-9]*/' % TOWER_NAME, '', x.op.name)
tf.histogram_summary(tensor_name + '/activations', x)
tf.scalar_summary(tensor_name + '/sparsity', tf.nn.zero_fraction(x)) | [
"def",
"_activation_summary",
"(",
"x",
")",
":",
"# Remove 'tower_[0-9]/' from the name in case this is a multi-GPU training",
"# session. This helps the clarity of presentation on tensorboard.",
"tensor_name",
"=",
"re",
".",
"sub",
"(",
"'%s_[0-9]*/'",
"%",
"TOWER_NAME",
",",
... | https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/tensorflow/models/image/cifar10/cifar10.py#L80-L95 | ||
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | qt/python/mantidqtinterfaces/mantidqtinterfaces/Muon/GUI/Common/fitting_widgets/basic_fitting/basic_fitting_view.py | python | BasicFittingView.set_slot_for_dataset_changed | (self, slot) | Connect the slot for the display workspace combo box being changed. | Connect the slot for the display workspace combo box being changed. | [
"Connect",
"the",
"slot",
"for",
"the",
"display",
"workspace",
"combo",
"box",
"being",
"changed",
"."
] | def set_slot_for_dataset_changed(self, slot) -> None:
"""Connect the slot for the display workspace combo box being changed."""
self.workspace_selector.set_slot_for_dataset_changed(slot) | [
"def",
"set_slot_for_dataset_changed",
"(",
"self",
",",
"slot",
")",
"->",
"None",
":",
"self",
".",
"workspace_selector",
".",
"set_slot_for_dataset_changed",
"(",
"slot",
")"
] | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqtinterfaces/mantidqtinterfaces/Muon/GUI/Common/fitting_widgets/basic_fitting/basic_fitting_view.py#L60-L62 | ||
hpi-xnor/BMXNet | ed0b201da6667887222b8e4b5f997c4f6b61943d | example/rcnn/rcnn/pycocotools/coco.py | python | COCO.getImgIds | (self, imgIds=[], catIds=[]) | return list(ids) | Get img ids that satisfy given filter conditions.
:param imgIds (int array) : get imgs for given ids
:param catIds (int array) : get imgs with all given cats
:return: ids (int array) : integer array of img ids | Get img ids that satisfy given filter conditions.
:param imgIds (int array) : get imgs for given ids
:param catIds (int array) : get imgs with all given cats
:return: ids (int array) : integer array of img ids | [
"Get",
"img",
"ids",
"that",
"satisfy",
"given",
"filter",
"conditions",
".",
":",
"param",
"imgIds",
"(",
"int",
"array",
")",
":",
"get",
"imgs",
"for",
"given",
"ids",
":",
"param",
"catIds",
"(",
"int",
"array",
")",
":",
"get",
"imgs",
"with",
"... | def getImgIds(self, imgIds=[], catIds=[]):
'''
Get img ids that satisfy given filter conditions.
:param imgIds (int array) : get imgs for given ids
:param catIds (int array) : get imgs with all given cats
:return: ids (int array) : integer array of img ids
'''
imgIds = imgIds if type(imgIds) == list else [imgIds]
catIds = catIds if type(catIds) == list else [catIds]
if len(imgIds) == len(catIds) == 0:
ids = self.imgs.keys()
else:
ids = set(imgIds)
for i, catId in enumerate(catIds):
if i == 0 and len(ids) == 0:
ids = set(self.catToImgs[catId])
else:
ids &= set(self.catToImgs[catId])
return list(ids) | [
"def",
"getImgIds",
"(",
"self",
",",
"imgIds",
"=",
"[",
"]",
",",
"catIds",
"=",
"[",
"]",
")",
":",
"imgIds",
"=",
"imgIds",
"if",
"type",
"(",
"imgIds",
")",
"==",
"list",
"else",
"[",
"imgIds",
"]",
"catIds",
"=",
"catIds",
"if",
"type",
"("... | https://github.com/hpi-xnor/BMXNet/blob/ed0b201da6667887222b8e4b5f997c4f6b61943d/example/rcnn/rcnn/pycocotools/coco.py#L191-L210 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/llvmlite/ir/module.py | python | Module.add_metadata | (self, operands) | return md | Add an unnamed metadata to the module with the given *operands*
(a sequence of values) or return a previous equivalent metadata.
A MDValue instance is returned, it can then be associated to
e.g. an instruction. | Add an unnamed metadata to the module with the given *operands*
(a sequence of values) or return a previous equivalent metadata.
A MDValue instance is returned, it can then be associated to
e.g. an instruction. | [
"Add",
"an",
"unnamed",
"metadata",
"to",
"the",
"module",
"with",
"the",
"given",
"*",
"operands",
"*",
"(",
"a",
"sequence",
"of",
"values",
")",
"or",
"return",
"a",
"previous",
"equivalent",
"metadata",
".",
"A",
"MDValue",
"instance",
"is",
"returned"... | def add_metadata(self, operands):
"""
Add an unnamed metadata to the module with the given *operands*
(a sequence of values) or return a previous equivalent metadata.
A MDValue instance is returned, it can then be associated to
e.g. an instruction.
"""
if not isinstance(operands, (list, tuple)):
raise TypeError("expected a list or tuple of metadata values, "
"got %r" % (operands,))
operands = self._fix_metadata_operands(operands)
key = tuple(operands)
if key not in self._metadatacache:
n = len(self.metadata)
md = values.MDValue(self, operands, name=str(n))
self._metadatacache[key] = md
else:
md = self._metadatacache[key]
return md | [
"def",
"add_metadata",
"(",
"self",
",",
"operands",
")",
":",
"if",
"not",
"isinstance",
"(",
"operands",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"raise",
"TypeError",
"(",
"\"expected a list or tuple of metadata values, \"",
"\"got %r\"",
"%",
"(",
"o... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/llvmlite/ir/module.py#L47-L65 | |
mindspore-ai/mindspore | fb8fd3338605bb34fa5cea054e535a8b1d753fab | mindspore/python/mindspore/nn/probability/distribution/log_normal.py | python | LogNormal._log_prob | (self, value, loc=None, scale=None) | return unadjust_prob + log_jacobian | r"""
Compute the log prob via the below formula,
where g is the exp bijector,
and P is the pdf of the underlying normal dist
.. math::
Y = g(X)
Py(a) = Px(g^{-1}(a)) * (g^{-1})'(a)
\log(Py(a)) = \log(Px(g^{-1}(a))) + \log((g^{-1})'(a)) | r"""
Compute the log prob via the below formula,
where g is the exp bijector,
and P is the pdf of the underlying normal dist
.. math::
Y = g(X)
Py(a) = Px(g^{-1}(a)) * (g^{-1})'(a)
\log(Py(a)) = \log(Px(g^{-1}(a))) + \log((g^{-1})'(a)) | [
"r",
"Compute",
"the",
"log",
"prob",
"via",
"the",
"below",
"formula",
"where",
"g",
"is",
"the",
"exp",
"bijector",
"and",
"P",
"is",
"the",
"pdf",
"of",
"the",
"underlying",
"normal",
"dist",
"..",
"math",
"::",
"Y",
"=",
"g",
"(",
"X",
")",
"Py... | def _log_prob(self, value, loc=None, scale=None):
r"""
Compute the log prob via the below formula,
where g is the exp bijector,
and P is the pdf of the underlying normal dist
.. math::
Y = g(X)
Py(a) = Px(g^{-1}(a)) * (g^{-1})'(a)
\log(Py(a)) = \log(Px(g^{-1}(a))) + \log((g^{-1})'(a))
"""
mean, sd = self._check_param_type(loc, scale)
inverse_value = self.bijector("inverse", value)
unadjust_prob = self.distribution("log_prob", inverse_value, mean, sd)
log_jacobian = self.bijector("inverse_log_jacobian", value)
return unadjust_prob + log_jacobian | [
"def",
"_log_prob",
"(",
"self",
",",
"value",
",",
"loc",
"=",
"None",
",",
"scale",
"=",
"None",
")",
":",
"mean",
",",
"sd",
"=",
"self",
".",
"_check_param_type",
"(",
"loc",
",",
"scale",
")",
"inverse_value",
"=",
"self",
".",
"bijector",
"(",
... | https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/nn/probability/distribution/log_normal.py#L222-L236 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/x86/toolchain/lib/python2.7/lib-tk/ttk.py | python | Treeview.column | (self, column, option=None, **kw) | return _val_or_dict(kw, self.tk.call, self._w, "column", column) | Query or modify the options for the specified column.
If kw is not given, returns a dict of the column option values. If
option is specified then the value for that option is returned.
Otherwise, sets the options to the corresponding values. | Query or modify the options for the specified column. | [
"Query",
"or",
"modify",
"the",
"options",
"for",
"the",
"specified",
"column",
"."
] | def column(self, column, option=None, **kw):
"""Query or modify the options for the specified column.
If kw is not given, returns a dict of the column option values. If
option is specified then the value for that option is returned.
Otherwise, sets the options to the corresponding values."""
if option is not None:
kw[option] = None
return _val_or_dict(kw, self.tk.call, self._w, "column", column) | [
"def",
"column",
"(",
"self",
",",
"column",
",",
"option",
"=",
"None",
",",
"*",
"*",
"kw",
")",
":",
"if",
"option",
"is",
"not",
"None",
":",
"kw",
"[",
"option",
"]",
"=",
"None",
"return",
"_val_or_dict",
"(",
"kw",
",",
"self",
".",
"tk",
... | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/lib-tk/ttk.py#L1203-L1211 | |
rdkit/rdkit | ede860ae316d12d8568daf5ee800921c3389c84e | rdkit/sping/pid.py | python | Canvas.save | (self, file=None, format=None) | For backends that can be save to a file or sent to a
stream, create a valid file out of what's currently been
drawn on the canvas. Trigger any finalization here.
Though some backends may allow further drawing after this call,
presume that this is not possible for maximum portability
file may be either a string or a file object with a write method
if left as the default, the canvas's current name will be used
format may be used to specify the type of file format to use as
well as any corresponding extension to use for the filename
This is an optional argument and backends may ignore it if
they only produce one file format. | For backends that can be save to a file or sent to a
stream, create a valid file out of what's currently been
drawn on the canvas. Trigger any finalization here.
Though some backends may allow further drawing after this call,
presume that this is not possible for maximum portability | [
"For",
"backends",
"that",
"can",
"be",
"save",
"to",
"a",
"file",
"or",
"sent",
"to",
"a",
"stream",
"create",
"a",
"valid",
"file",
"out",
"of",
"what",
"s",
"currently",
"been",
"drawn",
"on",
"the",
"canvas",
".",
"Trigger",
"any",
"finalization",
... | def save(self, file=None, format=None):
"""For backends that can be save to a file or sent to a
stream, create a valid file out of what's currently been
drawn on the canvas. Trigger any finalization here.
Though some backends may allow further drawing after this call,
presume that this is not possible for maximum portability
file may be either a string or a file object with a write method
if left as the default, the canvas's current name will be used
format may be used to specify the type of file format to use as
well as any corresponding extension to use for the filename
This is an optional argument and backends may ignore it if
they only produce one file format."""
pass | [
"def",
"save",
"(",
"self",
",",
"file",
"=",
"None",
",",
"format",
"=",
"None",
")",
":",
"pass"
] | https://github.com/rdkit/rdkit/blob/ede860ae316d12d8568daf5ee800921c3389c84e/rdkit/sping/pid.py#L264-L278 | ||
thalium/icebox | 99d147d5b9269222225443ce171b4fd46d8985d4 | third_party/virtualbox/src/libs/libxml2-2.9.4/python/libxml2.py | python | xpathContext.xpathNewParserContext | (self, str) | return __tmp | Create a new xmlXPathParserContext | Create a new xmlXPathParserContext | [
"Create",
"a",
"new",
"xmlXPathParserContext"
] | def xpathNewParserContext(self, str):
"""Create a new xmlXPathParserContext """
ret = libxml2mod.xmlXPathNewParserContext(str, self._o)
if ret is None:raise xpathError('xmlXPathNewParserContext() failed')
__tmp = xpathParserContext(_obj=ret)
return __tmp | [
"def",
"xpathNewParserContext",
"(",
"self",
",",
"str",
")",
":",
"ret",
"=",
"libxml2mod",
".",
"xmlXPathNewParserContext",
"(",
"str",
",",
"self",
".",
"_o",
")",
"if",
"ret",
"is",
"None",
":",
"raise",
"xpathError",
"(",
"'xmlXPathNewParserContext() fail... | https://github.com/thalium/icebox/blob/99d147d5b9269222225443ce171b4fd46d8985d4/third_party/virtualbox/src/libs/libxml2-2.9.4/python/libxml2.py#L7357-L7362 | |
macchina-io/macchina.io | ef24ba0e18379c3dd48fb84e6dbf991101cb8db0 | platform/JS/V8/tools/gyp/pylib/gyp/generator/msvs.py | python | _EscapeEnvironmentVariableExpansion | (s) | return s | Escapes % characters.
Escapes any % characters so that Windows-style environment variable
expansions will leave them alone.
See http://connect.microsoft.com/VisualStudio/feedback/details/106127/cl-d-name-text-containing-percentage-characters-doesnt-compile
to understand why we have to do this.
Args:
s: The string to be escaped.
Returns:
The escaped string. | Escapes % characters. | [
"Escapes",
"%",
"characters",
"."
] | def _EscapeEnvironmentVariableExpansion(s):
"""Escapes % characters.
Escapes any % characters so that Windows-style environment variable
expansions will leave them alone.
See http://connect.microsoft.com/VisualStudio/feedback/details/106127/cl-d-name-text-containing-percentage-characters-doesnt-compile
to understand why we have to do this.
Args:
s: The string to be escaped.
Returns:
The escaped string.
"""
s = s.replace('%', '%%')
return s | [
"def",
"_EscapeEnvironmentVariableExpansion",
"(",
"s",
")",
":",
"s",
"=",
"s",
".",
"replace",
"(",
"'%'",
",",
"'%%'",
")",
"return",
"s"
] | https://github.com/macchina-io/macchina.io/blob/ef24ba0e18379c3dd48fb84e6dbf991101cb8db0/platform/JS/V8/tools/gyp/pylib/gyp/generator/msvs.py#L684-L699 | |
giuspen/cherrytree | 84712f206478fcf9acf30174009ad28c648c6344 | pygtk2/modules/exports.py | python | ExportPrint.pango_text_add_node_name | (self, tree_iter, pango_text) | Add Node Name to Pango Text Vector | Add Node Name to Pango Text Vector | [
"Add",
"Node",
"Name",
"to",
"Pango",
"Text",
"Vector"
] | def pango_text_add_node_name(self, tree_iter, pango_text):
"""Add Node Name to Pango Text Vector"""
pango_text[0] = "<b><i><span size=\"xx-large\">" \
+ cgi.escape(self.dad.treestore[tree_iter][1]) \
+ "</span></i></b>" + 2*cons.CHAR_NEWLINE + pango_text[0] | [
"def",
"pango_text_add_node_name",
"(",
"self",
",",
"tree_iter",
",",
"pango_text",
")",
":",
"pango_text",
"[",
"0",
"]",
"=",
"\"<b><i><span size=\\\"xx-large\\\">\"",
"+",
"cgi",
".",
"escape",
"(",
"self",
".",
"dad",
".",
"treestore",
"[",
"tree_iter",
"... | https://github.com/giuspen/cherrytree/blob/84712f206478fcf9acf30174009ad28c648c6344/pygtk2/modules/exports.py#L261-L265 | ||
eventql/eventql | 7ca0dbb2e683b525620ea30dc40540a22d5eb227 | deps/3rdparty/spidermonkey/mozjs/media/webrtc/trunk/tools/gyp/pylib/gyp/MSVSNew.py | python | MSVSProject.__init__ | (self, path, name = None, dependencies = None, guid = None,
spec = None, build_file = None, config_platform_overrides = None,
fixpath_prefix = None) | Initializes the project.
Args:
path: Absolute path to the project file.
name: Name of project. If None, the name will be the same as the base
name of the project file.
dependencies: List of other Project objects this project is dependent
upon, if not None.
guid: GUID to use for project, if not None.
spec: Dictionary specifying how to build this project.
build_file: Filename of the .gyp file that the vcproj file comes from.
config_platform_overrides: optional dict of configuration platforms to
used in place of the default for this target.
fixpath_prefix: the path used to adjust the behavior of _fixpath | Initializes the project. | [
"Initializes",
"the",
"project",
"."
] | def __init__(self, path, name = None, dependencies = None, guid = None,
spec = None, build_file = None, config_platform_overrides = None,
fixpath_prefix = None):
"""Initializes the project.
Args:
path: Absolute path to the project file.
name: Name of project. If None, the name will be the same as the base
name of the project file.
dependencies: List of other Project objects this project is dependent
upon, if not None.
guid: GUID to use for project, if not None.
spec: Dictionary specifying how to build this project.
build_file: Filename of the .gyp file that the vcproj file comes from.
config_platform_overrides: optional dict of configuration platforms to
used in place of the default for this target.
fixpath_prefix: the path used to adjust the behavior of _fixpath
"""
self.path = path
self.guid = guid
self.spec = spec
self.build_file = build_file
# Use project filename if name not specified
self.name = name or os.path.splitext(os.path.basename(path))[0]
# Copy passed lists (or set to empty lists)
self.dependencies = list(dependencies or [])
self.entry_type_guid = ENTRY_TYPE_GUIDS['project']
if config_platform_overrides:
self.config_platform_overrides = config_platform_overrides
else:
self.config_platform_overrides = {}
self.fixpath_prefix = fixpath_prefix
self.msbuild_toolset = None | [
"def",
"__init__",
"(",
"self",
",",
"path",
",",
"name",
"=",
"None",
",",
"dependencies",
"=",
"None",
",",
"guid",
"=",
"None",
",",
"spec",
"=",
"None",
",",
"build_file",
"=",
"None",
",",
"config_platform_overrides",
"=",
"None",
",",
"fixpath_pref... | https://github.com/eventql/eventql/blob/7ca0dbb2e683b525620ea30dc40540a22d5eb227/deps/3rdparty/spidermonkey/mozjs/media/webrtc/trunk/tools/gyp/pylib/gyp/MSVSNew.py#L112-L147 | ||
D-X-Y/caffe-faster-rcnn | eb50c97ff48f3df115d0e85fe0a32b0c7e2aa4cb | python/caffe/io.py | python | Transformer.set_mean | (self, in_, mean) | Set the mean to subtract for centering the data.
Parameters
----------
in_ : which input to assign this mean.
mean : mean ndarray (input dimensional or broadcastable) | Set the mean to subtract for centering the data. | [
"Set",
"the",
"mean",
"to",
"subtract",
"for",
"centering",
"the",
"data",
"."
] | def set_mean(self, in_, mean):
"""
Set the mean to subtract for centering the data.
Parameters
----------
in_ : which input to assign this mean.
mean : mean ndarray (input dimensional or broadcastable)
"""
self.__check_input(in_)
ms = mean.shape
if mean.ndim == 1:
# broadcast channels
if ms[0] != self.inputs[in_][1]:
raise ValueError('Mean channels incompatible with input.')
mean = mean[:, np.newaxis, np.newaxis]
else:
# elementwise mean
if len(ms) == 2:
ms = (1,) + ms
if len(ms) != 3:
raise ValueError('Mean shape invalid')
if ms != self.inputs[in_][1:]:
in_shape = self.inputs[in_][1:]
m_min, m_max = mean.min(), mean.max()
normal_mean = (mean - m_min) / (m_max - m_min)
mean = resize_image(normal_mean.transpose((1,2,0)),
in_shape[1:]).transpose((2,0,1)) * \
(m_max - m_min) + m_min
self.mean[in_] = mean | [
"def",
"set_mean",
"(",
"self",
",",
"in_",
",",
"mean",
")",
":",
"self",
".",
"__check_input",
"(",
"in_",
")",
"ms",
"=",
"mean",
".",
"shape",
"if",
"mean",
".",
"ndim",
"==",
"1",
":",
"# broadcast channels",
"if",
"ms",
"[",
"0",
"]",
"!=",
... | https://github.com/D-X-Y/caffe-faster-rcnn/blob/eb50c97ff48f3df115d0e85fe0a32b0c7e2aa4cb/python/caffe/io.py#L236-L265 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/_core.py | python | BookCtrlBase.GetPageText | (*args, **kwargs) | return _core_.BookCtrlBase_GetPageText(*args, **kwargs) | GetPageText(self, size_t n) -> String | GetPageText(self, size_t n) -> String | [
"GetPageText",
"(",
"self",
"size_t",
"n",
")",
"-",
">",
"String"
] | def GetPageText(*args, **kwargs):
"""GetPageText(self, size_t n) -> String"""
return _core_.BookCtrlBase_GetPageText(*args, **kwargs) | [
"def",
"GetPageText",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_core_",
".",
"BookCtrlBase_GetPageText",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_core.py#L13554-L13556 | |
GJDuck/LowFat | ecf6a0f0fa1b73a27a626cf493cc39e477b6faea | llvm-4.0.0.src/tools/clang/bindings/python/clang/cindex.py | python | Token.spelling | (self) | return conf.lib.clang_getTokenSpelling(self._tu, self) | The spelling of this token.
This is the textual representation of the token in source. | The spelling of this token. | [
"The",
"spelling",
"of",
"this",
"token",
"."
] | def spelling(self):
"""The spelling of this token.
This is the textual representation of the token in source.
"""
return conf.lib.clang_getTokenSpelling(self._tu, self) | [
"def",
"spelling",
"(",
"self",
")",
":",
"return",
"conf",
".",
"lib",
".",
"clang_getTokenSpelling",
"(",
"self",
".",
"_tu",
",",
"self",
")"
] | https://github.com/GJDuck/LowFat/blob/ecf6a0f0fa1b73a27a626cf493cc39e477b6faea/llvm-4.0.0.src/tools/clang/bindings/python/clang/cindex.py#L3018-L3023 | |
benoitsteiner/tensorflow-opencl | cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5 | tensorflow/contrib/graph_editor/subgraph.py | python | SubGraphView.passthroughs | (self) | return util.ListView(self._passthrough_ts) | The passthrough tensors, going straight from input to output. | The passthrough tensors, going straight from input to output. | [
"The",
"passthrough",
"tensors",
"going",
"straight",
"from",
"input",
"to",
"output",
"."
] | def passthroughs(self):
"""The passthrough tensors, going straight from input to output."""
return util.ListView(self._passthrough_ts) | [
"def",
"passthroughs",
"(",
"self",
")",
":",
"return",
"util",
".",
"ListView",
"(",
"self",
".",
"_passthrough_ts",
")"
] | https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/contrib/graph_editor/subgraph.py#L514-L516 | |
CRYTEK/CRYENGINE | 232227c59a220cbbd311576f0fbeba7bb53b2a8c | Tools/CryVersionSelector/release_project.py | python | run | (project_file) | Entry point for setting up the process to release a packaged build. | Entry point for setting up the process to release a packaged build. | [
"Entry",
"point",
"for",
"setting",
"up",
"the",
"process",
"to",
"release",
"a",
"packaged",
"build",
"."
] | def run(project_file):
"""
Entry point for setting up the process to release a packaged build.
"""
# Path to the project file as created by the launcher
# Engine and project path are derivable from this.
project = cryproject.CryProject()
try:
project.load(project_file)
except Exception:
print("Unable to read project file %s" % (project_file))
raise
# The path the folder that contains the .cryproject file.
project_path = os.path.normpath(os.path.dirname(project_file))
project_path_long = LONG_PATH_PREFIX + project_path
# The path to the engine that is being used by the project.
engine_path = crypath.get_engine_path()
engine_path_long = LONG_PATH_PREFIX + engine_path
# Path to which the game is to be exported.
export_path = os.path.join(
project_path, '{}_package'.format(project.name()))
configurations = get_available_configurations(engine_path)
if not configurations:
print("Unable to find a valid engine configuration. Make sure to "
"build your engine to the following locations.")
for key, value in DEFAULT_CONFIGURATIONS:
print("Configuration: {} \n Location: {}".format(key, value))
print("Press Enter to exit")
input()
return
# configuration is returned as
# (export_path, config_name, config_bin_folder, include_symbols)
configuration = release_project_gui.configure_build(
export_path, configurations)
if not configuration:
# No configuration selected. Most likely because the user closed
# the window, so close this as well.
return
export_path = os.path.normpath(configuration[0])
export_path_long = LONG_PATH_PREFIX + export_path
config_type = configuration[1]
bin_path = os.path.normpath(configuration[2])
include_symbols = configuration[3]
bit_type = CONFIGURATION_BUILD_TARGET_LOOKUP[config_type]
print("Packaging project {}".format(project.name()))
print("Configuration: {}".format(config_type))
print("Debug symbols are {}".format(
"included" if include_symbols else "excluded"))
print("Building to: {}".format(export_path))
task_list = []
if os.path.exists(export_path_long):
task_list.append(("Deleting previous build...",
delete_previous_build, export_path_long))
task_list.append(("Packaging custom engine assets...",
package_engine_assets, engine_path, export_path))
task_list.append(("Copying default engine assets...",
copy_engine_assets, engine_path_long, export_path_long))
task_list.append(("Copying engine binaries...", copy_engine_binaries,
engine_path_long, export_path_long, bin_path,
include_symbols))
if requires_mono(project, project_path_long):
task_list.append((
"Copying mono files...", copy_mono_files, engine_path_long,
export_path_long))
task_list.append((
"Copying game binaries...", copy_project_plugins, project,
project_path, export_path, bin_path, config_type, include_symbols))
task_list.append((
"Copying shared libraries...", copy_libs,
project, project_path, export_path, bin_path, bit_type, include_symbols))
task_list.append((
"Copying existing game asset packages...",
copy_assets, project, project_path_long, export_path_long))
task_list.append((
"Packaging game assets...", package_assets,
project, engine_path, project_path, export_path))
task_list.append((
"Cleaning up temp folders...",
delete_temp_folders, engine_path_long, project_path_long))
task_list.append((
"Creating config files...", create_config, project_file, export_path,
bin_path, config_type))
i = 0
count = len(task_list)
for task in task_list:
description = task[0]
print(description)
set_title("{}% {}".format(int(get_percentage(i, count)), description))
task[1](*task[2:])
i += 1
set_title("100% Build packaged successfully")
print("Build packaged successfully")
print("Press Enter to exit")
input() | [
"def",
"run",
"(",
"project_file",
")",
":",
"# Path to the project file as created by the launcher",
"# Engine and project path are derivable from this.",
"project",
"=",
"cryproject",
".",
"CryProject",
"(",
")",
"try",
":",
"project",
".",
"load",
"(",
"project_file",
... | https://github.com/CRYTEK/CRYENGINE/blob/232227c59a220cbbd311576f0fbeba7bb53b2a8c/Tools/CryVersionSelector/release_project.py#L67-L174 | ||
mindspore-ai/mindspore | fb8fd3338605bb34fa5cea054e535a8b1d753fab | mindspore/python/mindspore/ops/_op_impl/tbe/hsigmoid.py | python | _hsigmoid_tbe | () | return | HSigmoid TBE register | HSigmoid TBE register | [
"HSigmoid",
"TBE",
"register"
] | def _hsigmoid_tbe():
"""HSigmoid TBE register"""
return | [
"def",
"_hsigmoid_tbe",
"(",
")",
":",
"return"
] | https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/ops/_op_impl/tbe/hsigmoid.py#L43-L45 | |
y123456yz/reading-and-annotate-mongodb-3.6 | 93280293672ca7586dc24af18132aa61e4ed7fcf | mongo/buildscripts/hang_analyzer.py | python | WindowsProcessList.__find_ps | (self) | return os.path.join(os.environ["WINDIR"], "system32", "tasklist.exe") | Finds tasklist | Finds tasklist | [
"Finds",
"tasklist"
] | def __find_ps(self):
"""Finds tasklist """
return os.path.join(os.environ["WINDIR"], "system32", "tasklist.exe") | [
"def",
"__find_ps",
"(",
"self",
")",
":",
"return",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"environ",
"[",
"\"WINDIR\"",
"]",
",",
"\"system32\"",
",",
"\"tasklist.exe\"",
")"
] | https://github.com/y123456yz/reading-and-annotate-mongodb-3.6/blob/93280293672ca7586dc24af18132aa61e4ed7fcf/mongo/buildscripts/hang_analyzer.py#L168-L170 | |
facebook/openr | ed38bdfd6bf290084bfab4821b59f83e7b59315d | openr/py/openr/cli/utils/utils.py | python | build_global_prefix_db | (resp) | return global_prefix_db | build a map of all prefixes in the network. this is used
for checking for changes in topology
:param resp kv_store_types.Publication: the parsed publication
:return map(node, set([prefix])): the global prefix map,
prefixes mapped to the node | build a map of all prefixes in the network. this is used
for checking for changes in topology | [
"build",
"a",
"map",
"of",
"all",
"prefixes",
"in",
"the",
"network",
".",
"this",
"is",
"used",
"for",
"checking",
"for",
"changes",
"in",
"topology"
] | def build_global_prefix_db(resp):
"""build a map of all prefixes in the network. this is used
for checking for changes in topology
:param resp kv_store_types.Publication: the parsed publication
:return map(node, set([prefix])): the global prefix map,
prefixes mapped to the node
"""
# map: (node) -> set([prefix])
global_prefix_db = {}
prefix_maps = collate_prefix_keys(resp.keyVals)
for _, prefix_db in prefix_maps.items():
update_global_prefix_db(global_prefix_db, prefix_db)
return global_prefix_db | [
"def",
"build_global_prefix_db",
"(",
"resp",
")",
":",
"# map: (node) -> set([prefix])",
"global_prefix_db",
"=",
"{",
"}",
"prefix_maps",
"=",
"collate_prefix_keys",
"(",
"resp",
".",
"keyVals",
")",
"for",
"_",
",",
"prefix_db",
"in",
"prefix_maps",
".",
"items... | https://github.com/facebook/openr/blob/ed38bdfd6bf290084bfab4821b59f83e7b59315d/openr/py/openr/cli/utils/utils.py#L436-L453 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/tkinter/__init__.py | python | Canvas.addtag_above | (self, newtag, tagOrId) | Add tag NEWTAG to all items above TAGORID. | Add tag NEWTAG to all items above TAGORID. | [
"Add",
"tag",
"NEWTAG",
"to",
"all",
"items",
"above",
"TAGORID",
"."
] | def addtag_above(self, newtag, tagOrId):
"""Add tag NEWTAG to all items above TAGORID."""
self.addtag(newtag, 'above', tagOrId) | [
"def",
"addtag_above",
"(",
"self",
",",
"newtag",
",",
"tagOrId",
")",
":",
"self",
".",
"addtag",
"(",
"newtag",
",",
"'above'",
",",
"tagOrId",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/tkinter/__init__.py#L2409-L2411 | ||
turi-code/SFrame | 796b9bdfb2fa1b881d82080754643c7e68629cd2 | oss_src/unity/python/sframe/data_structures/gframe.py | python | GFrame.num_rows | (self) | Returns the number of rows.
Returns
-------
out : int
Number of rows in the SFrame. | Returns the number of rows. | [
"Returns",
"the",
"number",
"of",
"rows",
"."
] | def num_rows(self):
"""
Returns the number of rows.
Returns
-------
out : int
Number of rows in the SFrame.
"""
if self._is_vertex_frame():
return self.__graph__.summary()['num_vertices']
elif self._is_edge_frame():
return self.__graph__.summary()['num_edges'] | [
"def",
"num_rows",
"(",
"self",
")",
":",
"if",
"self",
".",
"_is_vertex_frame",
"(",
")",
":",
"return",
"self",
".",
"__graph__",
".",
"summary",
"(",
")",
"[",
"'num_vertices'",
"]",
"elif",
"self",
".",
"_is_edge_frame",
"(",
")",
":",
"return",
"s... | https://github.com/turi-code/SFrame/blob/796b9bdfb2fa1b881d82080754643c7e68629cd2/oss_src/unity/python/sframe/data_structures/gframe.py#L222-L234 | ||
microsoft/checkedc-clang | a173fefde5d7877b7750e7ce96dd08cf18baebf2 | llvm/utils/git/pre-push.py | python | handle_push | (args, local_ref, local_sha, remote_ref, remote_sha) | return | Check a single push request (which can include multiple revisions) | Check a single push request (which can include multiple revisions) | [
"Check",
"a",
"single",
"push",
"request",
"(",
"which",
"can",
"include",
"multiple",
"revisions",
")"
] | def handle_push(args, local_ref, local_sha, remote_ref, remote_sha):
'''Check a single push request (which can include multiple revisions)'''
log_verbose('Handle push, reproduce with '
'`echo %s %s %s %s | pre-push.py %s %s'
% (local_ref, local_sha, remote_ref, remote_sha, args.remote,
args.url))
# Handle request to delete
if local_sha == z40:
if not ask_confirm('Are you sure you want to delete "%s" on remote "%s"?' % (remote_ref, args.url)):
die("Aborting")
return
# Push a new branch
if remote_sha == z40:
if not ask_confirm('Are you sure you want to push a new branch/tag "%s" on remote "%s"?' % (remote_ref, args.url)):
die("Aborting")
range=local_sha
return
else:
# Update to existing branch, examine new commits
range='%s..%s' % (remote_sha, local_sha)
# Check that the remote commit exists, otherwise let git proceed
if "commit" not in git('cat-file','-t', remote_sha, ignore_errors=True):
return
revs = get_revs_to_push(range)
if not revs:
# This can happen if someone is force pushing an older revision to a branch
return
# Print the revision about to be pushed commits
print('Pushing to "%s" on remote "%s"' % (remote_ref, args.url))
for sha in revs:
print(' - ' + git('show', '--oneline', '--quiet', sha))
if len(revs) > 1:
if not ask_confirm('Are you sure you want to push %d commits?' % len(revs)):
die('Aborting')
for sha in revs:
msg = git('log', '--format=%B', '-n1', sha)
if 'Differential Revision' not in msg:
continue
for line in msg.splitlines():
for tag in ['Summary', 'Reviewers', 'Subscribers', 'Tags']:
if line.startswith(tag + ':'):
eprint('Please remove arcanist tags from the commit message (found "%s" tag in %s)' % (tag, sha[:12]))
if len(revs) == 1:
eprint('Try running: llvm/utils/git/arcfilter.sh')
die('Aborting (force push by adding "--no-verify")')
return | [
"def",
"handle_push",
"(",
"args",
",",
"local_ref",
",",
"local_sha",
",",
"remote_ref",
",",
"remote_sha",
")",
":",
"log_verbose",
"(",
"'Handle push, reproduce with '",
"'`echo %s %s %s %s | pre-push.py %s %s'",
"%",
"(",
"local_ref",
",",
"local_sha",
",",
"remot... | https://github.com/microsoft/checkedc-clang/blob/a173fefde5d7877b7750e7ce96dd08cf18baebf2/llvm/utils/git/pre-push.py#L141-L193 | |
arangodb/arangodb | 0d658689c7d1b721b314fa3ca27d38303e1570c8 | 3rdParty/V8/gyp/xcode_emulation.py | python | XcodeArchsDefault._VariableMapping | (self, sdkroot) | Returns the dictionary of variable mapping depending on the SDKROOT. | Returns the dictionary of variable mapping depending on the SDKROOT. | [
"Returns",
"the",
"dictionary",
"of",
"variable",
"mapping",
"depending",
"on",
"the",
"SDKROOT",
"."
] | def _VariableMapping(self, sdkroot):
"""Returns the dictionary of variable mapping depending on the SDKROOT."""
sdkroot = sdkroot.lower()
if 'iphoneos' in sdkroot:
return self._archs['ios']
elif 'iphonesimulator' in sdkroot:
return self._archs['iossim']
else:
return self._archs['mac'] | [
"def",
"_VariableMapping",
"(",
"self",
",",
"sdkroot",
")",
":",
"sdkroot",
"=",
"sdkroot",
".",
"lower",
"(",
")",
"if",
"'iphoneos'",
"in",
"sdkroot",
":",
"return",
"self",
".",
"_archs",
"[",
"'ios'",
"]",
"elif",
"'iphonesimulator'",
"in",
"sdkroot",... | https://github.com/arangodb/arangodb/blob/0d658689c7d1b721b314fa3ca27d38303e1570c8/3rdParty/V8/gyp/xcode_emulation.py#L57-L65 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python3/src/Lib/ssl.py | python | SSLSocket.write | (self, data) | return self._sslobj.write(data) | Write DATA to the underlying SSL channel. Returns
number of bytes of DATA actually transmitted. | Write DATA to the underlying SSL channel. Returns
number of bytes of DATA actually transmitted. | [
"Write",
"DATA",
"to",
"the",
"underlying",
"SSL",
"channel",
".",
"Returns",
"number",
"of",
"bytes",
"of",
"DATA",
"actually",
"transmitted",
"."
] | def write(self, data):
"""Write DATA to the underlying SSL channel. Returns
number of bytes of DATA actually transmitted."""
self._checkClosed()
if self._sslobj is None:
raise ValueError("Write on closed or unwrapped SSL socket.")
return self._sslobj.write(data) | [
"def",
"write",
"(",
"self",
",",
"data",
")",
":",
"self",
".",
"_checkClosed",
"(",
")",
"if",
"self",
".",
"_sslobj",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"Write on closed or unwrapped SSL socket.\"",
")",
"return",
"self",
".",
"_sslobj",
"."... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/ssl.py#L1129-L1136 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | tools/android/appstats.py | python | DeviceSnapshot.GetUserIdForPid | (self, search_pid) | return None | Returns the application userId for an associated |pid|. This only works
if |search_pid| is tracked by this snapshot and the application userId is
queryable. | Returns the application userId for an associated |pid|. This only works
if |search_pid| is tracked by this snapshot and the application userId is
queryable. | [
"Returns",
"the",
"application",
"userId",
"for",
"an",
"associated",
"|pid|",
".",
"This",
"only",
"works",
"if",
"|search_pid|",
"is",
"tracked",
"by",
"this",
"snapshot",
"and",
"the",
"application",
"userId",
"is",
"queryable",
"."
] | def GetUserIdForPid(self, search_pid):
"""Returns the application userId for an associated |pid|. This only works
if |search_pid| is tracked by this snapshot and the application userId is
queryable."""
for (userid, pid, name) in self.pids:
if pid == search_pid:
return userid
return None | [
"def",
"GetUserIdForPid",
"(",
"self",
",",
"search_pid",
")",
":",
"for",
"(",
"userid",
",",
"pid",
",",
"name",
")",
"in",
"self",
".",
"pids",
":",
"if",
"pid",
"==",
"search_pid",
":",
"return",
"userid",
"return",
"None"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/tools/android/appstats.py#L383-L390 | |
namecoin/namecoin-legacy | b043fba28018721b68c90edfc81b9eacb070b47d | client/socks.py | python | socksocket.__negotiatehttp | (self,destaddr,destport) | __negotiatehttp(self,destaddr,destport)
Negotiates a connection through an HTTP server. | __negotiatehttp(self,destaddr,destport)
Negotiates a connection through an HTTP server. | [
"__negotiatehttp",
"(",
"self",
"destaddr",
"destport",
")",
"Negotiates",
"a",
"connection",
"through",
"an",
"HTTP",
"server",
"."
] | def __negotiatehttp(self,destaddr,destport):
"""__negotiatehttp(self,destaddr,destport)
Negotiates a connection through an HTTP server.
"""
# If we need to resolve locally, we do this now
if self.__proxy[3] == False:
addr = socket.gethostbyname(destaddr)
else:
addr = destaddr
self.sendall("CONNECT " + addr + ":" + str(destport) + " HTTP/1.1\r\n" + "Host: " + destaddr + "\r\n\r\n")
# We read the response until we get the string "\r\n\r\n"
resp = self.recv(1)
while resp.find("\r\n\r\n")==-1:
resp = resp + self.recv(1)
# We just need the first line to check if the connection
# was successful
statusline = resp.splitlines()[0].split(" ",2)
if statusline[0] not in ("HTTP/1.0","HTTP/1.1"):
self.close()
raise GeneralProxyError((1,_generalerrors[1]))
try:
statuscode = int(statusline[1])
except ValueError:
self.close()
raise GeneralProxyError((1,_generalerrors[1]))
if statuscode != 200:
self.close()
raise HTTPError((statuscode,statusline[2]))
self.__proxysockname = ("0.0.0.0",0)
self.__proxypeername = (addr,destport) | [
"def",
"__negotiatehttp",
"(",
"self",
",",
"destaddr",
",",
"destport",
")",
":",
"# If we need to resolve locally, we do this now",
"if",
"self",
".",
"__proxy",
"[",
"3",
"]",
"==",
"False",
":",
"addr",
"=",
"socket",
".",
"gethostbyname",
"(",
"destaddr",
... | https://github.com/namecoin/namecoin-legacy/blob/b043fba28018721b68c90edfc81b9eacb070b47d/client/socks.py#L322-L351 | ||
mindspore-ai/mindspore | fb8fd3338605bb34fa5cea054e535a8b1d753fab | mindspore/python/mindspore/scipy/optimize/line_search.py | python | line_search | (f, xk, pk, gfk=None, old_fval=None, old_old_fval=None, c1=1e-4,
c2=0.9, maxiter=20) | return state | Inexact line search that satisfies strong Wolfe conditions.
Algorithm 3.5 from Wright and Nocedal, 'Numerical Optimization', 1999, pg. 59-61
Args:
f (function): function of the form f(x) where x is a flat Tensor and returns a real
scalar. The function should be composed of operations with vjp defined.
xk (Tensor): initial guess.
pk (Tensor): direction to search in. Assumes the direction is a descent direction.
gfk (Tensor): initial value of value_and_gradient as position. Default: None.
old_fval (Tensor): The same as `gfk`. Default: None.
old_old_fval (Tensor): unused argument, only for scipy API compliance. Default: None.
c1 (float): Wolfe criteria constant, see ref. Default: 1e-4.
c2 (float): The same as `c1`. Default: 0.9.
maxiter (int): maximum number of iterations to search. Default: 20.
Returns:
LineSearchResults, results of line search results.
Supported Platforms:
``CPU`` ``GPU``
Examples:
>>> import numpy as onp
>>> from mindspore.scipy.optimize import line_search
>>> from mindspore.common import Tensor
>>> x0 = Tensor(onp.ones(2).astype(onp.float32))
>>> p0 = Tensor(onp.array([-1, -1]).astype(onp.float32))
>>> def func(x):
>>> return x[0] ** 2 - x[1] ** 3
>>> res = line_search(func, x0, p0)
>>> res.a_k
1.0 | Inexact line search that satisfies strong Wolfe conditions. | [
"Inexact",
"line",
"search",
"that",
"satisfies",
"strong",
"Wolfe",
"conditions",
"."
] | def line_search(f, xk, pk, gfk=None, old_fval=None, old_old_fval=None, c1=1e-4,
c2=0.9, maxiter=20):
"""Inexact line search that satisfies strong Wolfe conditions.
Algorithm 3.5 from Wright and Nocedal, 'Numerical Optimization', 1999, pg. 59-61
Args:
f (function): function of the form f(x) where x is a flat Tensor and returns a real
scalar. The function should be composed of operations with vjp defined.
xk (Tensor): initial guess.
pk (Tensor): direction to search in. Assumes the direction is a descent direction.
gfk (Tensor): initial value of value_and_gradient as position. Default: None.
old_fval (Tensor): The same as `gfk`. Default: None.
old_old_fval (Tensor): unused argument, only for scipy API compliance. Default: None.
c1 (float): Wolfe criteria constant, see ref. Default: 1e-4.
c2 (float): The same as `c1`. Default: 0.9.
maxiter (int): maximum number of iterations to search. Default: 20.
Returns:
LineSearchResults, results of line search results.
Supported Platforms:
``CPU`` ``GPU``
Examples:
>>> import numpy as onp
>>> from mindspore.scipy.optimize import line_search
>>> from mindspore.common import Tensor
>>> x0 = Tensor(onp.ones(2).astype(onp.float32))
>>> p0 = Tensor(onp.array([-1, -1]).astype(onp.float32))
>>> def func(x):
>>> return x[0] ** 2 - x[1] ** 3
>>> res = line_search(func, x0, p0)
>>> res.a_k
1.0
"""
state = LineSearch(f)(xk, pk, old_fval, old_old_fval, gfk, c1, c2, maxiter)
# If running in graph mode, the state is a tuple.
if isinstance(state, tuple):
state = _LineSearchResults(failed=_to_scalar(state[1] or not state[0]),
nit=_to_scalar(state[2] - 1),
nfev=_to_scalar(state[6]),
ngev=_to_scalar(state[7]),
k=_to_scalar(state[2]),
a_k=_to_scalar(state[8]),
f_k=_to_scalar(state[9]),
g_k=state[11],
status=_to_scalar(state[12]))
else:
state = _LineSearchResults(failed=_to_scalar(state["failed"] or not state["done"]),
nit=_to_scalar(state["i"] - 1),
nfev=_to_scalar(state["nfev"]),
ngev=_to_scalar(state["ngev"]),
k=_to_scalar(state["i"]),
a_k=_to_scalar(state["a_star"]),
f_k=_to_scalar(state["phi_star"]),
g_k=state["g_star"],
status=_to_scalar(state["status"]))
return state | [
"def",
"line_search",
"(",
"f",
",",
"xk",
",",
"pk",
",",
"gfk",
"=",
"None",
",",
"old_fval",
"=",
"None",
",",
"old_old_fval",
"=",
"None",
",",
"c1",
"=",
"1e-4",
",",
"c2",
"=",
"0.9",
",",
"maxiter",
"=",
"20",
")",
":",
"state",
"=",
"Li... | https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/scipy/optimize/line_search.py#L305-L364 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/richtext.py | python | RichTextCtrl.GetTargetRect | (*args, **kwargs) | return _richtext.RichTextCtrl_GetTargetRect(*args, **kwargs) | GetTargetRect(self) -> Rect | GetTargetRect(self) -> Rect | [
"GetTargetRect",
"(",
"self",
")",
"-",
">",
"Rect"
] | def GetTargetRect(*args, **kwargs):
"""GetTargetRect(self) -> Rect"""
return _richtext.RichTextCtrl_GetTargetRect(*args, **kwargs) | [
"def",
"GetTargetRect",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_richtext",
".",
"RichTextCtrl_GetTargetRect",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/richtext.py#L4198-L4200 | |
tenzir/vast | ff450d61f35c721db1760339869085a89222386f | scripts/splunk-search.py | python | outputResults | (results, fields = None, mvdelim = '\n',
outputfile = sys.stdout) | Outputs the contents of a result set to STDOUT in Interplunk format. | Outputs the contents of a result set to STDOUT in Interplunk format. | [
"Outputs",
"the",
"contents",
"of",
"a",
"result",
"set",
"to",
"STDOUT",
"in",
"Interplunk",
"format",
"."
] | def outputResults(results, fields = None, mvdelim = '\n',
outputfile = sys.stdout):
'''
Outputs the contents of a result set to STDOUT in Interplunk format.
'''
if results == None:
return
s = set()
'''
Check each entry to see if it is a list (multivalued). If so, set
the multivalued key to the proper encoding. Replace the list with a
newline separated string of the values
'''
for i in range(1,len(results)+1):
for key in results[str(i)].keys():
if(isinstance(results[str(i)][key], list)):
results[str(i)]['__mv_' + key] = \
getEncodedMV(results[str(i)][key])
results[str(i)][key] = \
string.join(results[str(i)][key], mvdelim)
if not fields.count('__mv_' + key):
fields.append('__mv_' + key)
s.update(results[str(i)].keys())
if fields is None:
h = list(s)
else:
h = fields
dw = csv.DictWriter(outputfile, h)
dw.writerow(dict(zip(h, h)))
for i in range(1,len(results)+1):
dw.writerow(results[str(i)]) | [
"def",
"outputResults",
"(",
"results",
",",
"fields",
"=",
"None",
",",
"mvdelim",
"=",
"'\\n'",
",",
"outputfile",
"=",
"sys",
".",
"stdout",
")",
":",
"if",
"results",
"==",
"None",
":",
"return",
"s",
"=",
"set",
"(",
")",
"'''\n Check each entry ... | https://github.com/tenzir/vast/blob/ff450d61f35c721db1760339869085a89222386f/scripts/splunk-search.py#L96-L132 | ||
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | scripts/SANS/sans/command_interface/ISISCommandInterface.py | python | TransmissionSample | (sample, direct, reload=True,
period_t=ALL_PERIODS, period_d=ALL_PERIODS) | Specify the transmission and direct runs for the sample.
@param sample: the transmission run
@param direct: direct run
@param reload: if to replace the workspace if it is already there
@param period_t: the entry number of the transmission run (default single entry file)
@param period_d: the entry number of the direct run (default single entry file) | Specify the transmission and direct runs for the sample. | [
"Specify",
"the",
"transmission",
"and",
"direct",
"runs",
"for",
"the",
"sample",
"."
] | def TransmissionSample(sample, direct, reload=True,
period_t=ALL_PERIODS, period_d=ALL_PERIODS):
"""
Specify the transmission and direct runs for the sample.
@param sample: the transmission run
@param direct: direct run
@param reload: if to replace the workspace if it is already there
@param period_t: the entry number of the transmission run (default single entry file)
@param period_d: the entry number of the direct run (default single entry file)
"""
_ = reload # noqa
# First of all the default for all periods used to be -1. If we encounter this then set periods to ALL_PERIODS
period_t = int(period_t)
period_d = int(period_d)
period_t = ALL_PERIODS if period_t == -1 else period_t
period_d = ALL_PERIODS if period_d == -1 else period_d
print_message('TransmissionSample("' + str(sample) + '","' + str(direct) + '")')
# Get the full file name of the run
trans_file_name = find_sans_file(sample)
direct_file_name = find_sans_file(direct)
# Set the command
trans_command = DataCommand(command_id=DataCommandId.SAMPLE_TRANSMISSION, file_name=trans_file_name,
period=period_t)
direct_command = DataCommand(command_id=DataCommandId.SAMPLE_DIRECT, file_name=direct_file_name, period=period_d)
director.add_command(trans_command)
director.add_command(direct_command) | [
"def",
"TransmissionSample",
"(",
"sample",
",",
"direct",
",",
"reload",
"=",
"True",
",",
"period_t",
"=",
"ALL_PERIODS",
",",
"period_d",
"=",
"ALL_PERIODS",
")",
":",
"_",
"=",
"reload",
"# noqa",
"# First of all the default for all periods used to be -1. If we en... | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/scripts/SANS/sans/command_interface/ISISCommandInterface.py#L206-L235 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/_controls.py | python | DragImage.DoDrawImage | (*args, **kwargs) | return _controls_.DragImage_DoDrawImage(*args, **kwargs) | DoDrawImage(self, DC dc, Point pos) -> bool | DoDrawImage(self, DC dc, Point pos) -> bool | [
"DoDrawImage",
"(",
"self",
"DC",
"dc",
"Point",
"pos",
")",
"-",
">",
"bool"
] | def DoDrawImage(*args, **kwargs):
"""DoDrawImage(self, DC dc, Point pos) -> bool"""
return _controls_.DragImage_DoDrawImage(*args, **kwargs) | [
"def",
"DoDrawImage",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_controls_",
".",
"DragImage_DoDrawImage",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_controls.py#L6384-L6386 | |
utsaslab/RECIPE | e13136ce5644de35f5c09d6da82f4fe7d792ab9c | index-microbench/read_email_key.py | python | read_new_file | () | return ret | This function reads the 27MB file into a list and return | This function reads the 27MB file into a list and return | [
"This",
"function",
"reads",
"the",
"27MB",
"file",
"into",
"a",
"list",
"and",
"return"
] | def read_new_file():
"""
This function reads the 27MB file into a list and return
"""
filename = sys.argv[3]
if os.path.isfile(filename) is False:
raise TypeError("Illegal 27M file: %s" % (filename, ))
fp = open(filename, "r")
ret = []
for line in fp:
ret.append(line.strip())
fp.close()
return ret | [
"def",
"read_new_file",
"(",
")",
":",
"filename",
"=",
"sys",
".",
"argv",
"[",
"3",
"]",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"filename",
")",
"is",
"False",
":",
"raise",
"TypeError",
"(",
"\"Illegal 27M file: %s\"",
"%",
"(",
"filename",
",... | https://github.com/utsaslab/RECIPE/blob/e13136ce5644de35f5c09d6da82f4fe7d792ab9c/index-microbench/read_email_key.py#L40-L54 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/telemetry/third_party/web-page-replay/third_party/dns/rcode.py | python | to_text | (value) | return text | Convert rcode into text.
@param value: the rcode
@type value: int
@rtype: string | Convert rcode into text. | [
"Convert",
"rcode",
"into",
"text",
"."
] | def to_text(value):
"""Convert rcode into text.
@param value: the rcode
@type value: int
@rtype: string
"""
text = _by_value.get(value)
if text is None:
text = str(value)
return text | [
"def",
"to_text",
"(",
"value",
")",
":",
"text",
"=",
"_by_value",
".",
"get",
"(",
"value",
")",
"if",
"text",
"is",
"None",
":",
"text",
"=",
"str",
"(",
"value",
")",
"return",
"text"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/telemetry/third_party/web-page-replay/third_party/dns/rcode.py#L108-L119 | |
naver/sling | 5671cd445a2caae0b4dd0332299e4cfede05062c | webkit/Tools/Scripts/webkitpy/thirdparty/mod_pywebsocket/mux.py | python | _LogicalConnection.set_read_state | (self, new_state) | Sets the state of this connection. Called when an event for this
connection has occurred.
Args:
new_state: state to be set. new_state must be one of followings:
- STATE_GRACEFULLY_CLOSED: when closing handshake for this
connection has been received.
- STATE_TERMINATED: when the physical connection has closed or
DropChannel of this connection has received. | Sets the state of this connection. Called when an event for this
connection has occurred. | [
"Sets",
"the",
"state",
"of",
"this",
"connection",
".",
"Called",
"when",
"an",
"event",
"for",
"this",
"connection",
"has",
"occurred",
"."
] | def set_read_state(self, new_state):
"""Sets the state of this connection. Called when an event for this
connection has occurred.
Args:
new_state: state to be set. new_state must be one of followings:
- STATE_GRACEFULLY_CLOSED: when closing handshake for this
connection has been received.
- STATE_TERMINATED: when the physical connection has closed or
DropChannel of this connection has received.
"""
self._read_condition.acquire()
self._read_state = new_state
self._read_condition.notify()
self._read_condition.release() | [
"def",
"set_read_state",
"(",
"self",
",",
"new_state",
")",
":",
"self",
".",
"_read_condition",
".",
"acquire",
"(",
")",
"self",
".",
"_read_state",
"=",
"new_state",
"self",
".",
"_read_condition",
".",
"notify",
"(",
")",
"self",
".",
"_read_condition",... | https://github.com/naver/sling/blob/5671cd445a2caae0b4dd0332299e4cfede05062c/webkit/Tools/Scripts/webkitpy/thirdparty/mod_pywebsocket/mux.py#L682-L697 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/_misc.py | python | Joystick.GetMaxAxes | (*args, **kwargs) | return _misc_.Joystick_GetMaxAxes(*args, **kwargs) | GetMaxAxes(self) -> int | GetMaxAxes(self) -> int | [
"GetMaxAxes",
"(",
"self",
")",
"-",
">",
"int"
] | def GetMaxAxes(*args, **kwargs):
"""GetMaxAxes(self) -> int"""
return _misc_.Joystick_GetMaxAxes(*args, **kwargs) | [
"def",
"GetMaxAxes",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_misc_",
".",
"Joystick_GetMaxAxes",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_misc.py#L2222-L2224 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/_misc.py | python | AboutDialogInfo.SetVersion | (*args, **kwargs) | return _misc_.AboutDialogInfo_SetVersion(*args, **kwargs) | SetVersion(self, String version, String longVersion=wxEmptyString)
Set the version of the program. The version is in free format,
i.e. not necessarily in the x.y.z form but it shouldn't contain the
"version" word. | SetVersion(self, String version, String longVersion=wxEmptyString) | [
"SetVersion",
"(",
"self",
"String",
"version",
"String",
"longVersion",
"=",
"wxEmptyString",
")"
] | def SetVersion(*args, **kwargs):
"""
SetVersion(self, String version, String longVersion=wxEmptyString)
Set the version of the program. The version is in free format,
i.e. not necessarily in the x.y.z form but it shouldn't contain the
"version" word.
"""
return _misc_.AboutDialogInfo_SetVersion(*args, **kwargs) | [
"def",
"SetVersion",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_misc_",
".",
"AboutDialogInfo_SetVersion",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_misc.py#L6605-L6613 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/ipython/py3/IPython/lib/guisupport.py | python | is_event_loop_running_qt4 | (app=None) | Is the qt4 event loop running. | Is the qt4 event loop running. | [
"Is",
"the",
"qt4",
"event",
"loop",
"running",
"."
] | def is_event_loop_running_qt4(app=None):
"""Is the qt4 event loop running."""
# New way: check attribute on shell instance
ip = get_ipython()
if ip is not None:
return ip.active_eventloop and ip.active_eventloop.startswith('qt')
# Old way: check attribute on QApplication singleton
if app is None:
app = get_app_qt4([''])
if hasattr(app, '_in_event_loop'):
return app._in_event_loop
else:
# Does qt4 provide a other way to detect this?
return False | [
"def",
"is_event_loop_running_qt4",
"(",
"app",
"=",
"None",
")",
":",
"# New way: check attribute on shell instance",
"ip",
"=",
"get_ipython",
"(",
")",
"if",
"ip",
"is",
"not",
"None",
":",
"return",
"ip",
".",
"active_eventloop",
"and",
"ip",
".",
"active_ev... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/ipython/py3/IPython/lib/guisupport.py#L122-L136 | ||
oracle/graaljs | 36a56e8e993d45fc40939a3a4d9c0c24990720f1 | graal-nodejs/tools/inspector_protocol/jinja2/bccache.py | python | Bucket.load_bytecode | (self, f) | Loads bytecode from a file or file like object. | Loads bytecode from a file or file like object. | [
"Loads",
"bytecode",
"from",
"a",
"file",
"or",
"file",
"like",
"object",
"."
] | def load_bytecode(self, f):
"""Loads bytecode from a file or file like object."""
# make sure the magic header is correct
magic = f.read(len(bc_magic))
if magic != bc_magic:
self.reset()
return
# the source code of the file changed, we need to reload
checksum = pickle.load(f)
if self.checksum != checksum:
self.reset()
return
# if marshal_load fails then we need to reload
try:
self.code = marshal_load(f)
except (EOFError, ValueError, TypeError):
self.reset()
return | [
"def",
"load_bytecode",
"(",
"self",
",",
"f",
")",
":",
"# make sure the magic header is correct",
"magic",
"=",
"f",
".",
"read",
"(",
"len",
"(",
"bc_magic",
")",
")",
"if",
"magic",
"!=",
"bc_magic",
":",
"self",
".",
"reset",
"(",
")",
"return",
"# ... | https://github.com/oracle/graaljs/blob/36a56e8e993d45fc40939a3a4d9c0c24990720f1/graal-nodejs/tools/inspector_protocol/jinja2/bccache.py#L79-L96 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/datamodel/models.py | python | DataModel.traverse | (self, builder) | return [] | Traverse contained members.
Returns a iterable of contained (types, getters).
Each getter is a one-argument function accepting a LLVM value. | Traverse contained members.
Returns a iterable of contained (types, getters).
Each getter is a one-argument function accepting a LLVM value. | [
"Traverse",
"contained",
"members",
".",
"Returns",
"a",
"iterable",
"of",
"contained",
"(",
"types",
"getters",
")",
".",
"Each",
"getter",
"is",
"a",
"one",
"-",
"argument",
"function",
"accepting",
"a",
"LLVM",
"value",
"."
] | def traverse(self, builder):
"""
Traverse contained members.
Returns a iterable of contained (types, getters).
Each getter is a one-argument function accepting a LLVM value.
"""
return [] | [
"def",
"traverse",
"(",
"self",
",",
"builder",
")",
":",
"return",
"[",
"]"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/datamodel/models.py#L89-L95 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/stc.py | python | StyledTextCtrl.GetMainSelection | (*args, **kwargs) | return _stc.StyledTextCtrl_GetMainSelection(*args, **kwargs) | GetMainSelection(self) -> int
Which selection is the main selection | GetMainSelection(self) -> int | [
"GetMainSelection",
"(",
"self",
")",
"-",
">",
"int"
] | def GetMainSelection(*args, **kwargs):
"""
GetMainSelection(self) -> int
Which selection is the main selection
"""
return _stc.StyledTextCtrl_GetMainSelection(*args, **kwargs) | [
"def",
"GetMainSelection",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_stc",
".",
"StyledTextCtrl_GetMainSelection",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/stc.py#L6136-L6142 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python/src/Lib/ftplib.py | python | Netrc.get_macros | (self) | return self.__macros.keys() | Return a list of all defined macro names. | Return a list of all defined macro names. | [
"Return",
"a",
"list",
"of",
"all",
"defined",
"macro",
"names",
"."
] | def get_macros(self):
"""Return a list of all defined macro names."""
return self.__macros.keys() | [
"def",
"get_macros",
"(",
"self",
")",
":",
"return",
"self",
".",
"__macros",
".",
"keys",
"(",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/ftplib.py#L1024-L1026 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numpy/lib/nanfunctions.py | python | nanvar | (a, axis=None, dtype=None, out=None, ddof=0, keepdims=np._NoValue) | return var | Compute the variance along the specified axis, while ignoring NaNs.
Returns the variance of the array elements, a measure of the spread of
a distribution. The variance is computed for the flattened array by
default, otherwise over the specified axis.
For all-NaN slices or slices with zero degrees of freedom, NaN is
returned and a `RuntimeWarning` is raised.
.. versionadded:: 1.8.0
Parameters
----------
a : array_like
Array containing numbers whose variance is desired. If `a` is not an
array, a conversion is attempted.
axis : {int, tuple of int, None}, optional
Axis or axes along which the variance is computed. The default is to compute
the variance of the flattened array.
dtype : data-type, optional
Type to use in computing the variance. For arrays of integer type
the default is `float64`; for arrays of float types it is the same as
the array type.
out : ndarray, optional
Alternate output array in which to place the result. It must have
the same shape as the expected output, but the type is cast if
necessary.
ddof : int, optional
"Delta Degrees of Freedom": the divisor used in the calculation is
``N - ddof``, where ``N`` represents the number of non-NaN
elements. By default `ddof` is zero.
keepdims : bool, optional
If this is set to True, the axes which are reduced are left
in the result as dimensions with size one. With this option,
the result will broadcast correctly against the original `a`.
Returns
-------
variance : ndarray, see dtype parameter above
If `out` is None, return a new array containing the variance,
otherwise return a reference to the output array. If ddof is >= the
number of non-NaN elements in a slice or the slice contains only
NaNs, then the result for that slice is NaN.
See Also
--------
std : Standard deviation
mean : Average
var : Variance while not ignoring NaNs
nanstd, nanmean
ufuncs-output-type
Notes
-----
The variance is the average of the squared deviations from the mean,
i.e., ``var = mean(abs(x - x.mean())**2)``.
The mean is normally calculated as ``x.sum() / N``, where ``N = len(x)``.
If, however, `ddof` is specified, the divisor ``N - ddof`` is used
instead. In standard statistical practice, ``ddof=1`` provides an
unbiased estimator of the variance of a hypothetical infinite
population. ``ddof=0`` provides a maximum likelihood estimate of the
variance for normally distributed variables.
Note that for complex numbers, the absolute value is taken before
squaring, so that the result is always real and nonnegative.
For floating-point input, the variance is computed using the same
precision the input has. Depending on the input data, this can cause
the results to be inaccurate, especially for `float32` (see example
below). Specifying a higher-accuracy accumulator using the ``dtype``
keyword can alleviate this issue.
For this function to work on sub-classes of ndarray, they must define
`sum` with the kwarg `keepdims`
Examples
--------
>>> a = np.array([[1, np.nan], [3, 4]])
>>> np.nanvar(a)
1.5555555555555554
>>> np.nanvar(a, axis=0)
array([1., 0.])
>>> np.nanvar(a, axis=1)
array([0., 0.25]) # may vary | Compute the variance along the specified axis, while ignoring NaNs. | [
"Compute",
"the",
"variance",
"along",
"the",
"specified",
"axis",
"while",
"ignoring",
"NaNs",
"."
] | def nanvar(a, axis=None, dtype=None, out=None, ddof=0, keepdims=np._NoValue):
"""
Compute the variance along the specified axis, while ignoring NaNs.
Returns the variance of the array elements, a measure of the spread of
a distribution. The variance is computed for the flattened array by
default, otherwise over the specified axis.
For all-NaN slices or slices with zero degrees of freedom, NaN is
returned and a `RuntimeWarning` is raised.
.. versionadded:: 1.8.0
Parameters
----------
a : array_like
Array containing numbers whose variance is desired. If `a` is not an
array, a conversion is attempted.
axis : {int, tuple of int, None}, optional
Axis or axes along which the variance is computed. The default is to compute
the variance of the flattened array.
dtype : data-type, optional
Type to use in computing the variance. For arrays of integer type
the default is `float64`; for arrays of float types it is the same as
the array type.
out : ndarray, optional
Alternate output array in which to place the result. It must have
the same shape as the expected output, but the type is cast if
necessary.
ddof : int, optional
"Delta Degrees of Freedom": the divisor used in the calculation is
``N - ddof``, where ``N`` represents the number of non-NaN
elements. By default `ddof` is zero.
keepdims : bool, optional
If this is set to True, the axes which are reduced are left
in the result as dimensions with size one. With this option,
the result will broadcast correctly against the original `a`.
Returns
-------
variance : ndarray, see dtype parameter above
If `out` is None, return a new array containing the variance,
otherwise return a reference to the output array. If ddof is >= the
number of non-NaN elements in a slice or the slice contains only
NaNs, then the result for that slice is NaN.
See Also
--------
std : Standard deviation
mean : Average
var : Variance while not ignoring NaNs
nanstd, nanmean
ufuncs-output-type
Notes
-----
The variance is the average of the squared deviations from the mean,
i.e., ``var = mean(abs(x - x.mean())**2)``.
The mean is normally calculated as ``x.sum() / N``, where ``N = len(x)``.
If, however, `ddof` is specified, the divisor ``N - ddof`` is used
instead. In standard statistical practice, ``ddof=1`` provides an
unbiased estimator of the variance of a hypothetical infinite
population. ``ddof=0`` provides a maximum likelihood estimate of the
variance for normally distributed variables.
Note that for complex numbers, the absolute value is taken before
squaring, so that the result is always real and nonnegative.
For floating-point input, the variance is computed using the same
precision the input has. Depending on the input data, this can cause
the results to be inaccurate, especially for `float32` (see example
below). Specifying a higher-accuracy accumulator using the ``dtype``
keyword can alleviate this issue.
For this function to work on sub-classes of ndarray, they must define
`sum` with the kwarg `keepdims`
Examples
--------
>>> a = np.array([[1, np.nan], [3, 4]])
>>> np.nanvar(a)
1.5555555555555554
>>> np.nanvar(a, axis=0)
array([1., 0.])
>>> np.nanvar(a, axis=1)
array([0., 0.25]) # may vary
"""
arr, mask = _replace_nan(a, 0)
if mask is None:
return np.var(arr, axis=axis, dtype=dtype, out=out, ddof=ddof,
keepdims=keepdims)
if dtype is not None:
dtype = np.dtype(dtype)
if dtype is not None and not issubclass(dtype.type, np.inexact):
raise TypeError("If a is inexact, then dtype must be inexact")
if out is not None and not issubclass(out.dtype.type, np.inexact):
raise TypeError("If a is inexact, then out must be inexact")
# Compute mean
if type(arr) is np.matrix:
_keepdims = np._NoValue
else:
_keepdims = True
# we need to special case matrix for reverse compatibility
# in order for this to work, these sums need to be called with
# keepdims=True, however matrix now raises an error in this case, but
# the reason that it drops the keepdims kwarg is to force keepdims=True
# so this used to work by serendipity.
cnt = np.sum(~mask, axis=axis, dtype=np.intp, keepdims=_keepdims)
avg = np.sum(arr, axis=axis, dtype=dtype, keepdims=_keepdims)
avg = _divide_by_count(avg, cnt)
# Compute squared deviation from mean.
np.subtract(arr, avg, out=arr, casting='unsafe')
arr = _copyto(arr, 0, mask)
if issubclass(arr.dtype.type, np.complexfloating):
sqr = np.multiply(arr, arr.conj(), out=arr).real
else:
sqr = np.multiply(arr, arr, out=arr)
# Compute variance.
var = np.sum(sqr, axis=axis, dtype=dtype, out=out, keepdims=keepdims)
if var.ndim < cnt.ndim:
# Subclasses of ndarray may ignore keepdims, so check here.
cnt = cnt.squeeze(axis)
dof = cnt - ddof
var = _divide_by_count(var, dof)
isbad = (dof <= 0)
if np.any(isbad):
warnings.warn("Degrees of freedom <= 0 for slice.", RuntimeWarning,
stacklevel=3)
# NaN, inf, or negative numbers are all possible bad
# values, so explicitly replace them with NaN.
var = _copyto(var, np.nan, isbad)
return var | [
"def",
"nanvar",
"(",
"a",
",",
"axis",
"=",
"None",
",",
"dtype",
"=",
"None",
",",
"out",
"=",
"None",
",",
"ddof",
"=",
"0",
",",
"keepdims",
"=",
"np",
".",
"_NoValue",
")",
":",
"arr",
",",
"mask",
"=",
"_replace_nan",
"(",
"a",
",",
"0",
... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numpy/lib/nanfunctions.py#L1424-L1563 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/richtext.py | python | RichTextBuffer.GetFloatingLayoutMode | (*args, **kwargs) | return _richtext.RichTextBuffer_GetFloatingLayoutMode(*args, **kwargs) | GetFloatingLayoutMode() -> bool | GetFloatingLayoutMode() -> bool | [
"GetFloatingLayoutMode",
"()",
"-",
">",
"bool"
] | def GetFloatingLayoutMode(*args, **kwargs):
"""GetFloatingLayoutMode() -> bool"""
return _richtext.RichTextBuffer_GetFloatingLayoutMode(*args, **kwargs) | [
"def",
"GetFloatingLayoutMode",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_richtext",
".",
"RichTextBuffer_GetFloatingLayoutMode",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/richtext.py#L2643-L2645 | |
google/syzygy | 8164b24ebde9c5649c9a09e88a7fc0b0fcbd1bc5 | third_party/numpy/files/numpy/core/defchararray.py | python | decode | (a, encoding=None, errors=None) | return _to_string_or_unicode_array(
_vec_string(a, object_, 'decode', _clean_args(encoding, errors))) | Calls `str.decode` element-wise.
The set of available codecs comes from the Python standard library,
and may be extended at runtime. For more information, see the
:mod:`codecs` module.
Parameters
----------
a : array_like of str or unicode
encoding : str, optional
The name of an encoding
errors : str, optional
Specifies how to handle encoding errors
Returns
-------
out : ndarray
See also
--------
str.decode
Notes
-----
The type of the result will depend on the encoding specified.
Examples
--------
>>> c = np.array(['aAaAaA', ' aA ', 'abBABba'])
>>> c
array(['aAaAaA', ' aA ', 'abBABba'],
dtype='|S7')
>>> np.char.encode(c, encoding='cp037')
array(['\\x81\\xc1\\x81\\xc1\\x81\\xc1', '@@\\x81\\xc1@@',
'\\x81\\x82\\xc2\\xc1\\xc2\\x82\\x81'],
dtype='|S7') | Calls `str.decode` element-wise. | [
"Calls",
"str",
".",
"decode",
"element",
"-",
"wise",
"."
] | def decode(a, encoding=None, errors=None):
"""
Calls `str.decode` element-wise.
The set of available codecs comes from the Python standard library,
and may be extended at runtime. For more information, see the
:mod:`codecs` module.
Parameters
----------
a : array_like of str or unicode
encoding : str, optional
The name of an encoding
errors : str, optional
Specifies how to handle encoding errors
Returns
-------
out : ndarray
See also
--------
str.decode
Notes
-----
The type of the result will depend on the encoding specified.
Examples
--------
>>> c = np.array(['aAaAaA', ' aA ', 'abBABba'])
>>> c
array(['aAaAaA', ' aA ', 'abBABba'],
dtype='|S7')
>>> np.char.encode(c, encoding='cp037')
array(['\\x81\\xc1\\x81\\xc1\\x81\\xc1', '@@\\x81\\xc1@@',
'\\x81\\x82\\xc2\\xc1\\xc2\\x82\\x81'],
dtype='|S7')
"""
return _to_string_or_unicode_array(
_vec_string(a, object_, 'decode', _clean_args(encoding, errors))) | [
"def",
"decode",
"(",
"a",
",",
"encoding",
"=",
"None",
",",
"errors",
"=",
"None",
")",
":",
"return",
"_to_string_or_unicode_array",
"(",
"_vec_string",
"(",
"a",
",",
"object_",
",",
"'decode'",
",",
"_clean_args",
"(",
"encoding",
",",
"errors",
")",
... | https://github.com/google/syzygy/blob/8164b24ebde9c5649c9a09e88a7fc0b0fcbd1bc5/third_party/numpy/files/numpy/core/defchararray.py#L479-L522 | |
apache/singa | 93fd9da72694e68bfe3fb29d0183a65263d238a1 | python/singa/autograd.py | python | reduce_mean | (x, axes=None, keepdims=1) | return ReduceMean(axes, keepdims)(x)[0] | Init a ReduceMean, computes the mean of the input tensor's element along
the provided axes.
Args:
x (Tensor): input tensor.
axes (list of int): A list of integers, along which to reduce.
Accepted range is [-r, r-1] where r = rank(data). The default
is None, which reduces over all the dimensions of the input tensor.
keepdims (int): Keep the reduced dimension or not, default 1 mean
keep reduced dimension.
Returns:
the output Tensor. | Init a ReduceMean, computes the mean of the input tensor's element along
the provided axes.
Args:
x (Tensor): input tensor.
axes (list of int): A list of integers, along which to reduce.
Accepted range is [-r, r-1] where r = rank(data). The default
is None, which reduces over all the dimensions of the input tensor.
keepdims (int): Keep the reduced dimension or not, default 1 mean
keep reduced dimension.
Returns:
the output Tensor. | [
"Init",
"a",
"ReduceMean",
"computes",
"the",
"mean",
"of",
"the",
"input",
"tensor",
"s",
"element",
"along",
"the",
"provided",
"axes",
".",
"Args",
":",
"x",
"(",
"Tensor",
")",
":",
"input",
"tensor",
".",
"axes",
"(",
"list",
"of",
"int",
")",
"... | def reduce_mean(x, axes=None, keepdims=1):
"""
Init a ReduceMean, computes the mean of the input tensor's element along
the provided axes.
Args:
x (Tensor): input tensor.
axes (list of int): A list of integers, along which to reduce.
Accepted range is [-r, r-1] where r = rank(data). The default
is None, which reduces over all the dimensions of the input tensor.
keepdims (int): Keep the reduced dimension or not, default 1 mean
keep reduced dimension.
Returns:
the output Tensor.
"""
return ReduceMean(axes, keepdims)(x)[0] | [
"def",
"reduce_mean",
"(",
"x",
",",
"axes",
"=",
"None",
",",
"keepdims",
"=",
"1",
")",
":",
"return",
"ReduceMean",
"(",
"axes",
",",
"keepdims",
")",
"(",
"x",
")",
"[",
"0",
"]"
] | https://github.com/apache/singa/blob/93fd9da72694e68bfe3fb29d0183a65263d238a1/python/singa/autograd.py#L4142-L4156 | |
kevin-ssy/Optical-Flow-Guided-Feature | 07d4501a29002ee7821c38c1820e4a64c1acf6e8 | lib/caffe-action/scripts/cpp_lint.py | python | IsErrorSuppressedByNolint | (category, linenum) | return (linenum in _error_suppressions.get(category, set()) or
linenum in _error_suppressions.get(None, set())) | Returns true if the specified error category is suppressed on this line.
Consults the global error_suppressions map populated by
ParseNolintSuppressions/ResetNolintSuppressions.
Args:
category: str, the category of the error.
linenum: int, the current line number.
Returns:
bool, True iff the error should be suppressed due to a NOLINT comment. | Returns true if the specified error category is suppressed on this line. | [
"Returns",
"true",
"if",
"the",
"specified",
"error",
"category",
"is",
"suppressed",
"on",
"this",
"line",
"."
] | def IsErrorSuppressedByNolint(category, linenum):
"""Returns true if the specified error category is suppressed on this line.
Consults the global error_suppressions map populated by
ParseNolintSuppressions/ResetNolintSuppressions.
Args:
category: str, the category of the error.
linenum: int, the current line number.
Returns:
bool, True iff the error should be suppressed due to a NOLINT comment.
"""
return (linenum in _error_suppressions.get(category, set()) or
linenum in _error_suppressions.get(None, set())) | [
"def",
"IsErrorSuppressedByNolint",
"(",
"category",
",",
"linenum",
")",
":",
"return",
"(",
"linenum",
"in",
"_error_suppressions",
".",
"get",
"(",
"category",
",",
"set",
"(",
")",
")",
"or",
"linenum",
"in",
"_error_suppressions",
".",
"get",
"(",
"None... | https://github.com/kevin-ssy/Optical-Flow-Guided-Feature/blob/07d4501a29002ee7821c38c1820e4a64c1acf6e8/lib/caffe-action/scripts/cpp_lint.py#L500-L513 | |
lawy623/SVS | b7c7ae367c82a4797ff4a896a2ff304f02e7f724 | caffe/scripts/cpp_lint.py | python | _NestingState.CheckCompletedBlocks | (self, filename, error) | Checks that all classes and namespaces have been completely parsed.
Call this when all lines in a file have been processed.
Args:
filename: The name of the current file.
error: The function to call with any errors found. | Checks that all classes and namespaces have been completely parsed. | [
"Checks",
"that",
"all",
"classes",
"and",
"namespaces",
"have",
"been",
"completely",
"parsed",
"."
] | def CheckCompletedBlocks(self, filename, error):
"""Checks that all classes and namespaces have been completely parsed.
Call this when all lines in a file have been processed.
Args:
filename: The name of the current file.
error: The function to call with any errors found.
"""
# Note: This test can result in false positives if #ifdef constructs
# get in the way of brace matching. See the testBuildClass test in
# cpplint_unittest.py for an example of this.
for obj in self.stack:
if isinstance(obj, _ClassInfo):
error(filename, obj.starting_linenum, 'build/class', 5,
'Failed to find complete declaration of class %s' %
obj.name)
elif isinstance(obj, _NamespaceInfo):
error(filename, obj.starting_linenum, 'build/namespaces', 5,
'Failed to find complete declaration of namespace %s' %
obj.name) | [
"def",
"CheckCompletedBlocks",
"(",
"self",
",",
"filename",
",",
"error",
")",
":",
"# Note: This test can result in false positives if #ifdef constructs",
"# get in the way of brace matching. See the testBuildClass test in",
"# cpplint_unittest.py for an example of this.",
"for",
"obj"... | https://github.com/lawy623/SVS/blob/b7c7ae367c82a4797ff4a896a2ff304f02e7f724/caffe/scripts/cpp_lint.py#L2172-L2191 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scipy/scipy/interpolate/interpolate.py | python | NdPPoly.construct_fast | (cls, c, x, extrapolate=None) | return self | Construct the piecewise polynomial without making checks.
Takes the same parameters as the constructor. Input arguments
`c` and `x` must be arrays of the correct shape and type. The
`c` array can only be of dtypes float and complex, and `x`
array must have dtype float. | Construct the piecewise polynomial without making checks. | [
"Construct",
"the",
"piecewise",
"polynomial",
"without",
"making",
"checks",
"."
] | def construct_fast(cls, c, x, extrapolate=None):
"""
Construct the piecewise polynomial without making checks.
Takes the same parameters as the constructor. Input arguments
`c` and `x` must be arrays of the correct shape and type. The
`c` array can only be of dtypes float and complex, and `x`
array must have dtype float.
"""
self = object.__new__(cls)
self.c = c
self.x = x
if extrapolate is None:
extrapolate = True
self.extrapolate = extrapolate
return self | [
"def",
"construct_fast",
"(",
"cls",
",",
"c",
",",
"x",
",",
"extrapolate",
"=",
"None",
")",
":",
"self",
"=",
"object",
".",
"__new__",
"(",
"cls",
")",
"self",
".",
"c",
"=",
"c",
"self",
".",
"x",
"=",
"x",
"if",
"extrapolate",
"is",
"None",... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/scipy/interpolate/interpolate.py#L1848-L1864 | |
idaholab/moose | 9eeebc65e098b4c30f8205fb41591fd5b61eb6ff | python/moosetree/Node.py | python | Node.__iter__ | (self) | return iter(self.__children) | Iterate of the children (e.g., `for child in node:`) | Iterate of the children (e.g., `for child in node:`) | [
"Iterate",
"of",
"the",
"children",
"(",
"e",
".",
"g",
".",
"for",
"child",
"in",
"node",
":",
")"
] | def __iter__(self):
"""Iterate of the children (e.g., `for child in node:`)"""
return iter(self.__children) | [
"def",
"__iter__",
"(",
"self",
")",
":",
"return",
"iter",
"(",
"self",
".",
"__children",
")"
] | https://github.com/idaholab/moose/blob/9eeebc65e098b4c30f8205fb41591fd5b61eb6ff/python/moosetree/Node.py#L81-L83 | |
rapidsai/cudf | d5b2448fc69f17509304d594f029d0df56984962 | python/custreamz/custreamz/kafka.py | python | Consumer.get_watermark_offsets | (self, partition, timeout=10000, cached=False) | return offsets[b"low"], offsets[b"high"] | Retrieve the low and high watermark offsets from the Kafka consumer
Returns
-------
Tuple with a [low, high] value
Examples
--------
>>> from custream import kafka
>>> kafka_configs = {
... "metadata.broker.list": "localhost:9092",
... "enable.partition.eof": "true",
... "group.id": "groupid",
... "auto.offset.reset": "earliest",
... "enable.auto.commit": "false"
... }
>>> consumer = kafka.KafkaHandle(kafka_configs,
... topics=["kafka-topic"], partitions=[0]))
>>> low, high = consumer.get_watermark_offsets("kafka-topic", 0) | Retrieve the low and high watermark offsets from the Kafka consumer | [
"Retrieve",
"the",
"low",
"and",
"high",
"watermark",
"offsets",
"from",
"the",
"Kafka",
"consumer"
] | def get_watermark_offsets(self, partition, timeout=10000, cached=False):
"""
Retrieve the low and high watermark offsets from the Kafka consumer
Returns
-------
Tuple with a [low, high] value
Examples
--------
>>> from custream import kafka
>>> kafka_configs = {
... "metadata.broker.list": "localhost:9092",
... "enable.partition.eof": "true",
... "group.id": "groupid",
... "auto.offset.reset": "earliest",
... "enable.auto.commit": "false"
... }
>>> consumer = kafka.KafkaHandle(kafka_configs,
... topics=["kafka-topic"], partitions=[0]))
>>> low, high = consumer.get_watermark_offsets("kafka-topic", 0)
"""
offsets = ()
try:
offsets = self.kafka_meta_client.get_watermark_offset(
topic=partition.topic.encode(),
partition=partition.partition,
timeout=timeout,
cached=cached,
)
except RuntimeError:
raise RuntimeError("Unable to connect to Kafka broker")
if len(offsets) != 2:
raise RuntimeError(
f"Multiple watermark offsets encountered. "
f"Only 2 were expected and {len(offsets)} encountered"
)
if offsets[b"low"] < 0:
offsets[b"low"] = 0
if offsets[b"high"] < 0:
offsets[b"high"] = 0
return offsets[b"low"], offsets[b"high"] | [
"def",
"get_watermark_offsets",
"(",
"self",
",",
"partition",
",",
"timeout",
"=",
"10000",
",",
"cached",
"=",
"False",
")",
":",
"offsets",
"=",
"(",
")",
"try",
":",
"offsets",
"=",
"self",
".",
"kafka_meta_client",
".",
"get_watermark_offset",
"(",
"t... | https://github.com/rapidsai/cudf/blob/d5b2448fc69f17509304d594f029d0df56984962/python/custreamz/custreamz/kafka.py#L212-L259 | |
benoitsteiner/tensorflow-opencl | cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5 | tensorflow/python/ops/linalg/linear_operator_full_matrix.py | python | LinearOperatorFullMatrix.__init__ | (self,
matrix,
is_non_singular=None,
is_self_adjoint=None,
is_positive_definite=None,
is_square=None,
name="LinearOperatorFullMatrix") | r"""Initialize a `LinearOperatorFullMatrix`.
Args:
matrix: Shape `[B1,...,Bb, M, N]` with `b >= 0`, `M, N >= 0`.
Allowed dtypes: `float32`, `float64`, `complex64`, `complex128`.
is_non_singular: Expect that this operator is non-singular.
is_self_adjoint: Expect that this operator is equal to its hermitian
transpose.
is_positive_definite: Expect that this operator is positive definite,
meaning the quadratic form `x^H A x` has positive real part for all
nonzero `x`. Note that we do not require the operator to be
self-adjoint to be positive-definite. See:
https://en.wikipedia.org/wiki/Positive-definite_matrix\
#Extension_for_non_symmetric_matrices
is_square: Expect that this operator acts like square [batch] matrices.
name: A name for this `LinearOperator`.
Raises:
TypeError: If `diag.dtype` is not an allowed type. | r"""Initialize a `LinearOperatorFullMatrix`. | [
"r",
"Initialize",
"a",
"LinearOperatorFullMatrix",
"."
] | def __init__(self,
matrix,
is_non_singular=None,
is_self_adjoint=None,
is_positive_definite=None,
is_square=None,
name="LinearOperatorFullMatrix"):
r"""Initialize a `LinearOperatorFullMatrix`.
Args:
matrix: Shape `[B1,...,Bb, M, N]` with `b >= 0`, `M, N >= 0`.
Allowed dtypes: `float32`, `float64`, `complex64`, `complex128`.
is_non_singular: Expect that this operator is non-singular.
is_self_adjoint: Expect that this operator is equal to its hermitian
transpose.
is_positive_definite: Expect that this operator is positive definite,
meaning the quadratic form `x^H A x` has positive real part for all
nonzero `x`. Note that we do not require the operator to be
self-adjoint to be positive-definite. See:
https://en.wikipedia.org/wiki/Positive-definite_matrix\
#Extension_for_non_symmetric_matrices
is_square: Expect that this operator acts like square [batch] matrices.
name: A name for this `LinearOperator`.
Raises:
TypeError: If `diag.dtype` is not an allowed type.
"""
with ops.name_scope(name, values=[matrix]):
self._matrix = ops.convert_to_tensor(matrix, name="matrix")
self._check_matrix(self._matrix)
super(LinearOperatorFullMatrix, self).__init__(
dtype=self._matrix.dtype,
graph_parents=[self._matrix],
is_non_singular=is_non_singular,
is_self_adjoint=is_self_adjoint,
is_positive_definite=is_positive_definite,
is_square=is_square,
name=name) | [
"def",
"__init__",
"(",
"self",
",",
"matrix",
",",
"is_non_singular",
"=",
"None",
",",
"is_self_adjoint",
"=",
"None",
",",
"is_positive_definite",
"=",
"None",
",",
"is_square",
"=",
"None",
",",
"name",
"=",
"\"LinearOperatorFullMatrix\"",
")",
":",
"with"... | https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/ops/linalg/linear_operator_full_matrix.py#L106-L145 | ||
bulletphysics/bullet3 | f0f2a952e146f016096db6f85cf0c44ed75b0b9a | examples/pybullet/gym/pybullet_envs/minitaur/envs/minitaur.py | python | Minitaur.SetMotorStrengthRatios | (self, ratios) | Set the strength of each motor relative to the default value.
Args:
ratios: The relative strength. A numpy array ranging from 0.0 to 1.0. | Set the strength of each motor relative to the default value. | [
"Set",
"the",
"strength",
"of",
"each",
"motor",
"relative",
"to",
"the",
"default",
"value",
"."
] | def SetMotorStrengthRatios(self, ratios):
"""Set the strength of each motor relative to the default value.
Args:
ratios: The relative strength. A numpy array ranging from 0.0 to 1.0.
"""
if self._accurate_motor_model_enabled:
self._motor_model.set_strength_ratios(ratios) | [
"def",
"SetMotorStrengthRatios",
"(",
"self",
",",
"ratios",
")",
":",
"if",
"self",
".",
"_accurate_motor_model_enabled",
":",
"self",
".",
"_motor_model",
".",
"set_strength_ratios",
"(",
"ratios",
")"
] | https://github.com/bulletphysics/bullet3/blob/f0f2a952e146f016096db6f85cf0c44ed75b0b9a/examples/pybullet/gym/pybullet_envs/minitaur/envs/minitaur.py#L937-L944 | ||
mongodb/mongo | d8ff665343ad29cf286ee2cf4a1960d29371937b | buildscripts/resmokelib/logging/buildlogger.py | python | BuildloggerServer.get_build_log_url | (build_id) | return "%s/%s" % (base_url, endpoint.strip("/")) | Return the build log URL. | Return the build log URL. | [
"Return",
"the",
"build",
"log",
"URL",
"."
] | def get_build_log_url(build_id):
"""Return the build log URL."""
base_url = _config.BUILDLOGGER_URL.rstrip("/")
endpoint = APPEND_GLOBAL_LOGS_ENDPOINT % {"build_id": build_id}
return "%s/%s" % (base_url, endpoint.strip("/")) | [
"def",
"get_build_log_url",
"(",
"build_id",
")",
":",
"base_url",
"=",
"_config",
".",
"BUILDLOGGER_URL",
".",
"rstrip",
"(",
"\"/\"",
")",
"endpoint",
"=",
"APPEND_GLOBAL_LOGS_ENDPOINT",
"%",
"{",
"\"build_id\"",
":",
"build_id",
"}",
"return",
"\"%s/%s\"",
"%... | https://github.com/mongodb/mongo/blob/d8ff665343ad29cf286ee2cf4a1960d29371937b/buildscripts/resmokelib/logging/buildlogger.py#L329-L333 | |
timi-liuliang/echo | 40a5a24d430eee4118314459ab7e03afcb3b8719 | thirdparty/protobuf/python/ez_setup.py | python | main | (argv, version=DEFAULT_VERSION) | Install or upgrade setuptools and EasyInstall | Install or upgrade setuptools and EasyInstall | [
"Install",
"or",
"upgrade",
"setuptools",
"and",
"EasyInstall"
] | def main(argv, version=DEFAULT_VERSION):
"""Install or upgrade setuptools and EasyInstall"""
try:
import setuptools
except ImportError:
egg = None
try:
egg = download_setuptools(version, delay=0)
sys.path.insert(0,egg)
from setuptools.command.easy_install import main
return main(list(argv)+[egg]) # we're done here
finally:
if egg and os.path.exists(egg):
os.unlink(egg)
else:
if setuptools.__version__ == '0.0.1':
print >>sys.stderr, (
"You have an obsolete version of setuptools installed. Please\n"
"remove it from your system entirely before rerunning this script."
)
sys.exit(2)
req = "setuptools>="+version
import pkg_resources
try:
pkg_resources.require(req)
except pkg_resources.VersionConflict:
try:
from setuptools.command.easy_install import main
except ImportError:
from easy_install import main
main(list(argv)+[download_setuptools(delay=0)])
sys.exit(0) # try to force an exit
else:
if argv:
from setuptools.command.easy_install import main
main(argv)
else:
print "Setuptools version",version,"or greater has been installed."
print '(Run "ez_setup.py -U setuptools" to reinstall or upgrade.)' | [
"def",
"main",
"(",
"argv",
",",
"version",
"=",
"DEFAULT_VERSION",
")",
":",
"try",
":",
"import",
"setuptools",
"except",
"ImportError",
":",
"egg",
"=",
"None",
"try",
":",
"egg",
"=",
"download_setuptools",
"(",
"version",
",",
"delay",
"=",
"0",
")"... | https://github.com/timi-liuliang/echo/blob/40a5a24d430eee4118314459ab7e03afcb3b8719/thirdparty/protobuf/python/ez_setup.py#L209-L248 | ||
intel/llvm | e6d0547e9d99b5a56430c4749f6c7e328bf221ab | mlir/python/mlir/dialects/_pdl_ops_ext.py | python | RewriteOp.body | (self) | return self.regions[0].blocks[0] | Return the body (block) of the rewrite. | Return the body (block) of the rewrite. | [
"Return",
"the",
"body",
"(",
"block",
")",
"of",
"the",
"rewrite",
"."
] | def body(self):
"""Return the body (block) of the rewrite."""
return self.regions[0].blocks[0] | [
"def",
"body",
"(",
"self",
")",
":",
"return",
"self",
".",
"regions",
"[",
"0",
"]",
".",
"blocks",
"[",
"0",
"]"
] | https://github.com/intel/llvm/blob/e6d0547e9d99b5a56430c4749f6c7e328bf221ab/mlir/python/mlir/dialects/_pdl_ops_ext.py#L255-L257 | |
windystrife/UnrealEngine_NVIDIAGameWorks | b50e6338a7c5b26374d66306ebc7807541ff815e | Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/idlelib/tabbedpages.py | python | TabSet._arrange_tabs | (self) | Arrange the tabs in rows, in the order in which they were added.
If n_rows >= 1, this will be the number of rows used. Otherwise the
number of rows will be calculated according to the number of tabs and
max_tabs_per_row. In this case, the number of rows may change when
adding/removing tabs. | Arrange the tabs in rows, in the order in which they were added. | [
"Arrange",
"the",
"tabs",
"in",
"rows",
"in",
"the",
"order",
"in",
"which",
"they",
"were",
"added",
"."
] | def _arrange_tabs(self):
"""
Arrange the tabs in rows, in the order in which they were added.
If n_rows >= 1, this will be the number of rows used. Otherwise the
number of rows will be calculated according to the number of tabs and
max_tabs_per_row. In this case, the number of rows may change when
adding/removing tabs.
"""
# remove all tabs and rows
for tab_name in self._tabs.keys():
self._tabs.pop(tab_name).destroy()
self._reset_tab_rows()
if not self._tab_names:
return
if self.n_rows is not None and self.n_rows > 0:
n_rows = self.n_rows
else:
# calculate the required number of rows
n_rows = (len(self._tab_names) - 1) // self.max_tabs_per_row + 1
# not expanding the tabs with more than one row is very ugly
expand_tabs = self.expand_tabs or n_rows > 1
i = 0 # index in self._tab_names
for row_index in xrange(n_rows):
# calculate required number of tabs in this row
n_tabs = (len(self._tab_names) - i - 1) // (n_rows - row_index) + 1
tab_names = self._tab_names[i:i + n_tabs]
i += n_tabs
self._add_tab_row(tab_names, expand_tabs)
# re-select selected tab so it is properly displayed
selected = self._selected_tab
self.set_selected_tab(None)
if selected in self._tab_names:
self.set_selected_tab(selected) | [
"def",
"_arrange_tabs",
"(",
"self",
")",
":",
"# remove all tabs and rows",
"for",
"tab_name",
"in",
"self",
".",
"_tabs",
".",
"keys",
"(",
")",
":",
"self",
".",
"_tabs",
".",
"pop",
"(",
"tab_name",
")",
".",
"destroy",
"(",
")",
"self",
".",
"_res... | https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/idlelib/tabbedpages.py#L135-L173 | ||
lhmRyan/deep-supervised-hashing-DSH | 631901f82e2ab031fbac33f914a5b08ef8e21d57 | python/caffe/io.py | python | load_image | (filename, color=True) | return img | Load an image converting from grayscale or alpha as needed.
Parameters
----------
filename : string
color : boolean
flag for color format. True (default) loads as RGB while False
loads as intensity (if image is already grayscale).
Returns
-------
image : an image with type np.float32 in range [0, 1]
of size (H x W x 3) in RGB or
of size (H x W x 1) in grayscale. | Load an image converting from grayscale or alpha as needed. | [
"Load",
"an",
"image",
"converting",
"from",
"grayscale",
"or",
"alpha",
"as",
"needed",
"."
] | def load_image(filename, color=True):
"""
Load an image converting from grayscale or alpha as needed.
Parameters
----------
filename : string
color : boolean
flag for color format. True (default) loads as RGB while False
loads as intensity (if image is already grayscale).
Returns
-------
image : an image with type np.float32 in range [0, 1]
of size (H x W x 3) in RGB or
of size (H x W x 1) in grayscale.
"""
img = skimage.img_as_float(skimage.io.imread(filename, as_grey=not color)).astype(np.float32)
if img.ndim == 2:
img = img[:, :, np.newaxis]
if color:
img = np.tile(img, (1, 1, 3))
elif img.shape[2] == 4:
img = img[:, :, :3]
return img | [
"def",
"load_image",
"(",
"filename",
",",
"color",
"=",
"True",
")",
":",
"img",
"=",
"skimage",
".",
"img_as_float",
"(",
"skimage",
".",
"io",
".",
"imread",
"(",
"filename",
",",
"as_grey",
"=",
"not",
"color",
")",
")",
".",
"astype",
"(",
"np",... | https://github.com/lhmRyan/deep-supervised-hashing-DSH/blob/631901f82e2ab031fbac33f914a5b08ef8e21d57/python/caffe/io.py#L278-L302 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/tools/Editra/src/ed_print.py | python | EdPrinter.SetStc | (self, stc) | Set the stc we are printing for
@param stc: instance of wx.stc.StyledTextCtrl
@note: MUST be called prior to any other print operations | Set the stc we are printing for
@param stc: instance of wx.stc.StyledTextCtrl
@note: MUST be called prior to any other print operations | [
"Set",
"the",
"stc",
"we",
"are",
"printing",
"for",
"@param",
"stc",
":",
"instance",
"of",
"wx",
".",
"stc",
".",
"StyledTextCtrl",
"@note",
":",
"MUST",
"be",
"called",
"prior",
"to",
"any",
"other",
"print",
"operations"
] | def SetStc(self, stc):
"""Set the stc we are printing for
@param stc: instance of wx.stc.StyledTextCtrl
@note: MUST be called prior to any other print operations
"""
self.stc = stc | [
"def",
"SetStc",
"(",
"self",
",",
"stc",
")",
":",
"self",
".",
"stc",
"=",
"stc"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/ed_print.py#L157-L163 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/llvmlite/ir/types.py | python | Type.wrap_constant_value | (self, value) | return value | Wrap constant *value* if necessary. This method may be overriden
by subclasses (especially aggregate types). | Wrap constant *value* if necessary. This method may be overriden
by subclasses (especially aggregate types). | [
"Wrap",
"constant",
"*",
"value",
"*",
"if",
"necessary",
".",
"This",
"method",
"may",
"be",
"overriden",
"by",
"subclasses",
"(",
"especially",
"aggregate",
"types",
")",
"."
] | def wrap_constant_value(self, value):
"""
Wrap constant *value* if necessary. This method may be overriden
by subclasses (especially aggregate types).
"""
return value | [
"def",
"wrap_constant_value",
"(",
"self",
",",
"value",
")",
":",
"return",
"value"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/llvmlite/ir/types.py#L72-L77 | |
hpi-xnor/BMXNet-v2 | af2b1859eafc5c721b1397cef02f946aaf2ce20d | python/mxnet/notebook/callback.py | python | LiveBokehChart.setup_chart | (self) | Render a bokeh object and return a handle to it. | Render a bokeh object and return a handle to it. | [
"Render",
"a",
"bokeh",
"object",
"and",
"return",
"a",
"handle",
"to",
"it",
"."
] | def setup_chart(self):
"""Render a bokeh object and return a handle to it.
"""
raise NotImplementedError("Incomplete base class: LiveBokehChart must be sub-classed") | [
"def",
"setup_chart",
"(",
"self",
")",
":",
"raise",
"NotImplementedError",
"(",
"\"Incomplete base class: LiveBokehChart must be sub-classed\"",
")"
] | https://github.com/hpi-xnor/BMXNet-v2/blob/af2b1859eafc5c721b1397cef02f946aaf2ce20d/python/mxnet/notebook/callback.py#L225-L228 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/_gdi.py | python | GraphicsPath.AddPath | (*args, **kwargs) | return _gdi_.GraphicsPath_AddPath(*args, **kwargs) | AddPath(self, GraphicsPath path)
Adds another path | AddPath(self, GraphicsPath path) | [
"AddPath",
"(",
"self",
"GraphicsPath",
"path",
")"
] | def AddPath(*args, **kwargs):
"""
AddPath(self, GraphicsPath path)
Adds another path
"""
return _gdi_.GraphicsPath_AddPath(*args, **kwargs) | [
"def",
"AddPath",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_gdi_",
".",
"GraphicsPath_AddPath",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_gdi.py#L5725-L5731 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/site-packages/setuptools/_vendor/pyparsing.py | python | ParserElement.setDebug | ( self, flag=True ) | return self | Enable display of debugging messages while doing pattern matching.
Set C{flag} to True to enable, False to disable.
Example::
wd = Word(alphas).setName("alphaword")
integer = Word(nums).setName("numword")
term = wd | integer
# turn on debugging for wd
wd.setDebug()
OneOrMore(term).parseString("abc 123 xyz 890")
prints::
Match alphaword at loc 0(1,1)
Matched alphaword -> ['abc']
Match alphaword at loc 3(1,4)
Exception raised:Expected alphaword (at char 4), (line:1, col:5)
Match alphaword at loc 7(1,8)
Matched alphaword -> ['xyz']
Match alphaword at loc 11(1,12)
Exception raised:Expected alphaword (at char 12), (line:1, col:13)
Match alphaword at loc 15(1,16)
Exception raised:Expected alphaword (at char 15), (line:1, col:16)
The output shown is that produced by the default debug actions - custom debug actions can be
specified using L{setDebugActions}. Prior to attempting
to match the C{wd} expression, the debugging message C{"Match <exprname> at loc <n>(<line>,<col>)"}
is shown. Then if the parse succeeds, a C{"Matched"} message is shown, or an C{"Exception raised"}
message is shown. Also note the use of L{setName} to assign a human-readable name to the expression,
which makes debugging and exception messages easier to understand - for instance, the default
name created for the C{Word} expression without calling C{setName} is C{"W:(ABCD...)"}. | Enable display of debugging messages while doing pattern matching.
Set C{flag} to True to enable, False to disable. | [
"Enable",
"display",
"of",
"debugging",
"messages",
"while",
"doing",
"pattern",
"matching",
".",
"Set",
"C",
"{",
"flag",
"}",
"to",
"True",
"to",
"enable",
"False",
"to",
"disable",
"."
] | def setDebug( self, flag=True ):
"""
Enable display of debugging messages while doing pattern matching.
Set C{flag} to True to enable, False to disable.
Example::
wd = Word(alphas).setName("alphaword")
integer = Word(nums).setName("numword")
term = wd | integer
# turn on debugging for wd
wd.setDebug()
OneOrMore(term).parseString("abc 123 xyz 890")
prints::
Match alphaword at loc 0(1,1)
Matched alphaword -> ['abc']
Match alphaword at loc 3(1,4)
Exception raised:Expected alphaword (at char 4), (line:1, col:5)
Match alphaword at loc 7(1,8)
Matched alphaword -> ['xyz']
Match alphaword at loc 11(1,12)
Exception raised:Expected alphaword (at char 12), (line:1, col:13)
Match alphaword at loc 15(1,16)
Exception raised:Expected alphaword (at char 15), (line:1, col:16)
The output shown is that produced by the default debug actions - custom debug actions can be
specified using L{setDebugActions}. Prior to attempting
to match the C{wd} expression, the debugging message C{"Match <exprname> at loc <n>(<line>,<col>)"}
is shown. Then if the parse succeeds, a C{"Matched"} message is shown, or an C{"Exception raised"}
message is shown. Also note the use of L{setName} to assign a human-readable name to the expression,
which makes debugging and exception messages easier to understand - for instance, the default
name created for the C{Word} expression without calling C{setName} is C{"W:(ABCD...)"}.
"""
if flag:
self.setDebugActions( _defaultStartDebugAction, _defaultSuccessDebugAction, _defaultExceptionDebugAction )
else:
self.debug = False
return self | [
"def",
"setDebug",
"(",
"self",
",",
"flag",
"=",
"True",
")",
":",
"if",
"flag",
":",
"self",
".",
"setDebugActions",
"(",
"_defaultStartDebugAction",
",",
"_defaultSuccessDebugAction",
",",
"_defaultExceptionDebugAction",
")",
"else",
":",
"self",
".",
"debug"... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/setuptools/_vendor/pyparsing.py#L2112-L2151 | |
pytorch/pytorch | 7176c92687d3cc847cc046bf002269c6949a21c2 | torch/autograd/functional.py | python | hvp | (func, inputs, v=None, create_graph=False, strict=False) | return _tuple_postprocess(outputs, is_outputs_tuple), _tuple_postprocess(hvp, is_inputs_tuple) | r"""Function that computes the dot product between the Hessian of a given scalar
function and a vector ``v`` at the point given by the inputs.
Args:
func (function): a Python function that takes Tensor inputs and returns
a Tensor with a single element.
inputs (tuple of Tensors or Tensor): inputs to the function ``func``.
v (tuple of Tensors or Tensor): The vector for which the Hessian vector
product is computed. Must be the same size as the input of
``func``. This argument is optional when ``func``'s input contains
a single element and (if it is not provided) will be set as a
Tensor containing a single ``1``.
create_graph (bool, optional): If ``True``, both the output and result will be
computed in a differentiable way. Note that when ``strict`` is
``False``, the result can not require gradients or be disconnected
from the inputs. Defaults to ``False``.
strict (bool, optional): If ``True``, an error will be raised when we
detect that there exists an input such that all the outputs are
independent of it. If ``False``, we return a Tensor of zeros as the
hvp for said inputs, which is the expected mathematical value.
Defaults to ``False``.
Returns:
output (tuple): tuple with:
func_output (tuple of Tensors or Tensor): output of ``func(inputs)``
hvp (tuple of Tensors or Tensor): result of the dot product with
the same shape as the inputs.
Example:
>>> def pow_reducer(x):
... return x.pow(3).sum()
>>> inputs = torch.rand(2, 2)
>>> v = torch.ones(2, 2)
>>> hvp(pow_reducer, inputs, v)
(tensor(0.1448),
tensor([[2.0239, 1.6456],
[2.4988, 1.4310]]))
>>> hvp(pow_reducer, inputs, v, create_graph=True)
(tensor(0.1448, grad_fn=<SumBackward0>),
tensor([[2.0239, 1.6456],
[2.4988, 1.4310]], grad_fn=<MulBackward0>))
>>> def pow_adder_reducer(x, y):
... return (2 * x.pow(2) + 3 * y.pow(2)).sum()
>>> inputs = (torch.rand(2), torch.rand(2))
>>> v = (torch.zeros(2), torch.ones(2))
>>> hvp(pow_adder_reducer, inputs, v)
(tensor(2.3030),
(tensor([0., 0.]),
tensor([6., 6.])))
Note:
This function is significantly slower than `vhp` due to backward mode AD constraints.
If your functions is twice continuously differentiable, then hvp = vhp.t(). So if you
know that your function satisfies this condition, you should use vhp instead that is
much faster with the current implementation. | r"""Function that computes the dot product between the Hessian of a given scalar
function and a vector ``v`` at the point given by the inputs. | [
"r",
"Function",
"that",
"computes",
"the",
"dot",
"product",
"between",
"the",
"Hessian",
"of",
"a",
"given",
"scalar",
"function",
"and",
"a",
"vector",
"v",
"at",
"the",
"point",
"given",
"by",
"the",
"inputs",
"."
] | def hvp(func, inputs, v=None, create_graph=False, strict=False):
r"""Function that computes the dot product between the Hessian of a given scalar
function and a vector ``v`` at the point given by the inputs.
Args:
func (function): a Python function that takes Tensor inputs and returns
a Tensor with a single element.
inputs (tuple of Tensors or Tensor): inputs to the function ``func``.
v (tuple of Tensors or Tensor): The vector for which the Hessian vector
product is computed. Must be the same size as the input of
``func``. This argument is optional when ``func``'s input contains
a single element and (if it is not provided) will be set as a
Tensor containing a single ``1``.
create_graph (bool, optional): If ``True``, both the output and result will be
computed in a differentiable way. Note that when ``strict`` is
``False``, the result can not require gradients or be disconnected
from the inputs. Defaults to ``False``.
strict (bool, optional): If ``True``, an error will be raised when we
detect that there exists an input such that all the outputs are
independent of it. If ``False``, we return a Tensor of zeros as the
hvp for said inputs, which is the expected mathematical value.
Defaults to ``False``.
Returns:
output (tuple): tuple with:
func_output (tuple of Tensors or Tensor): output of ``func(inputs)``
hvp (tuple of Tensors or Tensor): result of the dot product with
the same shape as the inputs.
Example:
>>> def pow_reducer(x):
... return x.pow(3).sum()
>>> inputs = torch.rand(2, 2)
>>> v = torch.ones(2, 2)
>>> hvp(pow_reducer, inputs, v)
(tensor(0.1448),
tensor([[2.0239, 1.6456],
[2.4988, 1.4310]]))
>>> hvp(pow_reducer, inputs, v, create_graph=True)
(tensor(0.1448, grad_fn=<SumBackward0>),
tensor([[2.0239, 1.6456],
[2.4988, 1.4310]], grad_fn=<MulBackward0>))
>>> def pow_adder_reducer(x, y):
... return (2 * x.pow(2) + 3 * y.pow(2)).sum()
>>> inputs = (torch.rand(2), torch.rand(2))
>>> v = (torch.zeros(2), torch.ones(2))
>>> hvp(pow_adder_reducer, inputs, v)
(tensor(2.3030),
(tensor([0., 0.]),
tensor([6., 6.])))
Note:
This function is significantly slower than `vhp` due to backward mode AD constraints.
If your functions is twice continuously differentiable, then hvp = vhp.t(). So if you
know that your function satisfies this condition, you should use vhp instead that is
much faster with the current implementation.
"""
with torch.enable_grad():
is_inputs_tuple, inputs = _as_tuple(inputs, "inputs", "hvp")
inputs = _grad_preprocess(inputs, create_graph=create_graph, need_graph=True)
if v is not None:
_, v = _as_tuple(v, "v", "hvp")
v = _grad_preprocess(v, create_graph=create_graph, need_graph=False)
_validate_v(v, inputs, is_inputs_tuple)
else:
if len(inputs) != 1 or inputs[0].nelement() != 1:
raise RuntimeError("The vector v can only be None if the input to the user-provided function "
"is a single Tensor with a single element.")
outputs = func(*inputs)
is_outputs_tuple, outputs = _as_tuple(outputs, "outputs of the user-provided function", "hvp")
_check_requires_grad(outputs, "outputs", strict=strict)
if is_outputs_tuple or not isinstance(outputs[0], torch.Tensor):
raise RuntimeError("The function given to hvp should return a single Tensor")
if outputs[0].nelement() != 1:
raise RuntimeError("The Tensor returned by the function given to hvp should contain a single element")
jac = _autograd_grad(outputs, inputs, create_graph=True)
_check_requires_grad(jac, "jacobian", strict=strict)
grad_jac = tuple(torch.zeros_like(inp, requires_grad=True) for inp in inputs)
double_back = _autograd_grad(jac, inputs, grad_jac, create_graph=True)
_check_requires_grad(jac, "hessian", strict=strict)
enable_grad = True if create_graph else torch.is_grad_enabled()
with torch.set_grad_enabled(enable_grad):
grad_res = _autograd_grad(double_back, grad_jac, v, create_graph=create_graph)
hvp = _fill_in_zeros(grad_res, inputs, strict, create_graph, "double_back_trick")
outputs = _grad_postprocess(outputs, create_graph)
hvp = _grad_postprocess(hvp, create_graph)
return _tuple_postprocess(outputs, is_outputs_tuple), _tuple_postprocess(hvp, is_inputs_tuple) | [
"def",
"hvp",
"(",
"func",
",",
"inputs",
",",
"v",
"=",
"None",
",",
"create_graph",
"=",
"False",
",",
"strict",
"=",
"False",
")",
":",
"with",
"torch",
".",
"enable_grad",
"(",
")",
":",
"is_inputs_tuple",
",",
"inputs",
"=",
"_as_tuple",
"(",
"i... | https://github.com/pytorch/pytorch/blob/7176c92687d3cc847cc046bf002269c6949a21c2/torch/autograd/functional.py#L903-L1005 | |
thalium/icebox | 99d147d5b9269222225443ce171b4fd46d8985d4 | third_party/virtualbox/src/libs/libxml2-2.9.4/python/libxml2.py | python | xmlNode.getContent | (self) | return ret | Read the value of a node, this can be either the text
carried directly by this node if it's a TEXT node or the
aggregate string of the values carried by this node child's
(TEXT and ENTITY_REF). Entity references are substituted. | Read the value of a node, this can be either the text
carried directly by this node if it's a TEXT node or the
aggregate string of the values carried by this node child's
(TEXT and ENTITY_REF). Entity references are substituted. | [
"Read",
"the",
"value",
"of",
"a",
"node",
"this",
"can",
"be",
"either",
"the",
"text",
"carried",
"directly",
"by",
"this",
"node",
"if",
"it",
"s",
"a",
"TEXT",
"node",
"or",
"the",
"aggregate",
"string",
"of",
"the",
"values",
"carried",
"by",
"thi... | def getContent(self):
"""Read the value of a node, this can be either the text
carried directly by this node if it's a TEXT node or the
aggregate string of the values carried by this node child's
(TEXT and ENTITY_REF). Entity references are substituted. """
ret = libxml2mod.xmlNodeGetContent(self._o)
return ret | [
"def",
"getContent",
"(",
"self",
")",
":",
"ret",
"=",
"libxml2mod",
".",
"xmlNodeGetContent",
"(",
"self",
".",
"_o",
")",
"return",
"ret"
] | https://github.com/thalium/icebox/blob/99d147d5b9269222225443ce171b4fd46d8985d4/third_party/virtualbox/src/libs/libxml2-2.9.4/python/libxml2.py#L3250-L3256 | |
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/parsing_ops.py | python | parse_single_example_v2_unoptimized | (
serialized, features, example_names=None, name=None
) | return _construct_sparse_tensors_for_sparse_features(features, outputs) | Parses a single `Example` proto.
Similar to `parse_example`, except:
For dense tensors, the returned `Tensor` is identical to the output of
`parse_example`, except there is no batch dimension, the output shape is the
same as the shape given in `dense_shape`.
For `SparseTensor`s, the first (batch) column of the indices matrix is removed
(the indices matrix is a column vector), the values vector is unchanged, and
the first (`batch_size`) entry of the shape vector is removed (it is now a
single element vector).
One might see performance advantages by batching `Example` protos with
`parse_example` instead of using this function directly.
Args:
serialized: A scalar string Tensor, a single serialized Example.
See `_parse_single_example_raw` documentation for more details.
features: A `dict` mapping feature keys to `FixedLenFeature` or
`VarLenFeature` values.
example_names: (Optional) A scalar string Tensor, the associated name.
See `_parse_single_example_raw` documentation for more details.
name: A name for this operation (optional).
Returns:
A `dict` mapping feature keys to `Tensor` and `SparseTensor` values.
Raises:
ValueError: if any feature is invalid. | Parses a single `Example` proto. | [
"Parses",
"a",
"single",
"Example",
"proto",
"."
] | def parse_single_example_v2_unoptimized(
serialized, features, example_names=None, name=None
):
"""Parses a single `Example` proto.
Similar to `parse_example`, except:
For dense tensors, the returned `Tensor` is identical to the output of
`parse_example`, except there is no batch dimension, the output shape is the
same as the shape given in `dense_shape`.
For `SparseTensor`s, the first (batch) column of the indices matrix is removed
(the indices matrix is a column vector), the values vector is unchanged, and
the first (`batch_size`) entry of the shape vector is removed (it is now a
single element vector).
One might see performance advantages by batching `Example` protos with
`parse_example` instead of using this function directly.
Args:
serialized: A scalar string Tensor, a single serialized Example.
See `_parse_single_example_raw` documentation for more details.
features: A `dict` mapping feature keys to `FixedLenFeature` or
`VarLenFeature` values.
example_names: (Optional) A scalar string Tensor, the associated name.
See `_parse_single_example_raw` documentation for more details.
name: A name for this operation (optional).
Returns:
A `dict` mapping feature keys to `Tensor` and `SparseTensor` values.
Raises:
ValueError: if any feature is invalid.
"""
if not features:
raise ValueError("Missing features.")
if example_names is None:
return parse_single_example_v2(serialized, features, name)
features = _prepend_none_dimension(features)
(sparse_keys, sparse_types, dense_keys, dense_types, dense_defaults,
dense_shapes) = _features_to_raw_params(
features,
[VarLenFeature, FixedLenFeature, FixedLenSequenceFeature, SparseFeature])
outputs = _parse_single_example_raw(
serialized, example_names, sparse_keys, sparse_types, dense_keys,
dense_types, dense_defaults, dense_shapes, name)
return _construct_sparse_tensors_for_sparse_features(features, outputs) | [
"def",
"parse_single_example_v2_unoptimized",
"(",
"serialized",
",",
"features",
",",
"example_names",
"=",
"None",
",",
"name",
"=",
"None",
")",
":",
"if",
"not",
"features",
":",
"raise",
"ValueError",
"(",
"\"Missing features.\"",
")",
"if",
"example_names",
... | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/parsing_ops.py#L1026-L1072 | |
naver/sling | 5671cd445a2caae0b4dd0332299e4cfede05062c | webkit/Tools/Scripts/webkitpy/thirdparty/mod_pywebsocket/standalone.py | python | _StandaloneRequest.get_unparsed_uri | (self) | return self._request_handler.path | Getter to mimic request.unparsed_uri. | Getter to mimic request.unparsed_uri. | [
"Getter",
"to",
"mimic",
"request",
".",
"unparsed_uri",
"."
] | def get_unparsed_uri(self):
"""Getter to mimic request.unparsed_uri."""
return self._request_handler.path | [
"def",
"get_unparsed_uri",
"(",
"self",
")",
":",
"return",
"self",
".",
"_request_handler",
".",
"path"
] | https://github.com/naver/sling/blob/5671cd445a2caae0b4dd0332299e4cfede05062c/webkit/Tools/Scripts/webkitpy/thirdparty/mod_pywebsocket/standalone.py#L240-L243 | |
CMU-Perceptual-Computing-Lab/caffe_rtpose | a4778bb1c3eb74d7250402016047216f77b4dba6 | scripts/cpp_lint.py | python | CheckForBadCharacters | (filename, lines, error) | Logs an error for each line containing bad characters.
Two kinds of bad characters:
1. Unicode replacement characters: These indicate that either the file
contained invalid UTF-8 (likely) or Unicode replacement characters (which
it shouldn't). Note that it's possible for this to throw off line
numbering if the invalid UTF-8 occurred adjacent to a newline.
2. NUL bytes. These are problematic for some tools.
Args:
filename: The name of the current file.
lines: An array of strings, each representing a line of the file.
error: The function to call with any errors found. | Logs an error for each line containing bad characters. | [
"Logs",
"an",
"error",
"for",
"each",
"line",
"containing",
"bad",
"characters",
"."
] | def CheckForBadCharacters(filename, lines, error):
"""Logs an error for each line containing bad characters.
Two kinds of bad characters:
1. Unicode replacement characters: These indicate that either the file
contained invalid UTF-8 (likely) or Unicode replacement characters (which
it shouldn't). Note that it's possible for this to throw off line
numbering if the invalid UTF-8 occurred adjacent to a newline.
2. NUL bytes. These are problematic for some tools.
Args:
filename: The name of the current file.
lines: An array of strings, each representing a line of the file.
error: The function to call with any errors found.
"""
for linenum, line in enumerate(lines):
if u'\ufffd' in line:
error(filename, linenum, 'readability/utf8', 5,
'Line contains invalid UTF-8 (or Unicode replacement character).')
if '\0' in line:
error(filename, linenum, 'readability/nul', 5, 'Line contains NUL byte.') | [
"def",
"CheckForBadCharacters",
"(",
"filename",
",",
"lines",
",",
"error",
")",
":",
"for",
"linenum",
",",
"line",
"in",
"enumerate",
"(",
"lines",
")",
":",
"if",
"u'\\ufffd'",
"in",
"line",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'reada... | https://github.com/CMU-Perceptual-Computing-Lab/caffe_rtpose/blob/a4778bb1c3eb74d7250402016047216f77b4dba6/scripts/cpp_lint.py#L1483-L1505 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.