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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Komnomnomnom/swigibpy | cfd307fdbfaffabc69a2dc037538d7e34a8b8daf | swigibpy.py | python | TagValueList.rend | (self) | return _swigibpy.TagValueList_rend(self) | rend(TagValueList self) -> std::vector< shared_ptr< TagValue > >::reverse_iterator | rend(TagValueList self) -> std::vector< shared_ptr< TagValue > >::reverse_iterator | [
"rend",
"(",
"TagValueList",
"self",
")",
"-",
">",
"std",
"::",
"vector<",
"shared_ptr<",
"TagValue",
">",
">",
"::",
"reverse_iterator"
] | def rend(self):
"""rend(TagValueList self) -> std::vector< shared_ptr< TagValue > >::reverse_iterator"""
return _swigibpy.TagValueList_rend(self) | [
"def",
"rend",
"(",
"self",
")",
":",
"return",
"_swigibpy",
".",
"TagValueList_rend",
"(",
"self",
")"
] | https://github.com/Komnomnomnom/swigibpy/blob/cfd307fdbfaffabc69a2dc037538d7e34a8b8daf/swigibpy.py#L804-L806 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/html.py | python | HtmlWinParser.GetCharHeight | (*args, **kwargs) | return _html.HtmlWinParser_GetCharHeight(*args, **kwargs) | GetCharHeight(self) -> int | GetCharHeight(self) -> int | [
"GetCharHeight",
"(",
"self",
")",
"-",
">",
"int"
] | def GetCharHeight(*args, **kwargs):
"""GetCharHeight(self) -> int"""
return _html.HtmlWinParser_GetCharHeight(*args, **kwargs) | [
"def",
"GetCharHeight",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_html",
".",
"HtmlWinParser_GetCharHeight",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/html.py#L252-L254 | |
apple/swift-lldb | d74be846ef3e62de946df343e8c234bde93a8912 | scripts/Python/static-binding/lldb.py | python | SBProcess_GetStructuredDataFromEvent | (event) | return _lldb.SBProcess_GetStructuredDataFromEvent(event) | SBProcess_GetStructuredDataFromEvent(SBEvent event) -> SBStructuredData | SBProcess_GetStructuredDataFromEvent(SBEvent event) -> SBStructuredData | [
"SBProcess_GetStructuredDataFromEvent",
"(",
"SBEvent",
"event",
")",
"-",
">",
"SBStructuredData"
] | def SBProcess_GetStructuredDataFromEvent(event):
"""SBProcess_GetStructuredDataFromEvent(SBEvent event) -> SBStructuredData"""
return _lldb.SBProcess_GetStructuredDataFromEvent(event) | [
"def",
"SBProcess_GetStructuredDataFromEvent",
"(",
"event",
")",
":",
"return",
"_lldb",
".",
"SBProcess_GetStructuredDataFromEvent",
"(",
"event",
")"
] | https://github.com/apple/swift-lldb/blob/d74be846ef3e62de946df343e8c234bde93a8912/scripts/Python/static-binding/lldb.py#L8922-L8924 | |
deepmind/open_spiel | 4ca53bea32bb2875c7385d215424048ae92f78c8 | open_spiel/python/jax/deep_cfr.py | python | DeepCFRSolver._learn_advantage_network | (self, player) | return main_loss | Compute the loss on sampled transitions and perform a Q-network update.
If there are not enough elements in the buffer, no loss is computed and
`None` is returned instead.
Args:
player: (int) player index.
Returns:
The average loss over the advantage network of the last batch. | Compute the loss on sampled transitions and perform a Q-network update. | [
"Compute",
"the",
"loss",
"on",
"sampled",
"transitions",
"and",
"perform",
"a",
"Q",
"-",
"network",
"update",
"."
] | def _learn_advantage_network(self, player):
"""Compute the loss on sampled transitions and perform a Q-network update.
If there are not enough elements in the buffer, no loss is computed and
`None` is returned instead.
Args:
player: (int) player index.
Returns:
The average loss over the advantage network of the last batch.
"""
for data in self._get_advantage_dataset(
player, self._advantage_network_train_steps):
(self._params_adv_network[player], self._opt_adv_state[player],
main_loss) = self._jitted_adv_update(self._params_adv_network[player],
self._opt_adv_state[player],
*data, jnp.array(self._iteration))
return main_loss | [
"def",
"_learn_advantage_network",
"(",
"self",
",",
"player",
")",
":",
"for",
"data",
"in",
"self",
".",
"_get_advantage_dataset",
"(",
"player",
",",
"self",
".",
"_advantage_network_train_steps",
")",
":",
"(",
"self",
".",
"_params_adv_network",
"[",
"playe... | https://github.com/deepmind/open_spiel/blob/4ca53bea32bb2875c7385d215424048ae92f78c8/open_spiel/python/jax/deep_cfr.py#L531-L550 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/lib/agw/genericmessagedialog.py | python | GenericMessageDialog.GetCustomHelpBitmap | (self) | return (self._helpBitmap and [self._helpBitmap] or [self.GetDefaultHelpBitmap()])[0] | If a custom icon has been used for the ``Help`` button, this method will return
it as an instance of :class:`Bitmap`. Otherwise, the default one (as defined in
:meth:`~GenericMessageDialog.GetDefaultHelpBitmap`) is returned.
.. versionadded:: 0.9.3 | If a custom icon has been used for the ``Help`` button, this method will return
it as an instance of :class:`Bitmap`. Otherwise, the default one (as defined in
:meth:`~GenericMessageDialog.GetDefaultHelpBitmap`) is returned. | [
"If",
"a",
"custom",
"icon",
"has",
"been",
"used",
"for",
"the",
"Help",
"button",
"this",
"method",
"will",
"return",
"it",
"as",
"an",
"instance",
"of",
":",
"class",
":",
"Bitmap",
".",
"Otherwise",
"the",
"default",
"one",
"(",
"as",
"defined",
"i... | def GetCustomHelpBitmap(self):
"""
If a custom icon has been used for the ``Help`` button, this method will return
it as an instance of :class:`Bitmap`. Otherwise, the default one (as defined in
:meth:`~GenericMessageDialog.GetDefaultHelpBitmap`) is returned.
.. versionadded:: 0.9.3
"""
return (self._helpBitmap and [self._helpBitmap] or [self.GetDefaultHelpBitmap()])[0] | [
"def",
"GetCustomHelpBitmap",
"(",
"self",
")",
":",
"return",
"(",
"self",
".",
"_helpBitmap",
"and",
"[",
"self",
".",
"_helpBitmap",
"]",
"or",
"[",
"self",
".",
"GetDefaultHelpBitmap",
"(",
")",
"]",
")",
"[",
"0",
"]"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/genericmessagedialog.py#L1355-L1364 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/ipython/py3/IPython/lib/guisupport.py | python | start_event_loop_qt4 | (app=None) | Start the qt4 event loop in a consistent manner. | Start the qt4 event loop in a consistent manner. | [
"Start",
"the",
"qt4",
"event",
"loop",
"in",
"a",
"consistent",
"manner",
"."
] | def start_event_loop_qt4(app=None):
"""Start the qt4 event loop in a consistent manner."""
if app is None:
app = get_app_qt4([''])
if not is_event_loop_running_qt4(app):
app._in_event_loop = True
app.exec_()
app._in_event_loop = False
else:
app._in_event_loop = True | [
"def",
"start_event_loop_qt4",
"(",
"app",
"=",
"None",
")",
":",
"if",
"app",
"is",
"None",
":",
"app",
"=",
"get_app_qt4",
"(",
"[",
"''",
"]",
")",
"if",
"not",
"is_event_loop_running_qt4",
"(",
"app",
")",
":",
"app",
".",
"_in_event_loop",
"=",
"T... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/ipython/py3/IPython/lib/guisupport.py#L138-L147 | ||
pmq20/node-packer | 12c46c6e44fbc14d9ee645ebd17d5296b324f7e0 | current/deps/v8/third_party/jinja2/parser.py | python | Parser.parse_tuple | (self, simplified=False, with_condexpr=True,
extra_end_rules=None, explicit_parentheses=False) | return nodes.Tuple(args, 'load', lineno=lineno) | Works like `parse_expression` but if multiple expressions are
delimited by a comma a :class:`~jinja2.nodes.Tuple` node is created.
This method could also return a regular expression instead of a tuple
if no commas where found.
The default parsing mode is a full tuple. If `simplified` is `True`
only names and literals are parsed. The `no_condexpr` parameter is
forwarded to :meth:`parse_expression`.
Because tuples do not require delimiters and may end in a bogus comma
an extra hint is needed that marks the end of a tuple. For example
for loops support tuples between `for` and `in`. In that case the
`extra_end_rules` is set to ``['name:in']``.
`explicit_parentheses` is true if the parsing was triggered by an
expression in parentheses. This is used to figure out if an empty
tuple is a valid expression or not. | Works like `parse_expression` but if multiple expressions are
delimited by a comma a :class:`~jinja2.nodes.Tuple` node is created.
This method could also return a regular expression instead of a tuple
if no commas where found. | [
"Works",
"like",
"parse_expression",
"but",
"if",
"multiple",
"expressions",
"are",
"delimited",
"by",
"a",
"comma",
"a",
":",
"class",
":",
"~jinja2",
".",
"nodes",
".",
"Tuple",
"node",
"is",
"created",
".",
"This",
"method",
"could",
"also",
"return",
"... | def parse_tuple(self, simplified=False, with_condexpr=True,
extra_end_rules=None, explicit_parentheses=False):
"""Works like `parse_expression` but if multiple expressions are
delimited by a comma a :class:`~jinja2.nodes.Tuple` node is created.
This method could also return a regular expression instead of a tuple
if no commas where found.
The default parsing mode is a full tuple. If `simplified` is `True`
only names and literals are parsed. The `no_condexpr` parameter is
forwarded to :meth:`parse_expression`.
Because tuples do not require delimiters and may end in a bogus comma
an extra hint is needed that marks the end of a tuple. For example
for loops support tuples between `for` and `in`. In that case the
`extra_end_rules` is set to ``['name:in']``.
`explicit_parentheses` is true if the parsing was triggered by an
expression in parentheses. This is used to figure out if an empty
tuple is a valid expression or not.
"""
lineno = self.stream.current.lineno
if simplified:
parse = self.parse_primary
elif with_condexpr:
parse = self.parse_expression
else:
parse = lambda: self.parse_expression(with_condexpr=False)
args = []
is_tuple = False
while 1:
if args:
self.stream.expect('comma')
if self.is_tuple_end(extra_end_rules):
break
args.append(parse())
if self.stream.current.type == 'comma':
is_tuple = True
else:
break
lineno = self.stream.current.lineno
if not is_tuple:
if args:
return args[0]
# if we don't have explicit parentheses, an empty tuple is
# not a valid expression. This would mean nothing (literally
# nothing) in the spot of an expression would be an empty
# tuple.
if not explicit_parentheses:
self.fail('Expected an expression, got \'%s\'' %
describe_token(self.stream.current))
return nodes.Tuple(args, 'load', lineno=lineno) | [
"def",
"parse_tuple",
"(",
"self",
",",
"simplified",
"=",
"False",
",",
"with_condexpr",
"=",
"True",
",",
"extra_end_rules",
"=",
"None",
",",
"explicit_parentheses",
"=",
"False",
")",
":",
"lineno",
"=",
"self",
".",
"stream",
".",
"current",
".",
"lin... | https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/current/deps/v8/third_party/jinja2/parser.py#L586-L639 | |
krishauser/Klampt | 972cc83ea5befac3f653c1ba20f80155768ad519 | Python/klampt/src/robotsim.py | python | IKObjective.setPlanarPosConstraint | (self, tlocal: "double const [3]", nworld: "double const [3]", oworld: "double") | return _robotsim.IKObjective_setPlanarPosConstraint(self, tlocal, nworld, oworld) | r"""
setPlanarPosConstraint(IKObjective self, double const [3] tlocal, double const [3] nworld, double oworld)
Manual: Sets a planar position constraint nworld^T T(link)*tlocal + oworld = 0. | r"""
setPlanarPosConstraint(IKObjective self, double const [3] tlocal, double const [3] nworld, double oworld) | [
"r",
"setPlanarPosConstraint",
"(",
"IKObjective",
"self",
"double",
"const",
"[",
"3",
"]",
"tlocal",
"double",
"const",
"[",
"3",
"]",
"nworld",
"double",
"oworld",
")"
] | def setPlanarPosConstraint(self, tlocal: "double const [3]", nworld: "double const [3]", oworld: "double") -> "void":
r"""
setPlanarPosConstraint(IKObjective self, double const [3] tlocal, double const [3] nworld, double oworld)
Manual: Sets a planar position constraint nworld^T T(link)*tlocal + oworld = 0.
"""
return _robotsim.IKObjective_setPlanarPosConstraint(self, tlocal, nworld, oworld) | [
"def",
"setPlanarPosConstraint",
"(",
"self",
",",
"tlocal",
":",
"\"double const [3]\"",
",",
"nworld",
":",
"\"double const [3]\"",
",",
"oworld",
":",
"\"double\"",
")",
"->",
"\"void\"",
":",
"return",
"_robotsim",
".",
"IKObjective_setPlanarPosConstraint",
"(",
... | https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/klampt/src/robotsim.py#L6436-L6444 | |
baidu/tera | dbcd28af792d879d961bf9fc7eb60de81b437646 | src/sdk/python/TeraSdk.py | python | RowReader.SetTimeout | (self, timeout) | set timeout | set timeout | [
"set",
"timeout"
] | def SetTimeout(self, timeout):
""" set timeout """
lib.tera_row_reader_set_timeout(self.reader, timeout) | [
"def",
"SetTimeout",
"(",
"self",
",",
"timeout",
")",
":",
"lib",
".",
"tera_row_reader_set_timeout",
"(",
"self",
".",
"reader",
",",
"timeout",
")"
] | https://github.com/baidu/tera/blob/dbcd28af792d879d961bf9fc7eb60de81b437646/src/sdk/python/TeraSdk.py#L735-L737 | ||
adobe/chromium | cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7 | third_party/closure_linter/closure_linter/statetracker.py | python | StateTracker.IsFunctionOpen | (self) | return (self._functions and
self._functions[-1].block_depth == self._block_depth - 1) | Returns true if the current token is a function block open.
Returns:
True if the current token is a function block open. | Returns true if the current token is a function block open. | [
"Returns",
"true",
"if",
"the",
"current",
"token",
"is",
"a",
"function",
"block",
"open",
"."
] | def IsFunctionOpen(self):
"""Returns true if the current token is a function block open.
Returns:
True if the current token is a function block open.
"""
return (self._functions and
self._functions[-1].block_depth == self._block_depth - 1) | [
"def",
"IsFunctionOpen",
"(",
"self",
")",
":",
"return",
"(",
"self",
".",
"_functions",
"and",
"self",
".",
"_functions",
"[",
"-",
"1",
"]",
".",
"block_depth",
"==",
"self",
".",
"_block_depth",
"-",
"1",
")"
] | https://github.com/adobe/chromium/blob/cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7/third_party/closure_linter/closure_linter/statetracker.py#L643-L650 | |
natanielruiz/android-yolo | 1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f | jni-build/jni/include/tensorflow/contrib/rnn/python/ops/lstm_ops.py | python | LSTMFusedCell.__init__ | (self, num_units, forget_bias=1.0, use_peephole=False) | Initialize the basic LSTM cell.
Args:
num_units: int, The number of units in the LSTM cell.
forget_bias: float, The bias added to forget gates (see above).
use_peephole: Whether to use peephole connections or not. | Initialize the basic LSTM cell. | [
"Initialize",
"the",
"basic",
"LSTM",
"cell",
"."
] | def __init__(self, num_units, forget_bias=1.0, use_peephole=False):
"""Initialize the basic LSTM cell.
Args:
num_units: int, The number of units in the LSTM cell.
forget_bias: float, The bias added to forget gates (see above).
use_peephole: Whether to use peephole connections or not.
"""
self._num_units = num_units
self._forget_bias = forget_bias
self._use_peephole = use_peephole | [
"def",
"__init__",
"(",
"self",
",",
"num_units",
",",
"forget_bias",
"=",
"1.0",
",",
"use_peephole",
"=",
"False",
")",
":",
"self",
".",
"_num_units",
"=",
"num_units",
"self",
".",
"_forget_bias",
"=",
"forget_bias",
"self",
".",
"_use_peephole",
"=",
... | https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/tensorflow/contrib/rnn/python/ops/lstm_ops.py#L408-L418 | ||
rrwick/Unicycler | 96ffea71e3a78d63ade19d6124946773e65cf129 | ez_setup.py | python | _install | (archive_filename, install_args=()) | Install Setuptools. | Install Setuptools. | [
"Install",
"Setuptools",
"."
] | def _install(archive_filename, install_args=()):
"""Install Setuptools."""
with archive_context(archive_filename):
# installing
log.warn('Installing Setuptools')
if not _python_cmd('setup.py', 'install', *install_args):
log.warn('Something went wrong during the installation.')
log.warn('See the error message above.')
# exitcode will be 2
return 2 | [
"def",
"_install",
"(",
"archive_filename",
",",
"install_args",
"=",
"(",
")",
")",
":",
"with",
"archive_context",
"(",
"archive_filename",
")",
":",
"# installing",
"log",
".",
"warn",
"(",
"'Installing Setuptools'",
")",
"if",
"not",
"_python_cmd",
"(",
"'... | https://github.com/rrwick/Unicycler/blob/96ffea71e3a78d63ade19d6124946773e65cf129/ez_setup.py#L57-L66 | ||
mapnik/mapnik | f3da900c355e1d15059c4a91b00203dcc9d9f0ef | scons/scons-local-4.1.0/SCons/Tool/MSCommon/common.py | python | read_script_env_cache | () | return envcache | fetch cached msvc env vars if requested, else return empty dict | fetch cached msvc env vars if requested, else return empty dict | [
"fetch",
"cached",
"msvc",
"env",
"vars",
"if",
"requested",
"else",
"return",
"empty",
"dict"
] | def read_script_env_cache():
""" fetch cached msvc env vars if requested, else return empty dict """
envcache = {}
if CONFIG_CACHE:
try:
with open(CONFIG_CACHE, 'r') as f:
envcache = json.load(f)
except FileNotFoundError:
# don't fail if no cache file, just proceed without it
pass
return envcache | [
"def",
"read_script_env_cache",
"(",
")",
":",
"envcache",
"=",
"{",
"}",
"if",
"CONFIG_CACHE",
":",
"try",
":",
"with",
"open",
"(",
"CONFIG_CACHE",
",",
"'r'",
")",
"as",
"f",
":",
"envcache",
"=",
"json",
".",
"load",
"(",
"f",
")",
"except",
"Fil... | https://github.com/mapnik/mapnik/blob/f3da900c355e1d15059c4a91b00203dcc9d9f0ef/scons/scons-local-4.1.0/SCons/Tool/MSCommon/common.py#L95-L105 | |
MythTV/mythtv | d282a209cb8be85d036f85a62a8ec971b67d45f4 | mythtv/contrib/imports/mirobridge/mirobridge.py | python | useImageMagick | (cmd) | return subprocess.call(u'%s > /dev/null' % cmd, shell=True) | Process graphics files using ImageMagick's utility 'mogrify'.
>>> useImageMagick('convert screenshot.jpg -resize 50% screenshot.png')
>>> 0
>>> -1 | Process graphics files using ImageMagick's utility 'mogrify'.
>>> useImageMagick('convert screenshot.jpg -resize 50% screenshot.png')
>>> 0
>>> -1 | [
"Process",
"graphics",
"files",
"using",
"ImageMagick",
"s",
"utility",
"mogrify",
".",
">>>",
"useImageMagick",
"(",
"convert",
"screenshot",
".",
"jpg",
"-",
"resize",
"50%",
"screenshot",
".",
"png",
")",
">>>",
"0",
">>>",
"-",
"1"
] | def useImageMagick(cmd):
""" Process graphics files using ImageMagick's utility 'mogrify'.
>>> useImageMagick('convert screenshot.jpg -resize 50% screenshot.png')
>>> 0
>>> -1
"""
return subprocess.call(u'%s > /dev/null' % cmd, shell=True) | [
"def",
"useImageMagick",
"(",
"cmd",
")",
":",
"return",
"subprocess",
".",
"call",
"(",
"u'%s > /dev/null'",
"%",
"cmd",
",",
"shell",
"=",
"True",
")"
] | https://github.com/MythTV/mythtv/blob/d282a209cb8be85d036f85a62a8ec971b67d45f4/mythtv/contrib/imports/mirobridge/mirobridge.py#L584-L590 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python/src/Lib/cgi.py | python | print_environ | (environ=os.environ) | Dump the shell environment as HTML. | Dump the shell environment as HTML. | [
"Dump",
"the",
"shell",
"environment",
"as",
"HTML",
"."
] | def print_environ(environ=os.environ):
"""Dump the shell environment as HTML."""
keys = environ.keys()
keys.sort()
print
print "<H3>Shell Environment:</H3>"
print "<DL>"
for key in keys:
print "<DT>", escape(key), "<DD>", escape(environ[key])
print "</DL>"
print | [
"def",
"print_environ",
"(",
"environ",
"=",
"os",
".",
"environ",
")",
":",
"keys",
"=",
"environ",
".",
"keys",
"(",
")",
"keys",
".",
"sort",
"(",
")",
"print",
"print",
"\"<H3>Shell Environment:</H3>\"",
"print",
"\"<DL>\"",
"for",
"key",
"in",
"keys",... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/cgi.py#L968-L978 | ||
gem5/gem5 | 141cc37c2d4b93959d4c249b8f7e6a8b2ef75338 | ext/ply/example/ansic/cparse.py | python | p_inclusive_or_expression_2 | (t) | inclusive_or_expression : inclusive_or_expression OR exclusive_or_expression | inclusive_or_expression : inclusive_or_expression OR exclusive_or_expression | [
"inclusive_or_expression",
":",
"inclusive_or_expression",
"OR",
"exclusive_or_expression"
] | def p_inclusive_or_expression_2(t):
'inclusive_or_expression : inclusive_or_expression OR exclusive_or_expression'
pass | [
"def",
"p_inclusive_or_expression_2",
"(",
"t",
")",
":",
"pass"
] | https://github.com/gem5/gem5/blob/141cc37c2d4b93959d4c249b8f7e6a8b2ef75338/ext/ply/example/ansic/cparse.py#L641-L643 | ||
idaholab/moose | 9eeebc65e098b4c30f8205fb41591fd5b61eb6ff | python/peacock/Input/InputFileEditorWithMesh.py | python | InputFileEditorWithMesh.setViewerEnabled | (self, enabled) | Toggles all the graphics widgets
Input:
enabled[bool]: Whether to set them enabled or disabled | Toggles all the graphics widgets
Input:
enabled[bool]: Whether to set them enabled or disabled | [
"Toggles",
"all",
"the",
"graphics",
"widgets",
"Input",
":",
"enabled",
"[",
"bool",
"]",
":",
"Whether",
"to",
"set",
"them",
"enabled",
"or",
"disabled"
] | def setViewerEnabled(self, enabled):
"""
Toggles all the graphics widgets
Input:
enabled[bool]: Whether to set them enabled or disabled
"""
self.BlockHighlighterPlugin.setEnabled(enabled)
self.BackgroundPlugin.setEnabled(enabled) | [
"def",
"setViewerEnabled",
"(",
"self",
",",
"enabled",
")",
":",
"self",
".",
"BlockHighlighterPlugin",
".",
"setEnabled",
"(",
"enabled",
")",
"self",
".",
"BackgroundPlugin",
".",
"setEnabled",
"(",
"enabled",
")"
] | https://github.com/idaholab/moose/blob/9eeebc65e098b4c30f8205fb41591fd5b61eb6ff/python/peacock/Input/InputFileEditorWithMesh.py#L147-L154 | ||
tzutalin/dlib-android | 989627cb7fe81cd1d41d73434b0e91ce1dd2683f | tools/lint/cpplint.py | python | _FunctionState.Begin | (self, function_name) | Start analyzing function body.
Args:
function_name: The name of the function being tracked. | Start analyzing function body.
Args:
function_name: The name of the function being tracked. | [
"Start",
"analyzing",
"function",
"body",
".",
"Args",
":",
"function_name",
":",
"The",
"name",
"of",
"the",
"function",
"being",
"tracked",
"."
] | def Begin(self, function_name):
"""Start analyzing function body.
Args:
function_name: The name of the function being tracked.
"""
self.in_a_function = True
self.lines_in_function = 0
self.current_function = function_name | [
"def",
"Begin",
"(",
"self",
",",
"function_name",
")",
":",
"self",
".",
"in_a_function",
"=",
"True",
"self",
".",
"lines_in_function",
"=",
"0",
"self",
".",
"current_function",
"=",
"function_name"
] | https://github.com/tzutalin/dlib-android/blob/989627cb7fe81cd1d41d73434b0e91ce1dd2683f/tools/lint/cpplint.py#L955-L962 | ||
cvxpy/cvxpy | 5165b4fb750dfd237de8659383ef24b4b2e33aaf | cvxpy/expressions/expression.py | python | Expression.is_scalar | (self) | return all(d == 1 for d in self.shape) | Is the expression a scalar? | Is the expression a scalar? | [
"Is",
"the",
"expression",
"a",
"scalar?"
] | def is_scalar(self) -> bool:
"""Is the expression a scalar?
"""
return all(d == 1 for d in self.shape) | [
"def",
"is_scalar",
"(",
"self",
")",
"->",
"bool",
":",
"return",
"all",
"(",
"d",
"==",
"1",
"for",
"d",
"in",
"self",
".",
"shape",
")"
] | https://github.com/cvxpy/cvxpy/blob/5165b4fb750dfd237de8659383ef24b4b2e33aaf/cvxpy/expressions/expression.py#L405-L408 | |
PX4/PX4-Autopilot | 0b9f60a0370be53d683352c63fd92db3d6586e18 | Tools/mavlink_px4.py | python | MAVLink.file_transfer_start_send | (self, transfer_uid, dest_path, direction, file_size, flags) | return self.send(self.file_transfer_start_encode(transfer_uid, dest_path, direction, file_size, flags)) | Begin file transfer
transfer_uid : Unique transfer ID (uint64_t)
dest_path : Destination path (char)
direction : Transfer direction: 0: from requester, 1: to requester (uint8_t)
file_size : File size in bytes (uint32_t)
flags : RESERVED (uint8_t) | Begin file transfer | [
"Begin",
"file",
"transfer"
] | def file_transfer_start_send(self, transfer_uid, dest_path, direction, file_size, flags):
'''
Begin file transfer
transfer_uid : Unique transfer ID (uint64_t)
dest_path : Destination path (char)
direction : Transfer direction: 0: from requester, 1: to requester (uint8_t)
file_size : File size in bytes (uint32_t)
flags : RESERVED (uint8_t)
'''
return self.send(self.file_transfer_start_encode(transfer_uid, dest_path, direction, file_size, flags)) | [
"def",
"file_transfer_start_send",
"(",
"self",
",",
"transfer_uid",
",",
"dest_path",
",",
"direction",
",",
"file_size",
",",
"flags",
")",
":",
"return",
"self",
".",
"send",
"(",
"self",
".",
"file_transfer_start_encode",
"(",
"transfer_uid",
",",
"dest_path... | https://github.com/PX4/PX4-Autopilot/blob/0b9f60a0370be53d683352c63fd92db3d6586e18/Tools/mavlink_px4.py#L4928-L4939 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/_windows.py | python | VListBox.DeselectAll | (*args, **kwargs) | return _windows_.VListBox_DeselectAll(*args, **kwargs) | DeselectAll(self) -> bool | DeselectAll(self) -> bool | [
"DeselectAll",
"(",
"self",
")",
"-",
">",
"bool"
] | def DeselectAll(*args, **kwargs):
"""DeselectAll(self) -> bool"""
return _windows_.VListBox_DeselectAll(*args, **kwargs) | [
"def",
"DeselectAll",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_windows_",
".",
"VListBox_DeselectAll",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_windows.py#L2676-L2678 | |
FreeCAD/FreeCAD | ba42231b9c6889b89e064d6d563448ed81e376ec | src/Mod/Fem/ObjectsFem.py | python | makeResultMechanical | (
doc,
name="ResultMechanical"
) | return obj | makeResultMechanical(document, [name]):
creates a mechanical result object to hold FEM results | makeResultMechanical(document, [name]):
creates a mechanical result object to hold FEM results | [
"makeResultMechanical",
"(",
"document",
"[",
"name",
"]",
")",
":",
"creates",
"a",
"mechanical",
"result",
"object",
"to",
"hold",
"FEM",
"results"
] | def makeResultMechanical(
doc,
name="ResultMechanical"
):
"""makeResultMechanical(document, [name]):
creates a mechanical result object to hold FEM results"""
obj = doc.addObject("Fem::FemResultObjectPython", name)
from femobjects import result_mechanical
result_mechanical.ResultMechanical(obj)
if FreeCAD.GuiUp:
from femviewprovider import view_result_mechanical
view_result_mechanical.VPResultMechanical(obj.ViewObject)
return obj | [
"def",
"makeResultMechanical",
"(",
"doc",
",",
"name",
"=",
"\"ResultMechanical\"",
")",
":",
"obj",
"=",
"doc",
".",
"addObject",
"(",
"\"Fem::FemResultObjectPython\"",
",",
"name",
")",
"from",
"femobjects",
"import",
"result_mechanical",
"result_mechanical",
"."... | https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/Fem/ObjectsFem.py#L603-L615 | |
google/mozc | 7329757e1ad30e327c1ae823a8302c79482d6b9c | src/rewriter/gen_single_kanji_rewriter_data.py | python | ReadSingleKanji | (stream) | return outputs | Parses single kanji dictionary data from stream. | Parses single kanji dictionary data from stream. | [
"Parses",
"single",
"kanji",
"dictionary",
"data",
"from",
"stream",
"."
] | def ReadSingleKanji(stream):
"""Parses single kanji dictionary data from stream."""
stream = code_generator_util.SkipLineComment(stream)
stream = code_generator_util.ParseColumnStream(stream, num_column=2)
outputs = list(stream)
# For binary search by |key|, sort outputs here.
outputs.sort(key=lambda x: x[0])
return outputs | [
"def",
"ReadSingleKanji",
"(",
"stream",
")",
":",
"stream",
"=",
"code_generator_util",
".",
"SkipLineComment",
"(",
"stream",
")",
"stream",
"=",
"code_generator_util",
".",
"ParseColumnStream",
"(",
"stream",
",",
"num_column",
"=",
"2",
")",
"outputs",
"=",
... | https://github.com/google/mozc/blob/7329757e1ad30e327c1ae823a8302c79482d6b9c/src/rewriter/gen_single_kanji_rewriter_data.py#L50-L58 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numpy/lib/function_base.py | python | extract | (condition, arr) | return _nx.take(ravel(arr), nonzero(ravel(condition))[0]) | Return the elements of an array that satisfy some condition.
This is equivalent to ``np.compress(ravel(condition), ravel(arr))``. If
`condition` is boolean ``np.extract`` is equivalent to ``arr[condition]``.
Note that `place` does the exact opposite of `extract`.
Parameters
----------
condition : array_like
An array whose nonzero or True entries indicate the elements of `arr`
to extract.
arr : array_like
Input array of the same size as `condition`.
Returns
-------
extract : ndarray
Rank 1 array of values from `arr` where `condition` is True.
See Also
--------
take, put, copyto, compress, place
Examples
--------
>>> arr = np.arange(12).reshape((3, 4))
>>> arr
array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]])
>>> condition = np.mod(arr, 3)==0
>>> condition
array([[ True, False, False, True],
[False, False, True, False],
[False, True, False, False]])
>>> np.extract(condition, arr)
array([0, 3, 6, 9])
If `condition` is boolean:
>>> arr[condition]
array([0, 3, 6, 9]) | Return the elements of an array that satisfy some condition. | [
"Return",
"the",
"elements",
"of",
"an",
"array",
"that",
"satisfy",
"some",
"condition",
"."
] | def extract(condition, arr):
"""
Return the elements of an array that satisfy some condition.
This is equivalent to ``np.compress(ravel(condition), ravel(arr))``. If
`condition` is boolean ``np.extract`` is equivalent to ``arr[condition]``.
Note that `place` does the exact opposite of `extract`.
Parameters
----------
condition : array_like
An array whose nonzero or True entries indicate the elements of `arr`
to extract.
arr : array_like
Input array of the same size as `condition`.
Returns
-------
extract : ndarray
Rank 1 array of values from `arr` where `condition` is True.
See Also
--------
take, put, copyto, compress, place
Examples
--------
>>> arr = np.arange(12).reshape((3, 4))
>>> arr
array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]])
>>> condition = np.mod(arr, 3)==0
>>> condition
array([[ True, False, False, True],
[False, False, True, False],
[False, True, False, False]])
>>> np.extract(condition, arr)
array([0, 3, 6, 9])
If `condition` is boolean:
>>> arr[condition]
array([0, 3, 6, 9])
"""
return _nx.take(ravel(arr), nonzero(ravel(condition))[0]) | [
"def",
"extract",
"(",
"condition",
",",
"arr",
")",
":",
"return",
"_nx",
".",
"take",
"(",
"ravel",
"(",
"arr",
")",
",",
"nonzero",
"(",
"ravel",
"(",
"condition",
")",
")",
"[",
"0",
"]",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numpy/lib/function_base.py#L1629-L1677 | |
ucbrise/clipper | 9f25e3fc7f8edc891615e81c5b80d3d8aed72608 | clipper_admin/clipper_admin/docker/docker_metric_utils.py | python | _get_prometheus_base_config | () | return conf | Generate a basic configuration dictionary for prometheus
:return: dictionary | Generate a basic configuration dictionary for prometheus
:return: dictionary | [
"Generate",
"a",
"basic",
"configuration",
"dictionary",
"for",
"prometheus",
":",
"return",
":",
"dictionary"
] | def _get_prometheus_base_config():
"""
Generate a basic configuration dictionary for prometheus
:return: dictionary
"""
conf = dict()
conf['global'] = {'evaluation_interval': '5s', 'scrape_interval': '5s'}
conf['scrape_configs'] = []
return conf | [
"def",
"_get_prometheus_base_config",
"(",
")",
":",
"conf",
"=",
"dict",
"(",
")",
"conf",
"[",
"'global'",
"]",
"=",
"{",
"'evaluation_interval'",
":",
"'5s'",
",",
"'scrape_interval'",
":",
"'5s'",
"}",
"conf",
"[",
"'scrape_configs'",
"]",
"=",
"[",
"]... | https://github.com/ucbrise/clipper/blob/9f25e3fc7f8edc891615e81c5b80d3d8aed72608/clipper_admin/clipper_admin/docker/docker_metric_utils.py#L10-L18 | |
wujixiu/helmet-detection | 8eff5c59ddfba5a29e0b76aeb48babcb49246178 | hardhat-wearing-detection/SSD-RPA/python/caffe/pycaffe.py | python | _Net_forward_all | (self, blobs=None, **kwargs) | return all_outs | Run net forward in batches.
Parameters
----------
blobs : list of blobs to extract as in forward()
kwargs : Keys are input blob names and values are blob ndarrays.
Refer to forward().
Returns
-------
all_outs : {blob name: list of blobs} dict. | Run net forward in batches. | [
"Run",
"net",
"forward",
"in",
"batches",
"."
] | def _Net_forward_all(self, blobs=None, **kwargs):
"""
Run net forward in batches.
Parameters
----------
blobs : list of blobs to extract as in forward()
kwargs : Keys are input blob names and values are blob ndarrays.
Refer to forward().
Returns
-------
all_outs : {blob name: list of blobs} dict.
"""
# Collect outputs from batches
all_outs = {out: [] for out in set(self.outputs + (blobs or []))}
for batch in self._batch(kwargs):
outs = self.forward(blobs=blobs, **batch)
for out, out_blob in six.iteritems(outs):
all_outs[out].extend(out_blob.copy())
# Package in ndarray.
for out in all_outs:
all_outs[out] = np.asarray(all_outs[out])
# Discard padding.
pad = len(six.next(six.itervalues(all_outs))) - len(six.next(six.itervalues(kwargs)))
if pad:
for out in all_outs:
all_outs[out] = all_outs[out][:-pad]
return all_outs | [
"def",
"_Net_forward_all",
"(",
"self",
",",
"blobs",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"# Collect outputs from batches",
"all_outs",
"=",
"{",
"out",
":",
"[",
"]",
"for",
"out",
"in",
"set",
"(",
"self",
".",
"outputs",
"+",
"(",
"blobs... | https://github.com/wujixiu/helmet-detection/blob/8eff5c59ddfba5a29e0b76aeb48babcb49246178/hardhat-wearing-detection/SSD-RPA/python/caffe/pycaffe.py#L175-L203 | |
nnrg/opennero | 43e12a1bcba6e228639db3886fec1dc47ddc24cb | mods/Maze/environment.py | python | EgocentricMazeEnvironment.reset | (self, agent) | return True | reset the environment to its initial state | reset the environment to its initial state | [
"reset",
"the",
"environment",
"to",
"its",
"initial",
"state"
] | def reset(self, agent):
"""
reset the environment to its initial state
"""
print 'Episode %d complete' % agent.episode
if not self.prepare_for_new_episode:
self.generate_init_pos()
self.prepare_for_new_episode = False
(r, c) = self.init_pos
(x, y) = MazeEnvironment.maze.rc2xy(r, c)
agent.state.position = Vector3f(x,y,0)
agent.state.rotation = Vector3f(0,0,0)
self.agents_at_goal.discard(agent)
print 'Episode %d complete' % agent.episode
return True | [
"def",
"reset",
"(",
"self",
",",
"agent",
")",
":",
"print",
"'Episode %d complete'",
"%",
"agent",
".",
"episode",
"if",
"not",
"self",
".",
"prepare_for_new_episode",
":",
"self",
".",
"generate_init_pos",
"(",
")",
"self",
".",
"prepare_for_new_episode",
"... | https://github.com/nnrg/opennero/blob/43e12a1bcba6e228639db3886fec1dc47ddc24cb/mods/Maze/environment.py#L460-L475 | |
GJDuck/LowFat | ecf6a0f0fa1b73a27a626cf493cc39e477b6faea | llvm-4.0.0.src/projects/compiler-rt/lib/sanitizer_common/scripts/cpplint.py | python | GetHeaderGuardCPPVariable | (filename) | return re.sub(r'[-./\s]', '_', file_path_from_root).upper() + '_' | Returns the CPP variable that should be used as a header guard.
Args:
filename: The name of a C++ header file.
Returns:
The CPP variable that should be used as a header guard in the
named file. | Returns the CPP variable that should be used as a header guard. | [
"Returns",
"the",
"CPP",
"variable",
"that",
"should",
"be",
"used",
"as",
"a",
"header",
"guard",
"."
] | def GetHeaderGuardCPPVariable(filename):
"""Returns the CPP variable that should be used as a header guard.
Args:
filename: The name of a C++ header file.
Returns:
The CPP variable that should be used as a header guard in the
named file.
"""
# Restores original filename in case that cpplint is invoked from Emacs's
# flymake.
filename = re.sub(r'_flymake\.h$', '.h', filename)
filename = re.sub(r'/\.flymake/([^/]*)$', r'/\1', filename)
fileinfo = FileInfo(filename)
file_path_from_root = fileinfo.RepositoryName()
if _root:
file_path_from_root = re.sub('^' + _root + os.sep, '', file_path_from_root)
return re.sub(r'[-./\s]', '_', file_path_from_root).upper() + '_' | [
"def",
"GetHeaderGuardCPPVariable",
"(",
"filename",
")",
":",
"# Restores original filename in case that cpplint is invoked from Emacs's",
"# flymake.",
"filename",
"=",
"re",
".",
"sub",
"(",
"r'_flymake\\.h$'",
",",
"'.h'",
",",
"filename",
")",
"filename",
"=",
"re",
... | https://github.com/GJDuck/LowFat/blob/ecf6a0f0fa1b73a27a626cf493cc39e477b6faea/llvm-4.0.0.src/projects/compiler-rt/lib/sanitizer_common/scripts/cpplint.py#L1111-L1132 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/dataview.py | python | DataViewCtrl.ClearColumns | (*args, **kwargs) | return _dataview.DataViewCtrl_ClearColumns(*args, **kwargs) | ClearColumns(self) -> bool | ClearColumns(self) -> bool | [
"ClearColumns",
"(",
"self",
")",
"-",
">",
"bool"
] | def ClearColumns(*args, **kwargs):
"""ClearColumns(self) -> bool"""
return _dataview.DataViewCtrl_ClearColumns(*args, **kwargs) | [
"def",
"ClearColumns",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_dataview",
".",
"DataViewCtrl_ClearColumns",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/dataview.py#L1719-L1721 | |
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/seq2seq/python/ops/decoder.py | python | BaseDecoder.output_dtype | (self) | A (possibly nested tuple of...) dtype[s]. | A (possibly nested tuple of...) dtype[s]. | [
"A",
"(",
"possibly",
"nested",
"tuple",
"of",
"...",
")",
"dtype",
"[",
"s",
"]",
"."
] | def output_dtype(self):
"""A (possibly nested tuple of...) dtype[s]."""
raise NotImplementedError | [
"def",
"output_dtype",
"(",
"self",
")",
":",
"raise",
"NotImplementedError"
] | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/seq2seq/python/ops/decoder.py#L206-L208 | ||
microsoft/onnxruntime | f92e47e95b13a240e37caf7b36577983544f98fc | onnxruntime/python/onnxruntime_inference_collection.py | python | Session.set_providers | (self, providers=None, provider_options=None) | Register the input list of execution providers. The underlying session is re-created.
:param providers: Optional sequence of providers in order of decreasing
precedence. Values can either be provider names or tuples of
(provider name, options dict). If not provided, then all available
providers are used with the default precedence.
:param provider_options: Optional sequence of options dicts corresponding
to the providers listed in 'providers'.
'providers' can contain either names or names and options. When any options
are given in 'providers', 'provider_options' should not be used.
The list of providers is ordered by precedence. For example
`['CUDAExecutionProvider', 'CPUExecutionProvider']`
means execute a node using CUDAExecutionProvider if capable,
otherwise execute using CPUExecutionProvider. | Register the input list of execution providers. The underlying session is re-created. | [
"Register",
"the",
"input",
"list",
"of",
"execution",
"providers",
".",
"The",
"underlying",
"session",
"is",
"re",
"-",
"created",
"."
] | def set_providers(self, providers=None, provider_options=None):
"""
Register the input list of execution providers. The underlying session is re-created.
:param providers: Optional sequence of providers in order of decreasing
precedence. Values can either be provider names or tuples of
(provider name, options dict). If not provided, then all available
providers are used with the default precedence.
:param provider_options: Optional sequence of options dicts corresponding
to the providers listed in 'providers'.
'providers' can contain either names or names and options. When any options
are given in 'providers', 'provider_options' should not be used.
The list of providers is ordered by precedence. For example
`['CUDAExecutionProvider', 'CPUExecutionProvider']`
means execute a node using CUDAExecutionProvider if capable,
otherwise execute using CPUExecutionProvider.
"""
# recreate the underlying C.InferenceSession
self._reset_session(providers, provider_options) | [
"def",
"set_providers",
"(",
"self",
",",
"providers",
"=",
"None",
",",
"provider_options",
"=",
"None",
")",
":",
"# recreate the underlying C.InferenceSession",
"self",
".",
"_reset_session",
"(",
"providers",
",",
"provider_options",
")"
] | https://github.com/microsoft/onnxruntime/blob/f92e47e95b13a240e37caf7b36577983544f98fc/onnxruntime/python/onnxruntime_inference_collection.py#L135-L155 | ||
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | scripts/Inelastic/Direct/RunDescriptor.py | python | RunDescriptor.file_hint | (self,run_num_str=None,filePath=None,fileExt=None,**kwargs) | return hint,old_ext | Procedure to provide run file guess name from run properties
main purpose -- to support customized order of file extensions | Procedure to provide run file guess name from run properties | [
"Procedure",
"to",
"provide",
"run",
"file",
"guess",
"name",
"from",
"run",
"properties"
] | def file_hint(self,run_num_str=None,filePath=None,fileExt=None,**kwargs):
"""Procedure to provide run file guess name from run properties
main purpose -- to support customized order of file extensions
"""
if not run_num_str:
run_num_str = str(self.run_number())
inst_name = RunDescriptor._holder.short_inst_name
if 'file_hint' in kwargs:
hint = kwargs['file_hint']
fname,old_ext = os.path.splitext(hint)
if len(old_ext) == 0:
old_ext = self.get_fext()
fname = hint
else:
old_ext = self.get_fext()
if fileExt is None:
fileExt = old_ext
if filePath is None:
filePath = self._run_file_path
fname = build_run_file_name(run_num_str,inst_name,filePath,fileExt)
if os.path.exists(fname):
return fname,old_ext
else:
#pylint: disable=unused-variable
fp,hint = os.path.split(fname)
return hint,old_ext | [
"def",
"file_hint",
"(",
"self",
",",
"run_num_str",
"=",
"None",
",",
"filePath",
"=",
"None",
",",
"fileExt",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"run_num_str",
":",
"run_num_str",
"=",
"str",
"(",
"self",
".",
"run_number",
... | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/scripts/Inelastic/Direct/RunDescriptor.py#L1002-L1030 | |
oracle/graaljs | 36a56e8e993d45fc40939a3a4d9c0c24990720f1 | graal-nodejs/deps/v8/third_party/jinja2/filters.py | python | evalcontextfilter | (f) | return f | Decorator for marking eval-context dependent filters. An eval
context object is passed as first argument. For more information
about the eval context, see :ref:`eval-context`.
.. versionadded:: 2.4 | Decorator for marking eval-context dependent filters. An eval
context object is passed as first argument. For more information
about the eval context, see :ref:`eval-context`. | [
"Decorator",
"for",
"marking",
"eval",
"-",
"context",
"dependent",
"filters",
".",
"An",
"eval",
"context",
"object",
"is",
"passed",
"as",
"first",
"argument",
".",
"For",
"more",
"information",
"about",
"the",
"eval",
"context",
"see",
":",
"ref",
":",
... | def evalcontextfilter(f):
"""Decorator for marking eval-context dependent filters. An eval
context object is passed as first argument. For more information
about the eval context, see :ref:`eval-context`.
.. versionadded:: 2.4
"""
f.evalcontextfilter = True
return f | [
"def",
"evalcontextfilter",
"(",
"f",
")",
":",
"f",
".",
"evalcontextfilter",
"=",
"True",
"return",
"f"
] | https://github.com/oracle/graaljs/blob/36a56e8e993d45fc40939a3a4d9c0c24990720f1/graal-nodejs/deps/v8/third_party/jinja2/filters.py#L37-L45 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/encodings/zlib_codec.py | python | zlib_decode | (input,errors='strict') | return (output, len(input)) | Decodes the object input and returns a tuple (output
object, length consumed).
input must be an object which provides the bf_getreadbuf
buffer slot. Python strings, buffer objects and memory
mapped files are examples of objects providing this slot.
errors defines the error handling to apply. It defaults to
'strict' handling which is the only currently supported
error handling for this codec. | Decodes the object input and returns a tuple (output
object, length consumed). | [
"Decodes",
"the",
"object",
"input",
"and",
"returns",
"a",
"tuple",
"(",
"output",
"object",
"length",
"consumed",
")",
"."
] | def zlib_decode(input,errors='strict'):
""" Decodes the object input and returns a tuple (output
object, length consumed).
input must be an object which provides the bf_getreadbuf
buffer slot. Python strings, buffer objects and memory
mapped files are examples of objects providing this slot.
errors defines the error handling to apply. It defaults to
'strict' handling which is the only currently supported
error handling for this codec.
"""
assert errors == 'strict'
output = zlib.decompress(input)
return (output, len(input)) | [
"def",
"zlib_decode",
"(",
"input",
",",
"errors",
"=",
"'strict'",
")",
":",
"assert",
"errors",
"==",
"'strict'",
"output",
"=",
"zlib",
".",
"decompress",
"(",
"input",
")",
"return",
"(",
"output",
",",
"len",
"(",
"input",
")",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/encodings/zlib_codec.py#L28-L44 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/AWSPythonSDK/1.5.8/botocore/vendored/requests/packages/urllib3/_collections.py | python | HTTPHeaderDict.getlist | (self, key) | Returns a list of all the values for the named field. Returns an
empty list if the key doesn't exist. | Returns a list of all the values for the named field. Returns an
empty list if the key doesn't exist. | [
"Returns",
"a",
"list",
"of",
"all",
"the",
"values",
"for",
"the",
"named",
"field",
".",
"Returns",
"an",
"empty",
"list",
"if",
"the",
"key",
"doesn",
"t",
"exist",
"."
] | def getlist(self, key):
"""Returns a list of all the values for the named field. Returns an
empty list if the key doesn't exist."""
try:
vals = _dict_getitem(self, key.lower())
except KeyError:
return []
else:
if isinstance(vals, tuple):
return [vals[1]]
else:
return vals[1:] | [
"def",
"getlist",
"(",
"self",
",",
"key",
")",
":",
"try",
":",
"vals",
"=",
"_dict_getitem",
"(",
"self",
",",
"key",
".",
"lower",
"(",
")",
")",
"except",
"KeyError",
":",
"return",
"[",
"]",
"else",
":",
"if",
"isinstance",
"(",
"vals",
",",
... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/AWSPythonSDK/1.5.8/botocore/vendored/requests/packages/urllib3/_collections.py#L256-L267 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/tools/Editra/src/extern/pubsub.py | python | _TopicTreeRoot.__getTreeNode | (self, topic, make=False) | return node | Return the tree node for 'topic' from the topic tree. If it
doesnt exist and make=True, create it first. | Return the tree node for 'topic' from the topic tree. If it
doesnt exist and make=True, create it first. | [
"Return",
"the",
"tree",
"node",
"for",
"topic",
"from",
"the",
"topic",
"tree",
".",
"If",
"it",
"doesnt",
"exist",
"and",
"make",
"=",
"True",
"create",
"it",
"first",
"."
] | def __getTreeNode(self, topic, make=False):
"""Return the tree node for 'topic' from the topic tree. If it
doesnt exist and make=True, create it first."""
# if the all-topics, give root;
if topic == (ALL_TOPICS,):
return self
# not root, so traverse tree
node = self
path = ()
for topicItem in topic:
path += (topicItem,)
if topicItem == ALL_TOPICS:
raise ValueError, 'Topic tuple must not contain ""'
if make:
node = node.createSubtopic(topicItem, path)
elif node.hasSubtopic(topicItem):
node = node.getNode(topicItem)
else:
return None
# done
return node | [
"def",
"__getTreeNode",
"(",
"self",
",",
"topic",
",",
"make",
"=",
"False",
")",
":",
"# if the all-topics, give root; ",
"if",
"topic",
"==",
"(",
"ALL_TOPICS",
",",
")",
":",
"return",
"self",
"# not root, so traverse tree",
"node",
"=",
"self",
"path",
"=... | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/extern/pubsub.py#L514-L535 | |
CGRU/cgru | 1881a4128530e3d31ac6c25314c18314fc50c2c7 | afanasy/python/af.py | python | Block.setMaxRunningTasks | (self, value) | Missing DocString
:param value:
:return: | Missing DocString | [
"Missing",
"DocString"
] | def setMaxRunningTasks(self, value):
"""Missing DocString
:param value:
:return:
"""
if value >= 0:
self.data["max_running_tasks"] = int(value) | [
"def",
"setMaxRunningTasks",
"(",
"self",
",",
"value",
")",
":",
"if",
"value",
">=",
"0",
":",
"self",
".",
"data",
"[",
"\"max_running_tasks\"",
"]",
"=",
"int",
"(",
"value",
")"
] | https://github.com/CGRU/cgru/blob/1881a4128530e3d31ac6c25314c18314fc50c2c7/afanasy/python/af.py#L433-L440 | ||
RGF-team/rgf | 272afb85b4c91571f576e5fc83ecfacce3672eb4 | python-package/rgf/utils.py | python | RGFClassifierMixin.fit | (self, X, y, sample_weight=None) | return self | Build a classifier from the training set (X, y).
Parameters
----------
X : array-like or sparse matrix of shape = [n_samples, n_features]
The training input samples.
y : array-like, shape = [n_samples]
The target values (class labels in classification).
sample_weight : array-like, shape = [n_samples] or None
Individual weights for each sample.
Returns
-------
self : object
Returns self. | Build a classifier from the training set (X, y). | [
"Build",
"a",
"classifier",
"from",
"the",
"training",
"set",
"(",
"X",
"y",
")",
"."
] | def fit(self, X, y, sample_weight=None):
"""
Build a classifier from the training set (X, y).
Parameters
----------
X : array-like or sparse matrix of shape = [n_samples, n_features]
The training input samples.
y : array-like, shape = [n_samples]
The target values (class labels in classification).
sample_weight : array-like, shape = [n_samples] or None
Individual weights for each sample.
Returns
-------
self : object
Returns self.
"""
self._validate_params(**self.get_params())
X, y = check_X_y(X, y, accept_sparse=True)
if sp.isspmatrix(X):
self._is_sparse_train_X = True
else:
self._is_sparse_train_X = False
self._n_samples, self._n_features = X.shape
sample_weight = self._get_sample_weight(sample_weight)
check_consistent_length(X, y, sample_weight)
check_classification_targets(y)
self._classes = sorted(np.unique(y))
self._n_classes = len(self._classes)
self._classes_map = {}
self._set_params_with_dependencies()
params = self._get_params()
if self._n_classes == 2:
self._classes_map[0] = self._classes[0]
self._classes_map[1] = self._classes[1]
self._estimators = [None]
y = (y == self._classes[0]).astype(int)
self._fit_binary_task(X, y, sample_weight, params)
elif self._n_classes > 2:
if sp.isspmatrix_dok(X):
X = X.tocsr().tocoo() # Fix to avoid scipy 7699 issue
self._estimators = [None] * self._n_classes
self._fit_multiclass_task(X, y, sample_weight, params)
else:
raise ValueError("Classifier can't predict when only one class is present.")
self._fitted = True
self.n_features_in_ = self._n_features
return self | [
"def",
"fit",
"(",
"self",
",",
"X",
",",
"y",
",",
"sample_weight",
"=",
"None",
")",
":",
"self",
".",
"_validate_params",
"(",
"*",
"*",
"self",
".",
"get_params",
"(",
")",
")",
"X",
",",
"y",
"=",
"check_X_y",
"(",
"X",
",",
"y",
",",
"acc... | https://github.com/RGF-team/rgf/blob/272afb85b4c91571f576e5fc83ecfacce3672eb4/python-package/rgf/utils.py#L512-L567 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/pydoc.py | python | HTMLDoc.heading | (self, title, fgcol, bgcol, extras='') | return '''
<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="heading">
<tr bgcolor="%s">
<td valign=bottom> <br>
<font color="%s" face="helvetica, arial"> <br>%s</font></td
><td align=right valign=bottom
><font color="%s" face="helvetica, arial">%s</font></td></tr></table>
''' % (bgcol, fgcol, title, fgcol, extras or ' ') | Format a page heading. | Format a page heading. | [
"Format",
"a",
"page",
"heading",
"."
] | def heading(self, title, fgcol, bgcol, extras=''):
"""Format a page heading."""
return '''
<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="heading">
<tr bgcolor="%s">
<td valign=bottom> <br>
<font color="%s" face="helvetica, arial"> <br>%s</font></td
><td align=right valign=bottom
><font color="%s" face="helvetica, arial">%s</font></td></tr></table>
''' % (bgcol, fgcol, title, fgcol, extras or ' ') | [
"def",
"heading",
"(",
"self",
",",
"title",
",",
"fgcol",
",",
"bgcol",
",",
"extras",
"=",
"''",
")",
":",
"return",
"'''\n<table width=\"100%%\" cellspacing=0 cellpadding=2 border=0 summary=\"heading\">\n<tr bgcolor=\"%s\">\n<td valign=bottom> <br>\n<font color=\"%s\" face=... | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/pydoc.py#L434-L443 | |
mindspore-ai/mindspore | fb8fd3338605bb34fa5cea054e535a8b1d753fab | mindspore/python/mindspore/dataset/engine/offload.py | python | apply_offload_iterators | (data, offload_model) | return data | Apply offload for non sink mode pipeline. | Apply offload for non sink mode pipeline. | [
"Apply",
"offload",
"for",
"non",
"sink",
"mode",
"pipeline",
"."
] | def apply_offload_iterators(data, offload_model):
"""
Apply offload for non sink mode pipeline.
"""
if len(data) != 2:
# A temporary solution to ensure there are two columns in dataset.
raise RuntimeError("Offload can currently only use datasets with two columns.")
if isinstance(data[0], Tensor) is True:
data[0] = offload_model(data[0])
else:
data[0] = Tensor(data[0], dtype=mstype.float32)
data[0] = offload_model(data[0]).asnumpy()
return data | [
"def",
"apply_offload_iterators",
"(",
"data",
",",
"offload_model",
")",
":",
"if",
"len",
"(",
"data",
")",
"!=",
"2",
":",
"# A temporary solution to ensure there are two columns in dataset.",
"raise",
"RuntimeError",
"(",
"\"Offload can currently only use datasets with tw... | https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/dataset/engine/offload.py#L41-L54 | |
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | docs/sphinxext/mantiddoc/directives/base.py | python | AlgorithmBaseDirective.run | (self) | return nodes | The main entry point that docutils calls.
It calls self.execute to do the main work. If an
algorithm doesn't exist then the directive is
skipped a debug message is emitted
Derived classes should override execute() and insert
whatever rst they require with self.add_rst() | The main entry point that docutils calls.
It calls self.execute to do the main work. If an
algorithm doesn't exist then the directive is
skipped a debug message is emitted | [
"The",
"main",
"entry",
"point",
"that",
"docutils",
"calls",
".",
"It",
"calls",
"self",
".",
"execute",
"to",
"do",
"the",
"main",
"work",
".",
"If",
"an",
"algorithm",
"doesn",
"t",
"exist",
"then",
"the",
"directive",
"is",
"skipped",
"a",
"debug",
... | def run(self):
"""
The main entry point that docutils calls.
It calls self.execute to do the main work. If an
algorithm doesn't exist then the directive is
skipped a debug message is emitted
Derived classes should override execute() and insert
whatever rst they require with self.add_rst()
"""
nodes = []
skip_msg = self.skip()
if skip_msg != "":
self.add_rst("**ERROR: %s**" % skip_msg)
else:
nodes = self.execute()
if self.rst_lines is not None:
self.commit_rst()
return nodes | [
"def",
"run",
"(",
"self",
")",
":",
"nodes",
"=",
"[",
"]",
"skip_msg",
"=",
"self",
".",
"skip",
"(",
")",
"if",
"skip_msg",
"!=",
"\"\"",
":",
"self",
".",
"add_rst",
"(",
"\"**ERROR: %s**\"",
"%",
"skip_msg",
")",
"else",
":",
"nodes",
"=",
"se... | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/docs/sphinxext/mantiddoc/directives/base.py#L150-L169 | |
isc-projects/kea | c5836c791b63f42173bb604dd5f05d7110f3e716 | hammer.py | python | prepare_system_local | (features, check_times) | Prepare local system for Kea development based on requested features. | Prepare local system for Kea development based on requested features. | [
"Prepare",
"local",
"system",
"for",
"Kea",
"development",
"based",
"on",
"requested",
"features",
"."
] | def prepare_system_local(features, check_times):
"""Prepare local system for Kea development based on requested features."""
env = os.environ.copy()
env['LANGUAGE'] = env['LANG'] = env['LC_ALL'] = 'C'
# Actions decided before installing packages, but run afterwards
deferred_functions = []
system, revision = get_system_revision()
log.info('Preparing deps for %s %s', system, revision)
# prepare fedora
if system == 'fedora':
packages = ['make', 'autoconf', 'automake', 'libtool', 'gcc-c++', 'openssl-devel',
'log4cplus-devel', 'boost-devel', 'libpcap-devel', 'python3-virtualenv']
if 'native-pkg' in features:
packages.extend(['rpm-build', 'python3-devel'])
if 'docs' in features:
packages.extend(['python3-sphinx', 'texlive', 'texlive-collection-latexextra'])
if int(revision) >= 31:
packages.extend(['python3-sphinx_rtd_theme'])
if 'mysql' in features:
execute('sudo dnf remove -y community-mysql-devel || true')
packages.extend(['mariadb', 'mariadb-server', 'mariadb-connector-c-devel'])
if 'pgsql' in features:
packages.extend(['postgresql-devel', 'postgresql-server'])
if int(revision) >= 30:
packages.extend(['postgresql-server-devel'])
if 'radius' in features:
packages.extend(['git'])
if 'gssapi' in features:
packages.extend(['krb5-devel'])
if 'ccache' in features:
packages.extend(['ccache'])
if 'netconf' in features:
if int(revision) <= 33:
packages.extend(['cmake', 'pcre-devel'])
deferred_functions.extend([
_install_libyang_from_sources,
_install_sysrepo_from_sources,
])
else:
packages.extend(['cmake', 'libyang', 'libyang-devel', 'libyang-cpp', 'libyang-cpp-devel'])
deferred_functions.append(_install_sysrepo_from_sources)
install_pkgs(packages, timeout=300, env=env, check_times=check_times)
if 'unittest' in features:
_install_gtest_sources()
execute('sudo dnf clean packages', env=env, check_times=check_times)
if 'cql' in features:
_install_cassandra_rpm(system, revision, env, check_times)
# prepare centos
elif system == 'centos':
install_pkgs('epel-release', env=env, check_times=check_times)
packages = ['autoconf', 'automake', 'boost-devel', 'gcc-c++',
'libtool', 'log4cplus-devel', 'make', 'mariadb-devel',
'openssl-devel', 'postgresql-devel']
if revision == '7':
# Install newer version of Boost in case users want to opt-in with:
# --with-boost-include=/usr/include/boost169 --with-boost-lib-dir=/usr/lib64/boost169
packages.append('boost169-devel')
if 'native-pkg' in features:
packages.extend(['rpm-build', 'python3-devel'])
if 'docs' in features:
packages.extend(['python3-virtualenv'])
if 'mysql' in features:
packages.extend(['mariadb', 'mariadb-server', 'mariadb-devel'])
if 'pgsql' in features:
packages.extend(['postgresql-server'])
if revision == '7':
packages.extend(['postgresql-devel'])
else:
packages.extend(['postgresql-server-devel'])
if 'radius' in features:
packages.extend(['git'])
if 'gssapi' in features:
packages.extend(['krb5-devel'])
if 'ccache' in features:
packages.extend(['ccache'])
if 'netconf' in features:
# CentOS 8+ systems have the libyang package, but they are missing
# libyang-cpp which results in this error when building sysrepo:
# "Required libyang C++ bindings not found!"
# So until it is added, install libyang from sources.
packages.extend(['cmake', 'pcre-devel'])
deferred_functions.extend([
_install_libyang_from_sources,
_install_sysrepo_from_sources,
])
if 'unittest' in features:
packages.append('wget')
deferred_functions.append(_install_gtest_sources)
install_pkgs(packages, env=env, check_times=check_times)
if 'docs' in features:
execute('virtualenv-3 ~/venv',
env=env, timeout=60, check_times=check_times)
execute('~/venv/bin/pip install sphinx sphinx-rtd-theme',
env=env, timeout=120, check_times=check_times)
if 'cql' in features:
_install_cassandra_rpm(system, revision, env, check_times)
# prepare rhel
elif system == 'rhel':
packages = ['autoconf', 'automake', 'boost-devel', 'gcc-c++',
'libtool', 'log4cplus-devel', 'make', 'mariadb-devel',
'openssl-devel', 'postgresql-devel']
if revision == '7':
# Install newer version of Boost in case users want to opt-in with:
# --with-boost-include=/usr/include/boost169 --with-boost-lib-dir=/usr/lib64/boost169
packages.append('boost169-devel')
if 'native-pkg' in features:
packages.extend(['python3-devel', 'rpm-build'])
# TODO:
# if 'mysql' in features:
# packages.extend(['default-mysql-client-core', 'default-libmysqlclient-dev', 'mysql-server'])
# if 'pgsql' in features:
# packages.extend(['postgresql-client', 'libpq-dev', 'postgresql-all'])
if 'radius' in features:
packages.extend(['git'])
if 'forge' in features:
packages.extend(['freeradius'])
if 'ccache' in features:
packages.extend(['ccache'])
if 'netconf' in features:
# RHEL 8+ systems have the libyang package, but they are missing
# libyang-cpp which results in this error when building sysrepo:
# "Required libyang C++ bindings not found!"
# So until it is added, install libyang from sources.
packages.extend(['cmake', 'pcre-devel'])
deferred_functions.extend([
_install_libyang_from_sources,
_install_sysrepo_from_sources,
])
if 'unittest' in features:
packages.append('wget')
deferred_functions.append(_install_gtest_sources)
install_pkgs(packages, env=env, timeout=120, check_times=check_times)
if 'cql' in features:
_install_cassandra_rpm(system, revision, env, check_times)
# prepare ubuntu
elif system == 'ubuntu':
_apt_update(system, revision, env=env, check_times=check_times, attempts=3, sleep_time_after_attempt=10)
packages = ['gcc', 'g++', 'make', 'autoconf', 'automake', 'libtool', 'libssl-dev', 'liblog4cplus-dev',
'libboost-system-dev', 'gnupg', 'libpcap-dev', 'python3-venv']
if 'unittest' in features:
if revision.startswith('16.'):
_install_gtest_sources()
else:
packages.append('googletest')
if 'docs' in features:
packages.extend(['python3-sphinx', 'python3-sphinx-rtd-theme', 'texlive', 'texlive-latex-extra'])
if 'native-pkg' in features:
packages.extend(['build-essential', 'fakeroot', 'devscripts'])
packages.extend(['bison', 'debhelper', 'flex', 'libboost-dev', 'python3-dev'])
if 20.04 <= float(revision):
packages.extend(['dh-python'])
if 'mysql' in features:
if revision == '16.04':
packages.extend(['mysql-client', 'libmysqlclient-dev', 'mysql-server'])
else:
packages.extend(['default-mysql-client-core', 'default-libmysqlclient-dev', 'mysql-server'])
if 'pgsql' in features:
if revision == '16.04':
packages.extend(['postgresql-client', 'libpq-dev', 'postgresql', 'postgresql-server-dev-all'])
else:
packages.extend(['postgresql-client', 'libpq-dev', 'postgresql-all'])
if 'radius' in features:
packages.extend(['git'])
if 'gssapi' in features:
packages.extend(['libkrb5-dev'])
if 'ccache' in features:
packages.extend(['ccache'])
if 'netconf' in features:
if float(revision) <= 21.04:
packages.extend(['cmake', 'libpcre3-dev'])
deferred_functions.extend([
_install_libyang_from_sources,
_install_sysrepo_from_sources,
])
else:
packages.extend(['libyang-dev', 'libyang-cpp-dev',
'libsysrepo-dev', 'libsysrepo-cpp-dev'])
install_pkgs(packages, env=env, timeout=240, check_times=check_times)
if 'cql' in features:
_install_cassandra_deb(system, revision, env, check_times)
# prepare debian
elif system == 'debian':
_apt_update(system, revision, env=env, check_times=check_times, attempts=3, sleep_time_after_attempt=10)
packages = ['gcc', 'g++', 'make', 'autoconf', 'automake', 'libtool', 'libssl-dev',
'liblog4cplus-dev', 'libboost-system-dev', 'gnupg']
if 'unittest' in features:
if revision == '8':
# libgtest-dev does not work and googletest is not available
_install_gtest_sources()
else:
packages.append('googletest')
if 'netconf' in features:
if int(revision) <= 11:
packages.extend(['cmake', 'libpcre3-dev'])
deferred_functions.extend([
_install_libyang_from_sources,
_install_sysrepo_from_sources,
])
else:
packages.extend(['libyang-dev', 'libyang-cpp-dev', 'libsysrepo-dev', 'libsysrepo-cpp-dev'])
if 'docs' in features:
if revision == '8':
packages.extend(['virtualenv'])
else:
packages.extend(['python3-sphinx', 'python3-sphinx-rtd-theme', 'texlive', 'texlive-latex-extra'])
if revision == '9':
packages.extend(['texlive-generic-extra'])
if 'native-pkg' in features:
packages.extend(['build-essential', 'fakeroot', 'devscripts'])
packages.extend(['bison', 'debhelper', 'flex', 'libboost-dev', 'python3-dev'])
if int(revision) >= 11:
packages.extend(['dh-python'])
if 'mysql' in features:
if revision == '8':
packages.extend(['mysql-client', 'libmysqlclient-dev'])
else:
packages.extend(['default-mysql-client-core', 'default-libmysqlclient-dev'])
if revision in ['8', '9']:
packages.append('mysql-server')
else:
packages.append('mariadb-server')
if 'pgsql' in features:
packages.extend(['postgresql-client', 'libpq-dev'])
if revision == '8':
packages.extend(['postgresql', 'postgresql-client'])
else:
packages.append('postgresql-all')
if 'radius' in features:
packages.extend(['git'])
if 'gssapi' in features:
packages.extend(['libkrb5-dev'])
if 'ccache' in features:
packages.extend(['ccache'])
install_pkgs(packages, env=env, timeout=240, check_times=check_times)
if 'docs' in features and revision == '8':
execute('virtualenv -p /usr/bin/python3 ~/venv',
env=env, timeout=60, check_times=check_times)
execute('~/venv/bin/pip install sphinx sphinx-rtd-theme',
env=env, timeout=120, check_times=check_times)
if 'cql' in features and revision != '8':
# there is no libuv1 package in case of debian 8
_install_cassandra_deb(system, revision, env, check_times)
# prepare freebsd
elif system == 'freebsd':
packages = ['autoconf', 'automake', 'libtool', 'openssl', 'log4cplus', 'boost-libs', 'wget']
if 'docs' in features:
if float(revision.split('.')[0]) < 12.0:
packages.extend(['py37-sphinx', 'py37-sphinx_rtd_theme'])
else:
packages.extend(['py38-sphinx', 'py38-sphinx_rtd_theme'])
if 'mysql' in features:
if revision.startswith(('11', '12')):
packages.extend(['mysql57-server', 'mysql57-client'])
else:
packages.extend(['mysql80-server', 'mysql80-client'])
if 'pgsql' in features:
if revision.startswith(('11', '12')):
packages.extend(['postgresql11-server', 'postgresql11-client'])
else:
packages.extend(['postgresql13-server', 'postgresql13-client'])
if 'radius' in features:
packages.extend(['git'])
if 'gssapi' in features:
packages.extend(['krb5', 'krb5-devel'])
if 'ccache' in features:
packages.extend(['ccache'])
if 'netconf' in features:
# FreeBSD systems have the libyang package, but they are missing
# libyang-cpp which results in this error when building sysrepo:
# "Required libyang C++ bindings not found!"
# So until it is added, install libyang from sources.
packages.extend(['cmake', 'pcre'])
deferred_functions.extend([
_install_libyang_from_sources,
_install_sysrepo_from_sources,
])
install_pkgs(packages, env=env, timeout=6 * 60, check_times=check_times)
if 'unittest' in features:
_install_gtest_sources()
if 'mysql' in features:
execute('sudo sysrc mysql_enable="yes"', env=env, check_times=check_times)
execute('sudo service mysql-server start', env=env, check_times=check_times,
raise_error=False)
execute('sudo pkg clean -a -y')
execute('sudo rm -rf /usr/lib/debug')
# prepare alpine
elif system == 'alpine':
packages = ['gcc', 'g++', 'make', 'autoconf', 'automake', 'libtool', 'openssl-dev',
'boost-libs', 'boost-dev', 'procps', 'tar']
if 'docs' in features:
if revision == '3.10':
packages.extend(['py-sphinx', 'py-sphinx_rtd_theme'])
elif revision == '3.11':
packages.extend(['py3-sphinx'])
else:
packages.extend(['py3-sphinx', 'py3-sphinx_rtd_theme'])
if 'unittest' in features:
_install_gtest_sources()
if 'netconf' in features:
# Alpine systems have the libyang-dev package, but they are missing
# libyang-cpp-dev which results in this error when building sysrepo:
# "Required libyang C++ bindings not found!"
# So until it is added, install libyang from sources.
packages.extend(['cmake', 'pcre-dev'])
deferred_functions.extend([
_install_libyang_from_sources,
_install_sysrepo_from_sources,
])
if 'mysql' in features:
packages.extend(['mariadb-dev', 'mariadb', 'mariadb-client'])
if 'pgsql' in features:
packages.extend(['postgresql-dev', 'postgresql'])
packages.extend(['bison', 'flex', 'boost-dev', 'python3-dev'])
if 'gssapi' in features:
packages.extend(['krb5-dev'])
if 'native-pkg' in features:
packages.extend(['alpine-sdk'])
if 'ccache' in features:
packages.extend(['ccache'])
install_pkgs(packages, env=env, timeout=6 * 60, check_times=check_times)
# log4cplus needs to be taken from extra repository, edge testing
execute('sudo apk add log4cplus log4cplus-dev --update-cache --repository http://dl-3.alpinelinux.org/alpine/edge/testing/ --allow-untrusted',
env=env, timeout=60, check_times=check_times)
# check for existence of 'vagrant' user and 'abuild' group before adding him to the group
try:
pwd.getpwnam('vagrant')
grp.getgrnam('abuild')
except KeyError:
log.info("Can't add 'vagrant' user to 'abuild' group. Vagrant or abuild does not exist.")
else:
execute('sudo adduser vagrant abuild')
try:
current_user = getpass.getuser()
pwd.getpwnam(current_user)
grp.getgrnam('abuild')
except KeyError:
log.info("Can't add %s user to 'abuild' group. %s or abuild does not exist.", current_user, current_user)
else:
execute('sudo adduser %s abuild' % current_user)
elif system == 'arch':
if 'netconf' in features:
deferred_functions.extend([
_install_libyang_from_sources,
_install_sysrepo_from_sources,
])
else:
raise NotImplementedError('no implementation for %s' % system)
# Packages required by these functions have been installed. Now call them.
for f in deferred_functions:
f()
if 'mysql' in features:
_configure_mysql(system, revision, features)
if 'pgsql' in features:
_configure_pgsql(system, features)
if 'radius' in features and 'native-pkg' not in features:
_install_freeradius_client(system, revision, features, env, check_times)
#execute('sudo rm -rf /usr/share/doc')
log.info('Preparing deps completed successfully.') | [
"def",
"prepare_system_local",
"(",
"features",
",",
"check_times",
")",
":",
"env",
"=",
"os",
".",
"environ",
".",
"copy",
"(",
")",
"env",
"[",
"'LANGUAGE'",
"]",
"=",
"env",
"[",
"'LANG'",
"]",
"=",
"env",
"[",
"'LC_ALL'",
"]",
"=",
"'C'",
"# Act... | https://github.com/isc-projects/kea/blob/c5836c791b63f42173bb604dd5f05d7110f3e716/hammer.py#L1401-L1861 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | contrib/gizmos/osx_carbon/gizmos.py | python | TreeListCtrl.ScrollTo | (*args, **kwargs) | return _gizmos.TreeListCtrl_ScrollTo(*args, **kwargs) | ScrollTo(self, TreeItemId item) | ScrollTo(self, TreeItemId item) | [
"ScrollTo",
"(",
"self",
"TreeItemId",
"item",
")"
] | def ScrollTo(*args, **kwargs):
"""ScrollTo(self, TreeItemId item)"""
return _gizmos.TreeListCtrl_ScrollTo(*args, **kwargs) | [
"def",
"ScrollTo",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_gizmos",
".",
"TreeListCtrl_ScrollTo",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/contrib/gizmos/osx_carbon/gizmos.py#L911-L913 | |
mindspore-ai/mindspore | fb8fd3338605bb34fa5cea054e535a8b1d753fab | mindspore/python/mindspore/mindrecord/shardindexgenerator.py | python | ShardIndexGenerator.build | (self) | return ret | Build index generator.
Returns:
MSRStatus, SUCCESS or FAILED.
Raises:
MRMGenerateIndexError: If failed to build index generator. | Build index generator. | [
"Build",
"index",
"generator",
"."
] | def build(self):
"""
Build index generator.
Returns:
MSRStatus, SUCCESS or FAILED.
Raises:
MRMGenerateIndexError: If failed to build index generator.
"""
ret = self._generator.build()
if ret != ms.MSRStatus.SUCCESS:
logger.critical("Failed to build index generator.")
raise MRMGenerateIndexError
return ret | [
"def",
"build",
"(",
"self",
")",
":",
"ret",
"=",
"self",
".",
"_generator",
".",
"build",
"(",
")",
"if",
"ret",
"!=",
"ms",
".",
"MSRStatus",
".",
"SUCCESS",
":",
"logger",
".",
"critical",
"(",
"\"Failed to build index generator.\"",
")",
"raise",
"M... | https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/mindrecord/shardindexgenerator.py#L44-L58 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | contrib/gizmos/gtk/gizmos.py | python | TreeListColumnInfo.SetImage | (*args, **kwargs) | return _gizmos.TreeListColumnInfo_SetImage(*args, **kwargs) | SetImage(self, int image) | SetImage(self, int image) | [
"SetImage",
"(",
"self",
"int",
"image",
")"
] | def SetImage(*args, **kwargs):
"""SetImage(self, int image)"""
return _gizmos.TreeListColumnInfo_SetImage(*args, **kwargs) | [
"def",
"SetImage",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_gizmos",
".",
"TreeListColumnInfo_SetImage",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/contrib/gizmos/gtk/gizmos.py#L440-L442 | |
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/ragged/ragged_where_op.py | python | _elementwise_where | (condition, x, y) | Ragged version of tf.where(condition, x, y). | Ragged version of tf.where(condition, x, y). | [
"Ragged",
"version",
"of",
"tf",
".",
"where",
"(",
"condition",
"x",
"y",
")",
"."
] | def _elementwise_where(condition, x, y):
"""Ragged version of tf.where(condition, x, y)."""
condition_is_ragged = isinstance(condition, ragged_tensor.RaggedTensor)
x_is_ragged = isinstance(x, ragged_tensor.RaggedTensor)
y_is_ragged = isinstance(y, ragged_tensor.RaggedTensor)
if not (condition_is_ragged or x_is_ragged or y_is_ragged):
return array_ops.where(condition, x, y)
elif condition_is_ragged and x_is_ragged and y_is_ragged:
return ragged_functional_ops.map_flat_values(array_ops.where, condition, x,
y)
elif not condition_is_ragged:
# Concatenate x and y, and then use `gather` to assemble the selected rows.
condition.shape.assert_has_rank(1)
x_and_y = ragged_concat_ops.concat([x, y], axis=0)
x_nrows = _nrows(x, out_type=x_and_y.row_splits.dtype)
y_nrows = _nrows(y, out_type=x_and_y.row_splits.dtype)
indices = array_ops.where(condition, math_ops.range(x_nrows),
x_nrows + math_ops.range(y_nrows))
return ragged_gather_ops.gather(x_and_y, indices)
else:
raise ValueError('Input shapes do not match.') | [
"def",
"_elementwise_where",
"(",
"condition",
",",
"x",
",",
"y",
")",
":",
"condition_is_ragged",
"=",
"isinstance",
"(",
"condition",
",",
"ragged_tensor",
".",
"RaggedTensor",
")",
"x_is_ragged",
"=",
"isinstance",
"(",
"x",
",",
"ragged_tensor",
".",
"Rag... | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/ragged/ragged_where_op.py#L114-L137 | ||
dmlc/cxxnet | 9c58c278d129d0a275427cb5c989f75fff182c28 | wrapper/cxxnet.py | python | DataIter.__del__ | (self) | destructor | destructor | [
"destructor"
] | def __del__(self):
"""destructor"""
cxnlib.CXNIOFree(self.handle) | [
"def",
"__del__",
"(",
"self",
")",
":",
"cxnlib",
".",
"CXNIOFree",
"(",
"self",
".",
"handle",
")"
] | https://github.com/dmlc/cxxnet/blob/9c58c278d129d0a275427cb5c989f75fff182c28/wrapper/cxxnet.py#L73-L75 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/tornado/tornado-6/tornado/routing.py | python | Rule.__init__ | (
self,
matcher: "Matcher",
target: Any,
target_kwargs: Optional[Dict[str, Any]] = None,
name: Optional[str] = None,
) | Constructs a Rule instance.
:arg Matcher matcher: a `Matcher` instance used for determining
whether the rule should be considered a match for a specific
request.
:arg target: a Rule's target (typically a ``RequestHandler`` or
`~.httputil.HTTPServerConnectionDelegate` subclass or even a nested `Router`,
depending on routing implementation).
:arg dict target_kwargs: a dict of parameters that can be useful
at the moment of target instantiation (for example, ``status_code``
for a ``RequestHandler`` subclass). They end up in
``target_params['target_kwargs']`` of `RuleRouter.get_target_delegate`
method.
:arg str name: the name of the rule that can be used to find it
in `ReversibleRouter.reverse_url` implementation. | Constructs a Rule instance. | [
"Constructs",
"a",
"Rule",
"instance",
"."
] | def __init__(
self,
matcher: "Matcher",
target: Any,
target_kwargs: Optional[Dict[str, Any]] = None,
name: Optional[str] = None,
) -> None:
"""Constructs a Rule instance.
:arg Matcher matcher: a `Matcher` instance used for determining
whether the rule should be considered a match for a specific
request.
:arg target: a Rule's target (typically a ``RequestHandler`` or
`~.httputil.HTTPServerConnectionDelegate` subclass or even a nested `Router`,
depending on routing implementation).
:arg dict target_kwargs: a dict of parameters that can be useful
at the moment of target instantiation (for example, ``status_code``
for a ``RequestHandler`` subclass). They end up in
``target_params['target_kwargs']`` of `RuleRouter.get_target_delegate`
method.
:arg str name: the name of the rule that can be used to find it
in `ReversibleRouter.reverse_url` implementation.
"""
if isinstance(target, str):
# import the Module and instantiate the class
# Must be a fully qualified name (module.ClassName)
target = import_object(target)
self.matcher = matcher # type: Matcher
self.target = target
self.target_kwargs = target_kwargs if target_kwargs else {}
self.name = name | [
"def",
"__init__",
"(",
"self",
",",
"matcher",
":",
"\"Matcher\"",
",",
"target",
":",
"Any",
",",
"target_kwargs",
":",
"Optional",
"[",
"Dict",
"[",
"str",
",",
"Any",
"]",
"]",
"=",
"None",
",",
"name",
":",
"Optional",
"[",
"str",
"]",
"=",
"N... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/tornado/tornado-6/tornado/routing.py#L444-L475 | ||
microsoft/TSS.MSR | 0f2516fca2cd9929c31d5450e39301c9bde43688 | TSS.Py/src/TpmTypes.py | python | PolicySignedResponse.initFromTpm | (self, buf) | TpmMarshaller method | TpmMarshaller method | [
"TpmMarshaller",
"method"
] | def initFromTpm(self, buf):
""" TpmMarshaller method """
self.timeout = buf.readSizedByteBuf()
self.policyTicket = TPMT_TK_AUTH.fromTpm(buf) | [
"def",
"initFromTpm",
"(",
"self",
",",
"buf",
")",
":",
"self",
".",
"timeout",
"=",
"buf",
".",
"readSizedByteBuf",
"(",
")",
"self",
".",
"policyTicket",
"=",
"TPMT_TK_AUTH",
".",
"fromTpm",
"(",
"buf",
")"
] | https://github.com/microsoft/TSS.MSR/blob/0f2516fca2cd9929c31d5450e39301c9bde43688/TSS.Py/src/TpmTypes.py#L14225-L14228 | ||
rapidsai/cudf | d5b2448fc69f17509304d594f029d0df56984962 | python/cudf/cudf/core/multiindex.py | python | MultiIndex._compute_validity_mask | (self, index, row_tuple, max_length) | return result | Computes the valid set of indices of values in the lookup | Computes the valid set of indices of values in the lookup | [
"Computes",
"the",
"valid",
"set",
"of",
"indices",
"of",
"values",
"in",
"the",
"lookup"
] | def _compute_validity_mask(self, index, row_tuple, max_length):
"""Computes the valid set of indices of values in the lookup"""
lookup = cudf.DataFrame()
for i, row in enumerate(row_tuple):
if isinstance(row, slice) and row == slice(None):
continue
lookup[i] = cudf.Series(row)
frame = cudf.DataFrame(dict(enumerate(index._data.columns)))
data_table = cudf.concat(
[
frame,
cudf.DataFrame(
{"idx": cudf.Series(column.arange(len(frame)))}
),
],
axis=1,
)
result = lookup.merge(data_table)["idx"]
# Avoid computing levels unless the result of the merge is empty,
# which suggests that a KeyError should be raised.
if len(result) == 0:
for idx, row in enumerate(row_tuple):
if row == slice(None):
continue
if row not in index.levels[idx]._column:
raise KeyError(row)
return result | [
"def",
"_compute_validity_mask",
"(",
"self",
",",
"index",
",",
"row_tuple",
",",
"max_length",
")",
":",
"lookup",
"=",
"cudf",
".",
"DataFrame",
"(",
")",
"for",
"i",
",",
"row",
"in",
"enumerate",
"(",
"row_tuple",
")",
":",
"if",
"isinstance",
"(",
... | https://github.com/rapidsai/cudf/blob/d5b2448fc69f17509304d594f029d0df56984962/python/cudf/cudf/core/multiindex.py#L658-L684 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scipy/scipy/stats/morestats.py | python | bartlett | (*args) | return BartlettResult(T, pval) | Perform Bartlett's test for equal variances
Bartlett's test tests the null hypothesis that all input samples
are from populations with equal variances. For samples
from significantly non-normal populations, Levene's test
`levene` is more robust.
Parameters
----------
sample1, sample2,... : array_like
arrays of sample data. May be different lengths.
Returns
-------
statistic : float
The test statistic.
pvalue : float
The p-value of the test.
See Also
--------
fligner : A non-parametric test for the equality of k variances
levene : A robust parametric test for equality of k variances
Notes
-----
Conover et al. (1981) examine many of the existing parametric and
nonparametric tests by extensive simulations and they conclude that the
tests proposed by Fligner and Killeen (1976) and Levene (1960) appear to be
superior in terms of robustness of departures from normality and power [3]_.
References
----------
.. [1] http://www.itl.nist.gov/div898/handbook/eda/section3/eda357.htm
.. [2] Snedecor, George W. and Cochran, William G. (1989), Statistical
Methods, Eighth Edition, Iowa State University Press.
.. [3] Park, C. and Lindsay, B. G. (1999). Robust Scale Estimation and
Hypothesis Testing based on Quadratic Inference Function. Technical
Report #99-03, Center for Likelihood Studies, Pennsylvania State
University.
.. [4] Bartlett, M. S. (1937). Properties of Sufficiency and Statistical
Tests. Proceedings of the Royal Society of London. Series A,
Mathematical and Physical Sciences, Vol. 160, No.901, pp. 268-282. | Perform Bartlett's test for equal variances | [
"Perform",
"Bartlett",
"s",
"test",
"for",
"equal",
"variances"
] | def bartlett(*args):
"""
Perform Bartlett's test for equal variances
Bartlett's test tests the null hypothesis that all input samples
are from populations with equal variances. For samples
from significantly non-normal populations, Levene's test
`levene` is more robust.
Parameters
----------
sample1, sample2,... : array_like
arrays of sample data. May be different lengths.
Returns
-------
statistic : float
The test statistic.
pvalue : float
The p-value of the test.
See Also
--------
fligner : A non-parametric test for the equality of k variances
levene : A robust parametric test for equality of k variances
Notes
-----
Conover et al. (1981) examine many of the existing parametric and
nonparametric tests by extensive simulations and they conclude that the
tests proposed by Fligner and Killeen (1976) and Levene (1960) appear to be
superior in terms of robustness of departures from normality and power [3]_.
References
----------
.. [1] http://www.itl.nist.gov/div898/handbook/eda/section3/eda357.htm
.. [2] Snedecor, George W. and Cochran, William G. (1989), Statistical
Methods, Eighth Edition, Iowa State University Press.
.. [3] Park, C. and Lindsay, B. G. (1999). Robust Scale Estimation and
Hypothesis Testing based on Quadratic Inference Function. Technical
Report #99-03, Center for Likelihood Studies, Pennsylvania State
University.
.. [4] Bartlett, M. S. (1937). Properties of Sufficiency and Statistical
Tests. Proceedings of the Royal Society of London. Series A,
Mathematical and Physical Sciences, Vol. 160, No.901, pp. 268-282.
"""
# Handle empty input
for a in args:
if np.asanyarray(a).size == 0:
return BartlettResult(np.nan, np.nan)
k = len(args)
if k < 2:
raise ValueError("Must enter at least two input sample vectors.")
Ni = zeros(k)
ssq = zeros(k, 'd')
for j in range(k):
Ni[j] = len(args[j])
ssq[j] = np.var(args[j], ddof=1)
Ntot = np.sum(Ni, axis=0)
spsq = np.sum((Ni - 1)*ssq, axis=0) / (1.0*(Ntot - k))
numer = (Ntot*1.0 - k) * log(spsq) - np.sum((Ni - 1.0)*log(ssq), axis=0)
denom = 1.0 + 1.0/(3*(k - 1)) * ((np.sum(1.0/(Ni - 1.0), axis=0)) -
1.0/(Ntot - k))
T = numer / denom
pval = distributions.chi2.sf(T, k - 1) # 1 - cdf
return BartlettResult(T, pval) | [
"def",
"bartlett",
"(",
"*",
"args",
")",
":",
"# Handle empty input",
"for",
"a",
"in",
"args",
":",
"if",
"np",
".",
"asanyarray",
"(",
"a",
")",
".",
"size",
"==",
"0",
":",
"return",
"BartlettResult",
"(",
"np",
".",
"nan",
",",
"np",
".",
"nan... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/scipy/stats/morestats.py#L1803-L1874 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/x86/toolchain/lib/python2.7/mailbox.py | python | Maildir.unlock | (self) | return | Unlock the mailbox if it is locked. | Unlock the mailbox if it is locked. | [
"Unlock",
"the",
"mailbox",
"if",
"it",
"is",
"locked",
"."
] | def unlock(self):
"""Unlock the mailbox if it is locked."""
return | [
"def",
"unlock",
"(",
"self",
")",
":",
"return"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/mailbox.py#L405-L407 | |
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/ctc_ops.py | python | ctc_loss_dense | (labels,
logits,
label_length,
logit_length,
logits_time_major=True,
unique=None,
blank_index=0,
name=None) | Computes CTC (Connectionist Temporal Classification) loss.
This op implements the CTC loss as presented in the article:
[A. Graves, S. Fernandez, F. Gomez, J. Schmidhuber.
Connectionist Temporal Classification: Labeling Unsegmented Sequence Data
with Recurrent Neural Networks. ICML 2006, Pittsburgh, USA,
pp. 369-376.](http://www.cs.toronto.edu/~graves/icml_2006.pdf)
Using the batched forward backward algorithm described in:
[Sim, K. C., Narayanan, A., Bagby, T., Sainath, T. N., & Bacchiani, M.
Improving the efficiency of forward-backward algorithm using batched
computation in TensorFlow.
Automatic Speech Recognition and Understanding Workshop (ASRU),
2017 IEEE (pp. 258-264).
](https://ieeexplore.ieee.org/iel7/8260578/8268903/08268944.pdf)
Notes:
Significant differences from tf.compat.v1.nn.ctc_loss:
Supports GPU and TPU (tf.compat.v1.nn.ctc_loss supports CPU only):
For batched operations, GPU and TPU are significantly faster than using
ctc_loss on CPU.
This implementation runs on CPU, but significantly slower than ctc_loss.
Blank label is 0 rather num_classes - 1, unless overridden by blank_index.
Logits and labels are dense arrays with padding rather than SparseTensor.
The only mode supported is the same as:
preprocess_collapse_repeated=False, ctc_merge_repeated=True
To collapse labels, the caller can preprocess label sequence first.
The dense implementation supports both CPU, GPU and TPU. A fast path is
provided that significantly improves memory use for large vocabulary if the
caller preprocesses label sequences to get unique label indices on the CPU
(eg. in the data input pipeline) using ctc_ops.unique and simplies this in
the optional "unique" kwarg. This is especially useful for TPU and GPU but
also works with if used on CPU.
Args:
labels: tensor of shape [batch_size, max_label_seq_length]
logits: tensor of shape [frames, batch_size, num_labels], if
logits_time_major == False, shape is [batch_size, frames, num_labels].
label_length: tensor of shape [batch_size] Length of reference label
sequence in labels.
logit_length: tensor of shape [batch_size] Length of input sequence in
logits.
logits_time_major: (optional) If True (default), logits is shaped [time,
batch, logits]. If False, shape is [batch, time, logits]
unique: (optional) Unique label indices as computed by unique(labels). If
supplied, enable a faster, memory efficient implementation on TPU.
blank_index: (optional) Set the class index to use for the blank label.
Negative values will start from num_classes, ie, -1 will reproduce the
ctc_loss behavior of using num_classes - 1 for the blank symbol. There is
some memory/performance overhead to switching from the default of 0 as an
additional shifted copy of the logits may be created.
name: A name for this `Op`. Defaults to "ctc_loss_dense".
Returns:
loss: tensor of shape [batch_size], negative log probabilities. | Computes CTC (Connectionist Temporal Classification) loss. | [
"Computes",
"CTC",
"(",
"Connectionist",
"Temporal",
"Classification",
")",
"loss",
"."
] | def ctc_loss_dense(labels,
logits,
label_length,
logit_length,
logits_time_major=True,
unique=None,
blank_index=0,
name=None):
"""Computes CTC (Connectionist Temporal Classification) loss.
This op implements the CTC loss as presented in the article:
[A. Graves, S. Fernandez, F. Gomez, J. Schmidhuber.
Connectionist Temporal Classification: Labeling Unsegmented Sequence Data
with Recurrent Neural Networks. ICML 2006, Pittsburgh, USA,
pp. 369-376.](http://www.cs.toronto.edu/~graves/icml_2006.pdf)
Using the batched forward backward algorithm described in:
[Sim, K. C., Narayanan, A., Bagby, T., Sainath, T. N., & Bacchiani, M.
Improving the efficiency of forward-backward algorithm using batched
computation in TensorFlow.
Automatic Speech Recognition and Understanding Workshop (ASRU),
2017 IEEE (pp. 258-264).
](https://ieeexplore.ieee.org/iel7/8260578/8268903/08268944.pdf)
Notes:
Significant differences from tf.compat.v1.nn.ctc_loss:
Supports GPU and TPU (tf.compat.v1.nn.ctc_loss supports CPU only):
For batched operations, GPU and TPU are significantly faster than using
ctc_loss on CPU.
This implementation runs on CPU, but significantly slower than ctc_loss.
Blank label is 0 rather num_classes - 1, unless overridden by blank_index.
Logits and labels are dense arrays with padding rather than SparseTensor.
The only mode supported is the same as:
preprocess_collapse_repeated=False, ctc_merge_repeated=True
To collapse labels, the caller can preprocess label sequence first.
The dense implementation supports both CPU, GPU and TPU. A fast path is
provided that significantly improves memory use for large vocabulary if the
caller preprocesses label sequences to get unique label indices on the CPU
(eg. in the data input pipeline) using ctc_ops.unique and simplies this in
the optional "unique" kwarg. This is especially useful for TPU and GPU but
also works with if used on CPU.
Args:
labels: tensor of shape [batch_size, max_label_seq_length]
logits: tensor of shape [frames, batch_size, num_labels], if
logits_time_major == False, shape is [batch_size, frames, num_labels].
label_length: tensor of shape [batch_size] Length of reference label
sequence in labels.
logit_length: tensor of shape [batch_size] Length of input sequence in
logits.
logits_time_major: (optional) If True (default), logits is shaped [time,
batch, logits]. If False, shape is [batch, time, logits]
unique: (optional) Unique label indices as computed by unique(labels). If
supplied, enable a faster, memory efficient implementation on TPU.
blank_index: (optional) Set the class index to use for the blank label.
Negative values will start from num_classes, ie, -1 will reproduce the
ctc_loss behavior of using num_classes - 1 for the blank symbol. There is
some memory/performance overhead to switching from the default of 0 as an
additional shifted copy of the logits may be created.
name: A name for this `Op`. Defaults to "ctc_loss_dense".
Returns:
loss: tensor of shape [batch_size], negative log probabilities.
"""
with ops.name_scope(name, "ctc_loss_dense",
[logits, labels, label_length, logit_length]):
logits = ops.convert_to_tensor(logits, name="logits")
labels = ops.convert_to_tensor(labels, name="labels")
label_length = ops.convert_to_tensor(label_length, name="label_length")
logit_length = ops.convert_to_tensor(logit_length, name="logit_length")
if not logits_time_major:
logits = array_ops.transpose(logits, perm=[1, 0, 2])
if blank_index != 0:
if blank_index < 0:
blank_index += _get_dim(logits, 2)
logits = array_ops.concat([
logits[:, :, blank_index:blank_index + 1],
logits[:, :, :blank_index],
logits[:, :, blank_index + 1:],
],
axis=2)
labels = array_ops.where(labels < blank_index, labels + 1, labels)
args = [logits, labels, label_length, logit_length]
if unique:
unique_y, unique_idx = unique
args.extend([unique_y, unique_idx])
@custom_gradient.custom_gradient
def compute_ctc_loss(logits_t, labels_t, label_length_t, logit_length_t,
*unique_t):
"""Compute CTC loss."""
logits_t.set_shape(logits.shape)
labels_t.set_shape(labels.shape)
label_length_t.set_shape(label_length.shape)
logit_length_t.set_shape(logit_length.shape)
kwargs = dict(
logits=logits_t,
labels=labels_t,
label_length=label_length_t,
logit_length=logit_length_t)
if unique_t:
kwargs["unique"] = unique_t
result = ctc_loss_and_grad(**kwargs)
def grad(grad_loss):
grad = [array_ops.reshape(grad_loss, [1, -1, 1]) * result[1]]
grad += [None] * (len(args) - len(grad))
return grad
return result[0], grad
return compute_ctc_loss(*args) | [
"def",
"ctc_loss_dense",
"(",
"labels",
",",
"logits",
",",
"label_length",
",",
"logit_length",
",",
"logits_time_major",
"=",
"True",
",",
"unique",
"=",
"None",
",",
"blank_index",
"=",
"0",
",",
"name",
"=",
"None",
")",
":",
"with",
"ops",
".",
"nam... | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/ctc_ops.py#L692-L810 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/webkit.py | python | WebKitCtrl.Stop | (*args, **kwargs) | return _webkit.WebKitCtrl_Stop(*args, **kwargs) | Stop(self) | Stop(self) | [
"Stop",
"(",
"self",
")"
] | def Stop(*args, **kwargs):
"""Stop(self)"""
return _webkit.WebKitCtrl_Stop(*args, **kwargs) | [
"def",
"Stop",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_webkit",
".",
"WebKitCtrl_Stop",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/webkit.py#L108-L110 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python/src/Lib/urllib.py | python | splitnport | (host, defport=-1) | return host, defport | Split host and port, returning numeric port.
Return given default port if no ':' found; defaults to -1.
Return numerical port if a valid number are found after ':'.
Return None if ':' but not a valid number. | Split host and port, returning numeric port.
Return given default port if no ':' found; defaults to -1.
Return numerical port if a valid number are found after ':'.
Return None if ':' but not a valid number. | [
"Split",
"host",
"and",
"port",
"returning",
"numeric",
"port",
".",
"Return",
"given",
"default",
"port",
"if",
"no",
":",
"found",
";",
"defaults",
"to",
"-",
"1",
".",
"Return",
"numerical",
"port",
"if",
"a",
"valid",
"number",
"are",
"found",
"after... | def splitnport(host, defport=-1):
"""Split host and port, returning numeric port.
Return given default port if no ':' found; defaults to -1.
Return numerical port if a valid number are found after ':'.
Return None if ':' but not a valid number."""
global _nportprog
if _nportprog is None:
import re
_nportprog = re.compile('^(.*):(.*)$')
match = _nportprog.match(host)
if match:
host, port = match.group(1, 2)
if port:
try:
nport = int(port)
except ValueError:
nport = None
return host, nport
return host, defport | [
"def",
"splitnport",
"(",
"host",
",",
"defport",
"=",
"-",
"1",
")",
":",
"global",
"_nportprog",
"if",
"_nportprog",
"is",
"None",
":",
"import",
"re",
"_nportprog",
"=",
"re",
".",
"compile",
"(",
"'^(.*):(.*)$'",
")",
"match",
"=",
"_nportprog",
".",... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/urllib.py#L1148-L1167 | |
google/earthenterprise | 0fe84e29be470cd857e3a0e52e5d0afd5bb8cee9 | earth_enterprise/src/server/wsgi/serve/push/stream/stream_push_manager.py | python | StreamPushManager.HandleGarbageCollectRequest | (self, request, response) | Handles Garbage Collect request.
Removes all unnecessary files and file references from the publish root
volume and database.
Args:
request: request object.
response: response object.
Raises:
psycopg2.Error/Warning | Handles Garbage Collect request. | [
"Handles",
"Garbage",
"Collect",
"request",
"."
] | def HandleGarbageCollectRequest(self, request, response):
"""Handles Garbage Collect request.
Removes all unnecessary files and file references from the publish root
volume and database.
Args:
request: request object.
response: response object.
Raises:
psycopg2.Error/Warning
"""
logger.debug("HandleGarbageCollectRequest..")
assert request.GetParameter(constants.CMD) == constants.CMD_GARBAGE_COLLECT
parent_dirs_set = set()
delete_count = 0
delete_size = 0
# The "NOT IN" sql operator is painfully slow for large collections of
# files.
# Instead we do 2 queries of all the file_id(s) in files_table and
# db_files_table
# and walk through the list removing files_table entries that don't occur
# in db_files_table and vice versa.
query = ("SELECT file_id, host_name, file_path, file_size"
" FROM files_table ORDER BY file_id")
rs_files = self.DbQuery(query)
query = ("SELECT file_id FROM db_files_table"
" GROUP BY file_id ORDER BY file_id")
rs_db_files = self.DbQuery(query)
db_file_id = sys.maxint
if rs_db_files:
db_file_iter = iter(rs_db_files)
db_file_id = int(db_file_iter.next())
# Use a BatchSqlManager to batch up many individual SQL commands into
# one postgres invocation.
batcher = batch_sql_manager.BatchSqlManager(
self.stream_db, 1000, logger)
top_level_dir_prefix = self.server_prefix + "/"
delete_files_table_cmd = "DELETE FROM files_table WHERE file_id = %s"
delete_db_files_table_cmd = (
"DELETE FROM db_files_table WHERE file_id = %s")
# We have 2 sorted lists of file_id's in the query results.
# db_files_table is the subset of files_table
# We will walk the two lists removing any files_table entries that don't
# appear in db_files_table.
for rs_file in rs_files:
file_id = int(rs_file[0])
# Check the boundary case...this could happen and would basically mean
# pain for whomever this happens to.
if file_id == sys.maxint:
logger.error("HandleGarbageCollectRequest has encountered a file_id "
"equal to the max int value. "
"The database has run out of valid file id's.")
raise exceptions.StreamPushServeException(
"The publisher database has run out of valid file id's."
" This published database must likely be recreated from scratch.")
if file_id < db_file_id:
# Delete this file:
# the files_table entry does not exist in the db_files_table
# Check if the file exists and if so delete it.
top_level_dir = top_level_dir_prefix + rs_file[1]
server_file_path = os.path.normpath(top_level_dir + rs_file[2])
if os.path.exists(server_file_path):
# Keep a set of parent dirs so that we can delete them later if
# empty.
parent_dir = os.path.dirname(server_file_path)
while parent_dir != top_level_dir:
parent_dirs_set.add(parent_dir)
parent_dir = os.path.dirname(parent_dir)
# Now we can delete the file from the file system. And, whether
# it is successful, we delete the file entry from files_table.
try:
os.remove(server_file_path)
delete_count += 1
delete_size += rs_file[3]
# Delete the file entry from files_table.
batcher.AddModify(delete_files_table_cmd, [file_id])
except OSError:
logger.error(
"HandleGarbageCollectRequest: Could not delete file %s.",
server_file_path)
else:
# File does not exist - just delete the file entry from files_table.
batcher.AddModify(delete_files_table_cmd, [file_id])
elif file_id == db_file_id:
# This file is ok, skip to the next db_file_id
try:
db_file_id = int(db_file_iter.next())
except StopIteration:
db_file_id = sys.maxint
else:
# Note: db_files_table's file_id(s) should be a subset of
# files_table's file_id(s), if we encounter a db_files_table entry
# which has no files_table entry, we will delete the db_files_table
# entry. This really shouldn't happen, but who knows if a user pokes
# around the psql database and deletes something they shouldn't.
while db_file_id < file_id:
batcher.AddModify(delete_db_files_table_cmd, [db_file_id])
try:
db_file_id = int(db_file_iter.next())
except StopIteration:
db_file_id = sys.maxint
# Close up the sql objects and execute the remaining batch commands.
batcher.ExecuteRemaining()
batcher.Close()
# Finally delete all the dirs if they are empty. We walk the list in the
# reverse order coz we want to delete the child dirs before we try to
# delete the parent dirs.
parent_dirs_list = sorted(parent_dirs_set)
for parent_dir in reversed(parent_dirs_list):
try:
os.rmdir(parent_dir)
logger.debug("HandleGarbageCollectRequest: remove dir: %s", parent_dir)
except OSError:
pass
# Queue up the stats for the garbage collection.
http_io.ResponseWriter.AddBodyElement(
response, constants.HDR_DELETE_COUNT, delete_count)
http_io.ResponseWriter.AddBodyElement(
response, constants.HDR_DELETE_SIZE, delete_size)
http_io.ResponseWriter.AddBodyElement(
response, constants.HDR_STATUS_CODE, constants.STATUS_SUCCESS)
logger.debug("HandleGarbageCollectRequest done.") | [
"def",
"HandleGarbageCollectRequest",
"(",
"self",
",",
"request",
",",
"response",
")",
":",
"logger",
".",
"debug",
"(",
"\"HandleGarbageCollectRequest..\"",
")",
"assert",
"request",
".",
"GetParameter",
"(",
"constants",
".",
"CMD",
")",
"==",
"constants",
"... | https://github.com/google/earthenterprise/blob/0fe84e29be470cd857e3a0e52e5d0afd5bb8cee9/earth_enterprise/src/server/wsgi/serve/push/stream/stream_push_manager.py#L664-L794 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/lib/agw/customtreectrl.py | python | CustomTreeCtrl.GetChildrenCount | (self, item, recursively=True) | return item.GetChildrenCount(recursively) | Returns the item children count.
:param `item`: an instance of :class:`GenericTreeItem`;
:param bool `recursively`: if ``True``, returns the total number of descendants,
otherwise only one level of children is counted. | Returns the item children count. | [
"Returns",
"the",
"item",
"children",
"count",
"."
] | def GetChildrenCount(self, item, recursively=True):
"""
Returns the item children count.
:param `item`: an instance of :class:`GenericTreeItem`;
:param bool `recursively`: if ``True``, returns the total number of descendants,
otherwise only one level of children is counted.
"""
return item.GetChildrenCount(recursively) | [
"def",
"GetChildrenCount",
"(",
"self",
",",
"item",
",",
"recursively",
"=",
"True",
")",
":",
"return",
"item",
".",
"GetChildrenCount",
"(",
"recursively",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/customtreectrl.py#L3447-L3456 | |
cms-sw/cmssw | fd9de012d503d3405420bcbeec0ec879baa57cf2 | Alignment/MuonAlignmentAlgorithms/scripts/alignmentValidation.py | python | doMapPlotsDT | (dt_basedir, tfiles_plotting) | write DT map plots
"DTvsphi_st%dwh%s" % (station, wheelletter):
plots "integrated" over ALL SECTORS:
of x, y, dxdz, dydz vs. phi (y and dydz only for stations 1-3)
made for all (station,wheel) combinations
Access interface may be arranged into station(1 .. 4) vs. wheel(-2 .. +2) map.
It could be incorporated into a general DT chambers map (column1: wheel, column2: station,
columns3-16 correspond to sector #) by making station numbers in column 2 clickable.
"DTvsz_st%dsec%02d" % (station, sector)
plots "integrated" over ALL WHEELS:
of x, y, dxdz, dydz vs. z (y and dydz only for stations 1-3)
made for all (station,sector) combinations
Interface: may be arranged into station(1 .. 4) vs. sector(1 .. 14) map with sector range
(1 .. 12) for stations 1-3.
It could be incorporated into an EXTENDED general DT chambers map (extended by adding an
identifier "ALL" in column1 for wheel number).
"DTvsz_st%dsecALL" % (station)
plots spanning in z over ALL WHEELS and "integrated" over all sectors:
of x, y, dxdz, dydz vs. z (y and dydz only for stations 1-3)
made for all stations
Interface: may be arranged into station(1 .. 4) map
It could be incorporated into an EXTENDED general DT chambers map (extended by adding an
identifier "ALL" in column1 for wheel number). | write DT map plots | [
"write",
"DT",
"map",
"plots"
] | def doMapPlotsDT(dt_basedir, tfiles_plotting):
"""write DT map plots
"DTvsphi_st%dwh%s" % (station, wheelletter):
plots "integrated" over ALL SECTORS:
of x, y, dxdz, dydz vs. phi (y and dydz only for stations 1-3)
made for all (station,wheel) combinations
Access interface may be arranged into station(1 .. 4) vs. wheel(-2 .. +2) map.
It could be incorporated into a general DT chambers map (column1: wheel, column2: station,
columns3-16 correspond to sector #) by making station numbers in column 2 clickable.
"DTvsz_st%dsec%02d" % (station, sector)
plots "integrated" over ALL WHEELS:
of x, y, dxdz, dydz vs. z (y and dydz only for stations 1-3)
made for all (station,sector) combinations
Interface: may be arranged into station(1 .. 4) vs. sector(1 .. 14) map with sector range
(1 .. 12) for stations 1-3.
It could be incorporated into an EXTENDED general DT chambers map (extended by adding an
identifier "ALL" in column1 for wheel number).
"DTvsz_st%dsecALL" % (station)
plots spanning in z over ALL WHEELS and "integrated" over all sectors:
of x, y, dxdz, dydz vs. z (y and dydz only for stations 1-3)
made for all stations
Interface: may be arranged into station(1 .. 4) map
It could be incorporated into an EXTENDED general DT chambers map (extended by adding an
identifier "ALL" in column1 for wheel number)."""
for wheel in DT_TYPES:
if wheel[1]=="ALL": continue
for station in wheel[2]:
pdir = dt_basedir+'/'+wheel[0]+'/'+station[1]+'/'
label = "DTvsphi_st%dwh%s" % (int(station[1]), wheelLetter(int(wheel[1])))
htitle = "wheel %+d, station %s" % (int(wheel[1]), station[1])
#mapplot(tfiles_plotting, label, "x", window=25., title=htitle, fitsawteeth=True,fitsine=True)
mapplot(tfiles_plotting, label, "x", window=10., title=htitle, fitsine=True,fitpeaks=True,peaksbins=2)
c1.SaveAs(pdir+'map_DTvsphi_x.png')
#mapplot(tfiles_plotting, label, "dxdz", window=25., title=htitle, fitsawteeth=True,fitsine=True)
mapplot(tfiles_plotting, label, "dxdz", window=10., title=htitle,peaksbins=2)
c1.SaveAs(pdir+'map_DTvsphi_dxdz.png')
if station[1]=='4': continue
#mapplot(tfiles_plotting, label, "y", window=25., title=htitle, fitsawteeth=True,fitsine=True)
mapplot(tfiles_plotting, label, "y", window=10., title=htitle,peaksbins=2)
c1.SaveAs(pdir+'map_DTvsphi_y.png')
#mapplot(tfiles_plotting, label, "dydz", window=25., title=htitle, fitsawteeth=True,fitsine=True)
mapplot(tfiles_plotting, label, "dydz", window=10., title=htitle,peaksbins=2)
c1.SaveAs(pdir+'map_DTvsphi_dydz.png')
qcount=0
for wheel in DT_TYPES:
if wheel[1]!="ALL": continue
for station in wheel[2]:
for sector in range(1,station[2]+1):
if qcount>QUICKTESTN: break
qcount += 1
ssector = "%02d" % sector
pdir = dt_basedir+'/'+wheel[0]+'/'+station[1]+'/'+ssector+'/'
label = "DTvsz_st%ssec%s" % (station[1], ssector)
htitle = "station %s, sector %d" % (station[1], sector)
mapplot(tfiles_plotting, label, "x", window=10., title=htitle, peaksbins=2)
c1.SaveAs(pdir+'map_DTvsz_x.png')
mapplot(tfiles_plotting, label, "dxdz", window=10., title=htitle, peaksbins=2)
c1.SaveAs(pdir+'map_DTvsz_dxdz.png')
if station[1]=='4': continue
mapplot(tfiles_plotting, label, "y", window=10., title=htitle, peaksbins=2)
c1.SaveAs(pdir+'map_DTvsz_y.png')
mapplot(tfiles_plotting, label, "dydz", window=10., title=htitle, peaksbins=2)
c1.SaveAs(pdir+'map_DTvsz_dydz.png')
qcount=0
for wheel in DT_TYPES:
if wheel[1]!="ALL": continue
for station in wheel[2]:
if qcount>QUICKTESTN: break
qcount += 1
pdir = dt_basedir+'/'+wheel[0]+'/'+station[1]+'/'
label = "DTvsz_st%ssecALL" % (station[1])
htitle = "station %s" % (station[1])
print(label, end=' ')
mapplot(tfiles_plotting, label, "x", window=10., title=htitle, peaksbins=2)
c1.SaveAs(pdir+'map_DTvsz_all_x.png')
mapplot(tfiles_plotting, label, "dxdz", window=10., title=htitle, peaksbins=2)
c1.SaveAs(pdir+'map_DTvsz_all_dxdz.png')
if station[1]=='4': continue
mapplot(tfiles_plotting, label, "y", window=10., title=htitle, peaksbins=2)
c1.SaveAs(pdir+'map_DTvsz_all_y.png')
mapplot(tfiles_plotting, label, "dydz", window=10., title=htitle, peaksbins=2)
c1.SaveAs(pdir+'map_DTvsz_all_dydz.png')
saveTestResultsMap(options.runLabel) | [
"def",
"doMapPlotsDT",
"(",
"dt_basedir",
",",
"tfiles_plotting",
")",
":",
"for",
"wheel",
"in",
"DT_TYPES",
":",
"if",
"wheel",
"[",
"1",
"]",
"==",
"\"ALL\"",
":",
"continue",
"for",
"station",
"in",
"wheel",
"[",
"2",
"]",
":",
"pdir",
"=",
"dt_bas... | https://github.com/cms-sw/cmssw/blob/fd9de012d503d3405420bcbeec0ec879baa57cf2/Alignment/MuonAlignmentAlgorithms/scripts/alignmentValidation.py#L349-L452 | ||
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi/toolchain/share/gdb/python/gdb/command/explore.py | python | Explorer.return_to_parent_value_prompt | () | A utility function which prompts the user to press the 'enter' key
so that the exploration session can shift back to the parent value.
Useful when exploring values. | A utility function which prompts the user to press the 'enter' key
so that the exploration session can shift back to the parent value.
Useful when exploring values. | [
"A",
"utility",
"function",
"which",
"prompts",
"the",
"user",
"to",
"press",
"the",
"enter",
"key",
"so",
"that",
"the",
"exploration",
"session",
"can",
"shift",
"back",
"to",
"the",
"parent",
"value",
".",
"Useful",
"when",
"exploring",
"values",
"."
] | def return_to_parent_value_prompt():
"""A utility function which prompts the user to press the 'enter' key
so that the exploration session can shift back to the parent value.
Useful when exploring values.
"""
raw_input("\nPress enter to return to parent value: ") | [
"def",
"return_to_parent_value_prompt",
"(",
")",
":",
"raw_input",
"(",
"\"\\nPress enter to return to parent value: \"",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/share/gdb/python/gdb/command/explore.py#L166-L171 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/lib/agw/aui/auibar.py | python | AuiDefaultToolBarArt.DrawLabel | (self, dc, wnd, item, rect) | Draws a toolbar item label.
:param `dc`: a :class:`DC` device context;
:param `wnd`: a :class:`Window` derived window;
:param `item`: an instance of :class:`AuiToolBarItem`;
:param Rect `rect`: the :class:`AuiToolBarItem` rectangle. | Draws a toolbar item label.
:param `dc`: a :class:`DC` device context;
:param `wnd`: a :class:`Window` derived window;
:param `item`: an instance of :class:`AuiToolBarItem`;
:param Rect `rect`: the :class:`AuiToolBarItem` rectangle. | [
"Draws",
"a",
"toolbar",
"item",
"label",
".",
":",
"param",
"dc",
":",
"a",
":",
"class",
":",
"DC",
"device",
"context",
";",
":",
"param",
"wnd",
":",
"a",
":",
"class",
":",
"Window",
"derived",
"window",
";",
":",
"param",
"item",
":",
"an",
... | def DrawLabel(self, dc, wnd, item, rect):
"""
Draws a toolbar item label.
:param `dc`: a :class:`DC` device context;
:param `wnd`: a :class:`Window` derived window;
:param `item`: an instance of :class:`AuiToolBarItem`;
:param Rect `rect`: the :class:`AuiToolBarItem` rectangle.
"""
dc.SetFont(self._font)
if item.state & AUI_BUTTON_STATE_DISABLED:
dc.SetTextForeground(wx.SystemSettings.GetColour(wx.SYS_COLOUR_GRAYTEXT))
else:
dc.SetTextForeground(wx.SystemSettings.GetColour(wx.SYS_COLOUR_BTNTEXT))
orient = item.GetOrientation()
horizontal = orient == AUI_TBTOOL_HORIZONTAL
# we only care about the text height here since the text
# will get cropped based on the width of the item
label_size = GetLabelSize(dc, item.GetLabel(), not horizontal)
text_width = label_size.GetWidth()
text_height = label_size.GetHeight()
if orient == AUI_TBTOOL_HORIZONTAL:
text_x = rect.x
text_y = rect.y + (rect.height-text_height)/2
dc.DrawText(item.GetLabel(), text_x, text_y)
elif orient == AUI_TBTOOL_VERT_CLOCKWISE:
text_x = rect.x + (rect.width+text_width)/2
text_y = rect.y
dc.DrawRotatedText(item.GetLabel(), text_x, text_y, 270)
elif AUI_TBTOOL_VERT_COUNTERCLOCKWISE:
text_x = rect.x + (rect.width-text_width)/2
text_y = rect.y + text_height
dc.DrawRotatedText(item.GetLabel(), text_x, text_y, 90) | [
"def",
"DrawLabel",
"(",
"self",
",",
"dc",
",",
"wnd",
",",
"item",
",",
"rect",
")",
":",
"dc",
".",
"SetFont",
"(",
"self",
".",
"_font",
")",
"if",
"item",
".",
"state",
"&",
"AUI_BUTTON_STATE_DISABLED",
":",
"dc",
".",
"SetTextForeground",
"(",
... | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/aui/auibar.py#L941-L980 | ||
rdiankov/openrave | d1a23023fd4b58f077d2ca949ceaf1b91f3f13d7 | python/misc.py | python | OpenRAVEGlobalArguments.parseAndCreateThreadedUser | (options,userfn,createenv=openravepy_int.Environment,returnviewer=True,**kwargs) | Parse all options and create the global Environment. The left over arguments are passed to the parse functions.
If a viewer is requested, it is created in this thread, and another thread is executed with the user function. This is required for OSes that require viewer thread to be in main thread (Mac OSX)
:param userfn: Call with userfn(env,options)
:return: nothing | Parse all options and create the global Environment. The left over arguments are passed to the parse functions.
If a viewer is requested, it is created in this thread, and another thread is executed with the user function. This is required for OSes that require viewer thread to be in main thread (Mac OSX)
:param userfn: Call with userfn(env,options)
:return: nothing | [
"Parse",
"all",
"options",
"and",
"create",
"the",
"global",
"Environment",
".",
"The",
"left",
"over",
"arguments",
"are",
"passed",
"to",
"the",
"parse",
"functions",
".",
"If",
"a",
"viewer",
"is",
"requested",
"it",
"is",
"created",
"in",
"this",
"thre... | def parseAndCreateThreadedUser(options,userfn,createenv=openravepy_int.Environment,returnviewer=True,**kwargs):
"""Parse all options and create the global Environment. The left over arguments are passed to the parse functions.
If a viewer is requested, it is created in this thread, and another thread is executed with the user function. This is required for OSes that require viewer thread to be in main thread (Mac OSX)
:param userfn: Call with userfn(env,options)
:return: nothing
"""
openravepy_int.RaveInitialize(True)
for plugin in options._loadplugins:
openravepy_int.RaveLoadPlugin(plugin)
OpenRAVEGlobalArguments.parseGlobal(options,**kwargs)
if createenv is None:
raise OpenRAVEException('failed to create environment')
env = createenv()
viewername = OpenRAVEGlobalArguments.parseEnvironment(options,env,returnviewer=True,**kwargs)
SetViewerUserThread(env,viewername,lambda: userfn(env,options)) | [
"def",
"parseAndCreateThreadedUser",
"(",
"options",
",",
"userfn",
",",
"createenv",
"=",
"openravepy_int",
".",
"Environment",
",",
"returnviewer",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"openravepy_int",
".",
"RaveInitialize",
"(",
"True",
")",
"fo... | https://github.com/rdiankov/openrave/blob/d1a23023fd4b58f077d2ca949ceaf1b91f3f13d7/python/misc.py#L228-L242 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/pylowering.py | python | PyLower.cleanup_vars | (self) | Cleanup live variables. | Cleanup live variables. | [
"Cleanup",
"live",
"variables",
"."
] | def cleanup_vars(self):
"""
Cleanup live variables.
"""
for name in self._live_vars:
ptr = self._getvar(name)
self.decref(self.builder.load(ptr)) | [
"def",
"cleanup_vars",
"(",
"self",
")",
":",
"for",
"name",
"in",
"self",
".",
"_live_vars",
":",
"ptr",
"=",
"self",
".",
"_getvar",
"(",
"name",
")",
"self",
".",
"decref",
"(",
"self",
".",
"builder",
".",
"load",
"(",
"ptr",
")",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/pylowering.py#L595-L601 | ||
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/telemetry/third_party/mox3/mox3/mox.py | python | MultipleTimesGroup.AddMethod | (self, mock_method) | Add a method to this group.
Args:
mock_method: A mock method to be added to this group. | Add a method to this group. | [
"Add",
"a",
"method",
"to",
"this",
"group",
"."
] | def AddMethod(self, mock_method):
"""Add a method to this group.
Args:
mock_method: A mock method to be added to this group.
"""
self._methods.add(mock_method)
self._methods_left.add(mock_method) | [
"def",
"AddMethod",
"(",
"self",
",",
"mock_method",
")",
":",
"self",
".",
"_methods",
".",
"add",
"(",
"mock_method",
")",
"self",
".",
"_methods_left",
".",
"add",
"(",
"mock_method",
")"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/telemetry/third_party/mox3/mox3/mox.py#L2037-L2045 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/_controls.py | python | CollapsiblePane.Create | (*args, **kwargs) | return _controls_.CollapsiblePane_Create(*args, **kwargs) | Create(self, Window parent, int winid=-1, String label=EmptyString,
Point pos=DefaultPosition, Size size=DefaultSize,
long style=CP_DEFAULT_STYLE, Validator val=DefaultValidator,
String name=CollapsiblePaneNameStr) -> bool | Create(self, Window parent, int winid=-1, String label=EmptyString,
Point pos=DefaultPosition, Size size=DefaultSize,
long style=CP_DEFAULT_STYLE, Validator val=DefaultValidator,
String name=CollapsiblePaneNameStr) -> bool | [
"Create",
"(",
"self",
"Window",
"parent",
"int",
"winid",
"=",
"-",
"1",
"String",
"label",
"=",
"EmptyString",
"Point",
"pos",
"=",
"DefaultPosition",
"Size",
"size",
"=",
"DefaultSize",
"long",
"style",
"=",
"CP_DEFAULT_STYLE",
"Validator",
"val",
"=",
"D... | def Create(*args, **kwargs):
"""
Create(self, Window parent, int winid=-1, String label=EmptyString,
Point pos=DefaultPosition, Size size=DefaultSize,
long style=CP_DEFAULT_STYLE, Validator val=DefaultValidator,
String name=CollapsiblePaneNameStr) -> bool
"""
return _controls_.CollapsiblePane_Create(*args, **kwargs) | [
"def",
"Create",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_controls_",
".",
"CollapsiblePane_Create",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_controls.py#L7241-L7248 | |
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/graph_editor/edit.py | python | detach_inputs | (sgv, control_inputs=False) | return sgv, input_placeholders | Detach the inputs of a subgraph view.
Args:
sgv: the subgraph view to be detached. This argument is converted to a
subgraph using the same rules as the function subgraph.make_view.
Note that sgv is modified in place.
control_inputs: if True control_inputs are also detached.
Returns:
A tuple `(sgv, input_placeholders)` where
`sgv` is a new subgraph view of the detached subgraph;
`input_placeholders` is a list of the created input placeholders.
Raises:
StandardError: if sgv cannot be converted to a SubGraphView using
the same rules than the function subgraph.make_view. | Detach the inputs of a subgraph view. | [
"Detach",
"the",
"inputs",
"of",
"a",
"subgraph",
"view",
"."
] | def detach_inputs(sgv, control_inputs=False):
"""Detach the inputs of a subgraph view.
Args:
sgv: the subgraph view to be detached. This argument is converted to a
subgraph using the same rules as the function subgraph.make_view.
Note that sgv is modified in place.
control_inputs: if True control_inputs are also detached.
Returns:
A tuple `(sgv, input_placeholders)` where
`sgv` is a new subgraph view of the detached subgraph;
`input_placeholders` is a list of the created input placeholders.
Raises:
StandardError: if sgv cannot be converted to a SubGraphView using
the same rules than the function subgraph.make_view.
"""
sgv = subgraph.make_view(sgv)
with sgv.graph.as_default():
input_placeholders = [
tf_array_ops.placeholder(
dtype=input_t.dtype, name=util.placeholder_name(input_t))
for input_t in sgv.inputs
]
reroute.swap_inputs(sgv, input_placeholders)
if control_inputs:
detach_control_inputs(sgv)
return sgv, input_placeholders | [
"def",
"detach_inputs",
"(",
"sgv",
",",
"control_inputs",
"=",
"False",
")",
":",
"sgv",
"=",
"subgraph",
".",
"make_view",
"(",
"sgv",
")",
"with",
"sgv",
".",
"graph",
".",
"as_default",
"(",
")",
":",
"input_placeholders",
"=",
"[",
"tf_array_ops",
"... | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/graph_editor/edit.py#L70-L98 | |
hughperkins/tf-coriander | 970d3df6c11400ad68405f22b0c42a52374e94ca | tensorflow/python/client/session.py | python | _FetchMapper.unique_fetches | (self) | Return the list of unique tensors or ops needed by this fetch mapper.
Returns:
A list of tensors or ops. | Return the list of unique tensors or ops needed by this fetch mapper. | [
"Return",
"the",
"list",
"of",
"unique",
"tensors",
"or",
"ops",
"needed",
"by",
"this",
"fetch",
"mapper",
"."
] | def unique_fetches(self):
"""Return the list of unique tensors or ops needed by this fetch mapper.
Returns:
A list of tensors or ops.
"""
raise NotImplementedError('Must be implemented by subclasses') | [
"def",
"unique_fetches",
"(",
"self",
")",
":",
"raise",
"NotImplementedError",
"(",
"'Must be implemented by subclasses'",
")"
] | https://github.com/hughperkins/tf-coriander/blob/970d3df6c11400ad68405f22b0c42a52374e94ca/tensorflow/python/client/session.py#L140-L146 | ||
macchina-io/macchina.io | ef24ba0e18379c3dd48fb84e6dbf991101cb8db0 | platform/JS/V8/tools/gyp/pylib/gyp/xcodeproj_file.py | python | XCObject.Comment | (self) | return self.Name() | Return a comment string for the object.
Most objects just use their name as the comment, but PBXProject uses
different values.
The returned comment is not escaped and does not have any comment marker
strings applied to it. | Return a comment string for the object. | [
"Return",
"a",
"comment",
"string",
"for",
"the",
"object",
"."
] | def Comment(self):
"""Return a comment string for the object.
Most objects just use their name as the comment, but PBXProject uses
different values.
The returned comment is not escaped and does not have any comment marker
strings applied to it.
"""
return self.Name() | [
"def",
"Comment",
"(",
"self",
")",
":",
"return",
"self",
".",
"Name",
"(",
")"
] | https://github.com/macchina-io/macchina.io/blob/ef24ba0e18379c3dd48fb84e6dbf991101cb8db0/platform/JS/V8/tools/gyp/pylib/gyp/xcodeproj_file.py#L371-L381 | |
miyosuda/TensorFlowAndroidMNIST | 7b5a4603d2780a8a2834575706e9001977524007 | jni-build/jni/include/tensorflow/contrib/framework/python/ops/variables.py | python | get_local_variables | (scope=None, suffix=None) | return get_variables(scope, suffix, ops.GraphKeys.LOCAL_VARIABLES) | Gets the list of model variables, filtered by scope and/or suffix.
Args:
scope: an optional scope for filtering the variables to return.
suffix: an optional suffix for filtering the variables to return.
Returns:
a list of variables in colelction with scope and suffix. | Gets the list of model variables, filtered by scope and/or suffix. | [
"Gets",
"the",
"list",
"of",
"model",
"variables",
"filtered",
"by",
"scope",
"and",
"/",
"or",
"suffix",
"."
] | def get_local_variables(scope=None, suffix=None):
"""Gets the list of model variables, filtered by scope and/or suffix.
Args:
scope: an optional scope for filtering the variables to return.
suffix: an optional suffix for filtering the variables to return.
Returns:
a list of variables in colelction with scope and suffix.
"""
return get_variables(scope, suffix, ops.GraphKeys.LOCAL_VARIABLES) | [
"def",
"get_local_variables",
"(",
"scope",
"=",
"None",
",",
"suffix",
"=",
"None",
")",
":",
"return",
"get_variables",
"(",
"scope",
",",
"suffix",
",",
"ops",
".",
"GraphKeys",
".",
"LOCAL_VARIABLES",
")"
] | https://github.com/miyosuda/TensorFlowAndroidMNIST/blob/7b5a4603d2780a8a2834575706e9001977524007/jni-build/jni/include/tensorflow/contrib/framework/python/ops/variables.py#L310-L320 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/x86/toolchain/lib/python2.7/_osx_support.py | python | _override_all_archs | (_config_vars) | return _config_vars | Allow override of all archs with ARCHFLAGS env var | Allow override of all archs with ARCHFLAGS env var | [
"Allow",
"override",
"of",
"all",
"archs",
"with",
"ARCHFLAGS",
"env",
"var"
] | def _override_all_archs(_config_vars):
"""Allow override of all archs with ARCHFLAGS env var"""
# NOTE: This name was introduced by Apple in OSX 10.5 and
# is used by several scripting languages distributed with
# that OS release.
if 'ARCHFLAGS' in os.environ:
arch = os.environ['ARCHFLAGS']
for cv in _UNIVERSAL_CONFIG_VARS:
if cv in _config_vars and '-arch' in _config_vars[cv]:
flags = _config_vars[cv]
flags = re.sub('-arch\s+\w+\s', ' ', flags)
flags = flags + ' ' + arch
_save_modified_value(_config_vars, cv, flags)
return _config_vars | [
"def",
"_override_all_archs",
"(",
"_config_vars",
")",
":",
"# NOTE: This name was introduced by Apple in OSX 10.5 and",
"# is used by several scripting languages distributed with",
"# that OS release.",
"if",
"'ARCHFLAGS'",
"in",
"os",
".",
"environ",
":",
"arch",
"=",
"os",
... | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/_osx_support.py#L254-L268 | |
livecode/livecode | 4606a10ea10b16d5071d0f9f263ccdd7ede8b31d | gyp/pylib/gyp/win_tool.py | python | WinTool.Dispatch | (self, args) | return getattr(self, method)(*args[1:]) | Dispatches a string command to a method. | Dispatches a string command to a method. | [
"Dispatches",
"a",
"string",
"command",
"to",
"a",
"method",
"."
] | def Dispatch(self, args):
"""Dispatches a string command to a method."""
if len(args) < 1:
raise Exception("Not enough arguments")
method = "Exec%s" % self._CommandifyName(args[0])
return getattr(self, method)(*args[1:]) | [
"def",
"Dispatch",
"(",
"self",
",",
"args",
")",
":",
"if",
"len",
"(",
"args",
")",
"<",
"1",
":",
"raise",
"Exception",
"(",
"\"Not enough arguments\"",
")",
"method",
"=",
"\"Exec%s\"",
"%",
"self",
".",
"_CommandifyName",
"(",
"args",
"[",
"0",
"]... | https://github.com/livecode/livecode/blob/4606a10ea10b16d5071d0f9f263ccdd7ede8b31d/gyp/pylib/gyp/win_tool.py#L64-L70 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python3/src/Lib/uuid.py | python | getnode | () | Get the hardware address as a 48-bit positive integer.
The first time this runs, it may launch a separate program, which could
be quite slow. If all attempts to obtain the hardware address fail, we
choose a random 48-bit number with its eighth bit set to 1 as recommended
in RFC 4122. | Get the hardware address as a 48-bit positive integer. | [
"Get",
"the",
"hardware",
"address",
"as",
"a",
"48",
"-",
"bit",
"positive",
"integer",
"."
] | def getnode():
"""Get the hardware address as a 48-bit positive integer.
The first time this runs, it may launch a separate program, which could
be quite slow. If all attempts to obtain the hardware address fail, we
choose a random 48-bit number with its eighth bit set to 1 as recommended
in RFC 4122.
"""
global _node
if _node is not None:
return _node
for getter in _GETTERS + [_random_getnode]:
try:
_node = getter()
except:
continue
if (_node is not None) and (0 <= _node < (1 << 48)):
return _node
assert False, '_random_getnode() returned invalid value: {}'.format(_node) | [
"def",
"getnode",
"(",
")",
":",
"global",
"_node",
"if",
"_node",
"is",
"not",
"None",
":",
"return",
"_node",
"for",
"getter",
"in",
"_GETTERS",
"+",
"[",
"_random_getnode",
"]",
":",
"try",
":",
"_node",
"=",
"getter",
"(",
")",
"except",
":",
"co... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/uuid.py#L642-L661 | ||
geemaple/leetcode | 68bc5032e1ee52c22ef2f2e608053484c487af54 | leetcode/211.add-and-search-word-data-structure-design.py | python | WordDictionary.search | (self, word) | return self.search_dfs(self.root, word, 0) | Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter.
:type word: str
:rtype: bool | Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter.
:type word: str
:rtype: bool | [
"Returns",
"if",
"the",
"word",
"is",
"in",
"the",
"data",
"structure",
".",
"A",
"word",
"could",
"contain",
"the",
"dot",
"character",
".",
"to",
"represent",
"any",
"one",
"letter",
".",
":",
"type",
"word",
":",
"str",
":",
"rtype",
":",
"bool"
] | def search(self, word):
"""
Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter.
:type word: str
:rtype: bool
"""
return self.search_dfs(self.root, word, 0) | [
"def",
"search",
"(",
"self",
",",
"word",
")",
":",
"return",
"self",
".",
"search_dfs",
"(",
"self",
".",
"root",
",",
"word",
",",
"0",
")"
] | https://github.com/geemaple/leetcode/blob/68bc5032e1ee52c22ef2f2e608053484c487af54/leetcode/211.add-and-search-word-data-structure-design.py#L29-L35 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/propgrid.py | python | PGEditorDialogAdapter.ShowDialog | (*args, **kwargs) | return _propgrid.PGEditorDialogAdapter_ShowDialog(*args, **kwargs) | ShowDialog(self, PropertyGrid propGrid, PGProperty property) -> bool | ShowDialog(self, PropertyGrid propGrid, PGProperty property) -> bool | [
"ShowDialog",
"(",
"self",
"PropertyGrid",
"propGrid",
"PGProperty",
"property",
")",
"-",
">",
"bool"
] | def ShowDialog(*args, **kwargs):
"""ShowDialog(self, PropertyGrid propGrid, PGProperty property) -> bool"""
return _propgrid.PGEditorDialogAdapter_ShowDialog(*args, **kwargs) | [
"def",
"ShowDialog",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_propgrid",
".",
"PGEditorDialogAdapter_ShowDialog",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/propgrid.py#L2791-L2793 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/lib-tk/Tkinter.py | python | Listbox.scan_dragto | (self, x, y) | Adjust the view of the listbox to 10 times the
difference between X and Y and the coordinates given in
scan_mark. | Adjust the view of the listbox to 10 times the
difference between X and Y and the coordinates given in
scan_mark. | [
"Adjust",
"the",
"view",
"of",
"the",
"listbox",
"to",
"10",
"times",
"the",
"difference",
"between",
"X",
"and",
"Y",
"and",
"the",
"coordinates",
"given",
"in",
"scan_mark",
"."
] | def scan_dragto(self, x, y):
"""Adjust the view of the listbox to 10 times the
difference between X and Y and the coordinates given in
scan_mark."""
self.tk.call(self._w, 'scan', 'dragto', x, y) | [
"def",
"scan_dragto",
"(",
"self",
",",
"x",
",",
"y",
")",
":",
"self",
".",
"tk",
".",
"call",
"(",
"self",
".",
"_w",
",",
"'scan'",
",",
"'dragto'",
",",
"x",
",",
"y",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/lib-tk/Tkinter.py#L2588-L2592 | ||
windystrife/UnrealEngine_NVIDIAGameWorks | b50e6338a7c5b26374d66306ebc7807541ff815e | Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/site-packages/sipconfig.py | python | error | (msg) | Display an error message and terminate.
msg is the text of the error message. | Display an error message and terminate. | [
"Display",
"an",
"error",
"message",
"and",
"terminate",
"."
] | def error(msg):
"""Display an error message and terminate.
msg is the text of the error message.
"""
sys.stderr.write(format("Error: " + msg) + "\n")
sys.exit(1) | [
"def",
"error",
"(",
"msg",
")",
":",
"sys",
".",
"stderr",
".",
"write",
"(",
"format",
"(",
"\"Error: \"",
"+",
"msg",
")",
"+",
"\"\\n\"",
")",
"sys",
".",
"exit",
"(",
"1",
")"
] | https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/site-packages/sipconfig.py#L2314-L2320 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/_windows.py | python | FileDialog.SetPath | (*args, **kwargs) | return _windows_.FileDialog_SetPath(*args, **kwargs) | SetPath(self, String path)
Sets the path (the combined directory and filename that will be
returned when the dialog is dismissed). | SetPath(self, String path) | [
"SetPath",
"(",
"self",
"String",
"path",
")"
] | def SetPath(*args, **kwargs):
"""
SetPath(self, String path)
Sets the path (the combined directory and filename that will be
returned when the dialog is dismissed).
"""
return _windows_.FileDialog_SetPath(*args, **kwargs) | [
"def",
"SetPath",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_windows_",
".",
"FileDialog_SetPath",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_windows.py#L3150-L3157 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python/src/Lib/_pyio.py | python | BufferedReader.read1 | (self, n) | Reads up to n bytes, with at most one read() system call. | Reads up to n bytes, with at most one read() system call. | [
"Reads",
"up",
"to",
"n",
"bytes",
"with",
"at",
"most",
"one",
"read",
"()",
"system",
"call",
"."
] | def read1(self, n):
"""Reads up to n bytes, with at most one read() system call."""
# Returns up to n bytes. If at least one byte is buffered, we
# only return buffered bytes. Otherwise, we do one raw read.
if n < 0:
raise ValueError("number of bytes to read must be positive")
if n == 0:
return b""
with self._read_lock:
self._peek_unlocked(1)
return self._read_unlocked(
min(n, len(self._read_buf) - self._read_pos)) | [
"def",
"read1",
"(",
"self",
",",
"n",
")",
":",
"# Returns up to n bytes. If at least one byte is buffered, we",
"# only return buffered bytes. Otherwise, we do one raw read.",
"if",
"n",
"<",
"0",
":",
"raise",
"ValueError",
"(",
"\"number of bytes to read must be positive\""... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/_pyio.py#L1035-L1046 | ||
mongodb/mongo | d8ff665343ad29cf286ee2cf4a1960d29371937b | buildscripts/resmokelib/powercycle/lib/services.py | python | WindowsService.update | (self) | return ret, output | Update installed service. Return (code, output) tuple. | Update installed service. Return (code, output) tuple. | [
"Update",
"installed",
"service",
".",
"Return",
"(",
"code",
"output",
")",
"tuple",
"."
] | def update(self):
"""Update installed service. Return (code, output) tuple."""
if self.status() not in self._states.values():
return 1, "Service update '{}' status: {}".format(self.name, self.status())
try:
win32serviceutil.ChangeServiceConfig(pythonClassString="Service.{}".format(
self.name), serviceName=self.name, displayName=self.name, startType=self.start_type,
exeName=self.bin_path, exeArgs=self.bin_options)
ret = 0
output = "Service '{}' updated".format(self.name)
except pywintypes.error as err:
ret = err.winerror
output = f"{err.args[1]}: {err.args[2]}"
return ret, output | [
"def",
"update",
"(",
"self",
")",
":",
"if",
"self",
".",
"status",
"(",
")",
"not",
"in",
"self",
".",
"_states",
".",
"values",
"(",
")",
":",
"return",
"1",
",",
"\"Service update '{}' status: {}\"",
".",
"format",
"(",
"self",
".",
"name",
",",
... | https://github.com/mongodb/mongo/blob/d8ff665343ad29cf286ee2cf4a1960d29371937b/buildscripts/resmokelib/powercycle/lib/services.py#L80-L94 | |
google/skia | 82d65d0487bd72f5f7332d002429ec2dc61d2463 | infra/bots/recipe_modules/run/api.py | python | SkiaStepApi.__init__ | (self, *args, **kwargs) | Initialize the recipe module. | Initialize the recipe module. | [
"Initialize",
"the",
"recipe",
"module",
"."
] | def __init__(self, *args, **kwargs):
"""Initialize the recipe module."""
super(SkiaStepApi, self).__init__(*args, **kwargs)
self._already_ran = {}
self._ccache = None
self._checked_for_ccache = False
self._failed = [] | [
"def",
"__init__",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"super",
"(",
"SkiaStepApi",
",",
"self",
")",
".",
"__init__",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"self",
".",
"_already_ran",
"=",
"{",
"}",
"self... | https://github.com/google/skia/blob/82d65d0487bd72f5f7332d002429ec2dc61d2463/infra/bots/recipe_modules/run/api.py#L16-L23 | ||
Atarity/Lightpack | 4dee73a443cba4c4073291febe450e6c1941f3af | Software/apiexamples/liOSC/LiOSC.py | python | LightOSC.run | (self, oscClientHost, oscClientPort) | Запуск сервера
oscClientHost, oscClientPort - IP и порт OSC-клиента с пользовательским интерфейсом | Запуск сервера
oscClientHost, oscClientPort - IP и порт OSC-клиента с пользовательским интерфейсом | [
"Запуск",
"сервера",
"oscClientHost",
"oscClientPort",
"-",
"IP",
"и",
"порт",
"OSC",
"-",
"клиента",
"с",
"пользовательским",
"интерфейсом"
] | def run(self, oscClientHost, oscClientPort):
""" Запуск сервера
oscClientHost, oscClientPort - IP и порт OSC-клиента с пользовательским интерфейсом """ | [
"def",
"run",
"(",
"self",
",",
"oscClientHost",
",",
"oscClientPort",
")",
":"
] | https://github.com/Atarity/Lightpack/blob/4dee73a443cba4c4073291febe450e6c1941f3af/Software/apiexamples/liOSC/LiOSC.py#L42-L44 | ||
Mahlet-Inc/hobbits | 071d7a542f1af0a7791bcaab17b08224df9ecd4e | src/hobbits-plugins/analyzers/KaitaiStruct/ksy_py/archive/android_img.py | python | AndroidImg.tags_offset | (self) | return self._m_tags_offset if hasattr(self, '_m_tags_offset') else None | tags offset from base. | tags offset from base. | [
"tags",
"offset",
"from",
"base",
"."
] | def tags_offset(self):
"""tags offset from base."""
if hasattr(self, '_m_tags_offset'):
return self._m_tags_offset if hasattr(self, '_m_tags_offset') else None
self._m_tags_offset = (self.tags_load - self.base)
return self._m_tags_offset if hasattr(self, '_m_tags_offset') else None | [
"def",
"tags_offset",
"(",
"self",
")",
":",
"if",
"hasattr",
"(",
"self",
",",
"'_m_tags_offset'",
")",
":",
"return",
"self",
".",
"_m_tags_offset",
"if",
"hasattr",
"(",
"self",
",",
"'_m_tags_offset'",
")",
"else",
"None",
"self",
".",
"_m_tags_offset",
... | https://github.com/Mahlet-Inc/hobbits/blob/071d7a542f1af0a7791bcaab17b08224df9ecd4e/src/hobbits-plugins/analyzers/KaitaiStruct/ksy_py/archive/android_img.py#L204-L210 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/cython/Cython/Compiler/ExprNodes.py | python | MemoryViewSliceNode.calculate_result_code | (self) | return self.base.result() | This is called in case this is a no-op slicing node | This is called in case this is a no-op slicing node | [
"This",
"is",
"called",
"in",
"case",
"this",
"is",
"a",
"no",
"-",
"op",
"slicing",
"node"
] | def calculate_result_code(self):
"""This is called in case this is a no-op slicing node"""
return self.base.result() | [
"def",
"calculate_result_code",
"(",
"self",
")",
":",
"return",
"self",
".",
"base",
".",
"result",
"(",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/cython/Cython/Compiler/ExprNodes.py#L4595-L4597 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numpy/polynomial/hermite.py | python | hermint | (c, m=1, k=[], lbnd=0, scl=1, axis=0) | return c | Integrate a Hermite series.
Returns the Hermite series coefficients `c` integrated `m` times from
`lbnd` along `axis`. At each iteration the resulting series is
**multiplied** by `scl` and an integration constant, `k`, is added.
The scaling factor is for use in a linear change of variable. ("Buyer
beware": note that, depending on what one is doing, one may want `scl`
to be the reciprocal of what one might expect; for more information,
see the Notes section below.) The argument `c` is an array of
coefficients from low to high degree along each axis, e.g., [1,2,3]
represents the series ``H_0 + 2*H_1 + 3*H_2`` while [[1,2],[1,2]]
represents ``1*H_0(x)*H_0(y) + 1*H_1(x)*H_0(y) + 2*H_0(x)*H_1(y) +
2*H_1(x)*H_1(y)`` if axis=0 is ``x`` and axis=1 is ``y``.
Parameters
----------
c : array_like
Array of Hermite series coefficients. If c is multidimensional the
different axis correspond to different variables with the degree in
each axis given by the corresponding index.
m : int, optional
Order of integration, must be positive. (Default: 1)
k : {[], list, scalar}, optional
Integration constant(s). The value of the first integral at
``lbnd`` is the first value in the list, the value of the second
integral at ``lbnd`` is the second value, etc. If ``k == []`` (the
default), all constants are set to zero. If ``m == 1``, a single
scalar can be given instead of a list.
lbnd : scalar, optional
The lower bound of the integral. (Default: 0)
scl : scalar, optional
Following each integration the result is *multiplied* by `scl`
before the integration constant is added. (Default: 1)
axis : int, optional
Axis over which the integral is taken. (Default: 0).
.. versionadded:: 1.7.0
Returns
-------
S : ndarray
Hermite series coefficients of the integral.
Raises
------
ValueError
If ``m < 0``, ``len(k) > m``, ``np.ndim(lbnd) != 0``, or
``np.ndim(scl) != 0``.
See Also
--------
hermder
Notes
-----
Note that the result of each integration is *multiplied* by `scl`.
Why is this important to note? Say one is making a linear change of
variable :math:`u = ax + b` in an integral relative to `x`. Then
:math:`dx = du/a`, so one will need to set `scl` equal to
:math:`1/a` - perhaps not what one would have first thought.
Also note that, in general, the result of integrating a C-series needs
to be "reprojected" onto the C-series basis set. Thus, typically,
the result of this function is "unintuitive," albeit correct; see
Examples section below.
Examples
--------
>>> from numpy.polynomial.hermite import hermint
>>> hermint([1,2,3]) # integrate once, value 0 at 0.
array([1. , 0.5, 0.5, 0.5])
>>> hermint([1,2,3], m=2) # integrate twice, value & deriv 0 at 0
array([-0.5 , 0.5 , 0.125 , 0.08333333, 0.0625 ]) # may vary
>>> hermint([1,2,3], k=1) # integrate once, value 1 at 0.
array([2. , 0.5, 0.5, 0.5])
>>> hermint([1,2,3], lbnd=-1) # integrate once, value 0 at -1
array([-2. , 0.5, 0.5, 0.5])
>>> hermint([1,2,3], m=2, k=[1,2], lbnd=-1)
array([ 1.66666667, -0.5 , 0.125 , 0.08333333, 0.0625 ]) # may vary | Integrate a Hermite series. | [
"Integrate",
"a",
"Hermite",
"series",
"."
] | def hermint(c, m=1, k=[], lbnd=0, scl=1, axis=0):
"""
Integrate a Hermite series.
Returns the Hermite series coefficients `c` integrated `m` times from
`lbnd` along `axis`. At each iteration the resulting series is
**multiplied** by `scl` and an integration constant, `k`, is added.
The scaling factor is for use in a linear change of variable. ("Buyer
beware": note that, depending on what one is doing, one may want `scl`
to be the reciprocal of what one might expect; for more information,
see the Notes section below.) The argument `c` is an array of
coefficients from low to high degree along each axis, e.g., [1,2,3]
represents the series ``H_0 + 2*H_1 + 3*H_2`` while [[1,2],[1,2]]
represents ``1*H_0(x)*H_0(y) + 1*H_1(x)*H_0(y) + 2*H_0(x)*H_1(y) +
2*H_1(x)*H_1(y)`` if axis=0 is ``x`` and axis=1 is ``y``.
Parameters
----------
c : array_like
Array of Hermite series coefficients. If c is multidimensional the
different axis correspond to different variables with the degree in
each axis given by the corresponding index.
m : int, optional
Order of integration, must be positive. (Default: 1)
k : {[], list, scalar}, optional
Integration constant(s). The value of the first integral at
``lbnd`` is the first value in the list, the value of the second
integral at ``lbnd`` is the second value, etc. If ``k == []`` (the
default), all constants are set to zero. If ``m == 1``, a single
scalar can be given instead of a list.
lbnd : scalar, optional
The lower bound of the integral. (Default: 0)
scl : scalar, optional
Following each integration the result is *multiplied* by `scl`
before the integration constant is added. (Default: 1)
axis : int, optional
Axis over which the integral is taken. (Default: 0).
.. versionadded:: 1.7.0
Returns
-------
S : ndarray
Hermite series coefficients of the integral.
Raises
------
ValueError
If ``m < 0``, ``len(k) > m``, ``np.ndim(lbnd) != 0``, or
``np.ndim(scl) != 0``.
See Also
--------
hermder
Notes
-----
Note that the result of each integration is *multiplied* by `scl`.
Why is this important to note? Say one is making a linear change of
variable :math:`u = ax + b` in an integral relative to `x`. Then
:math:`dx = du/a`, so one will need to set `scl` equal to
:math:`1/a` - perhaps not what one would have first thought.
Also note that, in general, the result of integrating a C-series needs
to be "reprojected" onto the C-series basis set. Thus, typically,
the result of this function is "unintuitive," albeit correct; see
Examples section below.
Examples
--------
>>> from numpy.polynomial.hermite import hermint
>>> hermint([1,2,3]) # integrate once, value 0 at 0.
array([1. , 0.5, 0.5, 0.5])
>>> hermint([1,2,3], m=2) # integrate twice, value & deriv 0 at 0
array([-0.5 , 0.5 , 0.125 , 0.08333333, 0.0625 ]) # may vary
>>> hermint([1,2,3], k=1) # integrate once, value 1 at 0.
array([2. , 0.5, 0.5, 0.5])
>>> hermint([1,2,3], lbnd=-1) # integrate once, value 0 at -1
array([-2. , 0.5, 0.5, 0.5])
>>> hermint([1,2,3], m=2, k=[1,2], lbnd=-1)
array([ 1.66666667, -0.5 , 0.125 , 0.08333333, 0.0625 ]) # may vary
"""
c = np.array(c, ndmin=1, copy=True)
if c.dtype.char in '?bBhHiIlLqQpP':
c = c.astype(np.double)
if not np.iterable(k):
k = [k]
cnt = pu._deprecate_as_int(m, "the order of integration")
iaxis = pu._deprecate_as_int(axis, "the axis")
if cnt < 0:
raise ValueError("The order of integration must be non-negative")
if len(k) > cnt:
raise ValueError("Too many integration constants")
if np.ndim(lbnd) != 0:
raise ValueError("lbnd must be a scalar.")
if np.ndim(scl) != 0:
raise ValueError("scl must be a scalar.")
iaxis = normalize_axis_index(iaxis, c.ndim)
if cnt == 0:
return c
c = np.moveaxis(c, iaxis, 0)
k = list(k) + [0]*(cnt - len(k))
for i in range(cnt):
n = len(c)
c *= scl
if n == 1 and np.all(c[0] == 0):
c[0] += k[i]
else:
tmp = np.empty((n + 1,) + c.shape[1:], dtype=c.dtype)
tmp[0] = c[0]*0
tmp[1] = c[0]/2
for j in range(1, n):
tmp[j + 1] = c[j]/(2*(j + 1))
tmp[0] += k[i] - hermval(lbnd, tmp)
c = tmp
c = np.moveaxis(c, 0, iaxis)
return c | [
"def",
"hermint",
"(",
"c",
",",
"m",
"=",
"1",
",",
"k",
"=",
"[",
"]",
",",
"lbnd",
"=",
"0",
",",
"scl",
"=",
"1",
",",
"axis",
"=",
"0",
")",
":",
"c",
"=",
"np",
".",
"array",
"(",
"c",
",",
"ndmin",
"=",
"1",
",",
"copy",
"=",
"... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numpy/polynomial/hermite.py#L658-L777 | |
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | scripts/Inelastic/Direct/DirectEnergyConversion.py | python | DirectEnergyConversion.remove_empty_background | (self,masking_ws=None) | Remove empty background from the workspaces, described by RunDescriptors, specified here
Inputs:
masking_ws -- if provided, mask empty background workspace before extracting it from
workspaces requested | Remove empty background from the workspaces, described by RunDescriptors, specified here
Inputs:
masking_ws -- if provided, mask empty background workspace before extracting it from
workspaces requested | [
"Remove",
"empty",
"background",
"from",
"the",
"workspaces",
"described",
"by",
"RunDescriptors",
"specified",
"here",
"Inputs",
":",
"masking_ws",
"--",
"if",
"provided",
"mask",
"empty",
"background",
"workspace",
"before",
"extracting",
"it",
"from",
"workspaces... | def remove_empty_background(self,masking_ws=None):
"""Remove empty background from the workspaces, described by RunDescriptors, specified here
Inputs:
masking_ws -- if provided, mask empty background workspace before extracting it from
workspaces requested
"""
prop_man = self.prop_man
# list of RunDescriptors to extract and process workspaces
rd_to_process = ['sample_run','wb_run','monovan_run','wb_for_monovan_run']
# list of Background properties
bg_to_process = ['empty_bg_run','empty_bg_run_for_wb','empty_bg_run_for_monovan','empty_bg_run_for_monoWb']
for rd_name,bg_rd_name in zip(rd_to_process,bg_to_process):
rd_prop = prop_man.get_prop_class(rd_name)
bg_prop = prop_man.get_prop_class(bg_rd_name)
empty_bg_ws = bg_prop.get_workspace()
if masking_ws is not None and empty_bg_ws is not None:
MaskDetectors(empty_bg_ws, MaskedWorkspace=masking_ws)
rd_prop.remove_empty_background(empty_bg_ws) | [
"def",
"remove_empty_background",
"(",
"self",
",",
"masking_ws",
"=",
"None",
")",
":",
"prop_man",
"=",
"self",
".",
"prop_man",
"# list of RunDescriptors to extract and process workspaces",
"rd_to_process",
"=",
"[",
"'sample_run'",
",",
"'wb_run'",
",",
"'monovan_ru... | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/scripts/Inelastic/Direct/DirectEnergyConversion.py#L586-L605 | ||
adobe/chromium | cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7 | third_party/tlslite/tlslite/X509.py | python | X509.getCommonName | (self) | Get the Subject's Common Name from the certificate.
The cryptlib_py module must be installed in order to use this
function.
@rtype: str or None
@return: The CN component of the certificate's subject DN, if
present. | Get the Subject's Common Name from the certificate. | [
"Get",
"the",
"Subject",
"s",
"Common",
"Name",
"from",
"the",
"certificate",
"."
] | def getCommonName(self):
"""Get the Subject's Common Name from the certificate.
The cryptlib_py module must be installed in order to use this
function.
@rtype: str or None
@return: The CN component of the certificate's subject DN, if
present.
"""
import cryptlib_py
import array
c = cryptlib_py.cryptImportCert(self.bytes, cryptlib_py.CRYPT_UNUSED)
name = cryptlib_py.CRYPT_CERTINFO_COMMONNAME
try:
try:
length = cryptlib_py.cryptGetAttributeString(c, name, None)
returnVal = array.array('B', [0] * length)
cryptlib_py.cryptGetAttributeString(c, name, returnVal)
returnVal = returnVal.tostring()
except cryptlib_py.CryptException, e:
if e[0] == cryptlib_py.CRYPT_ERROR_NOTFOUND:
returnVal = None
return returnVal
finally:
cryptlib_py.cryptDestroyCert(c) | [
"def",
"getCommonName",
"(",
"self",
")",
":",
"import",
"cryptlib_py",
"import",
"array",
"c",
"=",
"cryptlib_py",
".",
"cryptImportCert",
"(",
"self",
".",
"bytes",
",",
"cryptlib_py",
".",
"CRYPT_UNUSED",
")",
"name",
"=",
"cryptlib_py",
".",
"CRYPT_CERTINF... | https://github.com/adobe/chromium/blob/cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7/third_party/tlslite/tlslite/X509.py#L112-L137 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/pydoc.py | python | HTMLDoc.section | (self, title, fgcol, bgcol, contents, width=6,
prelude='', marginalia=None, gap=' ') | return result + '\n<td width="100%%">%s</td></tr></table>' % contents | Format a section with a heading. | Format a section with a heading. | [
"Format",
"a",
"section",
"with",
"a",
"heading",
"."
] | def section(self, title, fgcol, bgcol, contents, width=6,
prelude='', marginalia=None, gap=' '):
"""Format a section with a heading."""
if marginalia is None:
marginalia = '<tt>' + ' ' * width + '</tt>'
result = '''<p>
<table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
<tr bgcolor="%s">
<td colspan=3 valign=bottom> <br>
<font color="%s" face="helvetica, arial">%s</font></td></tr>
''' % (bgcol, fgcol, title)
if prelude:
result = result + '''
<tr bgcolor="%s"><td rowspan=2>%s</td>
<td colspan=2>%s</td></tr>
<tr><td>%s</td>''' % (bgcol, marginalia, prelude, gap)
else:
result = result + '''
<tr><td bgcolor="%s">%s</td><td>%s</td>''' % (bgcol, marginalia, gap)
return result + '\n<td width="100%%">%s</td></tr></table>' % contents | [
"def",
"section",
"(",
"self",
",",
"title",
",",
"fgcol",
",",
"bgcol",
",",
"contents",
",",
"width",
"=",
"6",
",",
"prelude",
"=",
"''",
",",
"marginalia",
"=",
"None",
",",
"gap",
"=",
"' '",
")",
":",
"if",
"marginalia",
"is",
"None",
":... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/pydoc.py#L502-L522 | |
larroy/clearskies_core | 3574ddf0edc8555454c7044126e786a6c29444dc | tools/gyp/pylib/gyp/xcodeproj_file.py | python | XCObject.UpdateProperties | (self, properties, do_copy=False) | Merge the supplied properties into the _properties dictionary.
The input properties must adhere to the class schema or a KeyError or
TypeError exception will be raised. If adding an object of an XCObject
subclass and the schema indicates a strong relationship, the object's
parent will be set to this object.
If do_copy is True, then lists, dicts, strong-owned XCObjects, and
strong-owned XCObjects in lists will be copied instead of having their
references added. | Merge the supplied properties into the _properties dictionary. | [
"Merge",
"the",
"supplied",
"properties",
"into",
"the",
"_properties",
"dictionary",
"."
] | def UpdateProperties(self, properties, do_copy=False):
"""Merge the supplied properties into the _properties dictionary.
The input properties must adhere to the class schema or a KeyError or
TypeError exception will be raised. If adding an object of an XCObject
subclass and the schema indicates a strong relationship, the object's
parent will be set to this object.
If do_copy is True, then lists, dicts, strong-owned XCObjects, and
strong-owned XCObjects in lists will be copied instead of having their
references added.
"""
if properties is None:
return
for property, value in properties.iteritems():
# Make sure the property is in the schema.
if not property in self._schema:
raise KeyError, property + ' not in ' + self.__class__.__name__
# Make sure the property conforms to the schema.
(is_list, property_type, is_strong) = self._schema[property][0:3]
if is_list:
if value.__class__ != list:
raise TypeError, \
property + ' of ' + self.__class__.__name__ + \
' must be list, not ' + value.__class__.__name__
for item in value:
if not isinstance(item, property_type) and \
not (item.__class__ == unicode and property_type == str):
# Accept unicode where str is specified. str is treated as
# UTF-8-encoded.
raise TypeError, \
'item of ' + property + ' of ' + self.__class__.__name__ + \
' must be ' + property_type.__name__ + ', not ' + \
item.__class__.__name__
elif not isinstance(value, property_type) and \
not (value.__class__ == unicode and property_type == str):
# Accept unicode where str is specified. str is treated as
# UTF-8-encoded.
raise TypeError, \
property + ' of ' + self.__class__.__name__ + ' must be ' + \
property_type.__name__ + ', not ' + value.__class__.__name__
# Checks passed, perform the assignment.
if do_copy:
if isinstance(value, XCObject):
if is_strong:
self._properties[property] = value.Copy()
else:
self._properties[property] = value
elif isinstance(value, str) or isinstance(value, unicode) or \
isinstance(value, int):
self._properties[property] = value
elif isinstance(value, list):
if is_strong:
# If is_strong is True, each element is an XCObject, so it's safe
# to call Copy.
self._properties[property] = []
for item in value:
self._properties[property].append(item.Copy())
else:
self._properties[property] = value[:]
elif isinstance(value, dict):
self._properties[property] = value.copy()
else:
raise TypeError, "Don't know how to copy a " + \
value.__class__.__name__ + ' object for ' + \
property + ' in ' + self.__class__.__name__
else:
self._properties[property] = value
# Set up the child's back-reference to this object. Don't use |value|
# any more because it may not be right if do_copy is true.
if is_strong:
if not is_list:
self._properties[property].parent = self
else:
for item in self._properties[property]:
item.parent = self | [
"def",
"UpdateProperties",
"(",
"self",
",",
"properties",
",",
"do_copy",
"=",
"False",
")",
":",
"if",
"properties",
"is",
"None",
":",
"return",
"for",
"property",
",",
"value",
"in",
"properties",
".",
"iteritems",
"(",
")",
":",
"# Make sure the propert... | https://github.com/larroy/clearskies_core/blob/3574ddf0edc8555454c7044126e786a6c29444dc/tools/gyp/pylib/gyp/xcodeproj_file.py#L740-L820 | ||
hughperkins/tf-coriander | 970d3df6c11400ad68405f22b0c42a52374e94ca | tensorflow/python/framework/ops.py | python | Graph.control_dependencies | (self, control_inputs) | return self._ControlDependenciesController(self, control_ops) | Returns a context manager that specifies control dependencies.
Use with the `with` keyword to specify that all operations constructed
within the context should have control dependencies on
`control_inputs`. For example:
```python
with g.control_dependencies([a, b, c]):
# `d` and `e` will only run after `a`, `b`, and `c` have executed.
d = ...
e = ...
```
Multiple calls to `control_dependencies()` can be nested, and in
that case a new `Operation` will have control dependencies on the union
of `control_inputs` from all active contexts.
```python
with g.control_dependencies([a, b]):
# Ops constructed here run after `a` and `b`.
with g.control_dependencies([c, d]):
# Ops constructed here run after `a`, `b`, `c`, and `d`.
```
You can pass None to clear the control dependencies:
```python
with g.control_dependencies([a, b]):
# Ops constructed here run after `a` and `b`.
with g.control_dependencies(None):
# Ops constructed here run normally, not waiting for either `a` or `b`.
with g.control_dependencies([c, d]):
# Ops constructed here run after `c` and `d`, also not waiting
# for either `a` or `b`.
```
*N.B.* The control dependencies context applies *only* to ops that
are constructed within the context. Merely using an op or tensor
in the context does not add a control dependency. The following
example illustrates this point:
```python
# WRONG
def my_func(pred, tensor):
t = tf.matmul(tensor, tensor)
with tf.control_dependencies([pred]):
# The matmul op is created outside the context, so no control
# dependency will be added.
return t
# RIGHT
def my_func(pred, tensor):
with tf.control_dependencies([pred]):
# The matmul op is created in the context, so a control dependency
# will be added.
return tf.matmul(tensor, tensor)
```
Args:
control_inputs: A list of `Operation` or `Tensor` objects which
must be executed or computed before running the operations
defined in the context. Can also be `None` to clear the control
dependencies.
Returns:
A context manager that specifies control dependencies for all
operations constructed within the context.
Raises:
TypeError: If `control_inputs` is not a list of `Operation` or
`Tensor` objects. | Returns a context manager that specifies control dependencies. | [
"Returns",
"a",
"context",
"manager",
"that",
"specifies",
"control",
"dependencies",
"."
] | def control_dependencies(self, control_inputs):
"""Returns a context manager that specifies control dependencies.
Use with the `with` keyword to specify that all operations constructed
within the context should have control dependencies on
`control_inputs`. For example:
```python
with g.control_dependencies([a, b, c]):
# `d` and `e` will only run after `a`, `b`, and `c` have executed.
d = ...
e = ...
```
Multiple calls to `control_dependencies()` can be nested, and in
that case a new `Operation` will have control dependencies on the union
of `control_inputs` from all active contexts.
```python
with g.control_dependencies([a, b]):
# Ops constructed here run after `a` and `b`.
with g.control_dependencies([c, d]):
# Ops constructed here run after `a`, `b`, `c`, and `d`.
```
You can pass None to clear the control dependencies:
```python
with g.control_dependencies([a, b]):
# Ops constructed here run after `a` and `b`.
with g.control_dependencies(None):
# Ops constructed here run normally, not waiting for either `a` or `b`.
with g.control_dependencies([c, d]):
# Ops constructed here run after `c` and `d`, also not waiting
# for either `a` or `b`.
```
*N.B.* The control dependencies context applies *only* to ops that
are constructed within the context. Merely using an op or tensor
in the context does not add a control dependency. The following
example illustrates this point:
```python
# WRONG
def my_func(pred, tensor):
t = tf.matmul(tensor, tensor)
with tf.control_dependencies([pred]):
# The matmul op is created outside the context, so no control
# dependency will be added.
return t
# RIGHT
def my_func(pred, tensor):
with tf.control_dependencies([pred]):
# The matmul op is created in the context, so a control dependency
# will be added.
return tf.matmul(tensor, tensor)
```
Args:
control_inputs: A list of `Operation` or `Tensor` objects which
must be executed or computed before running the operations
defined in the context. Can also be `None` to clear the control
dependencies.
Returns:
A context manager that specifies control dependencies for all
operations constructed within the context.
Raises:
TypeError: If `control_inputs` is not a list of `Operation` or
`Tensor` objects.
"""
if control_inputs is None:
return self._ControlDependenciesController(self, None)
# First convert the inputs to ops, and deduplicate them.
# NOTE(mrry): Other than deduplication, we do not currently track direct
# or indirect dependencies between control_inputs, which may result in
# redundant control inputs.
control_ops = []
current = self._current_control_dependencies()
for c in control_inputs:
c = self.as_graph_element(c)
if isinstance(c, Tensor):
c = c.op
elif not isinstance(c, Operation):
raise TypeError("Control input must be Operation or Tensor: %s" % c)
if c not in current:
control_ops.append(c)
current.add(c)
return self._ControlDependenciesController(self, control_ops) | [
"def",
"control_dependencies",
"(",
"self",
",",
"control_inputs",
")",
":",
"if",
"control_inputs",
"is",
"None",
":",
"return",
"self",
".",
"_ControlDependenciesController",
"(",
"self",
",",
"None",
")",
"# First convert the inputs to ops, and deduplicate them.",
"#... | https://github.com/hughperkins/tf-coriander/blob/970d3df6c11400ad68405f22b0c42a52374e94ca/tensorflow/python/framework/ops.py#L3272-L3362 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/distutils/ccompiler.py | python | CCompiler._setup_compile | (self, outdir, macros, incdirs, sources, depends,
extra) | return macros, objects, extra, pp_opts, build | Process arguments and decide which source files to compile. | Process arguments and decide which source files to compile. | [
"Process",
"arguments",
"and",
"decide",
"which",
"source",
"files",
"to",
"compile",
"."
] | def _setup_compile(self, outdir, macros, incdirs, sources, depends,
extra):
"""Process arguments and decide which source files to compile."""
if outdir is None:
outdir = self.output_dir
elif not isinstance(outdir, str):
raise TypeError, "'output_dir' must be a string or None"
if macros is None:
macros = self.macros
elif isinstance(macros, list):
macros = macros + (self.macros or [])
else:
raise TypeError, "'macros' (if supplied) must be a list of tuples"
if incdirs is None:
incdirs = self.include_dirs
elif isinstance(incdirs, (list, tuple)):
incdirs = list(incdirs) + (self.include_dirs or [])
else:
raise TypeError, \
"'include_dirs' (if supplied) must be a list of strings"
if extra is None:
extra = []
# Get the list of expected output (object) files
objects = self.object_filenames(sources,
strip_dir=0,
output_dir=outdir)
assert len(objects) == len(sources)
pp_opts = gen_preprocess_options(macros, incdirs)
build = {}
for i in range(len(sources)):
src = sources[i]
obj = objects[i]
ext = os.path.splitext(src)[1]
self.mkpath(os.path.dirname(obj))
build[obj] = (src, ext)
return macros, objects, extra, pp_opts, build | [
"def",
"_setup_compile",
"(",
"self",
",",
"outdir",
",",
"macros",
",",
"incdirs",
",",
"sources",
",",
"depends",
",",
"extra",
")",
":",
"if",
"outdir",
"is",
"None",
":",
"outdir",
"=",
"self",
".",
"output_dir",
"elif",
"not",
"isinstance",
"(",
"... | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/distutils/ccompiler.py#L323-L365 | |
mindspore-ai/mindspore | fb8fd3338605bb34fa5cea054e535a8b1d753fab | mindspore/python/mindspore/nn/layer/quant.py | python | Conv2dQuant.__init__ | (self,
in_channels,
out_channels,
kernel_size,
stride=1,
pad_mode='same',
padding=0,
dilation=1,
group=1,
has_bias=False,
weight_init='normal',
bias_init='zeros',
quant_config=quant_config_default,
quant_dtype=QuantDtype.INT8) | Initialize Conv2dQuant. | Initialize Conv2dQuant. | [
"Initialize",
"Conv2dQuant",
"."
] | def __init__(self,
in_channels,
out_channels,
kernel_size,
stride=1,
pad_mode='same',
padding=0,
dilation=1,
group=1,
has_bias=False,
weight_init='normal',
bias_init='zeros',
quant_config=quant_config_default,
quant_dtype=QuantDtype.INT8):
"""Initialize Conv2dQuant."""
super(Conv2dQuant, self).__init__()
self.in_channels = Validator.check_positive_int(in_channels, "in_channels", self.cls_name)
self.out_channels = Validator.check_positive_int(out_channels, "out_channels", self.cls_name)
self.has_bias = has_bias
self.kernel_size = twice(kernel_size)
self.stride = twice(stride)
self.dilation = twice(dilation)
for kernel_size_elem in self.kernel_size:
Validator.check_positive_int(kernel_size_elem, 'kernel_size item', self.cls_name)
for stride_elem in self.stride:
Validator.check_positive_int(stride_elem, 'stride item', self.cls_name)
for dilation_elem in self.dilation:
Validator.check_positive_int(dilation_elem, 'dilation item', self.cls_name)
if pad_mode not in ('valid', 'same', 'pad'):
raise ValueError(f"For '{self.cls_name}', the 'pad_mode' should be one of values "
f"in ('valid', 'same', 'pad'), but got {pad_mode}.")
self.pad_mode = pad_mode
if isinstance(padding, int):
Validator.check_non_negative_int(padding, 'padding', self.cls_name)
self.padding = padding
elif isinstance(padding, tuple):
for pad in padding:
Validator.check_non_negative_int(pad, 'padding item', self.cls_name)
self.padding = padding
else:
raise TypeError(f"For '{self.cls_name}', the type of 'padding' must be int/tuple(int), "
f"but got {type(padding).__name__}!")
self.group = Validator.check_positive_int(group, "group", self.cls_name)
weight_shape = [out_channels, in_channels // group, *self.kernel_size]
self.weight = Parameter(initializer(weight_init, weight_shape), name='weight')
self.bias_add = P.BiasAdd()
if Validator.check_bool(has_bias, "has_bias", self.cls_name):
self.bias = Parameter(initializer(bias_init, [out_channels]), name='bias')
else:
self.bias = None
self.conv = P.Conv2D(out_channel=self.out_channels,
kernel_size=self.kernel_size,
mode=1,
pad_mode=self.pad_mode,
pad=self.padding,
stride=self.stride,
dilation=self.dilation,
group=self.group)
channel_axis = 0
self.fake_quant_weight = quant_config.weight(ema=False,
channel_axis=channel_axis,
num_channels=out_channels,
quant_dtype=quant_dtype) | [
"def",
"__init__",
"(",
"self",
",",
"in_channels",
",",
"out_channels",
",",
"kernel_size",
",",
"stride",
"=",
"1",
",",
"pad_mode",
"=",
"'same'",
",",
"padding",
"=",
"0",
",",
"dilation",
"=",
"1",
",",
"group",
"=",
"1",
",",
"has_bias",
"=",
"... | https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/nn/layer/quant.py#L1273-L1338 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/stc.py | python | StyledTextEvent.GetText | (*args, **kwargs) | return _stc.StyledTextEvent_GetText(*args, **kwargs) | GetText(self) -> String | GetText(self) -> String | [
"GetText",
"(",
"self",
")",
"-",
">",
"String"
] | def GetText(*args, **kwargs):
"""GetText(self) -> String"""
return _stc.StyledTextEvent_GetText(*args, **kwargs) | [
"def",
"GetText",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_stc",
".",
"StyledTextEvent_GetText",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/stc.py#L7138-L7140 | |
shader-slang/slang | b8982fcf43b86c1e39dcc3dd19bff2821633eda6 | external/vulkan/registry/vkconventions.py | python | VulkanConventions.nextpointer_member_name | (self) | return 'pNext' | Return name of the structure pointer chain member | Return name of the structure pointer chain member | [
"Return",
"name",
"of",
"the",
"structure",
"pointer",
"chain",
"member"
] | def nextpointer_member_name(self):
"""Return name of the structure pointer chain member"""
return 'pNext' | [
"def",
"nextpointer_member_name",
"(",
"self",
")",
":",
"return",
"'pNext'"
] | https://github.com/shader-slang/slang/blob/b8982fcf43b86c1e39dcc3dd19bff2821633eda6/external/vulkan/registry/vkconventions.py#L71-L73 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/_controls.py | python | ListView.GetFirstSelected | (*args, **kwargs) | return _controls_.ListView_GetFirstSelected(*args, **kwargs) | GetFirstSelected(self) -> long | GetFirstSelected(self) -> long | [
"GetFirstSelected",
"(",
"self",
")",
"-",
">",
"long"
] | def GetFirstSelected(*args, **kwargs):
"""GetFirstSelected(self) -> long"""
return _controls_.ListView_GetFirstSelected(*args, **kwargs) | [
"def",
"GetFirstSelected",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_controls_",
".",
"ListView_GetFirstSelected",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_controls.py#L4924-L4926 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/pyparsing/py3/pyparsing/exceptions.py | python | ParseBaseException._from_exception | (cls, pe) | return cls(pe.pstr, pe.loc, pe.msg, pe.parserElement) | internal factory method to simplify creating one type of ParseException
from another - avoids having __init__ signature conflicts among subclasses | internal factory method to simplify creating one type of ParseException
from another - avoids having __init__ signature conflicts among subclasses | [
"internal",
"factory",
"method",
"to",
"simplify",
"creating",
"one",
"type",
"of",
"ParseException",
"from",
"another",
"-",
"avoids",
"having",
"__init__",
"signature",
"conflicts",
"among",
"subclasses"
] | def _from_exception(cls, pe):
"""
internal factory method to simplify creating one type of ParseException
from another - avoids having __init__ signature conflicts among subclasses
"""
return cls(pe.pstr, pe.loc, pe.msg, pe.parserElement) | [
"def",
"_from_exception",
"(",
"cls",
",",
"pe",
")",
":",
"return",
"cls",
"(",
"pe",
".",
"pstr",
",",
"pe",
".",
"loc",
",",
"pe",
".",
"msg",
",",
"pe",
".",
"parserElement",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pyparsing/py3/pyparsing/exceptions.py#L108-L113 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/x86/toolchain/lib/python2.7/plat-mac/lib-scriptpackages/StdSuites/Standard_Suite.py | python | Standard_Suite_Events.make | (self, _no_object=None, _attributes={}, **_arguments) | make: Make a new element
Keyword argument new: the class of the new element
Keyword argument at: the location at which to insert the element
Keyword argument with_data: the initial data for the element
Keyword argument with_properties: the initial values for the properties of the element
Keyword argument _attributes: AppleEvent attribute dictionary
Returns: to the new object(s) | make: Make a new element
Keyword argument new: the class of the new element
Keyword argument at: the location at which to insert the element
Keyword argument with_data: the initial data for the element
Keyword argument with_properties: the initial values for the properties of the element
Keyword argument _attributes: AppleEvent attribute dictionary
Returns: to the new object(s) | [
"make",
":",
"Make",
"a",
"new",
"element",
"Keyword",
"argument",
"new",
":",
"the",
"class",
"of",
"the",
"new",
"element",
"Keyword",
"argument",
"at",
":",
"the",
"location",
"at",
"which",
"to",
"insert",
"the",
"element",
"Keyword",
"argument",
"with... | def make(self, _no_object=None, _attributes={}, **_arguments):
"""make: Make a new element
Keyword argument new: the class of the new element
Keyword argument at: the location at which to insert the element
Keyword argument with_data: the initial data for the element
Keyword argument with_properties: the initial values for the properties of the element
Keyword argument _attributes: AppleEvent attribute dictionary
Returns: to the new object(s)
"""
_code = 'core'
_subcode = 'crel'
aetools.keysubst(_arguments, self._argmap_make)
if _no_object is not None: raise TypeError, 'No direct arg expected'
_reply, _arguments, _attributes = self.send(_code, _subcode,
_arguments, _attributes)
if _arguments.get('errn', 0):
raise aetools.Error, aetools.decodeerror(_arguments)
# XXXX Optionally decode result
if _arguments.has_key('----'):
return _arguments['----'] | [
"def",
"make",
"(",
"self",
",",
"_no_object",
"=",
"None",
",",
"_attributes",
"=",
"{",
"}",
",",
"*",
"*",
"_arguments",
")",
":",
"_code",
"=",
"'core'",
"_subcode",
"=",
"'crel'",
"aetools",
".",
"keysubst",
"(",
"_arguments",
",",
"self",
".",
... | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/plat-mac/lib-scriptpackages/StdSuites/Standard_Suite.py#L245-L267 | ||
genn-team/genn | 75e1eb218cafa228bf36ae4613d1ce26e877b12c | pygenn/genn_model.py | python | GeNNModel.pull_current_spike_events_from_device | (self, pop_name) | Pull spike events from the device for a given population | Pull spike events from the device for a given population | [
"Pull",
"spike",
"events",
"from",
"the",
"device",
"for",
"a",
"given",
"population"
] | def pull_current_spike_events_from_device(self, pop_name):
"""Pull spike events from the device for a given population"""
if not self._loaded:
raise Exception("GeNN model has to be loaded before pulling")
self._slm.pull_current_spike_events_from_device(pop_name) | [
"def",
"pull_current_spike_events_from_device",
"(",
"self",
",",
"pop_name",
")",
":",
"if",
"not",
"self",
".",
"_loaded",
":",
"raise",
"Exception",
"(",
"\"GeNN model has to be loaded before pulling\"",
")",
"self",
".",
"_slm",
".",
"pull_current_spike_events_from_... | https://github.com/genn-team/genn/blob/75e1eb218cafa228bf36ae4613d1ce26e877b12c/pygenn/genn_model.py#L734-L739 | ||
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/devil/devil/android/sdk/adb_wrapper.py | python | AdbWrapper._RunDeviceAdbCmd | (self, args, timeout, retries, check_error=True) | return self._RunAdbCmd(args, timeout=timeout, retries=retries,
device_serial=self._device_serial,
check_error=check_error) | Runs an adb command on the device associated with this object.
Args:
args: A list of arguments to adb.
timeout: Timeout in seconds.
retries: Number of retries.
check_error: Check that the command doesn't return an error message. This
does NOT check the exit status of shell commands.
Returns:
The output of the command. | Runs an adb command on the device associated with this object. | [
"Runs",
"an",
"adb",
"command",
"on",
"the",
"device",
"associated",
"with",
"this",
"object",
"."
] | def _RunDeviceAdbCmd(self, args, timeout, retries, check_error=True):
"""Runs an adb command on the device associated with this object.
Args:
args: A list of arguments to adb.
timeout: Timeout in seconds.
retries: Number of retries.
check_error: Check that the command doesn't return an error message. This
does NOT check the exit status of shell commands.
Returns:
The output of the command.
"""
return self._RunAdbCmd(args, timeout=timeout, retries=retries,
device_serial=self._device_serial,
check_error=check_error) | [
"def",
"_RunDeviceAdbCmd",
"(",
"self",
",",
"args",
",",
"timeout",
",",
"retries",
",",
"check_error",
"=",
"True",
")",
":",
"return",
"self",
".",
"_RunAdbCmd",
"(",
"args",
",",
"timeout",
"=",
"timeout",
",",
"retries",
"=",
"retries",
",",
"device... | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/devil/devil/android/sdk/adb_wrapper.py#L263-L278 | |
arangodb/arangodb | 0d658689c7d1b721b314fa3ca27d38303e1570c8 | 3rdParty/V8/gyp/generator/eclipse.py | python | CalculateGeneratorInputInfo | (params) | Calculate the generator specific info that gets fed to input (called by
gyp). | Calculate the generator specific info that gets fed to input (called by
gyp). | [
"Calculate",
"the",
"generator",
"specific",
"info",
"that",
"gets",
"fed",
"to",
"input",
"(",
"called",
"by",
"gyp",
")",
"."
] | def CalculateGeneratorInputInfo(params):
"""Calculate the generator specific info that gets fed to input (called by
gyp)."""
generator_flags = params.get('generator_flags', {})
if generator_flags.get('adjust_static_libraries', False):
global generator_wants_static_library_dependencies_adjusted
generator_wants_static_library_dependencies_adjusted = True | [
"def",
"CalculateGeneratorInputInfo",
"(",
"params",
")",
":",
"generator_flags",
"=",
"params",
".",
"get",
"(",
"'generator_flags'",
",",
"{",
"}",
")",
"if",
"generator_flags",
".",
"get",
"(",
"'adjust_static_libraries'",
",",
"False",
")",
":",
"global",
... | https://github.com/arangodb/arangodb/blob/0d658689c7d1b721b314fa3ca27d38303e1570c8/3rdParty/V8/gyp/generator/eclipse.py#L67-L73 | ||
snap-stanford/snap-python | d53c51b0a26aa7e3e7400b014cdf728948fde80a | setup/snap.py | python | TVoid.GetMemUsed | (self) | return _snap.TVoid_GetMemUsed(self) | GetMemUsed(TVoid self) -> int
Parameters:
self: TVoid const * | GetMemUsed(TVoid self) -> int | [
"GetMemUsed",
"(",
"TVoid",
"self",
")",
"-",
">",
"int"
] | def GetMemUsed(self):
"""
GetMemUsed(TVoid self) -> int
Parameters:
self: TVoid const *
"""
return _snap.TVoid_GetMemUsed(self) | [
"def",
"GetMemUsed",
"(",
"self",
")",
":",
"return",
"_snap",
".",
"TVoid_GetMemUsed",
"(",
"self",
")"
] | https://github.com/snap-stanford/snap-python/blob/d53c51b0a26aa7e3e7400b014cdf728948fde80a/setup/snap.py#L12065-L12073 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/stc.py | python | StyledTextCtrl.GetIndent | (*args, **kwargs) | return _stc.StyledTextCtrl_GetIndent(*args, **kwargs) | GetIndent(self) -> int
Retrieve indentation size. | GetIndent(self) -> int | [
"GetIndent",
"(",
"self",
")",
"-",
">",
"int"
] | def GetIndent(*args, **kwargs):
"""
GetIndent(self) -> int
Retrieve indentation size.
"""
return _stc.StyledTextCtrl_GetIndent(*args, **kwargs) | [
"def",
"GetIndent",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_stc",
".",
"StyledTextCtrl_GetIndent",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/stc.py#L3278-L3284 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.