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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_vendor/pyparsing.py | python | unicode_set.alphanums | (cls) | return cls.alphas + cls.nums | all alphanumeric characters in this range | all alphanumeric characters in this range | [
"all",
"alphanumeric",
"characters",
"in",
"this",
"range"
] | def alphanums(cls):
"all alphanumeric characters in this range"
return cls.alphas + cls.nums | [
"def",
"alphanums",
"(",
"cls",
")",
":",
"return",
"cls",
".",
"alphas",
"+",
"cls",
".",
"nums"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_vendor/pyparsing.py#L6758-L6760 | |
makefile/frcnn | 8d9b9ebf8be8315ba2f374d460121b0adf1df29c | scripts/cpp_lint.py | python | CheckCaffeRandom | (filename, clean_lines, linenum, error) | Checks for calls to C random functions (rand, rand_r, random, ...).
Caffe code should (almost) always use the caffe_rng_* functions rather
than these, as the internal state of these C functions is independent of the
native Caffe RNG system which should produce deterministic results for a
fixed Caffe seed set using Caffe::set_random_seed(...).
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found. | Checks for calls to C random functions (rand, rand_r, random, ...). | [
"Checks",
"for",
"calls",
"to",
"C",
"random",
"functions",
"(",
"rand",
"rand_r",
"random",
"...",
")",
"."
] | def CheckCaffeRandom(filename, clean_lines, linenum, error):
"""Checks for calls to C random functions (rand, rand_r, random, ...).
Caffe code should (almost) always use the caffe_rng_* functions rather
than these, as the internal state of these C functions is independent of the
native Caffe RNG system which should produce deterministic results for a
fixed Caffe seed set using Caffe::set_random_seed(...).
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found.
"""
line = clean_lines.elided[linenum]
for function in c_random_function_list:
ix = line.find(function)
# Comparisons made explicit for clarity -- pylint: disable=g-explicit-bool-comparison
if ix >= 0 and (ix == 0 or (not line[ix - 1].isalnum() and
line[ix - 1] not in ('_', '.', '>'))):
error(filename, linenum, 'caffe/random_fn', 2,
'Use caffe_rng_rand() (or other caffe_rng_* function) instead of '
+ function +
') to ensure results are deterministic for a fixed Caffe seed.') | [
"def",
"CheckCaffeRandom",
"(",
"filename",
",",
"clean_lines",
",",
"linenum",
",",
"error",
")",
":",
"line",
"=",
"clean_lines",
".",
"elided",
"[",
"linenum",
"]",
"for",
"function",
"in",
"c_random_function_list",
":",
"ix",
"=",
"line",
".",
"find",
... | https://github.com/makefile/frcnn/blob/8d9b9ebf8be8315ba2f374d460121b0adf1df29c/scripts/cpp_lint.py#L1640-L1663 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/dataview.py | python | DataViewModel.GetParent | (*args, **kwargs) | return _dataview.DataViewModel_GetParent(*args, **kwargs) | GetParent(self, DataViewItem item) -> DataViewItem
Override this to indicate which item is the parent of the given item.
If the item is a child of the (hidden) root, then simply return an
invalid item, (one constructed with no ID.) | GetParent(self, DataViewItem item) -> DataViewItem | [
"GetParent",
"(",
"self",
"DataViewItem",
"item",
")",
"-",
">",
"DataViewItem"
] | def GetParent(*args, **kwargs):
"""
GetParent(self, DataViewItem item) -> DataViewItem
Override this to indicate which item is the parent of the given item.
If the item is a child of the (hidden) root, then simply return an
invalid item, (one constructed with no ID.)
"""
return _dataview.DataViewModel_GetParent(*args, **kwargs) | [
"def",
"GetParent",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_dataview",
".",
"DataViewModel_GetParent",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/dataview.py#L514-L522 | |
lightvector/KataGo | 20d34784703c5b4000643d3ccc43bb37d418f3b5 | python/sgfmill/sgf_grammar.py | python | tokenise | (bb, start_position=0) | return result, i | Tokenise a string containing SGF data.
bb -- bytes-like object
start_position -- index into 'bb'
Skips leading junk.
Returns a list of pairs of strings (token type, contents), and also the
index in 'bb' of the start of the unprocessed 'tail'.
token types and contents:
I -- PropIdent: upper-case letters
V -- PropValue: raw value, without the enclosing brackets
D -- delimiter: ';', '(', or ')'
Stops when it has seen as many closing parens as open ones, at the end of
the string, or when it first finds something it can't tokenise.
The first two tokens are always '(' and ';' (otherwise it won't find the
start of the content). | Tokenise a string containing SGF data. | [
"Tokenise",
"a",
"string",
"containing",
"SGF",
"data",
"."
] | def tokenise(bb, start_position=0):
"""Tokenise a string containing SGF data.
bb -- bytes-like object
start_position -- index into 'bb'
Skips leading junk.
Returns a list of pairs of strings (token type, contents), and also the
index in 'bb' of the start of the unprocessed 'tail'.
token types and contents:
I -- PropIdent: upper-case letters
V -- PropValue: raw value, without the enclosing brackets
D -- delimiter: ';', '(', or ')'
Stops when it has seen as many closing parens as open ones, at the end of
the string, or when it first finds something it can't tokenise.
The first two tokens are always '(' and ';' (otherwise it won't find the
start of the content).
"""
result = []
m = _find_start_re.search(bb, start_position)
if not m:
return [], 0
i = m.start()
depth = 0
while True:
m = _tokenise_re.match(bb, i)
if not m:
break
group = m.lastgroup
token = m.group(m.lastindex)
result.append((group, token))
i = m.end()
if group == 'D':
if token == b'(':
depth += 1
elif token == b')':
depth -= 1
if depth == 0:
break
return result, i | [
"def",
"tokenise",
"(",
"bb",
",",
"start_position",
"=",
"0",
")",
":",
"result",
"=",
"[",
"]",
"m",
"=",
"_find_start_re",
".",
"search",
"(",
"bb",
",",
"start_position",
")",
"if",
"not",
"m",
":",
"return",
"[",
"]",
",",
"0",
"i",
"=",
"m"... | https://github.com/lightvector/KataGo/blob/20d34784703c5b4000643d3ccc43bb37d418f3b5/python/sgfmill/sgf_grammar.py#L69-L113 | |
forkineye/ESPixelStick | 22926f1c0d1131f1369fc7cad405689a095ae3cb | dist/bin/esptool/serial/rfc2217.py | python | Serial._update_break_state | (self) | \
Set break: Controls TXD. When active, to transmitting is
possible. | \
Set break: Controls TXD. When active, to transmitting is
possible. | [
"\\",
"Set",
"break",
":",
"Controls",
"TXD",
".",
"When",
"active",
"to",
"transmitting",
"is",
"possible",
"."
] | def _update_break_state(self):
"""\
Set break: Controls TXD. When active, to transmitting is
possible.
"""
if not self.is_open:
raise portNotOpenError
if self.logger:
self.logger.info('set BREAK to {}'.format('active' if self._break_state else 'inactive'))
if self._break_state:
self.rfc2217_set_control(SET_CONTROL_BREAK_ON)
else:
self.rfc2217_set_control(SET_CONTROL_BREAK_OFF) | [
"def",
"_update_break_state",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"is_open",
":",
"raise",
"portNotOpenError",
"if",
"self",
".",
"logger",
":",
"self",
".",
"logger",
".",
"info",
"(",
"'set BREAK to {}'",
".",
"format",
"(",
"'active'",
"if"... | https://github.com/forkineye/ESPixelStick/blob/22926f1c0d1131f1369fc7cad405689a095ae3cb/dist/bin/esptool/serial/rfc2217.py#L656-L668 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/gettext.py | python | c2py | (plural) | Gets a C expression as used in PO files for plural forms and returns a
Python function that implements an equivalent expression. | Gets a C expression as used in PO files for plural forms and returns a
Python function that implements an equivalent expression. | [
"Gets",
"a",
"C",
"expression",
"as",
"used",
"in",
"PO",
"files",
"for",
"plural",
"forms",
"and",
"returns",
"a",
"Python",
"function",
"that",
"implements",
"an",
"equivalent",
"expression",
"."
] | def c2py(plural):
"""Gets a C expression as used in PO files for plural forms and returns a
Python function that implements an equivalent expression.
"""
if len(plural) > 1000:
raise ValueError('plural form expression is too long')
try:
result, nexttok = _parse(_tokenize(plural))
if nexttok:
raise _error(nexttok)
depth = 0
for c in result:
if c == '(':
depth += 1
if depth > 20:
# Python compiler limit is about 90.
# The most complex example has 2.
raise ValueError('plural form expression is too complex')
elif c == ')':
depth -= 1
ns = {'_as_int': _as_int}
exec('''if True:
def func(n):
if not isinstance(n, int):
n = _as_int(n)
return int(%s)
''' % result, ns)
return ns['func']
except RecursionError:
# Recursion error can be raised in _parse() or exec().
raise ValueError('plural form expression is too complex') | [
"def",
"c2py",
"(",
"plural",
")",
":",
"if",
"len",
"(",
"plural",
")",
">",
"1000",
":",
"raise",
"ValueError",
"(",
"'plural form expression is too long'",
")",
"try",
":",
"result",
",",
"nexttok",
"=",
"_parse",
"(",
"_tokenize",
"(",
"plural",
")",
... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/gettext.py#L175-L208 | ||
Xilinx/Vitis_Libraries | 4bd100518d93a8842d1678046ad7457f94eb355c | hpc/L3/src/sw/mlp/python_api/xfhpc_L3.py | python | XFHPCManager.destroy | (self, numKernel, idxDevice) | return self._lib.xfhpcDestroy(numKernel, idxDevice) | release handle used by the XFHPC library
Parameters
numKernel
number of CUs in the xclbin
idxDeivce
index of local device to be used | release handle used by the XFHPC library | [
"release",
"handle",
"used",
"by",
"the",
"XFHPC",
"library"
] | def destroy(self, numKernel, idxDevice):
'''
release handle used by the XFHPC library
Parameters
numKernel
number of CUs in the xclbin
idxDeivce
index of local device to be used
'''
return self._lib.xfhpcDestroy(numKernel, idxDevice) | [
"def",
"destroy",
"(",
"self",
",",
"numKernel",
",",
"idxDevice",
")",
":",
"return",
"self",
".",
"_lib",
".",
"xfhpcDestroy",
"(",
"numKernel",
",",
"idxDevice",
")"
] | https://github.com/Xilinx/Vitis_Libraries/blob/4bd100518d93a8842d1678046ad7457f94eb355c/hpc/L3/src/sw/mlp/python_api/xfhpc_L3.py#L156-L167 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/grid.py | python | Grid.SetCellTextColour | (*args, **kwargs) | return _grid.Grid_SetCellTextColour(*args, **kwargs) | SetCellTextColour(self, int row, int col, Colour ?) | SetCellTextColour(self, int row, int col, Colour ?) | [
"SetCellTextColour",
"(",
"self",
"int",
"row",
"int",
"col",
"Colour",
"?",
")"
] | def SetCellTextColour(*args, **kwargs):
"""SetCellTextColour(self, int row, int col, Colour ?)"""
return _grid.Grid_SetCellTextColour(*args, **kwargs) | [
"def",
"SetCellTextColour",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_grid",
".",
"Grid_SetCellTextColour",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/grid.py#L1946-L1948 | |
baidu-research/tensorflow-allreduce | 66d5b855e90b0949e9fa5cca5599fd729a70e874 | tensorflow/contrib/learn/python/learn/estimators/estimator.py | python | _make_metrics_ops | (metrics, features, labels, predictions) | return result | Add metrics based on `features`, `labels`, and `predictions`.
`metrics` contains a specification for how to run metrics. It is a dict
mapping friendly names to either `MetricSpec` objects, or directly to a metric
function (assuming that `predictions` and `labels` are single tensors), or to
`(pred_name, metric)` `tuple`, which passes `predictions[pred_name]` and
`labels` to `metric` (assuming `labels` is a single tensor).
Users are encouraged to use `MetricSpec` objects, which are more flexible and
cleaner. They also lead to clearer errors.
Args:
metrics: A dict mapping names to metrics specification, for example
`MetricSpec` objects.
features: A dict of tensors returned from an input_fn as features/inputs.
labels: A single tensor or a dict of tensors returned from an input_fn as
labels.
predictions: A single tensor or a dict of tensors output from a model as
predictions.
Returns:
A dict mapping the friendly given in `metrics` to the result of calling the
given metric function.
Raises:
ValueError: If metrics specifications do not work with the type of
`features`, `labels`, or `predictions` provided. Mostly, a dict is given
but no pred_name specified. | Add metrics based on `features`, `labels`, and `predictions`. | [
"Add",
"metrics",
"based",
"on",
"features",
"labels",
"and",
"predictions",
"."
] | def _make_metrics_ops(metrics, features, labels, predictions):
"""Add metrics based on `features`, `labels`, and `predictions`.
`metrics` contains a specification for how to run metrics. It is a dict
mapping friendly names to either `MetricSpec` objects, or directly to a metric
function (assuming that `predictions` and `labels` are single tensors), or to
`(pred_name, metric)` `tuple`, which passes `predictions[pred_name]` and
`labels` to `metric` (assuming `labels` is a single tensor).
Users are encouraged to use `MetricSpec` objects, which are more flexible and
cleaner. They also lead to clearer errors.
Args:
metrics: A dict mapping names to metrics specification, for example
`MetricSpec` objects.
features: A dict of tensors returned from an input_fn as features/inputs.
labels: A single tensor or a dict of tensors returned from an input_fn as
labels.
predictions: A single tensor or a dict of tensors output from a model as
predictions.
Returns:
A dict mapping the friendly given in `metrics` to the result of calling the
given metric function.
Raises:
ValueError: If metrics specifications do not work with the type of
`features`, `labels`, or `predictions` provided. Mostly, a dict is given
but no pred_name specified.
"""
metrics = metrics or {}
# If labels is a dict with a single key, unpack into a single tensor.
labels_tensor_or_dict = labels
if isinstance(labels, dict) and len(labels) == 1:
labels_tensor_or_dict = labels[list(labels.keys())[0]]
result = {}
# Iterate in lexicographic order, so the graph is identical among runs.
for name, metric in sorted(six.iteritems(metrics)):
if isinstance(metric, metric_spec.MetricSpec):
result[name] = metric.create_metric_ops(features, labels, predictions)
continue
# TODO(b/31229024): Remove the rest of this loop
logging.warning('Please specify metrics using MetricSpec. Using bare '
'functions or (key, fn) tuples is deprecated and support '
'for it will be removed on Oct 1, 2016.')
if isinstance(name, tuple):
# Multi-head metrics.
if len(name) != 2:
raise ValueError('Invalid metric for {}. It returned a tuple with '
'len {}, expected 2.'.format(name, len(name)))
if not isinstance(predictions, dict):
raise ValueError(
'Metrics passed provide (name, prediction), '
'but predictions are not dict. '
'Metrics: %s, Predictions: %s.' % (metrics, predictions))
# Here are two options: labels are single Tensor or a dict.
if isinstance(labels, dict) and name[1] in labels:
# If labels are dict and the prediction name is in it, apply metric.
result[name[0]] = metric(predictions[name[1]], labels[name[1]])
else:
# Otherwise pass the labels to the metric.
result[name[0]] = metric(predictions[name[1]], labels_tensor_or_dict)
else:
# Single head metrics.
if isinstance(predictions, dict):
raise ValueError(
'Metrics passed provide only name, no prediction, '
'but predictions are dict. '
'Metrics: %s, Labels: %s.' % (metrics, labels_tensor_or_dict))
result[name] = metric(predictions, labels_tensor_or_dict)
return result | [
"def",
"_make_metrics_ops",
"(",
"metrics",
",",
"features",
",",
"labels",
",",
"predictions",
")",
":",
"metrics",
"=",
"metrics",
"or",
"{",
"}",
"# If labels is a dict with a single key, unpack into a single tensor.",
"labels_tensor_or_dict",
"=",
"labels",
"if",
"i... | https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/contrib/learn/python/learn/estimators/estimator.py#L230-L304 | |
MicBosi/VisualizationLibrary | d2a0e321288152008957e29a0bc270ad192f75be | src/external/freetype/src/tools/docmaker/utils.py | python | file_exists | ( pathname ) | return result | checks that a given file exists | checks that a given file exists | [
"checks",
"that",
"a",
"given",
"file",
"exists"
] | def file_exists( pathname ):
"""checks that a given file exists"""
result = 1
try:
file = open( pathname, "r" )
file.close()
except:
result = None
sys.stderr.write( pathname + " couldn't be accessed\n" )
return result | [
"def",
"file_exists",
"(",
"pathname",
")",
":",
"result",
"=",
"1",
"try",
":",
"file",
"=",
"open",
"(",
"pathname",
",",
"\"r\"",
")",
"file",
".",
"close",
"(",
")",
"except",
":",
"result",
"=",
"None",
"sys",
".",
"stderr",
".",
"write",
"(",... | https://github.com/MicBosi/VisualizationLibrary/blob/d2a0e321288152008957e29a0bc270ad192f75be/src/external/freetype/src/tools/docmaker/utils.py#L93-L103 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/telemetry/telemetry/internal/util/binary_manager.py | python | LocalPath | (binary_name, arch, os_name, os_version=None) | return _binary_manager.LocalPath(binary_name, os_name, arch, os_version) | Return a local path to the given binary name, or None if an executable
cannot be found. Will not download the executable. | Return a local path to the given binary name, or None if an executable
cannot be found. Will not download the executable. | [
"Return",
"a",
"local",
"path",
"to",
"the",
"given",
"binary",
"name",
"or",
"None",
"if",
"an",
"executable",
"cannot",
"be",
"found",
".",
"Will",
"not",
"download",
"the",
"executable",
"."
] | def LocalPath(binary_name, arch, os_name, os_version=None):
""" Return a local path to the given binary name, or None if an executable
cannot be found. Will not download the executable.
"""
if _binary_manager is None:
raise exceptions.InitializationError(
'Called LocalPath with uninitialized binary manager.')
return _binary_manager.LocalPath(binary_name, os_name, arch, os_version) | [
"def",
"LocalPath",
"(",
"binary_name",
",",
"arch",
",",
"os_name",
",",
"os_version",
"=",
"None",
")",
":",
"if",
"_binary_manager",
"is",
"None",
":",
"raise",
"exceptions",
".",
"InitializationError",
"(",
"'Called LocalPath with uninitialized binary manager.'",
... | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/telemetry/telemetry/internal/util/binary_manager.py#L66-L73 | |
google/earthenterprise | 0fe84e29be470cd857e3a0e52e5d0afd5bb8cee9 | earth_enterprise/src/server/wsgi/serve/publish/publish_manager_helper.py | python | PublishManagerHelper._QueryTargetIdByPath | (self, target_path) | return target_id | Queries target point ID by its path.
Note: query is case-sensitive since we keep target path in database as user
have entered it.
Args:
target_path: target point path.
Raises:
psycopg2.Error/Warning.
Returns:
ID of target point in case of it exists otherwise -1. | Queries target point ID by its path. | [
"Queries",
"target",
"point",
"ID",
"by",
"its",
"path",
"."
] | def _QueryTargetIdByPath(self, target_path):
"""Queries target point ID by its path.
Note: query is case-sensitive since we keep target path in database as user
have entered it.
Args:
target_path: target point path.
Raises:
psycopg2.Error/Warning.
Returns:
ID of target point in case of it exists otherwise -1.
"""
query_string = "SELECT target_id FROM target_table WHERE target_path = %s"
result = self.DbQuery(query_string, (target_path,))
target_id = -1
if result:
target_id = int(result[0])
return target_id | [
"def",
"_QueryTargetIdByPath",
"(",
"self",
",",
"target_path",
")",
":",
"query_string",
"=",
"\"SELECT target_id FROM target_table WHERE target_path = %s\"",
"result",
"=",
"self",
".",
"DbQuery",
"(",
"query_string",
",",
"(",
"target_path",
",",
")",
")",
"target_... | https://github.com/google/earthenterprise/blob/0fe84e29be470cd857e3a0e52e5d0afd5bb8cee9/earth_enterprise/src/server/wsgi/serve/publish/publish_manager_helper.py#L995-L1014 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scipy/scipy/signal/filter_design.py | python | iirdesign | (wp, ws, gpass, gstop, analog=False, ftype='ellip', output='ba') | return iirfilter(N, Wn, rp=gpass, rs=gstop, analog=analog, btype=btype,
ftype=ftype, output=output) | Complete IIR digital and analog filter design.
Given passband and stopband frequencies and gains, construct an analog or
digital IIR filter of minimum order for a given basic type. Return the
output in numerator, denominator ('ba'), pole-zero ('zpk') or second order
sections ('sos') form.
Parameters
----------
wp, ws : float
Passband and stopband edge frequencies.
For digital filters, these are normalized from 0 to 1, where 1 is the
Nyquist frequency, pi radians/sample. (`wp` and `ws` are thus in
half-cycles / sample.) For example:
- Lowpass: wp = 0.2, ws = 0.3
- Highpass: wp = 0.3, ws = 0.2
- Bandpass: wp = [0.2, 0.5], ws = [0.1, 0.6]
- Bandstop: wp = [0.1, 0.6], ws = [0.2, 0.5]
For analog filters, `wp` and `ws` are angular frequencies (e.g. rad/s).
gpass : float
The maximum loss in the passband (dB).
gstop : float
The minimum attenuation in the stopband (dB).
analog : bool, optional
When True, return an analog filter, otherwise a digital filter is
returned.
ftype : str, optional
The type of IIR filter to design:
- Butterworth : 'butter'
- Chebyshev I : 'cheby1'
- Chebyshev II : 'cheby2'
- Cauer/elliptic: 'ellip'
- Bessel/Thomson: 'bessel'
output : {'ba', 'zpk', 'sos'}, optional
Type of output: numerator/denominator ('ba'), pole-zero ('zpk'), or
second-order sections ('sos'). Default is 'ba'.
Returns
-------
b, a : ndarray, ndarray
Numerator (`b`) and denominator (`a`) polynomials of the IIR filter.
Only returned if ``output='ba'``.
z, p, k : ndarray, ndarray, float
Zeros, poles, and system gain of the IIR filter transfer
function. Only returned if ``output='zpk'``.
sos : ndarray
Second-order sections representation of the IIR filter.
Only returned if ``output=='sos'``.
See Also
--------
butter : Filter design using order and critical points
cheby1, cheby2, ellip, bessel
buttord : Find order and critical points from passband and stopband spec
cheb1ord, cheb2ord, ellipord
iirfilter : General filter design using order and critical frequencies
Notes
-----
The ``'sos'`` output parameter was added in 0.16.0. | Complete IIR digital and analog filter design. | [
"Complete",
"IIR",
"digital",
"and",
"analog",
"filter",
"design",
"."
] | def iirdesign(wp, ws, gpass, gstop, analog=False, ftype='ellip', output='ba'):
"""Complete IIR digital and analog filter design.
Given passband and stopband frequencies and gains, construct an analog or
digital IIR filter of minimum order for a given basic type. Return the
output in numerator, denominator ('ba'), pole-zero ('zpk') or second order
sections ('sos') form.
Parameters
----------
wp, ws : float
Passband and stopband edge frequencies.
For digital filters, these are normalized from 0 to 1, where 1 is the
Nyquist frequency, pi radians/sample. (`wp` and `ws` are thus in
half-cycles / sample.) For example:
- Lowpass: wp = 0.2, ws = 0.3
- Highpass: wp = 0.3, ws = 0.2
- Bandpass: wp = [0.2, 0.5], ws = [0.1, 0.6]
- Bandstop: wp = [0.1, 0.6], ws = [0.2, 0.5]
For analog filters, `wp` and `ws` are angular frequencies (e.g. rad/s).
gpass : float
The maximum loss in the passband (dB).
gstop : float
The minimum attenuation in the stopband (dB).
analog : bool, optional
When True, return an analog filter, otherwise a digital filter is
returned.
ftype : str, optional
The type of IIR filter to design:
- Butterworth : 'butter'
- Chebyshev I : 'cheby1'
- Chebyshev II : 'cheby2'
- Cauer/elliptic: 'ellip'
- Bessel/Thomson: 'bessel'
output : {'ba', 'zpk', 'sos'}, optional
Type of output: numerator/denominator ('ba'), pole-zero ('zpk'), or
second-order sections ('sos'). Default is 'ba'.
Returns
-------
b, a : ndarray, ndarray
Numerator (`b`) and denominator (`a`) polynomials of the IIR filter.
Only returned if ``output='ba'``.
z, p, k : ndarray, ndarray, float
Zeros, poles, and system gain of the IIR filter transfer
function. Only returned if ``output='zpk'``.
sos : ndarray
Second-order sections representation of the IIR filter.
Only returned if ``output=='sos'``.
See Also
--------
butter : Filter design using order and critical points
cheby1, cheby2, ellip, bessel
buttord : Find order and critical points from passband and stopband spec
cheb1ord, cheb2ord, ellipord
iirfilter : General filter design using order and critical frequencies
Notes
-----
The ``'sos'`` output parameter was added in 0.16.0.
"""
try:
ordfunc = filter_dict[ftype][1]
except KeyError:
raise ValueError("Invalid IIR filter type: %s" % ftype)
except IndexError:
raise ValueError(("%s does not have order selection. Use "
"iirfilter function.") % ftype)
wp = atleast_1d(wp)
ws = atleast_1d(ws)
band_type = 2 * (len(wp) - 1)
band_type += 1
if wp[0] >= ws[0]:
band_type += 1
btype = {1: 'lowpass', 2: 'highpass',
3: 'bandstop', 4: 'bandpass'}[band_type]
N, Wn = ordfunc(wp, ws, gpass, gstop, analog=analog)
return iirfilter(N, Wn, rp=gpass, rs=gstop, analog=analog, btype=btype,
ftype=ftype, output=output) | [
"def",
"iirdesign",
"(",
"wp",
",",
"ws",
",",
"gpass",
",",
"gstop",
",",
"analog",
"=",
"False",
",",
"ftype",
"=",
"'ellip'",
",",
"output",
"=",
"'ba'",
")",
":",
"try",
":",
"ordfunc",
"=",
"filter_dict",
"[",
"ftype",
"]",
"[",
"1",
"]",
"e... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/scipy/signal/filter_design.py#L1454-L1541 | |
windystrife/UnrealEngine_NVIDIAGameWorks | b50e6338a7c5b26374d66306ebc7807541ff815e | Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/pydoc.py | python | classname | (object, modname) | return name | Get a class name and qualify it with a module name if necessary. | Get a class name and qualify it with a module name if necessary. | [
"Get",
"a",
"class",
"name",
"and",
"qualify",
"it",
"with",
"a",
"module",
"name",
"if",
"necessary",
"."
] | def classname(object, modname):
"""Get a class name and qualify it with a module name if necessary."""
name = object.__name__
if object.__module__ != modname:
name = object.__module__ + '.' + name
return name | [
"def",
"classname",
"(",
"object",
",",
"modname",
")",
":",
"name",
"=",
"object",
".",
"__name__",
"if",
"object",
".",
"__module__",
"!=",
"modname",
":",
"name",
"=",
"object",
".",
"__module__",
"+",
"'.'",
"+",
"name",
"return",
"name"
] | https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/pydoc.py#L95-L100 | |
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/training/device_setter.py | python | replica_device_setter | (ps_tasks=0,
ps_device="/job:ps",
worker_device="/job:worker",
merge_devices=True,
cluster=None,
ps_ops=None,
ps_strategy=None) | return chooser.device_function | Return a `device function` to use when building a Graph for replicas.
Device Functions are used in `with tf.device(device_function):` statement to
automatically assign devices to `Operation` objects as they are constructed,
Device constraints are added from the inner-most context first, working
outwards. The merging behavior adds constraints to fields that are yet unset
by a more inner context. Currently the fields are (job, task, cpu/gpu).
If `cluster` is `None`, and `ps_tasks` is 0, the returned function is a no-op.
Otherwise, the value of `ps_tasks` is derived from `cluster`.
By default, only Variable ops are placed on ps tasks, and the placement
strategy is round-robin over all ps tasks. A custom `ps_strategy` may be used
to do more intelligent placement, such as
`tf.contrib.training.GreedyLoadBalancingStrategy`.
For example,
```python
# To build a cluster with two ps jobs on hosts ps0 and ps1, and 3 worker
# jobs on hosts worker0, worker1 and worker2.
cluster_spec = {
"ps": ["ps0:2222", "ps1:2222"],
"worker": ["worker0:2222", "worker1:2222", "worker2:2222"]}
with
tf.device(tf.compat.v1.train.replica_device_setter(cluster=cluster_spec)):
# Build your graph
v1 = tf.Variable(...) # assigned to /job:ps/task:0
v2 = tf.Variable(...) # assigned to /job:ps/task:1
v3 = tf.Variable(...) # assigned to /job:ps/task:0
# Run compute
```
Args:
ps_tasks: Number of tasks in the `ps` job. Ignored if `cluster` is
provided.
ps_device: String. Device of the `ps` job. If empty no `ps` job is used.
Defaults to `ps`.
worker_device: String. Device of the `worker` job. If empty no `worker`
job is used.
merge_devices: `Boolean`. If `True`, merges or only sets a device if the
device constraint is completely unset. merges device specification rather
than overriding them.
cluster: `ClusterDef` proto or `ClusterSpec`.
ps_ops: List of strings representing `Operation` types that need to be
placed on `ps` devices. If `None`, defaults to `STANDARD_PS_OPS`.
ps_strategy: A callable invoked for every ps `Operation` (i.e. matched by
`ps_ops`), that takes the `Operation` and returns the ps task index to
use. If `None`, defaults to a round-robin strategy across all `ps`
devices.
Returns:
A function to pass to `tf.device()`.
Raises:
TypeError if `cluster` is not a dictionary or `ClusterDef` protocol buffer,
or if `ps_strategy` is provided but not a callable. | Return a `device function` to use when building a Graph for replicas. | [
"Return",
"a",
"device",
"function",
"to",
"use",
"when",
"building",
"a",
"Graph",
"for",
"replicas",
"."
] | def replica_device_setter(ps_tasks=0,
ps_device="/job:ps",
worker_device="/job:worker",
merge_devices=True,
cluster=None,
ps_ops=None,
ps_strategy=None):
"""Return a `device function` to use when building a Graph for replicas.
Device Functions are used in `with tf.device(device_function):` statement to
automatically assign devices to `Operation` objects as they are constructed,
Device constraints are added from the inner-most context first, working
outwards. The merging behavior adds constraints to fields that are yet unset
by a more inner context. Currently the fields are (job, task, cpu/gpu).
If `cluster` is `None`, and `ps_tasks` is 0, the returned function is a no-op.
Otherwise, the value of `ps_tasks` is derived from `cluster`.
By default, only Variable ops are placed on ps tasks, and the placement
strategy is round-robin over all ps tasks. A custom `ps_strategy` may be used
to do more intelligent placement, such as
`tf.contrib.training.GreedyLoadBalancingStrategy`.
For example,
```python
# To build a cluster with two ps jobs on hosts ps0 and ps1, and 3 worker
# jobs on hosts worker0, worker1 and worker2.
cluster_spec = {
"ps": ["ps0:2222", "ps1:2222"],
"worker": ["worker0:2222", "worker1:2222", "worker2:2222"]}
with
tf.device(tf.compat.v1.train.replica_device_setter(cluster=cluster_spec)):
# Build your graph
v1 = tf.Variable(...) # assigned to /job:ps/task:0
v2 = tf.Variable(...) # assigned to /job:ps/task:1
v3 = tf.Variable(...) # assigned to /job:ps/task:0
# Run compute
```
Args:
ps_tasks: Number of tasks in the `ps` job. Ignored if `cluster` is
provided.
ps_device: String. Device of the `ps` job. If empty no `ps` job is used.
Defaults to `ps`.
worker_device: String. Device of the `worker` job. If empty no `worker`
job is used.
merge_devices: `Boolean`. If `True`, merges or only sets a device if the
device constraint is completely unset. merges device specification rather
than overriding them.
cluster: `ClusterDef` proto or `ClusterSpec`.
ps_ops: List of strings representing `Operation` types that need to be
placed on `ps` devices. If `None`, defaults to `STANDARD_PS_OPS`.
ps_strategy: A callable invoked for every ps `Operation` (i.e. matched by
`ps_ops`), that takes the `Operation` and returns the ps task index to
use. If `None`, defaults to a round-robin strategy across all `ps`
devices.
Returns:
A function to pass to `tf.device()`.
Raises:
TypeError if `cluster` is not a dictionary or `ClusterDef` protocol buffer,
or if `ps_strategy` is provided but not a callable.
"""
if cluster is not None:
if isinstance(cluster, server_lib.ClusterSpec):
cluster_spec = cluster.as_dict()
else:
cluster_spec = server_lib.ClusterSpec(cluster).as_dict()
# Get ps_job_name from ps_device by stripping "/job:".
ps_job_name = pydev.DeviceSpec.from_string(ps_device).job
if ps_job_name not in cluster_spec or cluster_spec[ps_job_name] is None:
return None
ps_tasks = len(cluster_spec[ps_job_name])
if ps_tasks == 0:
return None
if ps_ops is None:
# TODO(sherrym): Variables in the LOCAL_VARIABLES collection should not be
# placed in the parameter server.
ps_ops = list(STANDARD_PS_OPS)
if not merge_devices:
logging.warning(
"DEPRECATION: It is recommended to set merge_devices=true in "
"replica_device_setter")
if ps_strategy is None:
ps_strategy = _RoundRobinStrategy(ps_tasks)
if not six.callable(ps_strategy):
raise TypeError("ps_strategy must be callable")
chooser = _ReplicaDeviceChooser(ps_tasks, ps_device, worker_device,
merge_devices, ps_ops, ps_strategy)
return chooser.device_function | [
"def",
"replica_device_setter",
"(",
"ps_tasks",
"=",
"0",
",",
"ps_device",
"=",
"\"/job:ps\"",
",",
"worker_device",
"=",
"\"/job:worker\"",
",",
"merge_devices",
"=",
"True",
",",
"cluster",
"=",
"None",
",",
"ps_ops",
"=",
"None",
",",
"ps_strategy",
"=",
... | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/training/device_setter.py#L136-L230 | |
mingchen/protobuf-ios | 0958df34558cd54cb7b6e6ca5c8855bf3d475046 | compiler/python/mox.py | python | MoxMetaTestBase.CleanUpTest | (cls, func) | return new_method | Adds Mox cleanup code to any MoxTestBase method.
Always unsets stubs after a test. Will verify all mocks for tests that
otherwise pass.
Args:
cls: MoxTestBase or subclass; the class whose test method we are altering.
func: method; the method of the MoxTestBase test class we wish to alter.
Returns:
The modified method. | Adds Mox cleanup code to any MoxTestBase method. | [
"Adds",
"Mox",
"cleanup",
"code",
"to",
"any",
"MoxTestBase",
"method",
"."
] | def CleanUpTest(cls, func):
"""Adds Mox cleanup code to any MoxTestBase method.
Always unsets stubs after a test. Will verify all mocks for tests that
otherwise pass.
Args:
cls: MoxTestBase or subclass; the class whose test method we are altering.
func: method; the method of the MoxTestBase test class we wish to alter.
Returns:
The modified method.
"""
def new_method(self, *args, **kwargs):
mox_obj = getattr(self, 'mox', None)
cleanup_mox = False
if mox_obj and isinstance(mox_obj, Mox):
cleanup_mox = True
try:
func(self, *args, **kwargs)
finally:
if cleanup_mox:
mox_obj.UnsetStubs()
if cleanup_mox:
mox_obj.VerifyAll()
new_method.__name__ = func.__name__
new_method.__doc__ = func.__doc__
new_method.__module__ = func.__module__
return new_method | [
"def",
"CleanUpTest",
"(",
"cls",
",",
"func",
")",
":",
"def",
"new_method",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"mox_obj",
"=",
"getattr",
"(",
"self",
",",
"'mox'",
",",
"None",
")",
"cleanup_mox",
"=",
"False",
"if... | https://github.com/mingchen/protobuf-ios/blob/0958df34558cd54cb7b6e6ca5c8855bf3d475046/compiler/python/mox.py#L1358-L1386 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/pandas/py2/pandas/io/sql.py | python | _engine_builder | (con) | return con | Returns a SQLAlchemy engine from a URI (if con is a string)
else it just return con without modifying it. | Returns a SQLAlchemy engine from a URI (if con is a string)
else it just return con without modifying it. | [
"Returns",
"a",
"SQLAlchemy",
"engine",
"from",
"a",
"URI",
"(",
"if",
"con",
"is",
"a",
"string",
")",
"else",
"it",
"just",
"return",
"con",
"without",
"modifying",
"it",
"."
] | def _engine_builder(con):
"""
Returns a SQLAlchemy engine from a URI (if con is a string)
else it just return con without modifying it.
"""
global _SQLALCHEMY_INSTALLED
if isinstance(con, string_types):
try:
import sqlalchemy
except ImportError:
_SQLALCHEMY_INSTALLED = False
else:
con = sqlalchemy.create_engine(con)
return con
return con | [
"def",
"_engine_builder",
"(",
"con",
")",
":",
"global",
"_SQLALCHEMY_INSTALLED",
"if",
"isinstance",
"(",
"con",
",",
"string_types",
")",
":",
"try",
":",
"import",
"sqlalchemy",
"except",
"ImportError",
":",
"_SQLALCHEMY_INSTALLED",
"=",
"False",
"else",
":"... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py2/pandas/io/sql.py#L490-L505 | |
microsoft/CNTK | e9396480025b9ca457d26b6f33dd07c474c6aa04 | bindings/python/cntk/internal/sanitize.py | python | sanitize_range | (x) | Convert ``x`` to a tuple such as the first element is less than or equal to the
second element.
Args:
x: a scalar number or a tuple of length 2 that contains the range values.
Returns:
A tuple of length two where the first element is less than or equal to the
second element. | Convert ``x`` to a tuple such as the first element is less than or equal to the
second element. | [
"Convert",
"x",
"to",
"a",
"tuple",
"such",
"as",
"the",
"first",
"element",
"is",
"less",
"than",
"or",
"equal",
"to",
"the",
"second",
"element",
"."
] | def sanitize_range(x):
'''
Convert ``x`` to a tuple such as the first element is less than or equal to the
second element.
Args:
x: a scalar number or a tuple of length 2 that contains the range values.
Returns:
A tuple of length two where the first element is less than or equal to the
second element.
'''
x = sanitize_2d_number(x)
if x[0] <= x[1]:
return x
raise ValueError('Input argument must be a number or a tuple of two numbers such as the first number is smaller than or equal to the second number.') | [
"def",
"sanitize_range",
"(",
"x",
")",
":",
"x",
"=",
"sanitize_2d_number",
"(",
"x",
")",
"if",
"x",
"[",
"0",
"]",
"<=",
"x",
"[",
"1",
"]",
":",
"return",
"x",
"raise",
"ValueError",
"(",
"'Input argument must be a number or a tuple of two numbers such as ... | https://github.com/microsoft/CNTK/blob/e9396480025b9ca457d26b6f33dd07c474c6aa04/bindings/python/cntk/internal/sanitize.py#L148-L164 | ||
domino-team/openwrt-cc | 8b181297c34d14d3ca521cc9f31430d561dbc688 | package/gli-pub/openwrt-node-packages-master/node/node-v6.9.1/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/ordered_dict.py | python | OrderedDict.keys | (self) | return list(self) | od.keys() -> list of keys in od | od.keys() -> list of keys in od | [
"od",
".",
"keys",
"()",
"-",
">",
"list",
"of",
"keys",
"in",
"od"
] | def keys(self):
'od.keys() -> list of keys in od'
return list(self) | [
"def",
"keys",
"(",
"self",
")",
":",
"return",
"list",
"(",
"self",
")"
] | https://github.com/domino-team/openwrt-cc/blob/8b181297c34d14d3ca521cc9f31430d561dbc688/package/gli-pub/openwrt-node-packages-master/node/node-v6.9.1/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/ordered_dict.py#L143-L145 | |
eclipse/sumo | 7132a9b8b6eea734bdec38479026b4d8c4336d03 | tools/contributed/sumopy/coremodules/misc/shapefile.py | python | Reader.shapes | (self) | return shapes | Returns all shapes in a shapefile. | Returns all shapes in a shapefile. | [
"Returns",
"all",
"shapes",
"in",
"a",
"shapefile",
"."
] | def shapes(self):
"""Returns all shapes in a shapefile."""
shp = self.__getFileObj(self.shp)
shp.seek(100)
shapes = []
while shp.tell() < self.shpLength:
shapes.append(self.__shape())
return shapes | [
"def",
"shapes",
"(",
"self",
")",
":",
"shp",
"=",
"self",
".",
"__getFileObj",
"(",
"self",
".",
"shp",
")",
"shp",
".",
"seek",
"(",
"100",
")",
"shapes",
"=",
"[",
"]",
"while",
"shp",
".",
"tell",
"(",
")",
"<",
"self",
".",
"shpLength",
"... | https://github.com/eclipse/sumo/blob/7132a9b8b6eea734bdec38479026b4d8c4336d03/tools/contributed/sumopy/coremodules/misc/shapefile.py#L335-L342 | |
xenia-project/xenia | 9b1fdac98665ac091b9660a5d0fbb259ed79e578 | third_party/google-styleguide/cpplint/cpplint.py | python | _SetFilters | (filters) | Sets the module's error-message filters.
These filters are applied when deciding whether to emit a given
error message.
Args:
filters: A string of comma-separated filters (eg "whitespace/indent").
Each filter should start with + or -; else we die. | Sets the module's error-message filters. | [
"Sets",
"the",
"module",
"s",
"error",
"-",
"message",
"filters",
"."
] | def _SetFilters(filters):
"""Sets the module's error-message filters.
These filters are applied when deciding whether to emit a given
error message.
Args:
filters: A string of comma-separated filters (eg "whitespace/indent").
Each filter should start with + or -; else we die.
"""
_cpplint_state.SetFilters(filters) | [
"def",
"_SetFilters",
"(",
"filters",
")",
":",
"_cpplint_state",
".",
"SetFilters",
"(",
"filters",
")"
] | https://github.com/xenia-project/xenia/blob/9b1fdac98665ac091b9660a5d0fbb259ed79e578/third_party/google-styleguide/cpplint/cpplint.py#L787-L797 | ||
PaddlePaddle/PaddleOCR | b756bf5f8c90142e0d89d3db0163965c686b6ffe | ppocr/data/imaug/pg_process.py | python | PGProcessTrain.gen_min_area_quad_from_poly | (self, poly) | return min_area_quad, center_point | Generate min area quad from poly. | Generate min area quad from poly. | [
"Generate",
"min",
"area",
"quad",
"from",
"poly",
"."
] | def gen_min_area_quad_from_poly(self, poly):
"""
Generate min area quad from poly.
"""
point_num = poly.shape[0]
min_area_quad = np.zeros((4, 2), dtype=np.float32)
if point_num == 4:
min_area_quad = poly
center_point = np.sum(poly, axis=0) / 4
else:
rect = cv2.minAreaRect(poly.astype(
np.int32)) # (center (x,y), (width, height), angle of rotation)
center_point = rect[0]
box = np.array(cv2.boxPoints(rect))
first_point_idx = 0
min_dist = 1e4
for i in range(4):
dist = np.linalg.norm(box[(i + 0) % 4] - poly[0]) + \
np.linalg.norm(box[(i + 1) % 4] - poly[point_num // 2 - 1]) + \
np.linalg.norm(box[(i + 2) % 4] - poly[point_num // 2]) + \
np.linalg.norm(box[(i + 3) % 4] - poly[-1])
if dist < min_dist:
min_dist = dist
first_point_idx = i
for i in range(4):
min_area_quad[i] = box[(first_point_idx + i) % 4]
return min_area_quad, center_point | [
"def",
"gen_min_area_quad_from_poly",
"(",
"self",
",",
"poly",
")",
":",
"point_num",
"=",
"poly",
".",
"shape",
"[",
"0",
"]",
"min_area_quad",
"=",
"np",
".",
"zeros",
"(",
"(",
"4",
",",
"2",
")",
",",
"dtype",
"=",
"np",
".",
"float32",
")",
"... | https://github.com/PaddlePaddle/PaddleOCR/blob/b756bf5f8c90142e0d89d3db0163965c686b6ffe/ppocr/data/imaug/pg_process.py#L486-L515 | |
adobe/chromium | cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7 | build/android/valgrind_tools.py | python | TSanTool.GetFilesForTool | (self) | return ['tools/valgrind/android/vg-chrome-wrapper-tsan.sh',
'tools/valgrind/tsan/suppressions.txt',
'tools/valgrind/tsan/suppressions_android.txt',
'tools/valgrind/tsan/ignores.txt'] | Returns a list of file names for the tool. | Returns a list of file names for the tool. | [
"Returns",
"a",
"list",
"of",
"file",
"names",
"for",
"the",
"tool",
"."
] | def GetFilesForTool(self):
"""Returns a list of file names for the tool."""
return ['tools/valgrind/android/vg-chrome-wrapper-tsan.sh',
'tools/valgrind/tsan/suppressions.txt',
'tools/valgrind/tsan/suppressions_android.txt',
'tools/valgrind/tsan/ignores.txt'] | [
"def",
"GetFilesForTool",
"(",
"self",
")",
":",
"return",
"[",
"'tools/valgrind/android/vg-chrome-wrapper-tsan.sh'",
",",
"'tools/valgrind/tsan/suppressions.txt'",
",",
"'tools/valgrind/tsan/suppressions_android.txt'",
",",
"'tools/valgrind/tsan/ignores.txt'",
"]"
] | https://github.com/adobe/chromium/blob/cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7/build/android/valgrind_tools.py#L145-L150 | |
Polidea/SiriusObfuscator | b0e590d8130e97856afe578869b83a209e2b19be | SymbolExtractorAndRenamer/lldb/scripts/Python/static-binding/lldb.py | python | SBProcess.GetDescription | (self, *args) | return _lldb.SBProcess_GetDescription(self, *args) | GetDescription(self, SBStream description) -> bool | GetDescription(self, SBStream description) -> bool | [
"GetDescription",
"(",
"self",
"SBStream",
"description",
")",
"-",
">",
"bool"
] | def GetDescription(self, *args):
"""GetDescription(self, SBStream description) -> bool"""
return _lldb.SBProcess_GetDescription(self, *args) | [
"def",
"GetDescription",
"(",
"self",
",",
"*",
"args",
")",
":",
"return",
"_lldb",
".",
"SBProcess_GetDescription",
"(",
"self",
",",
"*",
"args",
")"
] | https://github.com/Polidea/SiriusObfuscator/blob/b0e590d8130e97856afe578869b83a209e2b19be/SymbolExtractorAndRenamer/lldb/scripts/Python/static-binding/lldb.py#L7304-L7306 | |
gimli-org/gimli | 17aa2160de9b15ababd9ef99e89b1bc3277bbb23 | pygimli/physics/SIP/models.py | python | ColeColeComplexSigma.response | (self, par) | return pg.cat(np.real(spec), np.imag(spec)) | phase angle of the model | phase angle of the model | [
"phase",
"angle",
"of",
"the",
"model"
] | def response(self, par):
"""phase angle of the model"""
spec = modelColeColeSigma(self.f_, *par)
return pg.cat(np.real(spec), np.imag(spec)) | [
"def",
"response",
"(",
"self",
",",
"par",
")",
":",
"spec",
"=",
"modelColeColeSigma",
"(",
"self",
".",
"f_",
",",
"*",
"par",
")",
"return",
"pg",
".",
"cat",
"(",
"np",
".",
"real",
"(",
"spec",
")",
",",
"np",
".",
"imag",
"(",
"spec",
")... | https://github.com/gimli-org/gimli/blob/17aa2160de9b15ababd9ef99e89b1bc3277bbb23/pygimli/physics/SIP/models.py#L288-L291 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numpy/ma/mrecords.py | python | MaskedRecords.__setattr__ | (self, attr, val) | return obj | Sets the attribute attr to the value val. | Sets the attribute attr to the value val. | [
"Sets",
"the",
"attribute",
"attr",
"to",
"the",
"value",
"val",
"."
] | def __setattr__(self, attr, val):
"""
Sets the attribute attr to the value val.
"""
# Should we call __setmask__ first ?
if attr in ['mask', 'fieldmask']:
self.__setmask__(val)
return
# Create a shortcut (so that we don't have to call getattr all the time)
_localdict = object.__getattribute__(self, '__dict__')
# Check whether we're creating a new field
newattr = attr not in _localdict
try:
# Is attr a generic attribute ?
ret = object.__setattr__(self, attr, val)
except Exception:
# Not a generic attribute: exit if it's not a valid field
fielddict = ndarray.__getattribute__(self, 'dtype').fields or {}
optinfo = ndarray.__getattribute__(self, '_optinfo') or {}
if not (attr in fielddict or attr in optinfo):
raise
else:
# Get the list of names
fielddict = ndarray.__getattribute__(self, 'dtype').fields or {}
# Check the attribute
if attr not in fielddict:
return ret
if newattr:
# We just added this one or this setattr worked on an
# internal attribute.
try:
object.__delattr__(self, attr)
except Exception:
return ret
# Let's try to set the field
try:
res = fielddict[attr][:2]
except (TypeError, KeyError):
raise AttributeError("record array has no attribute %s" % attr)
if val is masked:
_fill_value = _localdict['_fill_value']
if _fill_value is not None:
dval = _localdict['_fill_value'][attr]
else:
dval = val
mval = True
else:
dval = filled(val)
mval = getmaskarray(val)
obj = ndarray.__getattribute__(self, '_data').setfield(dval, *res)
_localdict['_mask'].__setitem__(attr, mval)
return obj | [
"def",
"__setattr__",
"(",
"self",
",",
"attr",
",",
"val",
")",
":",
"# Should we call __setmask__ first ?",
"if",
"attr",
"in",
"[",
"'mask'",
",",
"'fieldmask'",
"]",
":",
"self",
".",
"__setmask__",
"(",
"val",
")",
"return",
"# Create a shortcut (so that we... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numpy/ma/mrecords.py#L242-L295 | |
rapidsai/cudf | d5b2448fc69f17509304d594f029d0df56984962 | python/cudf/cudf/core/_base_index.py | python | BaseIndex.dropna | (self, how="any") | return self._from_columns_like_self(
drop_nulls(data_columns, how=how, keys=range(len(data_columns)),),
self._column_names,
) | Drop null rows from Index.
how : {"any", "all"}, default "any"
Specifies how to decide whether to drop a row.
"any" (default) drops rows containing at least
one null value. "all" drops only rows containing
*all* null values. | Drop null rows from Index. | [
"Drop",
"null",
"rows",
"from",
"Index",
"."
] | def dropna(self, how="any"):
"""
Drop null rows from Index.
how : {"any", "all"}, default "any"
Specifies how to decide whether to drop a row.
"any" (default) drops rows containing at least
one null value. "all" drops only rows containing
*all* null values.
"""
# This is to be consistent with IndexedFrame.dropna to handle nans
# as nulls by default
data_columns = [
col.nans_to_nulls()
if isinstance(col, cudf.core.column.NumericalColumn)
else col
for col in self._columns
]
return self._from_columns_like_self(
drop_nulls(data_columns, how=how, keys=range(len(data_columns)),),
self._column_names,
) | [
"def",
"dropna",
"(",
"self",
",",
"how",
"=",
"\"any\"",
")",
":",
"# This is to be consistent with IndexedFrame.dropna to handle nans",
"# as nulls by default",
"data_columns",
"=",
"[",
"col",
".",
"nans_to_nulls",
"(",
")",
"if",
"isinstance",
"(",
"col",
",",
"... | https://github.com/rapidsai/cudf/blob/d5b2448fc69f17509304d594f029d0df56984962/python/cudf/cudf/core/_base_index.py#L1420-L1443 | |
apache/incubator-mxnet | f03fb23f1d103fec9541b5ae59ee06b1734a51d9 | python/mxnet/numpy/multiarray.py | python | fmod | (x1, x2, out=None, **kwargs) | return _mx_nd_np.fmod(x1, x2, out=out) | Return element-wise remainder of division.
Parameters
----------
x1 : ndarray or scalar
Dividend array.
x2 : ndarray or scalar
Divisor array.
out : ndarray
A location into which the result is stored. If provided, it must have a shape
that the inputs broadcast to. If not provided or None, a freshly-allocated array
is returned.
Returns
-------
out : ndarray or scalar
This is a scalar if both x1 and x2 are scalars.
Examples
--------
>>> np.fmod(np.arange(7), 5)
array([0., 1., 2., 3., 4., 0., 1.]) | Return element-wise remainder of division. | [
"Return",
"element",
"-",
"wise",
"remainder",
"of",
"division",
"."
] | def fmod(x1, x2, out=None, **kwargs):
"""
Return element-wise remainder of division.
Parameters
----------
x1 : ndarray or scalar
Dividend array.
x2 : ndarray or scalar
Divisor array.
out : ndarray
A location into which the result is stored. If provided, it must have a shape
that the inputs broadcast to. If not provided or None, a freshly-allocated array
is returned.
Returns
-------
out : ndarray or scalar
This is a scalar if both x1 and x2 are scalars.
Examples
--------
>>> np.fmod(np.arange(7), 5)
array([0., 1., 2., 3., 4., 0., 1.])
"""
return _mx_nd_np.fmod(x1, x2, out=out) | [
"def",
"fmod",
"(",
"x1",
",",
"x2",
",",
"out",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_mx_nd_np",
".",
"fmod",
"(",
"x1",
",",
"x2",
",",
"out",
"=",
"out",
")"
] | https://github.com/apache/incubator-mxnet/blob/f03fb23f1d103fec9541b5ae59ee06b1734a51d9/python/mxnet/numpy/multiarray.py#L3687-L3714 | |
physercoe/starquant | c00cad64d1de2da05081b3dc320ef264c6295e08 | cppsrc/fmt-5.3.0/support/docopt.py | python | parse_atom | (tokens, options) | atom ::= '(' expr ')' | '[' expr ']' | 'options'
| long | shorts | argument | command ; | atom ::= '(' expr ')' | '[' expr ']' | 'options'
| long | shorts | argument | command ; | [
"atom",
"::",
"=",
"(",
"expr",
")",
"|",
"[",
"expr",
"]",
"|",
"options",
"|",
"long",
"|",
"shorts",
"|",
"argument",
"|",
"command",
";"
] | def parse_atom(tokens, options):
"""atom ::= '(' expr ')' | '[' expr ']' | 'options'
| long | shorts | argument | command ;
"""
token = tokens.current()
result = []
if token in '([':
tokens.move()
matching, pattern = {'(': [')', Required], '[': [']', Optional]}[token]
result = pattern(*parse_expr(tokens, options))
if tokens.move() != matching:
raise tokens.error("unmatched '%s'" % token)
return [result]
elif token == 'options':
tokens.move()
return [OptionsShortcut()]
elif token.startswith('--') and token != '--':
return parse_long(tokens, options)
elif token.startswith('-') and token not in ('-', '--'):
return parse_shorts(tokens, options)
elif token.startswith('<') and token.endswith('>') or token.isupper():
return [Argument(tokens.move())]
else:
return [Command(tokens.move())] | [
"def",
"parse_atom",
"(",
"tokens",
",",
"options",
")",
":",
"token",
"=",
"tokens",
".",
"current",
"(",
")",
"result",
"=",
"[",
"]",
"if",
"token",
"in",
"'(['",
":",
"tokens",
".",
"move",
"(",
")",
"matching",
",",
"pattern",
"=",
"{",
"'('",... | https://github.com/physercoe/starquant/blob/c00cad64d1de2da05081b3dc320ef264c6295e08/cppsrc/fmt-5.3.0/support/docopt.py#L402-L425 | ||
eventql/eventql | 7ca0dbb2e683b525620ea30dc40540a22d5eb227 | deps/3rdparty/spidermonkey/mozjs/python/requests/requests/packages/urllib3/util/timeout.py | python | current_time | () | return time.time() | Retrieve the current time. This function is mocked out in unit testing. | Retrieve the current time. This function is mocked out in unit testing. | [
"Retrieve",
"the",
"current",
"time",
".",
"This",
"function",
"is",
"mocked",
"out",
"in",
"unit",
"testing",
"."
] | def current_time():
"""
Retrieve the current time. This function is mocked out in unit testing.
"""
return time.time() | [
"def",
"current_time",
"(",
")",
":",
"return",
"time",
".",
"time",
"(",
")"
] | https://github.com/eventql/eventql/blob/7ca0dbb2e683b525620ea30dc40540a22d5eb227/deps/3rdparty/spidermonkey/mozjs/python/requests/requests/packages/urllib3/util/timeout.py#L12-L16 | |
FreeCAD/FreeCAD | ba42231b9c6889b89e064d6d563448ed81e376ec | src/Mod/PartDesign/InvoluteGearFeature.py | python | _InvoluteGearTaskPanel.update | (self) | fills the widgets | fills the widgets | [
"fills",
"the",
"widgets"
] | def update(self):
'fills the widgets'
self.transferFrom() | [
"def",
"update",
"(",
"self",
")",
":",
"self",
".",
"transferFrom",
"(",
")"
] | https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/PartDesign/InvoluteGearFeature.py#L238-L240 | ||
pytorch/pytorch | 7176c92687d3cc847cc046bf002269c6949a21c2 | tools/linter/mypy_wrapper.py | python | config_files | () | return {str(ini): read_config(ini) for ini in Path().glob('mypy*.ini')} | Return a dict from all our `mypy` ini filenames to their `files`. | Return a dict from all our `mypy` ini filenames to their `files`. | [
"Return",
"a",
"dict",
"from",
"all",
"our",
"mypy",
"ini",
"filenames",
"to",
"their",
"files",
"."
] | def config_files() -> Dict[str, Set[str]]:
"""
Return a dict from all our `mypy` ini filenames to their `files`.
"""
return {str(ini): read_config(ini) for ini in Path().glob('mypy*.ini')} | [
"def",
"config_files",
"(",
")",
"->",
"Dict",
"[",
"str",
",",
"Set",
"[",
"str",
"]",
"]",
":",
"return",
"{",
"str",
"(",
"ini",
")",
":",
"read_config",
"(",
"ini",
")",
"for",
"ini",
"in",
"Path",
"(",
")",
".",
"glob",
"(",
"'mypy*.ini'",
... | https://github.com/pytorch/pytorch/blob/7176c92687d3cc847cc046bf002269c6949a21c2/tools/linter/mypy_wrapper.py#L49-L53 | |
mindspore-ai/mindspore | fb8fd3338605bb34fa5cea054e535a8b1d753fab | mindspore/python/mindspore/ops/operations/array_ops.py | python | Split.__init__ | (self, axis=0, output_num=1) | Initialize Split | Initialize Split | [
"Initialize",
"Split"
] | def __init__(self, axis=0, output_num=1):
"""Initialize Split"""
validator.check_value_type("axis", axis, [int], self.name)
validator.check_value_type("output_num", output_num, [int], self.name)
validator.check_positive_int(output_num, "output_num", self.name)
self.axis = axis
self.output_num = output_num | [
"def",
"__init__",
"(",
"self",
",",
"axis",
"=",
"0",
",",
"output_num",
"=",
"1",
")",
":",
"validator",
".",
"check_value_type",
"(",
"\"axis\"",
",",
"axis",
",",
"[",
"int",
"]",
",",
"self",
".",
"name",
")",
"validator",
".",
"check_value_type",... | https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/ops/operations/array_ops.py#L1117-L1123 | ||
google/filament | d21f092645b8e1e312307cbf89f1484891347c63 | third_party/spirv-tools/utils/generate_grammar_tables.py | python | generate_extension_enum | (extensions) | return ',\n'.join(['k' + extension for extension in extensions]) | Returns enumeration containing extensions declared in the grammar. | Returns enumeration containing extensions declared in the grammar. | [
"Returns",
"enumeration",
"containing",
"extensions",
"declared",
"in",
"the",
"grammar",
"."
] | def generate_extension_enum(extensions):
"""Returns enumeration containing extensions declared in the grammar."""
return ',\n'.join(['k' + extension for extension in extensions]) | [
"def",
"generate_extension_enum",
"(",
"extensions",
")",
":",
"return",
"',\\n'",
".",
"join",
"(",
"[",
"'k'",
"+",
"extension",
"for",
"extension",
"in",
"extensions",
"]",
")"
] | https://github.com/google/filament/blob/d21f092645b8e1e312307cbf89f1484891347c63/third_party/spirv-tools/utils/generate_grammar_tables.py#L591-L593 | |
generalized-intelligence/GAAS | 29ab17d3e8a4ba18edef3a57c36d8db6329fac73 | deprecated/algorithms/sfm/OpenSfM/opensfm/io.py | python | reconstructions_from_json | (obj) | return [reconstruction_from_json(i) for i in obj] | Read all reconstructions from a json object | Read all reconstructions from a json object | [
"Read",
"all",
"reconstructions",
"from",
"a",
"json",
"object"
] | def reconstructions_from_json(obj):
"""
Read all reconstructions from a json object
"""
return [reconstruction_from_json(i) for i in obj] | [
"def",
"reconstructions_from_json",
"(",
"obj",
")",
":",
"return",
"[",
"reconstruction_from_json",
"(",
"i",
")",
"for",
"i",
"in",
"obj",
"]"
] | https://github.com/generalized-intelligence/GAAS/blob/29ab17d3e8a4ba18edef3a57c36d8db6329fac73/deprecated/algorithms/sfm/OpenSfM/opensfm/io.py#L182-L186 | |
BlzFans/wke | b0fa21158312e40c5fbd84682d643022b6c34a93 | cygwin/lib/python2.6/fileinput.py | python | nextfile | () | return _state.nextfile() | Close the current file so that the next iteration will read the first
line from the next file (if any); lines not read from the file will
not count towards the cumulative line count. The filename is not
changed until after the first line of the next file has been read.
Before the first line has been read, this function has no effect;
it cannot be used to skip the first file. After the last line of the
last file has been read, this function has no effect. | Close the current file so that the next iteration will read the first
line from the next file (if any); lines not read from the file will
not count towards the cumulative line count. The filename is not
changed until after the first line of the next file has been read.
Before the first line has been read, this function has no effect;
it cannot be used to skip the first file. After the last line of the
last file has been read, this function has no effect. | [
"Close",
"the",
"current",
"file",
"so",
"that",
"the",
"next",
"iteration",
"will",
"read",
"the",
"first",
"line",
"from",
"the",
"next",
"file",
"(",
"if",
"any",
")",
";",
"lines",
"not",
"read",
"from",
"the",
"file",
"will",
"not",
"count",
"towa... | def nextfile():
"""
Close the current file so that the next iteration will read the first
line from the next file (if any); lines not read from the file will
not count towards the cumulative line count. The filename is not
changed until after the first line of the next file has been read.
Before the first line has been read, this function has no effect;
it cannot be used to skip the first file. After the last line of the
last file has been read, this function has no effect.
"""
if not _state:
raise RuntimeError, "no active input()"
return _state.nextfile() | [
"def",
"nextfile",
"(",
")",
":",
"if",
"not",
"_state",
":",
"raise",
"RuntimeError",
",",
"\"no active input()\"",
"return",
"_state",
".",
"nextfile",
"(",
")"
] | https://github.com/BlzFans/wke/blob/b0fa21158312e40c5fbd84682d643022b6c34a93/cygwin/lib/python2.6/fileinput.py#L114-L126 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/build/waf-1.7.13/lmbrwaflib/lumberyard.py | python | get_enabled_capabilities | (ctx) | return parsed_capabilities | Get the capabilities that were set through setup assistant
:param ctx: Context
:return: List of capabilities that were set by the setup assistant | Get the capabilities that were set through setup assistant
:param ctx: Context
:return: List of capabilities that were set by the setup assistant | [
"Get",
"the",
"capabilities",
"that",
"were",
"set",
"through",
"setup",
"assistant",
":",
"param",
"ctx",
":",
"Context",
":",
"return",
":",
"List",
"of",
"capabilities",
"that",
"were",
"set",
"by",
"the",
"setup",
"assistant"
] | def get_enabled_capabilities(ctx):
"""
Get the capabilities that were set through setup assistant
:param ctx: Context
:return: List of capabilities that were set by the setup assistant
"""
try:
return ctx.parsed_capabilities
except AttributeError:
pass
raw_capability_string = getattr(ctx.options,'bootstrap_tool_param',None)
if raw_capability_string:
capability_parser = argparse.ArgumentParser()
capability_parser.add_argument('--enablecapability', '-e', action='append')
params = [token.strip() for token in raw_capability_string.split()]
parsed_params = capability_parser.parse_known_args(params)[0]
parsed_capabilities = getattr(parsed_params, 'enablecapability', [])
else:
host_platform = Utils.unversioned_sys_platform()
# If bootstrap-tool-param is not set, that means setup assistant needs to be ran or we use default values
# if the source for setup assistant is available but setup assistant has not been built yet
base_lmbr_setup_path = os.path.join(ctx.engine_path, 'Tools', 'LmbrSetup')
setup_assistant_code_path = os.path.join(ctx.engine_path, 'Code', 'Tools', 'AZInstaller')
setup_assistant_spec_path = os.path.join(ctx.engine_path, '_WAF_', 'specs', 'lmbr_setup_tools.json')
# Use the defaults if this hasnt been set yet
parsed_capabilities = ['compilegame', 'compileengine', 'compilesandbox']
if host_platform == 'darwin':
setup_assistant_name = 'SetupAssistant'
lmbr_setup_platform = 'Mac'
parsed_capabilities.append('compileios')
parsed_capabilities.append('macOS')
minimal_setup_assistant_build_command = './lmbr_waf.sh build_darwin_x64_profile -p lmbr_setup_tools'
elif host_platform == 'win32':
setup_assistant_name = 'SetupAssistant.exe'
lmbr_setup_platform = 'Win'
parsed_capabilities.append('windows')
parsed_capabilities.append('vc141')
minimal_setup_assistant_build_command = 'lmbr_waf build_win_x64_vs2017_profile -p lmbr_setup_tools'
else:
lmbr_setup_platform = 'Linux'
setup_assistant_name = 'SetupAssistantBatch'
parsed_capabilities.append('setuplinux')
minimal_setup_assistant_build_command = './lmbr_waf.sh build_linux_x64_profile -p lmbr_setup_tools'
setup_assistant_binary_path = os.path.join(base_lmbr_setup_path, lmbr_setup_platform, setup_assistant_name)
setup_assistant_code_exists = os.path.exists(os.path.join(setup_assistant_code_path, 'wscript'))
if not os.path.exists(setup_assistant_binary_path):
# Setup assistant binary does not exist
if not setup_assistant_code_exists or not os.path.exists(setup_assistant_spec_path):
# The Setup Assistant binary does not exist and the source to build it does not exist. We cannot continue
raise Errors.WafError('[ERROR] Unable to locate the SetupAssistant application required to configure the build '
'settings for the project. Please contact support for assistance.')
else:
# If the source code exists, setup assistant will need to enable the minim capabilities in order to build it from source
ctx.warn_once('Defaulting to the minimal build options. Setup Assistant needs to be built and run to configure specific build options.')
ctx.warn_once('To build Setup Assistant, run "{}" from the command line after the configure is complete'.format(minimal_setup_assistant_build_command))
else:
if setup_assistant_code_exists:
# If the setup assistant binary exists, and the source code exists, default to the minimal build capabilities needed to build setup assistant but warn
# the user
ctx.warn_once('Defaulting to the minimal build options. Setup Assistant needs to be ran to configure specific build options.')
else:
# The setup assistant binary exists but setup assistant hasnt been run yet. Halt the process and inform the user
raise Errors.WafError('[ERROR] Setup Assistant has not configured the build settings for the project yet. You must run the tool ({}) and configure the build options first.'.format(setup_assistant_binary_path))
setattr(ctx, 'parsed_capabilities', parsed_capabilities)
return parsed_capabilities | [
"def",
"get_enabled_capabilities",
"(",
"ctx",
")",
":",
"try",
":",
"return",
"ctx",
".",
"parsed_capabilities",
"except",
"AttributeError",
":",
"pass",
"raw_capability_string",
"=",
"getattr",
"(",
"ctx",
".",
"options",
",",
"'bootstrap_tool_param'",
",",
"Non... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/build/waf-1.7.13/lmbrwaflib/lumberyard.py#L618-L693 | |
Genius-x/genius-x | 9fc9f194e6d1fb92dd0e33d43db19ddb67cda7b0 | cocos2d/tools/bindings-generator/clang/cindex.py | python | Token.kind | (self) | return TokenKind.from_value(conf.lib.clang_getTokenKind(self)) | Obtain the TokenKind of the current token. | Obtain the TokenKind of the current token. | [
"Obtain",
"the",
"TokenKind",
"of",
"the",
"current",
"token",
"."
] | def kind(self):
"""Obtain the TokenKind of the current token."""
return TokenKind.from_value(conf.lib.clang_getTokenKind(self)) | [
"def",
"kind",
"(",
"self",
")",
":",
"return",
"TokenKind",
".",
"from_value",
"(",
"conf",
".",
"lib",
".",
"clang_getTokenKind",
"(",
"self",
")",
")"
] | https://github.com/Genius-x/genius-x/blob/9fc9f194e6d1fb92dd0e33d43db19ddb67cda7b0/cocos2d/tools/bindings-generator/clang/cindex.py#L2672-L2674 | |
eventql/eventql | 7ca0dbb2e683b525620ea30dc40540a22d5eb227 | deps/3rdparty/spidermonkey/mozjs/build/upload.py | python | GetRemotePath | (path, local_file, base_path) | return path + dir | Given a remote path to upload to, a full path to a local file, and an
optional full path that is a base path of the local file, construct the
full remote path to place the file in. If base_path is not None, include
the relative path from base_path to file. | Given a remote path to upload to, a full path to a local file, and an
optional full path that is a base path of the local file, construct the
full remote path to place the file in. If base_path is not None, include
the relative path from base_path to file. | [
"Given",
"a",
"remote",
"path",
"to",
"upload",
"to",
"a",
"full",
"path",
"to",
"a",
"local",
"file",
"and",
"an",
"optional",
"full",
"path",
"that",
"is",
"a",
"base",
"path",
"of",
"the",
"local",
"file",
"construct",
"the",
"full",
"remote",
"path... | def GetRemotePath(path, local_file, base_path):
"""Given a remote path to upload to, a full path to a local file, and an
optional full path that is a base path of the local file, construct the
full remote path to place the file in. If base_path is not None, include
the relative path from base_path to file."""
if base_path is None or not local_file.startswith(base_path):
return path
dir = os.path.dirname(local_file)
# strip base_path + extra slash and make it unixy
dir = dir[len(base_path)+1:].replace('\\','/')
return path + dir | [
"def",
"GetRemotePath",
"(",
"path",
",",
"local_file",
",",
"base_path",
")",
":",
"if",
"base_path",
"is",
"None",
"or",
"not",
"local_file",
".",
"startswith",
"(",
"base_path",
")",
":",
"return",
"path",
"dir",
"=",
"os",
".",
"path",
".",
"dirname"... | https://github.com/eventql/eventql/blob/7ca0dbb2e683b525620ea30dc40540a22d5eb227/deps/3rdparty/spidermonkey/mozjs/build/upload.py#L106-L116 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numpy/lib/function_base.py | python | cov | (m, y=None, rowvar=True, bias=False, ddof=None, fweights=None,
aweights=None) | return c.squeeze() | Estimate a covariance matrix, given data and weights.
Covariance indicates the level to which two variables vary together.
If we examine N-dimensional samples, :math:`X = [x_1, x_2, ... x_N]^T`,
then the covariance matrix element :math:`C_{ij}` is the covariance of
:math:`x_i` and :math:`x_j`. The element :math:`C_{ii}` is the variance
of :math:`x_i`.
See the notes for an outline of the algorithm.
Parameters
----------
m : array_like
A 1-D or 2-D array containing multiple variables and observations.
Each row of `m` represents a variable, and each column a single
observation of all those variables. Also see `rowvar` below.
y : array_like, optional
An additional set of variables and observations. `y` has the same form
as that of `m`.
rowvar : bool, optional
If `rowvar` is True (default), then each row represents a
variable, with observations in the columns. Otherwise, the relationship
is transposed: each column represents a variable, while the rows
contain observations.
bias : bool, optional
Default normalization (False) is by ``(N - 1)``, where ``N`` is the
number of observations given (unbiased estimate). If `bias` is True,
then normalization is by ``N``. These values can be overridden by using
the keyword ``ddof`` in numpy versions >= 1.5.
ddof : int, optional
If not ``None`` the default value implied by `bias` is overridden.
Note that ``ddof=1`` will return the unbiased estimate, even if both
`fweights` and `aweights` are specified, and ``ddof=0`` will return
the simple average. See the notes for the details. The default value
is ``None``.
.. versionadded:: 1.5
fweights : array_like, int, optional
1-D array of integer frequency weights; the number of times each
observation vector should be repeated.
.. versionadded:: 1.10
aweights : array_like, optional
1-D array of observation vector weights. These relative weights are
typically large for observations considered "important" and smaller for
observations considered less "important". If ``ddof=0`` the array of
weights can be used to assign probabilities to observation vectors.
.. versionadded:: 1.10
Returns
-------
out : ndarray
The covariance matrix of the variables.
See Also
--------
corrcoef : Normalized covariance matrix
Notes
-----
Assume that the observations are in the columns of the observation
array `m` and let ``f = fweights`` and ``a = aweights`` for brevity. The
steps to compute the weighted covariance are as follows::
>>> m = np.arange(10, dtype=np.float64)
>>> f = np.arange(10) * 2
>>> a = np.arange(10) ** 2.
>>> ddof = 1
>>> w = f * a
>>> v1 = np.sum(w)
>>> v2 = np.sum(w * a)
>>> m -= np.sum(m * w, axis=None, keepdims=True) / v1
>>> cov = np.dot(m * w, m.T) * v1 / (v1**2 - ddof * v2)
Note that when ``a == 1``, the normalization factor
``v1 / (v1**2 - ddof * v2)`` goes over to ``1 / (np.sum(f) - ddof)``
as it should.
Examples
--------
Consider two variables, :math:`x_0` and :math:`x_1`, which
correlate perfectly, but in opposite directions:
>>> x = np.array([[0, 2], [1, 1], [2, 0]]).T
>>> x
array([[0, 1, 2],
[2, 1, 0]])
Note how :math:`x_0` increases while :math:`x_1` decreases. The covariance
matrix shows this clearly:
>>> np.cov(x)
array([[ 1., -1.],
[-1., 1.]])
Note that element :math:`C_{0,1}`, which shows the correlation between
:math:`x_0` and :math:`x_1`, is negative.
Further, note how `x` and `y` are combined:
>>> x = [-2.1, -1, 4.3]
>>> y = [3, 1.1, 0.12]
>>> X = np.stack((x, y), axis=0)
>>> np.cov(X)
array([[11.71 , -4.286 ], # may vary
[-4.286 , 2.144133]])
>>> np.cov(x, y)
array([[11.71 , -4.286 ], # may vary
[-4.286 , 2.144133]])
>>> np.cov(x)
array(11.71) | Estimate a covariance matrix, given data and weights. | [
"Estimate",
"a",
"covariance",
"matrix",
"given",
"data",
"and",
"weights",
"."
] | def cov(m, y=None, rowvar=True, bias=False, ddof=None, fweights=None,
aweights=None):
"""
Estimate a covariance matrix, given data and weights.
Covariance indicates the level to which two variables vary together.
If we examine N-dimensional samples, :math:`X = [x_1, x_2, ... x_N]^T`,
then the covariance matrix element :math:`C_{ij}` is the covariance of
:math:`x_i` and :math:`x_j`. The element :math:`C_{ii}` is the variance
of :math:`x_i`.
See the notes for an outline of the algorithm.
Parameters
----------
m : array_like
A 1-D or 2-D array containing multiple variables and observations.
Each row of `m` represents a variable, and each column a single
observation of all those variables. Also see `rowvar` below.
y : array_like, optional
An additional set of variables and observations. `y` has the same form
as that of `m`.
rowvar : bool, optional
If `rowvar` is True (default), then each row represents a
variable, with observations in the columns. Otherwise, the relationship
is transposed: each column represents a variable, while the rows
contain observations.
bias : bool, optional
Default normalization (False) is by ``(N - 1)``, where ``N`` is the
number of observations given (unbiased estimate). If `bias` is True,
then normalization is by ``N``. These values can be overridden by using
the keyword ``ddof`` in numpy versions >= 1.5.
ddof : int, optional
If not ``None`` the default value implied by `bias` is overridden.
Note that ``ddof=1`` will return the unbiased estimate, even if both
`fweights` and `aweights` are specified, and ``ddof=0`` will return
the simple average. See the notes for the details. The default value
is ``None``.
.. versionadded:: 1.5
fweights : array_like, int, optional
1-D array of integer frequency weights; the number of times each
observation vector should be repeated.
.. versionadded:: 1.10
aweights : array_like, optional
1-D array of observation vector weights. These relative weights are
typically large for observations considered "important" and smaller for
observations considered less "important". If ``ddof=0`` the array of
weights can be used to assign probabilities to observation vectors.
.. versionadded:: 1.10
Returns
-------
out : ndarray
The covariance matrix of the variables.
See Also
--------
corrcoef : Normalized covariance matrix
Notes
-----
Assume that the observations are in the columns of the observation
array `m` and let ``f = fweights`` and ``a = aweights`` for brevity. The
steps to compute the weighted covariance are as follows::
>>> m = np.arange(10, dtype=np.float64)
>>> f = np.arange(10) * 2
>>> a = np.arange(10) ** 2.
>>> ddof = 1
>>> w = f * a
>>> v1 = np.sum(w)
>>> v2 = np.sum(w * a)
>>> m -= np.sum(m * w, axis=None, keepdims=True) / v1
>>> cov = np.dot(m * w, m.T) * v1 / (v1**2 - ddof * v2)
Note that when ``a == 1``, the normalization factor
``v1 / (v1**2 - ddof * v2)`` goes over to ``1 / (np.sum(f) - ddof)``
as it should.
Examples
--------
Consider two variables, :math:`x_0` and :math:`x_1`, which
correlate perfectly, but in opposite directions:
>>> x = np.array([[0, 2], [1, 1], [2, 0]]).T
>>> x
array([[0, 1, 2],
[2, 1, 0]])
Note how :math:`x_0` increases while :math:`x_1` decreases. The covariance
matrix shows this clearly:
>>> np.cov(x)
array([[ 1., -1.],
[-1., 1.]])
Note that element :math:`C_{0,1}`, which shows the correlation between
:math:`x_0` and :math:`x_1`, is negative.
Further, note how `x` and `y` are combined:
>>> x = [-2.1, -1, 4.3]
>>> y = [3, 1.1, 0.12]
>>> X = np.stack((x, y), axis=0)
>>> np.cov(X)
array([[11.71 , -4.286 ], # may vary
[-4.286 , 2.144133]])
>>> np.cov(x, y)
array([[11.71 , -4.286 ], # may vary
[-4.286 , 2.144133]])
>>> np.cov(x)
array(11.71)
"""
# Check inputs
if ddof is not None and ddof != int(ddof):
raise ValueError(
"ddof must be integer")
# Handles complex arrays too
m = np.asarray(m)
if m.ndim > 2:
raise ValueError("m has more than 2 dimensions")
if y is None:
dtype = np.result_type(m, np.float64)
else:
y = np.asarray(y)
if y.ndim > 2:
raise ValueError("y has more than 2 dimensions")
dtype = np.result_type(m, y, np.float64)
X = array(m, ndmin=2, dtype=dtype)
if not rowvar and X.shape[0] != 1:
X = X.T
if X.shape[0] == 0:
return np.array([]).reshape(0, 0)
if y is not None:
y = array(y, copy=False, ndmin=2, dtype=dtype)
if not rowvar and y.shape[0] != 1:
y = y.T
X = np.concatenate((X, y), axis=0)
if ddof is None:
if bias == 0:
ddof = 1
else:
ddof = 0
# Get the product of frequencies and weights
w = None
if fweights is not None:
fweights = np.asarray(fweights, dtype=float)
if not np.all(fweights == np.around(fweights)):
raise TypeError(
"fweights must be integer")
if fweights.ndim > 1:
raise RuntimeError(
"cannot handle multidimensional fweights")
if fweights.shape[0] != X.shape[1]:
raise RuntimeError(
"incompatible numbers of samples and fweights")
if any(fweights < 0):
raise ValueError(
"fweights cannot be negative")
w = fweights
if aweights is not None:
aweights = np.asarray(aweights, dtype=float)
if aweights.ndim > 1:
raise RuntimeError(
"cannot handle multidimensional aweights")
if aweights.shape[0] != X.shape[1]:
raise RuntimeError(
"incompatible numbers of samples and aweights")
if any(aweights < 0):
raise ValueError(
"aweights cannot be negative")
if w is None:
w = aweights
else:
w *= aweights
avg, w_sum = average(X, axis=1, weights=w, returned=True)
w_sum = w_sum[0]
# Determine the normalization
if w is None:
fact = X.shape[1] - ddof
elif ddof == 0:
fact = w_sum
elif aweights is None:
fact = w_sum - ddof
else:
fact = w_sum - ddof*sum(w*aweights)/w_sum
if fact <= 0:
warnings.warn("Degrees of freedom <= 0 for slice",
RuntimeWarning, stacklevel=3)
fact = 0.0
X -= avg[:, None]
if w is None:
X_T = X.T
else:
X_T = (X*w).T
c = dot(X, X_T.conj())
c *= np.true_divide(1, fact)
return c.squeeze() | [
"def",
"cov",
"(",
"m",
",",
"y",
"=",
"None",
",",
"rowvar",
"=",
"True",
",",
"bias",
"=",
"False",
",",
"ddof",
"=",
"None",
",",
"fweights",
"=",
"None",
",",
"aweights",
"=",
"None",
")",
":",
"# Check inputs",
"if",
"ddof",
"is",
"not",
"No... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numpy/lib/function_base.py#L2246-L2456 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/core/arrays/categorical.py | python | Categorical.remove_categories | (self, removals, inplace=False) | return self.set_categories(
new_categories, ordered=self.ordered, rename=False, inplace=inplace
) | Remove the specified categories.
`removals` must be included in the old categories. Values which were in
the removed categories will be set to NaN
Parameters
----------
removals : category or list of categories
The categories which should be removed.
inplace : bool, default False
Whether or not to remove the categories inplace or return a copy of
this categorical with removed categories.
Returns
-------
cat : Categorical with removed categories or None if inplace.
Raises
------
ValueError
If the removals are not contained in the categories
See Also
--------
rename_categories
reorder_categories
add_categories
remove_unused_categories
set_categories | Remove the specified categories. | [
"Remove",
"the",
"specified",
"categories",
"."
] | def remove_categories(self, removals, inplace=False):
"""
Remove the specified categories.
`removals` must be included in the old categories. Values which were in
the removed categories will be set to NaN
Parameters
----------
removals : category or list of categories
The categories which should be removed.
inplace : bool, default False
Whether or not to remove the categories inplace or return a copy of
this categorical with removed categories.
Returns
-------
cat : Categorical with removed categories or None if inplace.
Raises
------
ValueError
If the removals are not contained in the categories
See Also
--------
rename_categories
reorder_categories
add_categories
remove_unused_categories
set_categories
"""
inplace = validate_bool_kwarg(inplace, "inplace")
if not is_list_like(removals):
removals = [removals]
removal_set = set(removals)
not_included = removal_set - set(self.dtype.categories)
new_categories = [c for c in self.dtype.categories if c not in removal_set]
# GH 10156
if any(isna(removals)):
not_included = {x for x in not_included if notna(x)}
new_categories = [x for x in new_categories if notna(x)]
if len(not_included) != 0:
raise ValueError(f"removals must all be in old categories: {not_included}")
return self.set_categories(
new_categories, ordered=self.ordered, rename=False, inplace=inplace
) | [
"def",
"remove_categories",
"(",
"self",
",",
"removals",
",",
"inplace",
"=",
"False",
")",
":",
"inplace",
"=",
"validate_bool_kwarg",
"(",
"inplace",
",",
"\"inplace\"",
")",
"if",
"not",
"is_list_like",
"(",
"removals",
")",
":",
"removals",
"=",
"[",
... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/core/arrays/categorical.py#L1039-L1089 | |
deepmind/open_spiel | 4ca53bea32bb2875c7385d215424048ae92f78c8 | open_spiel/python/egt/dynamics.py | python | time_average | (traj) | return sum_traj * norm[:, np.newaxis] | Time-averaged population state trajectory.
Args:
traj: Trajectory as `numpy.ndarray`. Time is along the first dimension,
types/strategies along the second.
Returns:
Time-averaged trajectory. | Time-averaged population state trajectory. | [
"Time",
"-",
"averaged",
"population",
"state",
"trajectory",
"."
] | def time_average(traj):
"""Time-averaged population state trajectory.
Args:
traj: Trajectory as `numpy.ndarray`. Time is along the first dimension,
types/strategies along the second.
Returns:
Time-averaged trajectory.
"""
n = traj.shape[0]
sum_traj = np.cumsum(traj, axis=0)
norm = 1. / np.arange(1, n + 1)
return sum_traj * norm[:, np.newaxis] | [
"def",
"time_average",
"(",
"traj",
")",
":",
"n",
"=",
"traj",
".",
"shape",
"[",
"0",
"]",
"sum_traj",
"=",
"np",
".",
"cumsum",
"(",
"traj",
",",
"axis",
"=",
"0",
")",
"norm",
"=",
"1.",
"/",
"np",
".",
"arange",
"(",
"1",
",",
"n",
"+",
... | https://github.com/deepmind/open_spiel/blob/4ca53bea32bb2875c7385d215424048ae92f78c8/open_spiel/python/egt/dynamics.py#L177-L190 | |
apache/singa | 93fd9da72694e68bfe3fb29d0183a65263d238a1 | python/singa/autograd.py | python | batchnorm_2d | (handle, x, scale, bias, running_mean, running_var) | return _BatchNorm2d(handle, running_mean, running_var)(x, scale, bias)[0] | Carries out batch normalization as described in the paper
https://arxiv.org/abs/1502.03167.
Args:
handle (object): BatchNormHandle for cpu and CudnnBatchNormHandle
for gpu
x (Tensor): the input tensor
scale (Tensor): the bias tensor
bias (Tensor): the bias tensor
running_mean (float): the running_mean
running_var (float): the running_var
Returns:
the result Tensor | Carries out batch normalization as described in the paper
https://arxiv.org/abs/1502.03167.
Args:
handle (object): BatchNormHandle for cpu and CudnnBatchNormHandle
for gpu
x (Tensor): the input tensor
scale (Tensor): the bias tensor
bias (Tensor): the bias tensor
running_mean (float): the running_mean
running_var (float): the running_var
Returns:
the result Tensor | [
"Carries",
"out",
"batch",
"normalization",
"as",
"described",
"in",
"the",
"paper",
"https",
":",
"//",
"arxiv",
".",
"org",
"/",
"abs",
"/",
"1502",
".",
"03167",
".",
"Args",
":",
"handle",
"(",
"object",
")",
":",
"BatchNormHandle",
"for",
"cpu",
"... | def batchnorm_2d(handle, x, scale, bias, running_mean, running_var):
"""
Carries out batch normalization as described in the paper
https://arxiv.org/abs/1502.03167.
Args:
handle (object): BatchNormHandle for cpu and CudnnBatchNormHandle
for gpu
x (Tensor): the input tensor
scale (Tensor): the bias tensor
bias (Tensor): the bias tensor
running_mean (float): the running_mean
running_var (float): the running_var
Returns:
the result Tensor
"""
return _BatchNorm2d(handle, running_mean, running_var)(x, scale, bias)[0] | [
"def",
"batchnorm_2d",
"(",
"handle",
",",
"x",
",",
"scale",
",",
"bias",
",",
"running_mean",
",",
"running_var",
")",
":",
"return",
"_BatchNorm2d",
"(",
"handle",
",",
"running_mean",
",",
"running_var",
")",
"(",
"x",
",",
"scale",
",",
"bias",
")",... | https://github.com/apache/singa/blob/93fd9da72694e68bfe3fb29d0183a65263d238a1/python/singa/autograd.py#L1829-L1844 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/AWSPythonSDK/1.5.8/docutils/statemachine.py | python | StringList.pad_double_width | (self, pad_char) | Pad all double-width characters in self by appending `pad_char` to each.
For East Asian language support. | Pad all double-width characters in self by appending `pad_char` to each.
For East Asian language support. | [
"Pad",
"all",
"double",
"-",
"width",
"characters",
"in",
"self",
"by",
"appending",
"pad_char",
"to",
"each",
".",
"For",
"East",
"Asian",
"language",
"support",
"."
] | def pad_double_width(self, pad_char):
"""
Pad all double-width characters in self by appending `pad_char` to each.
For East Asian language support.
"""
if hasattr(unicodedata, 'east_asian_width'):
east_asian_width = unicodedata.east_asian_width
else:
return # new in Python 2.4
for i in range(len(self.data)):
line = self.data[i]
if isinstance(line, unicode):
new = []
for char in line:
new.append(char)
if east_asian_width(char) in 'WF': # 'W'ide & 'F'ull-width
new.append(pad_char)
self.data[i] = ''.join(new) | [
"def",
"pad_double_width",
"(",
"self",
",",
"pad_char",
")",
":",
"if",
"hasattr",
"(",
"unicodedata",
",",
"'east_asian_width'",
")",
":",
"east_asian_width",
"=",
"unicodedata",
".",
"east_asian_width",
"else",
":",
"return",
"# new in Python 2.4",
"for",
"i",
... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/AWSPythonSDK/1.5.8/docutils/statemachine.py#L1450-L1467 | ||
eric612/Caffe-YOLOv3-Windows | 6736ca6e16781789b828cc64218ff77cc3454e5d | examples/pycaffe/tools.py | python | CaffeSolver.write | (self, filepath) | Export solver parameters to INPUT "filepath". Sorted alphabetically. | Export solver parameters to INPUT "filepath". Sorted alphabetically. | [
"Export",
"solver",
"parameters",
"to",
"INPUT",
"filepath",
".",
"Sorted",
"alphabetically",
"."
] | def write(self, filepath):
"""
Export solver parameters to INPUT "filepath". Sorted alphabetically.
"""
f = open(filepath, 'w')
for key, value in sorted(self.sp.items()):
if not(type(value) is str):
raise TypeError('All solver parameters must be strings')
f.write('%s: %s\n' % (key, value)) | [
"def",
"write",
"(",
"self",
",",
"filepath",
")",
":",
"f",
"=",
"open",
"(",
"filepath",
",",
"'w'",
")",
"for",
"key",
",",
"value",
"in",
"sorted",
"(",
"self",
".",
"sp",
".",
"items",
"(",
")",
")",
":",
"if",
"not",
"(",
"type",
"(",
"... | https://github.com/eric612/Caffe-YOLOv3-Windows/blob/6736ca6e16781789b828cc64218ff77cc3454e5d/examples/pycaffe/tools.py#L113-L121 | ||
eventql/eventql | 7ca0dbb2e683b525620ea30dc40540a22d5eb227 | deps/3rdparty/spidermonkey/mozjs/media/webrtc/trunk/tools/gyp/pylib/gyp/common.py | python | GetFlavor | (params) | return 'linux' | Returns |params.flavor| if it's set, the system's default flavor else. | Returns |params.flavor| if it's set, the system's default flavor else. | [
"Returns",
"|params",
".",
"flavor|",
"if",
"it",
"s",
"set",
"the",
"system",
"s",
"default",
"flavor",
"else",
"."
] | def GetFlavor(params):
"""Returns |params.flavor| if it's set, the system's default flavor else."""
flavors = {
'cygwin': 'win',
'win32': 'win',
'darwin': 'mac',
}
if 'flavor' in params:
return params['flavor']
if sys.platform in flavors:
return flavors[sys.platform]
if sys.platform.startswith('sunos'):
return 'solaris'
if sys.platform.startswith('freebsd'):
return 'freebsd'
return 'linux' | [
"def",
"GetFlavor",
"(",
"params",
")",
":",
"flavors",
"=",
"{",
"'cygwin'",
":",
"'win'",
",",
"'win32'",
":",
"'win'",
",",
"'darwin'",
":",
"'mac'",
",",
"}",
"if",
"'flavor'",
"in",
"params",
":",
"return",
"params",
"[",
"'flavor'",
"]",
"if",
... | https://github.com/eventql/eventql/blob/7ca0dbb2e683b525620ea30dc40540a22d5eb227/deps/3rdparty/spidermonkey/mozjs/media/webrtc/trunk/tools/gyp/pylib/gyp/common.py#L365-L382 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/grid.py | python | Grid.MoveCursorDownBlock | (*args, **kwargs) | return _grid.Grid_MoveCursorDownBlock(*args, **kwargs) | MoveCursorDownBlock(self, bool expandSelection) -> bool | MoveCursorDownBlock(self, bool expandSelection) -> bool | [
"MoveCursorDownBlock",
"(",
"self",
"bool",
"expandSelection",
")",
"-",
">",
"bool"
] | def MoveCursorDownBlock(*args, **kwargs):
"""MoveCursorDownBlock(self, bool expandSelection) -> bool"""
return _grid.Grid_MoveCursorDownBlock(*args, **kwargs) | [
"def",
"MoveCursorDownBlock",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_grid",
".",
"Grid_MoveCursorDownBlock",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/grid.py#L1458-L1460 | |
miyosuda/TensorFlowAndroidMNIST | 7b5a4603d2780a8a2834575706e9001977524007 | jni-build/jni/include/tensorflow/tools/docs/gen_cc_md.py | python | element_text | (member_elt, elt_name) | return '\n\n'.join(text) | Extract all `para` text from (`elt_name` in) `member_elt`. | Extract all `para` text from (`elt_name` in) `member_elt`. | [
"Extract",
"all",
"para",
"text",
"from",
"(",
"elt_name",
"in",
")",
"member_elt",
"."
] | def element_text(member_elt, elt_name):
"""Extract all `para` text from (`elt_name` in) `member_elt`."""
text = []
if elt_name:
elt = member_elt.find(elt_name)
else:
elt = member_elt
if elt:
paras = elt.findAll('para')
for p in paras:
text.append(p.getText(separator=u' ').strip())
return '\n\n'.join(text) | [
"def",
"element_text",
"(",
"member_elt",
",",
"elt_name",
")",
":",
"text",
"=",
"[",
"]",
"if",
"elt_name",
":",
"elt",
"=",
"member_elt",
".",
"find",
"(",
"elt_name",
")",
"else",
":",
"elt",
"=",
"member_elt",
"if",
"elt",
":",
"paras",
"=",
"el... | https://github.com/miyosuda/TensorFlowAndroidMNIST/blob/7b5a4603d2780a8a2834575706e9001977524007/jni-build/jni/include/tensorflow/tools/docs/gen_cc_md.py#L128-L140 | |
trilinos/Trilinos | 6168be6dd51e35e1cd681e9c4b24433e709df140 | packages/seacas/scripts/exomerge3.py | python | ExodusModel._order_nodes | (self) | Redefine node ordering in a consistent manner.
This was introduced because running exodiff on two different
models with the same information but differing node numbering will
fail. By running this routine before export_model, the numbering
will be consistent and will avoid this problem. | Redefine node ordering in a consistent manner. | [
"Redefine",
"node",
"ordering",
"in",
"a",
"consistent",
"manner",
"."
] | def _order_nodes(self):
"""
Redefine node ordering in a consistent manner.
This was introduced because running exodiff on two different
models with the same information but differing node numbering will
fail. By running this routine before export_model, the numbering
will be consistent and will avoid this problem.
"""
# Define new node numbering by the order in which nodes are encountered
# in element blocks by ascending element block id. For nodes not used
# in any element blocks, they are sorted by x coordinate, then y
# coordinate, then z coordinate.
# node i on old model becomes node_map[i]
# node i in new model was reverse_node_map[i]
next_index = 0
node_map = [None] * len(self.nodes)
for element_block_id in self.get_element_block_ids():
connectivity = self.get_connectivity(element_block_id)
for node_index in connectivity:
if node_map[node_index] is None:
node_map[node_index] = next_index
next_index += 1
still_to_sort = []
for index, map_ in enumerate(node_map):
if map_ is None:
still_to_sort.append((self.nodes[index], index))
still_to_sort.sort()
for _, node_index in still_to_sort:
node_map[node_index] = next_index
next_index += 1
self._apply_node_map(node_map) | [
"def",
"_order_nodes",
"(",
"self",
")",
":",
"# Define new node numbering by the order in which nodes are encountered",
"# in element blocks by ascending element block id. For nodes not used",
"# in any element blocks, they are sorted by x coordinate, then y",
"# coordinate, then z coordinate.",... | https://github.com/trilinos/Trilinos/blob/6168be6dd51e35e1cd681e9c4b24433e709df140/packages/seacas/scripts/exomerge3.py#L6704-L6736 | ||
microsoft/CNTK | e9396480025b9ca457d26b6f33dd07c474c6aa04 | Examples/ReinforcementLearning/FlappingBirdWithKeras/game/wrapped_flappy_bird.py | python | pixelCollision | (rect1, rect2, hitmask1, hitmask2) | return False | Checks if two objects collide and not just their rects | Checks if two objects collide and not just their rects | [
"Checks",
"if",
"two",
"objects",
"collide",
"and",
"not",
"just",
"their",
"rects"
] | def pixelCollision(rect1, rect2, hitmask1, hitmask2):
"""Checks if two objects collide and not just their rects"""
rect = rect1.clip(rect2)
if rect.width == 0 or rect.height == 0:
return False
x1, y1 = rect.x - rect1.x, rect.y - rect1.y
x2, y2 = rect.x - rect2.x, rect.y - rect2.y
for x in range(rect.width):
for y in range(rect.height):
if hitmask1[x1+x][y1+y] and hitmask2[x2+x][y2+y]:
return True
return False | [
"def",
"pixelCollision",
"(",
"rect1",
",",
"rect2",
",",
"hitmask1",
",",
"hitmask2",
")",
":",
"rect",
"=",
"rect1",
".",
"clip",
"(",
"rect2",
")",
"if",
"rect",
".",
"width",
"==",
"0",
"or",
"rect",
".",
"height",
"==",
"0",
":",
"return",
"Fa... | https://github.com/microsoft/CNTK/blob/e9396480025b9ca457d26b6f33dd07c474c6aa04/Examples/ReinforcementLearning/FlappingBirdWithKeras/game/wrapped_flappy_bird.py#L213-L227 | |
mindspore-ai/mindspore | fb8fd3338605bb34fa5cea054e535a8b1d753fab | mindspore/python/mindspore/nn/probability/distribution/bernoulli.py | python | Bernoulli._cdf | (self, value, probs1=None) | return self.select(comp_one, less_than_zero, ones) | r"""
Cumulative distribution function (cdf) of Bernoulli distributions.
Args:
value (Tensor): The value to be evaluated.
probs (Tensor): The probability of that the outcome is 1. Default: self.probs.
.. math::
cdf(k) = 0 if k < 0;
cdf(k) = probs0 if 0 <= k <1;
cdf(k) = 1 if k >=1; | r"""
Cumulative distribution function (cdf) of Bernoulli distributions. | [
"r",
"Cumulative",
"distribution",
"function",
"(",
"cdf",
")",
"of",
"Bernoulli",
"distributions",
"."
] | def _cdf(self, value, probs1=None):
r"""
Cumulative distribution function (cdf) of Bernoulli distributions.
Args:
value (Tensor): The value to be evaluated.
probs (Tensor): The probability of that the outcome is 1. Default: self.probs.
.. math::
cdf(k) = 0 if k < 0;
cdf(k) = probs0 if 0 <= k <1;
cdf(k) = 1 if k >=1;
"""
value = self._check_value(value, 'value')
value = self.cast(value, self.parameter_type)
value = self.floor(value)
probs1 = self._check_param_type(probs1)
broadcast_shape_tensor = value * probs1
value = self.broadcast(value, broadcast_shape_tensor)
probs0 = self.broadcast((1.0 - probs1), broadcast_shape_tensor)
comp_zero = self.less(value, 0.0)
comp_one = self.less(value, 1.0)
zeros = self.fill(self.parameter_type, self.shape(
broadcast_shape_tensor), 0.0)
ones = self.fill(self.parameter_type, self.shape(
broadcast_shape_tensor), 1.0)
less_than_zero = self.select(comp_zero, zeros, probs0)
return self.select(comp_one, less_than_zero, ones) | [
"def",
"_cdf",
"(",
"self",
",",
"value",
",",
"probs1",
"=",
"None",
")",
":",
"value",
"=",
"self",
".",
"_check_value",
"(",
"value",
",",
"'value'",
")",
"value",
"=",
"self",
".",
"cast",
"(",
"value",
",",
"self",
".",
"parameter_type",
")",
... | https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/nn/probability/distribution/bernoulli.py#L272-L299 | |
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | Framework/PythonInterface/plugins/algorithms/SaveGSSCW.py | python | SaveGSSCW._write_gsas_fxye | (self, workspace) | return gsas_content | Write GSAS file from a workspace to FXYE format
Example:
BANK 1 2438 488 CONST 1000.000 5.000 0 0 ESD
287.51 16.96 281.38 13.52 279.80 11.83 282.77 11.89 279.73 13.43
270.69 16.45 270.27 13.23 271.90 11.66 275.57 11.74 286.05 13.66
303.35 17.42 295.64 13.86 292.17 12.09 292.92 12.10 288.03 13.63
277.50 16.66 278.01 13.42 274.65 11.72 267.41 11.56 266.29 13.15
271.27 16.47 273.06 13.29 272.29 11.67 268.96 11.60 260.08 12.93
245.63 15.67 250.87 12.73 258.06 11.36 267.18 11.56 272.39 13.29
Returns
-------
str
GSAS file content | Write GSAS file from a workspace to FXYE format | [
"Write",
"GSAS",
"file",
"from",
"a",
"workspace",
"to",
"FXYE",
"format"
] | def _write_gsas_fxye(self, workspace):
"""
Write GSAS file from a workspace to FXYE format
Example:
BANK 1 2438 488 CONST 1000.000 5.000 0 0 ESD
287.51 16.96 281.38 13.52 279.80 11.83 282.77 11.89 279.73 13.43
270.69 16.45 270.27 13.23 271.90 11.66 275.57 11.74 286.05 13.66
303.35 17.42 295.64 13.86 292.17 12.09 292.92 12.10 288.03 13.63
277.50 16.66 278.01 13.42 274.65 11.72 267.41 11.56 266.29 13.15
271.27 16.47 273.06 13.29 272.29 11.67 268.96 11.60 260.08 12.93
245.63 15.67 250.87 12.73 258.06 11.36 267.18 11.56 272.39 13.29
Returns
-------
str
GSAS file content
"""
# generate header
header = self._create_gsas_header(workspace)
# generate body
body = self._create_gsas_body(workspace)
# construct the file
gsas_content = self.empty_line(80) + '\n' + header + body
return gsas_content | [
"def",
"_write_gsas_fxye",
"(",
"self",
",",
"workspace",
")",
":",
"# generate header",
"header",
"=",
"self",
".",
"_create_gsas_header",
"(",
"workspace",
")",
"# generate body",
"body",
"=",
"self",
".",
"_create_gsas_body",
"(",
"workspace",
")",
"# construct... | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/Framework/PythonInterface/plugins/algorithms/SaveGSSCW.py#L96-L125 | |
SpaceNetChallenge/BuildingDetectors | 3def3c44b5847c744cd2f3356182892d92496579 | qinhaifang/src/caffe-mnc/python/caffe/io.py | python | blobproto_to_array | (blob, return_diff=False) | Convert a blob proto to an array. In default, we will just return the data,
unless return_diff is True, in which case we will return the diff. | Convert a blob proto to an array. In default, we will just return the data,
unless return_diff is True, in which case we will return the diff. | [
"Convert",
"a",
"blob",
"proto",
"to",
"an",
"array",
".",
"In",
"default",
"we",
"will",
"just",
"return",
"the",
"data",
"unless",
"return_diff",
"is",
"True",
"in",
"which",
"case",
"we",
"will",
"return",
"the",
"diff",
"."
] | def blobproto_to_array(blob, return_diff=False):
"""
Convert a blob proto to an array. In default, we will just return the data,
unless return_diff is True, in which case we will return the diff.
"""
# Read the data into an array
if return_diff:
data = np.array(blob.diff)
else:
data = np.array(blob.data)
# Reshape the array
if blob.HasField('num') or blob.HasField('channels') or blob.HasField('height') or blob.HasField('width'):
# Use legacy 4D shape
return data.reshape(blob.num, blob.channels, blob.height, blob.width)
else:
return data.reshape(blob.shape.dim) | [
"def",
"blobproto_to_array",
"(",
"blob",
",",
"return_diff",
"=",
"False",
")",
":",
"# Read the data into an array",
"if",
"return_diff",
":",
"data",
"=",
"np",
".",
"array",
"(",
"blob",
".",
"diff",
")",
"else",
":",
"data",
"=",
"np",
".",
"array",
... | https://github.com/SpaceNetChallenge/BuildingDetectors/blob/3def3c44b5847c744cd2f3356182892d92496579/qinhaifang/src/caffe-mnc/python/caffe/io.py#L18-L34 | ||
RamadhanAmizudin/malware | 2c6c53c8b0d556f5d8078d6ca0fc4448f4697cf1 | Mazar/MazAr_Admin/apps/smsg_r/smsapp/remote_api.py | python | intercept_status_change | (rec, data) | Signals that the phone has changed its intercept status in reply to #intercept_sms_start & #intercept_sms_stop
data."rent status" contains either "started" or "stopped"
@param rec: Phone data record
@type rec: models.PhoneData
@param data: Phone data
@type data: dict
@rtype: None | Signals that the phone has changed its intercept status in reply to #intercept_sms_start & #intercept_sms_stop
data."rent status" contains either "started" or "stopped" | [
"Signals",
"that",
"the",
"phone",
"has",
"changed",
"its",
"intercept",
"status",
"in",
"reply",
"to",
"#intercept_sms_start",
"&",
"#intercept_sms_stop",
"data",
".",
"rent",
"status",
"contains",
"either",
"started",
"or",
"stopped"
] | def intercept_status_change(rec, data):
"""
Signals that the phone has changed its intercept status in reply to #intercept_sms_start & #intercept_sms_stop
data."rent status" contains either "started" or "stopped"
@param rec: Phone data record
@type rec: models.PhoneData
@param data: Phone data
@type data: dict
@rtype: None
"""
if rec.owner_id is None:
logger.error(u"No owner for phone {0} currently".format(rec))
return
new_status = data.get('rent status')
owner = rec.owner
if new_status == "started":
rec.sms_status = models.PhoneData.SMS_INTERCEPT
rec.save()
elif new_status == "stopped":
rec.owner = None
rec.sms_status = models.PhoneData.SMS_INITIAL
rec.save()
commands.set_phone_transient_state(rec.uniq_id, commands.PHONE_STATE_STABLE)
msg = {
'info': "Phone {0} SMS intercept {1}".format(rec, new_status),
'imei': rec.imei
}
logger.debug(u"Phone {0} status changed to {1}".format(rec, new_status))
sys_messages.add_message(rec.uniq_id, msg) | [
"def",
"intercept_status_change",
"(",
"rec",
",",
"data",
")",
":",
"if",
"rec",
".",
"owner_id",
"is",
"None",
":",
"logger",
".",
"error",
"(",
"u\"No owner for phone {0} currently\"",
".",
"format",
"(",
"rec",
")",
")",
"return",
"new_status",
"=",
"dat... | https://github.com/RamadhanAmizudin/malware/blob/2c6c53c8b0d556f5d8078d6ca0fc4448f4697cf1/Mazar/MazAr_Admin/apps/smsg_r/smsapp/remote_api.py#L246-L274 | ||
rrwick/Unicycler | 96ffea71e3a78d63ade19d6124946773e65cf129 | unicycler/assembly_graph.py | python | AssemblyGraph.gfa_link_line | (self, start, end) | return l_line | Returns an entire L line for GFA output, including the newline. | Returns an entire L line for GFA output, including the newline. | [
"Returns",
"an",
"entire",
"L",
"line",
"for",
"GFA",
"output",
"including",
"the",
"newline",
"."
] | def gfa_link_line(self, start, end):
"""
Returns an entire L line for GFA output, including the newline.
"""
l_line = 'L\t'
l_line += str(abs(start)) + '\t'
l_line += get_sign_string(start) + '\t'
l_line += str(abs(end)) + '\t'
l_line += get_sign_string(end) + '\t'
l_line += str(self.overlap) + 'M\n'
return l_line | [
"def",
"gfa_link_line",
"(",
"self",
",",
"start",
",",
"end",
")",
":",
"l_line",
"=",
"'L\\t'",
"l_line",
"+=",
"str",
"(",
"abs",
"(",
"start",
")",
")",
"+",
"'\\t'",
"l_line",
"+=",
"get_sign_string",
"(",
"start",
")",
"+",
"'\\t'",
"l_line",
"... | https://github.com/rrwick/Unicycler/blob/96ffea71e3a78d63ade19d6124946773e65cf129/unicycler/assembly_graph.py#L739-L749 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | samples/pySketch/pySketch.py | python | DrawingFrame.doDelete | (self, event) | Respond to the "Delete" menu command. | Respond to the "Delete" menu command. | [
"Respond",
"to",
"the",
"Delete",
"menu",
"command",
"."
] | def doDelete(self, event):
""" Respond to the "Delete" menu command.
"""
self.saveUndoInfo()
for obj in self.selection:
self.contents.remove(obj)
del obj
self.deselectAll() | [
"def",
"doDelete",
"(",
"self",
",",
"event",
")",
":",
"self",
".",
"saveUndoInfo",
"(",
")",
"for",
"obj",
"in",
"self",
".",
"selection",
":",
"self",
".",
"contents",
".",
"remove",
"(",
"obj",
")",
"del",
"obj",
"self",
".",
"deselectAll",
"(",
... | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/samples/pySketch/pySketch.py#L885-L893 | ||
msracver/Deep-Image-Analogy | 632b9287b42552e32dad64922967c8c9ec7fc4d3 | scripts/cpp_lint.py | python | _NamespaceInfo.CheckEnd | (self, filename, clean_lines, linenum, error) | Check end of namespace comments. | Check end of namespace comments. | [
"Check",
"end",
"of",
"namespace",
"comments",
"."
] | def CheckEnd(self, filename, clean_lines, linenum, error):
"""Check end of namespace comments."""
line = clean_lines.raw_lines[linenum]
# Check how many lines is enclosed in this namespace. Don't issue
# warning for missing namespace comments if there aren't enough
# lines. However, do apply checks if there is already an end of
# namespace comment and it's incorrect.
#
# TODO(unknown): We always want to check end of namespace comments
# if a namespace is large, but sometimes we also want to apply the
# check if a short namespace contained nontrivial things (something
# other than forward declarations). There is currently no logic on
# deciding what these nontrivial things are, so this check is
# triggered by namespace size only, which works most of the time.
if (linenum - self.starting_linenum < 10
and not Match(r'};*\s*(//|/\*).*\bnamespace\b', line)):
return
# Look for matching comment at end of namespace.
#
# Note that we accept C style "/* */" comments for terminating
# namespaces, so that code that terminate namespaces inside
# preprocessor macros can be cpplint clean.
#
# We also accept stuff like "// end of namespace <name>." with the
# period at the end.
#
# Besides these, we don't accept anything else, otherwise we might
# get false negatives when existing comment is a substring of the
# expected namespace.
if self.name:
# Named namespace
if not Match((r'};*\s*(//|/\*).*\bnamespace\s+' + re.escape(self.name) +
r'[\*/\.\\\s]*$'),
line):
error(filename, linenum, 'readability/namespace', 5,
'Namespace should be terminated with "// namespace %s"' %
self.name)
else:
# Anonymous namespace
if not Match(r'};*\s*(//|/\*).*\bnamespace[\*/\.\\\s]*$', line):
error(filename, linenum, 'readability/namespace', 5,
'Namespace should be terminated with "// namespace"') | [
"def",
"CheckEnd",
"(",
"self",
",",
"filename",
",",
"clean_lines",
",",
"linenum",
",",
"error",
")",
":",
"line",
"=",
"clean_lines",
".",
"raw_lines",
"[",
"linenum",
"]",
"# Check how many lines is enclosed in this namespace. Don't issue",
"# warning for missing n... | https://github.com/msracver/Deep-Image-Analogy/blob/632b9287b42552e32dad64922967c8c9ec7fc4d3/scripts/cpp_lint.py#L1856-L1899 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/inspect.py | python | Signature.replace | (self, *, parameters=_void, return_annotation=_void) | return type(self)(parameters,
return_annotation=return_annotation) | Creates a customized copy of the Signature.
Pass 'parameters' and/or 'return_annotation' arguments
to override them in the new copy. | Creates a customized copy of the Signature.
Pass 'parameters' and/or 'return_annotation' arguments
to override them in the new copy. | [
"Creates",
"a",
"customized",
"copy",
"of",
"the",
"Signature",
".",
"Pass",
"parameters",
"and",
"/",
"or",
"return_annotation",
"arguments",
"to",
"override",
"them",
"in",
"the",
"new",
"copy",
"."
] | def replace(self, *, parameters=_void, return_annotation=_void):
"""Creates a customized copy of the Signature.
Pass 'parameters' and/or 'return_annotation' arguments
to override them in the new copy.
"""
if parameters is _void:
parameters = self.parameters.values()
if return_annotation is _void:
return_annotation = self._return_annotation
return type(self)(parameters,
return_annotation=return_annotation) | [
"def",
"replace",
"(",
"self",
",",
"*",
",",
"parameters",
"=",
"_void",
",",
"return_annotation",
"=",
"_void",
")",
":",
"if",
"parameters",
"is",
"_void",
":",
"parameters",
"=",
"self",
".",
"parameters",
".",
"values",
"(",
")",
"if",
"return_annot... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/inspect.py#L2843-L2856 | |
thalium/icebox | 99d147d5b9269222225443ce171b4fd46d8985d4 | third_party/virtualbox/src/libs/libxml2-2.9.4/python/libxml2.py | python | xmlNode.setContent | (self, content) | Replace the content of a node. NOTE: @content is supposed
to be a piece of XML CDATA, so it allows entity references,
but XML special chars need to be escaped first by using
xmlEncodeEntitiesReentrant() resp. xmlEncodeSpecialChars(). | Replace the content of a node. NOTE: | [
"Replace",
"the",
"content",
"of",
"a",
"node",
".",
"NOTE",
":"
] | def setContent(self, content):
"""Replace the content of a node. NOTE: @content is supposed
to be a piece of XML CDATA, so it allows entity references,
but XML special chars need to be escaped first by using
xmlEncodeEntitiesReentrant() resp. xmlEncodeSpecialChars(). """
libxml2mod.xmlNodeSetContent(self._o, content) | [
"def",
"setContent",
"(",
"self",
",",
"content",
")",
":",
"libxml2mod",
".",
"xmlNodeSetContent",
"(",
"self",
".",
"_o",
",",
"content",
")"
] | https://github.com/thalium/icebox/blob/99d147d5b9269222225443ce171b4fd46d8985d4/third_party/virtualbox/src/libs/libxml2-2.9.4/python/libxml2.py#L3537-L3542 | ||
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | qt/python/mantidqtinterfaces/mantidqtinterfaces/Muon/GUI/Common/contexts/fitting_contexts/general_fitting_context.py | python | GeneralFittingContext.global_parameters | (self, global_parameters: list) | Sets the global parameters stored in the model. | Sets the global parameters stored in the model. | [
"Sets",
"the",
"global",
"parameters",
"stored",
"in",
"the",
"model",
"."
] | def global_parameters(self, global_parameters: list) -> None:
"""Sets the global parameters stored in the model."""
self._global_parameters = global_parameters | [
"def",
"global_parameters",
"(",
"self",
",",
"global_parameters",
":",
"list",
")",
"->",
"None",
":",
"self",
".",
"_global_parameters",
"=",
"global_parameters"
] | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqtinterfaces/mantidqtinterfaces/Muon/GUI/Common/contexts/fitting_contexts/general_fitting_context.py#L99-L101 | ||
okex/V3-Open-API-SDK | c5abb0db7e2287718e0055e17e57672ce0ec7fd9 | okex-python-sdk-api/venv/Lib/site-packages/pip-19.0.3-py3.8.egg/pip/_internal/wheel.py | python | WheelBuilder.build | (
self,
requirements, # type: Iterable[InstallRequirement]
session, # type: PipSession
autobuilding=False # type: bool
) | return build_failure | Build wheels.
:param unpack: If True, replace the sdist we built from with the
newly built wheel, in preparation for installation.
:return: True if all the wheels built correctly. | Build wheels. | [
"Build",
"wheels",
"."
] | def build(
self,
requirements, # type: Iterable[InstallRequirement]
session, # type: PipSession
autobuilding=False # type: bool
):
# type: (...) -> List[InstallRequirement]
"""Build wheels.
:param unpack: If True, replace the sdist we built from with the
newly built wheel, in preparation for installation.
:return: True if all the wheels built correctly.
"""
buildset = []
format_control = self.finder.format_control
# Whether a cache directory is available for autobuilding=True.
cache_available = bool(self._wheel_dir or self.wheel_cache.cache_dir)
for req in requirements:
ephem_cache = should_use_ephemeral_cache(
req, format_control=format_control, autobuilding=autobuilding,
cache_available=cache_available,
)
if ephem_cache is None:
continue
buildset.append((req, ephem_cache))
if not buildset:
return []
# Is any wheel build not using the ephemeral cache?
if any(not ephem_cache for _, ephem_cache in buildset):
have_directory_for_build = self._wheel_dir or (
autobuilding and self.wheel_cache.cache_dir
)
assert have_directory_for_build
# TODO by @pradyunsg
# Should break up this method into 2 separate methods.
# Build the wheels.
logger.info(
'Building wheels for collected packages: %s',
', '.join([req.name for (req, _) in buildset]),
)
_cache = self.wheel_cache # shorter name
with indent_log():
build_success, build_failure = [], []
for req, ephem in buildset:
python_tag = None
if autobuilding:
python_tag = pep425tags.implementation_tag
if ephem:
output_dir = _cache.get_ephem_path_for_link(req.link)
else:
output_dir = _cache.get_path_for_link(req.link)
try:
ensure_dir(output_dir)
except OSError as e:
logger.warning("Building wheel for %s failed: %s",
req.name, e)
build_failure.append(req)
continue
else:
output_dir = self._wheel_dir
wheel_file = self._build_one(
req, output_dir,
python_tag=python_tag,
)
if wheel_file:
build_success.append(req)
if autobuilding:
# XXX: This is mildly duplicative with prepare_files,
# but not close enough to pull out to a single common
# method.
# The code below assumes temporary source dirs -
# prevent it doing bad things.
if req.source_dir and not os.path.exists(os.path.join(
req.source_dir, PIP_DELETE_MARKER_FILENAME)):
raise AssertionError(
"bad source dir - missing marker")
# Delete the source we built the wheel from
req.remove_temporary_source()
# set the build directory again - name is known from
# the work prepare_files did.
req.source_dir = req.build_location(
self.preparer.build_dir
)
# Update the link for this.
req.link = Link(path_to_url(wheel_file))
assert req.link.is_wheel
# extract the wheel into the dir
unpack_url(
req.link, req.source_dir, None, False,
session=session,
)
else:
build_failure.append(req)
# notify success/failure
if build_success:
logger.info(
'Successfully built %s',
' '.join([req.name for req in build_success]),
)
if build_failure:
logger.info(
'Failed to build %s',
' '.join([req.name for req in build_failure]),
)
# Return a list of requirements that failed to build
return build_failure | [
"def",
"build",
"(",
"self",
",",
"requirements",
",",
"# type: Iterable[InstallRequirement]",
"session",
",",
"# type: PipSession",
"autobuilding",
"=",
"False",
"# type: bool",
")",
":",
"# type: (...) -> List[InstallRequirement]",
"buildset",
"=",
"[",
"]",
"format_con... | https://github.com/okex/V3-Open-API-SDK/blob/c5abb0db7e2287718e0055e17e57672ce0ec7fd9/okex-python-sdk-api/venv/Lib/site-packages/pip-19.0.3-py3.8.egg/pip/_internal/wheel.py#L983-L1095 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/third_party/gsutil/gslib/storage_url.py | python | StorageUrlFromString | (url_str) | return _CloudUrl(url_str) | Static factory function for creating a StorageUrl from a string. | Static factory function for creating a StorageUrl from a string. | [
"Static",
"factory",
"function",
"for",
"creating",
"a",
"StorageUrl",
"from",
"a",
"string",
"."
] | def StorageUrlFromString(url_str):
"""Static factory function for creating a StorageUrl from a string."""
scheme = _GetSchemeFromUrlString(url_str)
if scheme not in ('file', 's3', 'gs'):
raise InvalidUrlError('Unrecognized scheme "%s"' % scheme)
if scheme == 'file':
path = _GetPathFromUrlString(url_str)
is_stream = (path == '-')
return _FileUrl(url_str, is_stream=is_stream)
return _CloudUrl(url_str) | [
"def",
"StorageUrlFromString",
"(",
"url_str",
")",
":",
"scheme",
"=",
"_GetSchemeFromUrlString",
"(",
"url_str",
")",
"if",
"scheme",
"not",
"in",
"(",
"'file'",
",",
"'s3'",
",",
"'gs'",
")",
":",
"raise",
"InvalidUrlError",
"(",
"'Unrecognized scheme \"%s\"'... | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/gslib/storage_url.py#L295-L306 | |
trilinos/Trilinos | 6168be6dd51e35e1cd681e9c4b24433e709df140 | packages/seacas/libraries/ioss/src/visualization/catalyst/phactori/PhactoriDriver.py | python | PhactoriPipeAndViewsState.ExportOperationsData | (self, datadescription) | go through all the operation blocks and call the ExportOperationData()\n method on each to allow each operation to export non-image data if\n they need to do so | go through all the operation blocks and call the ExportOperationData()\n method on each to allow each operation to export non-image data if\n they need to do so | [
"go",
"through",
"all",
"the",
"operation",
"blocks",
"and",
"call",
"the",
"ExportOperationData",
"()",
"\\",
"n",
"method",
"on",
"each",
"to",
"allow",
"each",
"operation",
"to",
"export",
"non",
"-",
"image",
"data",
"if",
"\\",
"n",
"they",
"need",
... | def ExportOperationsData(self, datadescription):
"go through all the operation blocks and call the ExportOperationData()\n method on each to allow each operation to export non-image data if\n they need to do so"
for operationName, operationInstance in self.mOperationBlocks.items():
operationInstance.ExportOperationData(datadescription) | [
"def",
"ExportOperationsData",
"(",
"self",
",",
"datadescription",
")",
":",
"for",
"operationName",
",",
"operationInstance",
"in",
"self",
".",
"mOperationBlocks",
".",
"items",
"(",
")",
":",
"operationInstance",
".",
"ExportOperationData",
"(",
"datadescription... | https://github.com/trilinos/Trilinos/blob/6168be6dd51e35e1cd681e9c4b24433e709df140/packages/seacas/libraries/ioss/src/visualization/catalyst/phactori/PhactoriDriver.py#L19616-L19619 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/setuptools/command/easy_install.py | python | samefile | (p1, p2) | return norm_p1 == norm_p2 | Determine if two paths reference the same file.
Augments os.path.samefile to work on Windows and
suppresses errors if the path doesn't exist. | Determine if two paths reference the same file. | [
"Determine",
"if",
"two",
"paths",
"reference",
"the",
"same",
"file",
"."
] | def samefile(p1, p2):
"""
Determine if two paths reference the same file.
Augments os.path.samefile to work on Windows and
suppresses errors if the path doesn't exist.
"""
both_exist = os.path.exists(p1) and os.path.exists(p2)
use_samefile = hasattr(os.path, 'samefile') and both_exist
if use_samefile:
return os.path.samefile(p1, p2)
norm_p1 = os.path.normpath(os.path.normcase(p1))
norm_p2 = os.path.normpath(os.path.normcase(p2))
return norm_p1 == norm_p2 | [
"def",
"samefile",
"(",
"p1",
",",
"p2",
")",
":",
"both_exist",
"=",
"os",
".",
"path",
".",
"exists",
"(",
"p1",
")",
"and",
"os",
".",
"path",
".",
"exists",
"(",
"p2",
")",
"use_samefile",
"=",
"hasattr",
"(",
"os",
".",
"path",
",",
"'samefi... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/setuptools/command/easy_install.py#L83-L96 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/_controls.py | python | TreeCtrl.SetItemTextColour | (*args, **kwargs) | return _controls_.TreeCtrl_SetItemTextColour(*args, **kwargs) | SetItemTextColour(self, TreeItemId item, Colour col) | SetItemTextColour(self, TreeItemId item, Colour col) | [
"SetItemTextColour",
"(",
"self",
"TreeItemId",
"item",
"Colour",
"col",
")"
] | def SetItemTextColour(*args, **kwargs):
"""SetItemTextColour(self, TreeItemId item, Colour col)"""
return _controls_.TreeCtrl_SetItemTextColour(*args, **kwargs) | [
"def",
"SetItemTextColour",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_controls_",
".",
"TreeCtrl_SetItemTextColour",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_controls.py#L5315-L5317 | |
benoitsteiner/tensorflow-opencl | cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5 | tensorflow/python/keras/_impl/keras/layers/merge.py | python | average | (inputs, **kwargs) | return Average(**kwargs)(inputs) | Functional interface to the `Average` layer.
Arguments:
inputs: A list of input tensors (at least 2).
**kwargs: Standard layer keyword arguments.
Returns:
A tensor, the average of the inputs. | Functional interface to the `Average` layer. | [
"Functional",
"interface",
"to",
"the",
"Average",
"layer",
"."
] | def average(inputs, **kwargs):
"""Functional interface to the `Average` layer.
Arguments:
inputs: A list of input tensors (at least 2).
**kwargs: Standard layer keyword arguments.
Returns:
A tensor, the average of the inputs.
"""
return Average(**kwargs)(inputs) | [
"def",
"average",
"(",
"inputs",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"Average",
"(",
"*",
"*",
"kwargs",
")",
"(",
"inputs",
")"
] | https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/keras/_impl/keras/layers/merge.py#L561-L571 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/lib-tk/Tkinter.py | python | CallWrapper.__call__ | (self, *args) | Apply first function SUBST to arguments, than FUNC. | Apply first function SUBST to arguments, than FUNC. | [
"Apply",
"first",
"function",
"SUBST",
"to",
"arguments",
"than",
"FUNC",
"."
] | def __call__(self, *args):
"""Apply first function SUBST to arguments, than FUNC."""
try:
if self.subst:
args = self.subst(*args)
return self.func(*args)
except SystemExit, msg:
raise SystemExit, msg
except:
self.widget._report_exception() | [
"def",
"__call__",
"(",
"self",
",",
"*",
"args",
")",
":",
"try",
":",
"if",
"self",
".",
"subst",
":",
"args",
"=",
"self",
".",
"subst",
"(",
"*",
"args",
")",
"return",
"self",
".",
"func",
"(",
"*",
"args",
")",
"except",
"SystemExit",
",",
... | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/lib-tk/Tkinter.py#L1465-L1474 | ||
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/distutils/dist.py | python | Distribution.print_command_list | (self, commands, header, max_length) | Print a subset of the list of all commands -- used by
'print_commands()'. | Print a subset of the list of all commands -- used by
'print_commands()'. | [
"Print",
"a",
"subset",
"of",
"the",
"list",
"of",
"all",
"commands",
"--",
"used",
"by",
"print_commands",
"()",
"."
] | def print_command_list(self, commands, header, max_length):
"""Print a subset of the list of all commands -- used by
'print_commands()'.
"""
print(header + ":")
for cmd in commands:
klass = self.cmdclass.get(cmd)
if not klass:
klass = self.get_command_class(cmd)
try:
description = klass.description
except AttributeError:
description = "(no description available)"
print(" %-*s %s" % (max_length, cmd, description)) | [
"def",
"print_command_list",
"(",
"self",
",",
"commands",
",",
"header",
",",
"max_length",
")",
":",
"print",
"(",
"header",
"+",
"\":\"",
")",
"for",
"cmd",
"in",
"commands",
":",
"klass",
"=",
"self",
".",
"cmdclass",
".",
"get",
"(",
"cmd",
")",
... | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/distutils/dist.py#L697-L712 | ||
qgis/QGIS | 15a77662d4bb712184f6aa60d0bd663010a76a75 | python/plugins/db_manager/db_plugins/postgis/connector.py | python | PostGisDBConnector.deleteTableTrigger | (self, trigger, table) | Deletes trigger on table | Deletes trigger on table | [
"Deletes",
"trigger",
"on",
"table"
] | def deleteTableTrigger(self, trigger, table):
"""Deletes trigger on table """
sql = u"DROP TRIGGER %s ON %s" % (self.quoteId(trigger), self.quoteId(table))
self._execute_and_commit(sql) | [
"def",
"deleteTableTrigger",
"(",
"self",
",",
"trigger",
",",
"table",
")",
":",
"sql",
"=",
"u\"DROP TRIGGER %s ON %s\"",
"%",
"(",
"self",
".",
"quoteId",
"(",
"trigger",
")",
",",
"self",
".",
"quoteId",
"(",
"table",
")",
")",
"self",
".",
"_execute... | https://github.com/qgis/QGIS/blob/15a77662d4bb712184f6aa60d0bd663010a76a75/python/plugins/db_manager/db_plugins/postgis/connector.py#L744-L747 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/requests/utils.py | python | parse_dict_header | (value) | return result | Parse lists of key, value pairs as described by RFC 2068 Section 2 and
convert them into a python dict:
>>> d = parse_dict_header('foo="is a fish", bar="as well"')
>>> type(d) is dict
True
>>> sorted(d.items())
[('bar', 'as well'), ('foo', 'is a fish')]
If there is no value for a key it will be `None`:
>>> parse_dict_header('key_without_value')
{'key_without_value': None}
To create a header from the :class:`dict` again, use the
:func:`dump_header` function.
:param value: a string with a dict header.
:return: :class:`dict`
:rtype: dict | Parse lists of key, value pairs as described by RFC 2068 Section 2 and
convert them into a python dict: | [
"Parse",
"lists",
"of",
"key",
"value",
"pairs",
"as",
"described",
"by",
"RFC",
"2068",
"Section",
"2",
"and",
"convert",
"them",
"into",
"a",
"python",
"dict",
":"
] | def parse_dict_header(value):
"""Parse lists of key, value pairs as described by RFC 2068 Section 2 and
convert them into a python dict:
>>> d = parse_dict_header('foo="is a fish", bar="as well"')
>>> type(d) is dict
True
>>> sorted(d.items())
[('bar', 'as well'), ('foo', 'is a fish')]
If there is no value for a key it will be `None`:
>>> parse_dict_header('key_without_value')
{'key_without_value': None}
To create a header from the :class:`dict` again, use the
:func:`dump_header` function.
:param value: a string with a dict header.
:return: :class:`dict`
:rtype: dict
"""
result = {}
for item in _parse_list_header(value):
if '=' not in item:
result[item] = None
continue
name, value = item.split('=', 1)
if value[:1] == value[-1:] == '"':
value = unquote_header_value(value[1:-1])
result[name] = value
return result | [
"def",
"parse_dict_header",
"(",
"value",
")",
":",
"result",
"=",
"{",
"}",
"for",
"item",
"in",
"_parse_list_header",
"(",
"value",
")",
":",
"if",
"'='",
"not",
"in",
"item",
":",
"result",
"[",
"item",
"]",
"=",
"None",
"continue",
"name",
",",
"... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/requests/utils.py#L349-L380 | |
PaddlePaddle/Paddle | 1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c | python/paddle/distributed/fleet/meta_parallel/sharding/sharding_stage2.py | python | ShardingStage2.__sync_buffers | (self) | Sync all the param buffers from all ranks (exp: batch norm statistics). | Sync all the param buffers from all ranks (exp: batch norm statistics). | [
"Sync",
"all",
"the",
"param",
"buffers",
"from",
"all",
"ranks",
"(",
"exp",
":",
"batch",
"norm",
"statistics",
")",
"."
] | def __sync_buffers(self):
"""
Sync all the param buffers from all ranks (exp: batch norm statistics).
"""
for buffer in self._layer.buffers(include_sublayers=True):
dist.broadcast(
buffer,
self._global_root_rank,
self._group,
use_calc_stream=True)
# Multi stream operation will be supported later
dist.wait(tensor=buffer, group=self._group, use_calc_stream=True) | [
"def",
"__sync_buffers",
"(",
"self",
")",
":",
"for",
"buffer",
"in",
"self",
".",
"_layer",
".",
"buffers",
"(",
"include_sublayers",
"=",
"True",
")",
":",
"dist",
".",
"broadcast",
"(",
"buffer",
",",
"self",
".",
"_global_root_rank",
",",
"self",
".... | https://github.com/PaddlePaddle/Paddle/blob/1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c/python/paddle/distributed/fleet/meta_parallel/sharding/sharding_stage2.py#L268-L280 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/_misc.py | python | Log.RemoveTraceMask | (*args, **kwargs) | return _misc_.Log_RemoveTraceMask(*args, **kwargs) | RemoveTraceMask(String str) | RemoveTraceMask(String str) | [
"RemoveTraceMask",
"(",
"String",
"str",
")"
] | def RemoveTraceMask(*args, **kwargs):
"""RemoveTraceMask(String str)"""
return _misc_.Log_RemoveTraceMask(*args, **kwargs) | [
"def",
"RemoveTraceMask",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_misc_",
".",
"Log_RemoveTraceMask",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_misc.py#L1565-L1567 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pkg_resources/_vendor/packaging/specifiers.py | python | BaseSpecifier.__ne__ | (self, other) | Returns a boolean representing whether or not the two Specifier like
objects are not equal. | Returns a boolean representing whether or not the two Specifier like
objects are not equal. | [
"Returns",
"a",
"boolean",
"representing",
"whether",
"or",
"not",
"the",
"two",
"Specifier",
"like",
"objects",
"are",
"not",
"equal",
"."
] | def __ne__(self, other):
"""
Returns a boolean representing whether or not the two Specifier like
objects are not equal.
""" | [
"def",
"__ne__",
"(",
"self",
",",
"other",
")",
":"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pkg_resources/_vendor/packaging/specifiers.py#L44-L48 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/lib/agw/floatspin.py | python | FixedPoint.get_precision | (self) | return self.p | Return the precision of this :class:`FixedPoint`.
:note: The precision is the number of decimal digits carried after
the decimal point, and is an int >= 0. | Return the precision of this :class:`FixedPoint`. | [
"Return",
"the",
"precision",
"of",
"this",
":",
"class",
":",
"FixedPoint",
"."
] | def get_precision(self):
"""
Return the precision of this :class:`FixedPoint`.
:note: The precision is the number of decimal digits carried after
the decimal point, and is an int >= 0.
"""
return self.p | [
"def",
"get_precision",
"(",
"self",
")",
":",
"return",
"self",
".",
"p"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/floatspin.py#L1406-L1414 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/logging/__init__.py | python | Filterer.addFilter | (self, filter) | Add the specified filter to this handler. | Add the specified filter to this handler. | [
"Add",
"the",
"specified",
"filter",
"to",
"this",
"handler",
"."
] | def addFilter(self, filter):
"""
Add the specified filter to this handler.
"""
if not (filter in self.filters):
self.filters.append(filter) | [
"def",
"addFilter",
"(",
"self",
",",
"filter",
")",
":",
"if",
"not",
"(",
"filter",
"in",
"self",
".",
"filters",
")",
":",
"self",
".",
"filters",
".",
"append",
"(",
"filter",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/logging/__init__.py#L584-L589 | ||
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/ReflectometryILLAutoProcess.py | python | ReflectometryILLAutoProcess.summary | (self) | return "Performs reduction of ILL reflectometry data, instruments D17 and FIGARO." | Return a summary of the algorithm. | Return a summary of the algorithm. | [
"Return",
"a",
"summary",
"of",
"the",
"algorithm",
"."
] | def summary(self):
"""Return a summary of the algorithm."""
return "Performs reduction of ILL reflectometry data, instruments D17 and FIGARO." | [
"def",
"summary",
"(",
"self",
")",
":",
"return",
"\"Performs reduction of ILL reflectometry data, instruments D17 and FIGARO.\""
] | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/ReflectometryILLAutoProcess.py#L121-L123 | |
apple/swift-lldb | d74be846ef3e62de946df343e8c234bde93a8912 | utils/vim-lldb/python-vim-lldb/lldb_controller.py | python | LLDBController.getCommandOutput | (self, command, command_args="") | return (result.Succeeded(), result.GetOutput()
if result.Succeeded() else result.GetError()) | runs cmd in the command interpreter andreturns (status, result) | runs cmd in the command interpreter andreturns (status, result) | [
"runs",
"cmd",
"in",
"the",
"command",
"interpreter",
"andreturns",
"(",
"status",
"result",
")"
] | def getCommandOutput(self, command, command_args=""):
""" runs cmd in the command interpreter andreturns (status, result) """
result = lldb.SBCommandReturnObject()
cmd = "%s %s" % (command, command_args)
self.commandInterpreter.HandleCommand(cmd, result)
return (result.Succeeded(), result.GetOutput()
if result.Succeeded() else result.GetError()) | [
"def",
"getCommandOutput",
"(",
"self",
",",
"command",
",",
"command_args",
"=",
"\"\"",
")",
":",
"result",
"=",
"lldb",
".",
"SBCommandReturnObject",
"(",
")",
"cmd",
"=",
"\"%s %s\"",
"%",
"(",
"command",
",",
"command_args",
")",
"self",
".",
"command... | https://github.com/apple/swift-lldb/blob/d74be846ef3e62de946df343e8c234bde93a8912/utils/vim-lldb/python-vim-lldb/lldb_controller.py#L332-L338 | |
openweave/openweave-core | 11ceb6b7efd39fe05de7f79229247a5774d56766 | src/device-manager/python/weave-device-mgr.py | python | DeviceMgrCmd.do_testnetwork | (self, line) | test-network <network-id>
Perform a network connectivity test for a particular provisioned network. | test-network <network-id> | [
"test",
"-",
"network",
"<network",
"-",
"id",
">"
] | def do_testnetwork(self, line):
"""
test-network <network-id>
Perform a network connectivity test for a particular provisioned network.
"""
args = shlex.split(line)
if (len(args) == 0):
print("Usage:")
self.do_help('test-network')
return
if (len(args) < 1):
print("Please specify a network id")
return
if (len(args) > 1):
print("Unexpected argument: " + args[1])
return
networkId = self.parseNetworkId(args[0])
if (networkId == None):
return
self.lastNetworkId = networkId
try:
self.devMgr.TestNetworkConnectivity(networkId)
except WeaveStack.WeaveStackException as ex:
print(str(ex))
return
print("Network test complete") | [
"def",
"do_testnetwork",
"(",
"self",
",",
"line",
")",
":",
"args",
"=",
"shlex",
".",
"split",
"(",
"line",
")",
"if",
"(",
"len",
"(",
"args",
")",
"==",
"0",
")",
":",
"print",
"(",
"\"Usage:\"",
")",
"self",
".",
"do_help",
"(",
"'test-network... | https://github.com/openweave/openweave-core/blob/11ceb6b7efd39fe05de7f79229247a5774d56766/src/device-manager/python/weave-device-mgr.py#L1628-L1662 | ||
gnuradio/gnuradio | 09c3c4fa4bfb1a02caac74cb5334dfe065391e3b | grc/core/generator/top_block.py | python | TopBlockGenerator._build_python_code_from_template | (self) | return output | Convert the flow graph to python code.
Returns:
a string of python code | Convert the flow graph to python code. | [
"Convert",
"the",
"flow",
"graph",
"to",
"python",
"code",
"."
] | def _build_python_code_from_template(self):
"""
Convert the flow graph to python code.
Returns:
a string of python code
"""
output = []
fg = self._flow_graph
platform = fg.parent
title = fg.get_option('title') or fg.get_option(
'id').replace('_', ' ').title()
variables = fg.get_variables()
parameters = fg.get_parameters()
monitors = fg.get_monitors()
for block in fg.iter_enabled_blocks():
if block.key == 'epy_block':
src = block.params['_source_code'].get_value()
elif block.key == 'epy_module':
src = block.params['source_code'].get_value()
else:
continue
file_path = os.path.join(
self.output_dir, block.module_name + ".py")
output.append((file_path, src))
self.namespace = {
'flow_graph': fg,
'variables': variables,
'parameters': parameters,
'monitors': monitors,
'generate_options': self._generate_options,
'version': platform.config.version,
'catch_exceptions': fg.get_option('catch_exceptions')
}
flow_graph_code = python_template.render(
title=title,
imports=self._imports(),
blocks=self._blocks(),
callbacks=self._callbacks(),
connections=self._connections(),
**self.namespace
)
# strip trailing white-space
flow_graph_code = "\n".join(line.rstrip()
for line in flow_graph_code.split("\n"))
output.append((self.file_path, flow_graph_code))
return output | [
"def",
"_build_python_code_from_template",
"(",
"self",
")",
":",
"output",
"=",
"[",
"]",
"fg",
"=",
"self",
".",
"_flow_graph",
"platform",
"=",
"fg",
".",
"parent",
"title",
"=",
"fg",
".",
"get_option",
"(",
"'title'",
")",
"or",
"fg",
".",
"get_opti... | https://github.com/gnuradio/gnuradio/blob/09c3c4fa4bfb1a02caac74cb5334dfe065391e3b/grc/core/generator/top_block.py#L92-L143 | |
krishauser/Klampt | 972cc83ea5befac3f653c1ba20f80155768ad519 | Python/klampt/robotsim.py | python | RobotModelLink.getPointAcceleration | (self, plocal: Point, ddq: Vector) | return _robotsim.RobotModelLink_getPointAcceleration(self, plocal, ddq) | r"""
Computes the acceleration of the point given the robot's current joint
configuration and velocities, and the joint accelerations ddq.
Args:
plocal (:obj:`list of 3 floats`)
ddq (:obj:`list of floats`)
Returns:
list of 3 floats: the acceleration of the point, in
world coordinates. | r"""
Computes the acceleration of the point given the robot's current joint
configuration and velocities, and the joint accelerations ddq. | [
"r",
"Computes",
"the",
"acceleration",
"of",
"the",
"point",
"given",
"the",
"robot",
"s",
"current",
"joint",
"configuration",
"and",
"velocities",
"and",
"the",
"joint",
"accelerations",
"ddq",
"."
] | def getPointAcceleration(self, plocal: Point, ddq: Vector) ->None:
r"""
Computes the acceleration of the point given the robot's current joint
configuration and velocities, and the joint accelerations ddq.
Args:
plocal (:obj:`list of 3 floats`)
ddq (:obj:`list of floats`)
Returns:
list of 3 floats: the acceleration of the point, in
world coordinates.
"""
return _robotsim.RobotModelLink_getPointAcceleration(self, plocal, ddq) | [
"def",
"getPointAcceleration",
"(",
"self",
",",
"plocal",
":",
"Point",
",",
"ddq",
":",
"Vector",
")",
"->",
"None",
":",
"return",
"_robotsim",
".",
"RobotModelLink_getPointAcceleration",
"(",
"self",
",",
"plocal",
",",
"ddq",
")"
] | https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/klampt/robotsim.py#L4283-L4298 | |
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | qt/python/mantidqtinterfaces/mantidqtinterfaces/Muon/GUI/Common/results_tab_widget/results_tab_view.py | python | _create_empty_list_selector | (parent, col_zero_width) | return presenter | Create a ListSelector around the given parent
and return the presenter
:param parent: The parent widget for the selector
:param col_zero_width: The width of the first column
:return: A new presenter that controls the widget | Create a ListSelector around the given parent
and return the presenter | [
"Create",
"a",
"ListSelector",
"around",
"the",
"given",
"parent",
"and",
"return",
"the",
"presenter"
] | def _create_empty_list_selector(parent, col_zero_width):
"""
Create a ListSelector around the given parent
and return the presenter
:param parent: The parent widget for the selector
:param col_zero_width: The width of the first column
:return: A new presenter that controls the widget
"""
presenter = ListSelectorPresenter(ListSelectorView(parent), {})
return presenter | [
"def",
"_create_empty_list_selector",
"(",
"parent",
",",
"col_zero_width",
")",
":",
"presenter",
"=",
"ListSelectorPresenter",
"(",
"ListSelectorView",
"(",
"parent",
")",
",",
"{",
"}",
")",
"return",
"presenter"
] | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqtinterfaces/mantidqtinterfaces/Muon/GUI/Common/results_tab_widget/results_tab_view.py#L163-L173 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/richtext.py | python | RichTextFileHandler.LoadStream | (*args, **kwargs) | return _richtext.RichTextFileHandler_LoadStream(*args, **kwargs) | LoadStream(self, RichTextBuffer buffer, InputStream stream) -> bool | LoadStream(self, RichTextBuffer buffer, InputStream stream) -> bool | [
"LoadStream",
"(",
"self",
"RichTextBuffer",
"buffer",
"InputStream",
"stream",
")",
"-",
">",
"bool"
] | def LoadStream(*args, **kwargs):
"""LoadStream(self, RichTextBuffer buffer, InputStream stream) -> bool"""
return _richtext.RichTextFileHandler_LoadStream(*args, **kwargs) | [
"def",
"LoadStream",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_richtext",
".",
"RichTextFileHandler_LoadStream",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/richtext.py#L2752-L2754 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/setuptools/_vendor/pyparsing.py | python | ParseExpression.leaveWhitespace | ( self ) | return self | Extends C{leaveWhitespace} defined in base class, and also invokes C{leaveWhitespace} on
all contained expressions. | Extends C{leaveWhitespace} defined in base class, and also invokes C{leaveWhitespace} on
all contained expressions. | [
"Extends",
"C",
"{",
"leaveWhitespace",
"}",
"defined",
"in",
"base",
"class",
"and",
"also",
"invokes",
"C",
"{",
"leaveWhitespace",
"}",
"on",
"all",
"contained",
"expressions",
"."
] | def leaveWhitespace( self ):
"""Extends C{leaveWhitespace} defined in base class, and also invokes C{leaveWhitespace} on
all contained expressions."""
self.skipWhitespace = False
self.exprs = [ e.copy() for e in self.exprs ]
for e in self.exprs:
e.leaveWhitespace()
return self | [
"def",
"leaveWhitespace",
"(",
"self",
")",
":",
"self",
".",
"skipWhitespace",
"=",
"False",
"self",
".",
"exprs",
"=",
"[",
"e",
".",
"copy",
"(",
")",
"for",
"e",
"in",
"self",
".",
"exprs",
"]",
"for",
"e",
"in",
"self",
".",
"exprs",
":",
"e... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/setuptools/_vendor/pyparsing.py#L3288-L3295 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/pandas/py3/pandas/core/arrays/period.py | python | PeriodArray._add_timedeltalike_scalar | (self, other) | return super()._add_timedeltalike_scalar(other) | Parameters
----------
other : timedelta, Tick, np.timedelta64
Returns
-------
PeriodArray | Parameters
----------
other : timedelta, Tick, np.timedelta64 | [
"Parameters",
"----------",
"other",
":",
"timedelta",
"Tick",
"np",
".",
"timedelta64"
] | def _add_timedeltalike_scalar(self, other):
"""
Parameters
----------
other : timedelta, Tick, np.timedelta64
Returns
-------
PeriodArray
"""
if not isinstance(self.freq, Tick):
# We cannot add timedelta-like to non-tick PeriodArray
raise raise_on_incompatible(self, other)
if notna(other):
# special handling for np.timedelta64("NaT"), avoid calling
# _check_timedeltalike_freq_compat as that would raise TypeError
other = self._check_timedeltalike_freq_compat(other)
# Note: when calling parent class's _add_timedeltalike_scalar,
# it will call delta_to_nanoseconds(delta). Because delta here
# is an integer, delta_to_nanoseconds will return it unchanged.
return super()._add_timedeltalike_scalar(other) | [
"def",
"_add_timedeltalike_scalar",
"(",
"self",
",",
"other",
")",
":",
"if",
"not",
"isinstance",
"(",
"self",
".",
"freq",
",",
"Tick",
")",
":",
"# We cannot add timedelta-like to non-tick PeriodArray",
"raise",
"raise_on_incompatible",
"(",
"self",
",",
"other"... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py3/pandas/core/arrays/period.py#L744-L766 | |
berndpfrommer/tagslam | 406562abfb27ec0f409d7bd27dd6c45dabd9965d | src/align_trajectories.py | python | align_umeyama | (model, data) | return s, R, t | Implementation of the paper: S. Umeyama, Least-Squares Estimation
of Transformation Parameters Between Two Point Patterns,
IEEE Trans. Pattern Anal. Mach. Intell., vol. 13, no. 4, 1991.
model = s * R * data + t
Input:
model -- first trajectory (nx3), numpy array type
data -- second trajectory (nx3), numpy array type
Output:
s -- scale factor (scalar)
R -- rotation matrix (3x3)
t -- translation vector (3x1)
t_error -- translational error per point (1xn) | Implementation of the paper: S. Umeyama, Least-Squares Estimation
of Transformation Parameters Between Two Point Patterns,
IEEE Trans. Pattern Anal. Mach. Intell., vol. 13, no. 4, 1991.
model = s * R * data + t
Input:
model -- first trajectory (nx3), numpy array type
data -- second trajectory (nx3), numpy array type
Output:
s -- scale factor (scalar)
R -- rotation matrix (3x3)
t -- translation vector (3x1)
t_error -- translational error per point (1xn) | [
"Implementation",
"of",
"the",
"paper",
":",
"S",
".",
"Umeyama",
"Least",
"-",
"Squares",
"Estimation",
"of",
"Transformation",
"Parameters",
"Between",
"Two",
"Point",
"Patterns",
"IEEE",
"Trans",
".",
"Pattern",
"Anal",
".",
"Mach",
".",
"Intell",
".",
"v... | def align_umeyama(model, data):
"""Implementation of the paper: S. Umeyama, Least-Squares Estimation
of Transformation Parameters Between Two Point Patterns,
IEEE Trans. Pattern Anal. Mach. Intell., vol. 13, no. 4, 1991.
model = s * R * data + t
Input:
model -- first trajectory (nx3), numpy array type
data -- second trajectory (nx3), numpy array type
Output:
s -- scale factor (scalar)
R -- rotation matrix (3x3)
t -- translation vector (3x1)
t_error -- translational error per point (1xn)
"""
# originally from https://github.com/uzh-rpg/rpg_trajectory_evaluation/
# substract mean
mu_M = model.mean(0)
mu_D = data.mean(0)
model_zerocentered = model - mu_M
data_zerocentered = data - mu_D
n = np.shape(model)[0]
# correlation
C = 1.0/n*np.dot(model_zerocentered.transpose(), data_zerocentered)
sigma2 = 1.0/n*np.multiply(data_zerocentered, data_zerocentered).sum()
U_svd, D_svd, V_svd = np.linalg.linalg.svd(C)
D_svd = np.diag(D_svd)
V_svd = np.transpose(V_svd)
S = np.eye(3)
if(np.linalg.det(U_svd)*np.linalg.det(V_svd) < 0):
S[2, 2] = -1
R = np.dot(U_svd, np.dot(S, np.transpose(V_svd)))
s = 1
t = mu_M-s*np.dot(R, mu_D)
return s, R, t | [
"def",
"align_umeyama",
"(",
"model",
",",
"data",
")",
":",
"# originally from https://github.com/uzh-rpg/rpg_trajectory_evaluation/",
"# substract mean",
"mu_M",
"=",
"model",
".",
"mean",
"(",
"0",
")",
"mu_D",
"=",
"data",
".",
"mean",
"(",
"0",
")",
"model_ze... | https://github.com/berndpfrommer/tagslam/blob/406562abfb27ec0f409d7bd27dd6c45dabd9965d/src/align_trajectories.py#L22-L59 | |
ChromiumWebApps/chromium | c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7 | third_party/google_appengine_cloudstorage/cloudstorage/cloudstorage_api.py | python | _Bucket._should_get_another_batch | (self, content) | return True | Whether to issue another GET bucket call.
Args:
content: response XML.
Returns:
True if should, also update self._options for the next request.
False otherwise. | Whether to issue another GET bucket call. | [
"Whether",
"to",
"issue",
"another",
"GET",
"bucket",
"call",
"."
] | def _should_get_another_batch(self, content):
"""Whether to issue another GET bucket call.
Args:
content: response XML.
Returns:
True if should, also update self._options for the next request.
False otherwise.
"""
if ('max-keys' in self._options and
self._options['max-keys'] <= common._MAX_GET_BUCKET_RESULT):
return False
elements = self._find_elements(
content, set([common._T_IS_TRUNCATED,
common._T_NEXT_MARKER]))
if elements.get(common._T_IS_TRUNCATED, 'false').lower() != 'true':
return False
next_marker = elements.get(common._T_NEXT_MARKER)
if next_marker is None:
self._options.pop('marker', None)
return False
self._options['marker'] = next_marker
return True | [
"def",
"_should_get_another_batch",
"(",
"self",
",",
"content",
")",
":",
"if",
"(",
"'max-keys'",
"in",
"self",
".",
"_options",
"and",
"self",
".",
"_options",
"[",
"'max-keys'",
"]",
"<=",
"common",
".",
"_MAX_GET_BUCKET_RESULT",
")",
":",
"return",
"Fal... | https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/third_party/google_appengine_cloudstorage/cloudstorage/cloudstorage_api.py#L399-L424 | |
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | tools/Pylint/run_pylint.py | python | Results.update | (self, other) | Update this object with results from another | Update this object with results from another | [
"Update",
"this",
"object",
"with",
"results",
"from",
"another"
] | def update(self, other):
"""
Update this object with results from another
"""
self.totalchecks += other.totalchecks
self.failures.extend(other.failures) | [
"def",
"update",
"(",
"self",
",",
"other",
")",
":",
"self",
".",
"totalchecks",
"+=",
"other",
".",
"totalchecks",
"self",
".",
"failures",
".",
"extend",
"(",
"other",
".",
"failures",
")"
] | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/tools/Pylint/run_pylint.py#L103-L108 | ||
microsoft/EdgeML | ef9f8a77f096acbdeb941014791f8eda1c1bc35b | tf/edgeml_tf/trainer/protoNNTrainer.py | python | ProtoNNTrainer.train | (self, batchSize, totalEpochs, sess,
x_train, x_val, y_train, y_val, noInit=False,
redirFile=None, printStep=10, valStep=3) | Performs dense training of ProtoNN followed by iterative hard
thresholding to enforce sparsity constraints.
batchSize: Batch size per update
totalEpochs: The number of epochs to run training for. One epoch is
defined as one pass over the entire training data.
sess: The Tensorflow session to use for running various graph
operators.
x_train, x_val, y_train, y_val: The numpy array containing train and
validation data. x data is assumed to in of shape [-1,
featureDimension] while y should have shape [-1, numberLabels].
noInit: By default, all the tensors of the computation graph are
initialized at the start of the training session. Set noInit=False to
disable this behaviour.
printStep: Number of batches between echoing of loss and train accuracy.
valStep: Number of epochs between evolutions on validation set. | Performs dense training of ProtoNN followed by iterative hard
thresholding to enforce sparsity constraints. | [
"Performs",
"dense",
"training",
"of",
"ProtoNN",
"followed",
"by",
"iterative",
"hard",
"thresholding",
"to",
"enforce",
"sparsity",
"constraints",
"."
] | def train(self, batchSize, totalEpochs, sess,
x_train, x_val, y_train, y_val, noInit=False,
redirFile=None, printStep=10, valStep=3):
'''
Performs dense training of ProtoNN followed by iterative hard
thresholding to enforce sparsity constraints.
batchSize: Batch size per update
totalEpochs: The number of epochs to run training for. One epoch is
defined as one pass over the entire training data.
sess: The Tensorflow session to use for running various graph
operators.
x_train, x_val, y_train, y_val: The numpy array containing train and
validation data. x data is assumed to in of shape [-1,
featureDimension] while y should have shape [-1, numberLabels].
noInit: By default, all the tensors of the computation graph are
initialized at the start of the training session. Set noInit=False to
disable this behaviour.
printStep: Number of batches between echoing of loss and train accuracy.
valStep: Number of epochs between evolutions on validation set.
'''
d, d_cap, m, L, gamma = self.protoNNObj.getHyperParams()
assert batchSize >= 1, 'Batch size should be positive integer'
assert totalEpochs >= 1, 'Total epochs should be positive integer'
assert x_train.ndim == 2, 'Expected training data to be of rank 2'
assert x_train.shape[1] == d, 'Expected x_train to be [-1, %d]' % d
assert x_val.ndim == 2, 'Expected validation data to be of rank 2'
assert x_val.shape[1] == d, 'Expected x_val to be [-1, %d]' % d
assert y_train.ndim == 2, 'Expected training labels to be of rank 2'
assert y_train.shape[1] == L, 'Expected y_train to be [-1, %d]' % L
assert y_val.ndim == 2, 'Expected validation labels to be of rank 2'
assert y_val.shape[1] == L, 'Expected y_val to be [-1, %d]' % L
# Numpy will throw asserts for arrays
if sess is None:
raise ValueError('sess must be valid Tensorflow session.')
trainNumBatches = int(np.ceil(len(x_train) / batchSize))
valNumBatches = int(np.ceil(len(x_val) / batchSize))
x_train_batches = np.array_split(x_train, trainNumBatches)
y_train_batches = np.array_split(y_train, trainNumBatches)
x_val_batches = np.array_split(x_val, valNumBatches)
y_val_batches = np.array_split(y_val, valNumBatches)
if not noInit:
sess.run(tf.global_variables_initializer())
X, Y = self.X, self.Y
W, B, Z, _ = self.protoNNObj.getModelMatrices()
for epoch in range(totalEpochs):
for i in range(len(x_train_batches)):
batch_x = x_train_batches[i]
batch_y = y_train_batches[i]
feed_dict = {
X: batch_x,
Y: batch_y
}
sess.run(self.trainStep, feed_dict=feed_dict)
if i % printStep == 0:
loss, acc = sess.run([self.loss, self.accuracy],
feed_dict=feed_dict)
msg = "Epoch: %3d Batch: %3d" % (epoch, i)
msg += " Loss: %3.5f Accuracy: %2.5f" % (loss, acc)
print(msg, file=redirFile)
# Perform Hard thresholding
if self.sparseTraining:
W_, B_, Z_ = sess.run([W, B, Z])
fd_thrsd = {
self.W_th: utils.hardThreshold(W_, self.__sW),
self.B_th: utils.hardThreshold(B_, self.__sB),
self.Z_th: utils.hardThreshold(Z_, self.__sZ)
}
sess.run(self.__hthOp, feed_dict=fd_thrsd)
if (epoch + 1) % valStep == 0:
acc = 0.0
loss = 0.0
for j in range(len(x_val_batches)):
batch_x = x_val_batches[j]
batch_y = y_val_batches[j]
feed_dict = {
X: batch_x,
Y: batch_y
}
acc_, loss_ = sess.run([self.accuracy, self.loss],
feed_dict=feed_dict)
acc += acc_
loss += loss_
acc /= len(y_val_batches)
loss /= len(y_val_batches)
print("Test Loss: %2.5f Accuracy: %2.5f" % (loss, acc)) | [
"def",
"train",
"(",
"self",
",",
"batchSize",
",",
"totalEpochs",
",",
"sess",
",",
"x_train",
",",
"x_val",
",",
"y_train",
",",
"y_val",
",",
"noInit",
"=",
"False",
",",
"redirFile",
"=",
"None",
",",
"printStep",
"=",
"10",
",",
"valStep",
"=",
... | https://github.com/microsoft/EdgeML/blob/ef9f8a77f096acbdeb941014791f8eda1c1bc35b/tf/edgeml_tf/trainer/protoNNTrainer.py#L129-L218 | ||
idaholab/moose | 9eeebc65e098b4c30f8205fb41591fd5b61eb6ff | python/peacock/Execute/ExecuteOptionsPlugin.py | python | ExecuteOptionsPlugin._workingDirChanged | (self) | Slot called when working directory changed. | Slot called when working directory changed. | [
"Slot",
"called",
"when",
"working",
"directory",
"changed",
"."
] | def _workingDirChanged(self):
"""
Slot called when working directory changed.
"""
working = str(self.working_line.text())
self.setWorkingDir(working) | [
"def",
"_workingDirChanged",
"(",
"self",
")",
":",
"working",
"=",
"str",
"(",
"self",
".",
"working_line",
".",
"text",
"(",
")",
")",
"self",
".",
"setWorkingDir",
"(",
"working",
")"
] | https://github.com/idaholab/moose/blob/9eeebc65e098b4c30f8205fb41591fd5b61eb6ff/python/peacock/Execute/ExecuteOptionsPlugin.py#L210-L215 | ||
thalium/icebox | 99d147d5b9269222225443ce171b4fd46d8985d4 | third_party/virtualbox/src/libs/libxml2-2.9.4/python/libxml2.py | python | xpathParserContext.xpathCeilingFunction | (self, nargs) | Implement the ceiling() XPath function number
ceiling(number) The ceiling function returns the smallest
(closest to negative infinity) number that is not less than
the argument and that is an integer. | Implement the ceiling() XPath function number
ceiling(number) The ceiling function returns the smallest
(closest to negative infinity) number that is not less than
the argument and that is an integer. | [
"Implement",
"the",
"ceiling",
"()",
"XPath",
"function",
"number",
"ceiling",
"(",
"number",
")",
"The",
"ceiling",
"function",
"returns",
"the",
"smallest",
"(",
"closest",
"to",
"negative",
"infinity",
")",
"number",
"that",
"is",
"not",
"less",
"than",
"... | def xpathCeilingFunction(self, nargs):
"""Implement the ceiling() XPath function number
ceiling(number) The ceiling function returns the smallest
(closest to negative infinity) number that is not less than
the argument and that is an integer. """
libxml2mod.xmlXPathCeilingFunction(self._o, nargs) | [
"def",
"xpathCeilingFunction",
"(",
"self",
",",
"nargs",
")",
":",
"libxml2mod",
".",
"xmlXPathCeilingFunction",
"(",
"self",
".",
"_o",
",",
"nargs",
")"
] | https://github.com/thalium/icebox/blob/99d147d5b9269222225443ce171b4fd46d8985d4/third_party/virtualbox/src/libs/libxml2-2.9.4/python/libxml2.py#L7451-L7456 | ||
kevinlin311tw/Caffe-DeepBinaryCode | 9eaa7662be47d49f475ecbeea2bd51be105270d2 | scripts/cpp_lint.py | python | CheckSpacing | (filename, clean_lines, linenum, nesting_state, error) | Checks for the correctness of various spacing issues in the code.
Things we check for: spaces around operators, spaces after
if/for/while/switch, no spaces around parens in function calls, two
spaces between code and comment, don't start a block with a blank
line, don't end a function with a blank line, don't add a blank line
after public/protected/private, don't have too many blank lines in a row.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
nesting_state: A _NestingState instance which maintains information about
the current stack of nested blocks being parsed.
error: The function to call with any errors found. | Checks for the correctness of various spacing issues in the code. | [
"Checks",
"for",
"the",
"correctness",
"of",
"various",
"spacing",
"issues",
"in",
"the",
"code",
"."
] | def CheckSpacing(filename, clean_lines, linenum, nesting_state, error):
"""Checks for the correctness of various spacing issues in the code.
Things we check for: spaces around operators, spaces after
if/for/while/switch, no spaces around parens in function calls, two
spaces between code and comment, don't start a block with a blank
line, don't end a function with a blank line, don't add a blank line
after public/protected/private, don't have too many blank lines in a row.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
nesting_state: A _NestingState instance which maintains information about
the current stack of nested blocks being parsed.
error: The function to call with any errors found.
"""
# Don't use "elided" lines here, otherwise we can't check commented lines.
# Don't want to use "raw" either, because we don't want to check inside C++11
# raw strings,
raw = clean_lines.lines_without_raw_strings
line = raw[linenum]
# Before nixing comments, check if the line is blank for no good
# reason. This includes the first line after a block is opened, and
# blank lines at the end of a function (ie, right before a line like '}'
#
# Skip all the blank line checks if we are immediately inside a
# namespace body. In other words, don't issue blank line warnings
# for this block:
# namespace {
#
# }
#
# A warning about missing end of namespace comments will be issued instead.
if IsBlankLine(line) and not nesting_state.InNamespaceBody():
elided = clean_lines.elided
prev_line = elided[linenum - 1]
prevbrace = prev_line.rfind('{')
# TODO(unknown): Don't complain if line before blank line, and line after,
# both start with alnums and are indented the same amount.
# This ignores whitespace at the start of a namespace block
# because those are not usually indented.
if prevbrace != -1 and prev_line[prevbrace:].find('}') == -1:
# OK, we have a blank line at the start of a code block. Before we
# complain, we check if it is an exception to the rule: The previous
# non-empty line has the parameters of a function header that are indented
# 4 spaces (because they did not fit in a 80 column line when placed on
# the same line as the function name). We also check for the case where
# the previous line is indented 6 spaces, which may happen when the
# initializers of a constructor do not fit into a 80 column line.
exception = False
if Match(r' {6}\w', prev_line): # Initializer list?
# We are looking for the opening column of initializer list, which
# should be indented 4 spaces to cause 6 space indentation afterwards.
search_position = linenum-2
while (search_position >= 0
and Match(r' {6}\w', elided[search_position])):
search_position -= 1
exception = (search_position >= 0
and elided[search_position][:5] == ' :')
else:
# Search for the function arguments or an initializer list. We use a
# simple heuristic here: If the line is indented 4 spaces; and we have a
# closing paren, without the opening paren, followed by an opening brace
# or colon (for initializer lists) we assume that it is the last line of
# a function header. If we have a colon indented 4 spaces, it is an
# initializer list.
exception = (Match(r' {4}\w[^\(]*\)\s*(const\s*)?(\{\s*$|:)',
prev_line)
or Match(r' {4}:', prev_line))
if not exception:
error(filename, linenum, 'whitespace/blank_line', 2,
'Redundant blank line at the start of a code block '
'should be deleted.')
# Ignore blank lines at the end of a block in a long if-else
# chain, like this:
# if (condition1) {
# // Something followed by a blank line
#
# } else if (condition2) {
# // Something else
# }
if linenum + 1 < clean_lines.NumLines():
next_line = raw[linenum + 1]
if (next_line
and Match(r'\s*}', next_line)
and next_line.find('} else ') == -1):
error(filename, linenum, 'whitespace/blank_line', 3,
'Redundant blank line at the end of a code block '
'should be deleted.')
matched = Match(r'\s*(public|protected|private):', prev_line)
if matched:
error(filename, linenum, 'whitespace/blank_line', 3,
'Do not leave a blank line after "%s:"' % matched.group(1))
# Next, we complain if there's a comment too near the text
commentpos = line.find('//')
if commentpos != -1:
# Check if the // may be in quotes. If so, ignore it
# Comparisons made explicit for clarity -- pylint: disable=g-explicit-bool-comparison
if (line.count('"', 0, commentpos) -
line.count('\\"', 0, commentpos)) % 2 == 0: # not in quotes
# Allow one space for new scopes, two spaces otherwise:
if (not Match(r'^\s*{ //', line) and
((commentpos >= 1 and
line[commentpos-1] not in string.whitespace) or
(commentpos >= 2 and
line[commentpos-2] not in string.whitespace))):
error(filename, linenum, 'whitespace/comments', 2,
'At least two spaces is best between code and comments')
# There should always be a space between the // and the comment
commentend = commentpos + 2
if commentend < len(line) and not line[commentend] == ' ':
# but some lines are exceptions -- e.g. if they're big
# comment delimiters like:
# //----------------------------------------------------------
# or are an empty C++ style Doxygen comment, like:
# ///
# or C++ style Doxygen comments placed after the variable:
# ///< Header comment
# //!< Header comment
# or they begin with multiple slashes followed by a space:
# //////// Header comment
match = (Search(r'[=/-]{4,}\s*$', line[commentend:]) or
Search(r'^/$', line[commentend:]) or
Search(r'^!< ', line[commentend:]) or
Search(r'^/< ', line[commentend:]) or
Search(r'^/+ ', line[commentend:]))
if not match:
error(filename, linenum, 'whitespace/comments', 4,
'Should have a space between // and comment')
CheckComment(line[commentpos:], filename, linenum, error)
line = clean_lines.elided[linenum] # get rid of comments and strings
# Don't try to do spacing checks for operator methods
line = re.sub(r'operator(==|!=|<|<<|<=|>=|>>|>)\(', 'operator\(', line)
# We allow no-spaces around = within an if: "if ( (a=Foo()) == 0 )".
# Otherwise not. Note we only check for non-spaces on *both* sides;
# sometimes people put non-spaces on one side when aligning ='s among
# many lines (not that this is behavior that I approve of...)
if Search(r'[\w.]=[\w.]', line) and not Search(r'\b(if|while) ', line):
error(filename, linenum, 'whitespace/operators', 4,
'Missing spaces around =')
# It's ok not to have spaces around binary operators like + - * /, but if
# there's too little whitespace, we get concerned. It's hard to tell,
# though, so we punt on this one for now. TODO.
# You should always have whitespace around binary operators.
#
# Check <= and >= first to avoid false positives with < and >, then
# check non-include lines for spacing around < and >.
match = Search(r'[^<>=!\s](==|!=|<=|>=)[^<>=!\s]', line)
if match:
error(filename, linenum, 'whitespace/operators', 3,
'Missing spaces around %s' % match.group(1))
# We allow no-spaces around << when used like this: 10<<20, but
# not otherwise (particularly, not when used as streams)
# Also ignore using ns::operator<<;
match = Search(r'(operator|\S)(?:L|UL|ULL|l|ul|ull)?<<(\S)', line)
if (match and
not (match.group(1).isdigit() and match.group(2).isdigit()) and
not (match.group(1) == 'operator' and match.group(2) == ';')):
error(filename, linenum, 'whitespace/operators', 3,
'Missing spaces around <<')
elif not Match(r'#.*include', line):
# Avoid false positives on ->
reduced_line = line.replace('->', '')
# Look for < that is not surrounded by spaces. This is only
# triggered if both sides are missing spaces, even though
# technically should should flag if at least one side is missing a
# space. This is done to avoid some false positives with shifts.
match = Search(r'[^\s<]<([^\s=<].*)', reduced_line)
if (match and
not FindNextMatchingAngleBracket(clean_lines, linenum, match.group(1))):
error(filename, linenum, 'whitespace/operators', 3,
'Missing spaces around <')
# Look for > that is not surrounded by spaces. Similar to the
# above, we only trigger if both sides are missing spaces to avoid
# false positives with shifts.
match = Search(r'^(.*[^\s>])>[^\s=>]', reduced_line)
if (match and
not FindPreviousMatchingAngleBracket(clean_lines, linenum,
match.group(1))):
error(filename, linenum, 'whitespace/operators', 3,
'Missing spaces around >')
# We allow no-spaces around >> for almost anything. This is because
# C++11 allows ">>" to close nested templates, which accounts for
# most cases when ">>" is not followed by a space.
#
# We still warn on ">>" followed by alpha character, because that is
# likely due to ">>" being used for right shifts, e.g.:
# value >> alpha
#
# When ">>" is used to close templates, the alphanumeric letter that
# follows would be part of an identifier, and there should still be
# a space separating the template type and the identifier.
# type<type<type>> alpha
match = Search(r'>>[a-zA-Z_]', line)
if match:
error(filename, linenum, 'whitespace/operators', 3,
'Missing spaces around >>')
# There shouldn't be space around unary operators
match = Search(r'(!\s|~\s|[\s]--[\s;]|[\s]\+\+[\s;])', line)
if match:
error(filename, linenum, 'whitespace/operators', 4,
'Extra space for operator %s' % match.group(1))
# A pet peeve of mine: no spaces after an if, while, switch, or for
match = Search(r' (if\(|for\(|while\(|switch\()', line)
if match:
error(filename, linenum, 'whitespace/parens', 5,
'Missing space before ( in %s' % match.group(1))
# For if/for/while/switch, the left and right parens should be
# consistent about how many spaces are inside the parens, and
# there should either be zero or one spaces inside the parens.
# We don't want: "if ( foo)" or "if ( foo )".
# Exception: "for ( ; foo; bar)" and "for (foo; bar; )" are allowed.
match = Search(r'\b(if|for|while|switch)\s*'
r'\(([ ]*)(.).*[^ ]+([ ]*)\)\s*{\s*$',
line)
if match:
if len(match.group(2)) != len(match.group(4)):
if not (match.group(3) == ';' and
len(match.group(2)) == 1 + len(match.group(4)) or
not match.group(2) and Search(r'\bfor\s*\(.*; \)', line)):
error(filename, linenum, 'whitespace/parens', 5,
'Mismatching spaces inside () in %s' % match.group(1))
if len(match.group(2)) not in [0, 1]:
error(filename, linenum, 'whitespace/parens', 5,
'Should have zero or one spaces inside ( and ) in %s' %
match.group(1))
# You should always have a space after a comma (either as fn arg or operator)
#
# This does not apply when the non-space character following the
# comma is another comma, since the only time when that happens is
# for empty macro arguments.
#
# We run this check in two passes: first pass on elided lines to
# verify that lines contain missing whitespaces, second pass on raw
# lines to confirm that those missing whitespaces are not due to
# elided comments.
if Search(r',[^,\s]', line) and Search(r',[^,\s]', raw[linenum]):
error(filename, linenum, 'whitespace/comma', 3,
'Missing space after ,')
# You should always have a space after a semicolon
# except for few corner cases
# TODO(unknown): clarify if 'if (1) { return 1;}' is requires one more
# space after ;
if Search(r';[^\s};\\)/]', line):
error(filename, linenum, 'whitespace/semicolon', 3,
'Missing space after ;')
# Next we will look for issues with function calls.
CheckSpacingForFunctionCall(filename, line, linenum, error)
# Except after an opening paren, or after another opening brace (in case of
# an initializer list, for instance), you should have spaces before your
# braces. And since you should never have braces at the beginning of a line,
# this is an easy test.
match = Match(r'^(.*[^ ({]){', line)
if match:
# Try a bit harder to check for brace initialization. This
# happens in one of the following forms:
# Constructor() : initializer_list_{} { ... }
# Constructor{}.MemberFunction()
# Type variable{};
# FunctionCall(type{}, ...);
# LastArgument(..., type{});
# LOG(INFO) << type{} << " ...";
# map_of_type[{...}] = ...;
#
# We check for the character following the closing brace, and
# silence the warning if it's one of those listed above, i.e.
# "{.;,)<]".
#
# To account for nested initializer list, we allow any number of
# closing braces up to "{;,)<". We can't simply silence the
# warning on first sight of closing brace, because that would
# cause false negatives for things that are not initializer lists.
# Silence this: But not this:
# Outer{ if (...) {
# Inner{...} if (...){ // Missing space before {
# }; }
#
# There is a false negative with this approach if people inserted
# spurious semicolons, e.g. "if (cond){};", but we will catch the
# spurious semicolon with a separate check.
(endline, endlinenum, endpos) = CloseExpression(
clean_lines, linenum, len(match.group(1)))
trailing_text = ''
if endpos > -1:
trailing_text = endline[endpos:]
for offset in xrange(endlinenum + 1,
min(endlinenum + 3, clean_lines.NumLines() - 1)):
trailing_text += clean_lines.elided[offset]
if not Match(r'^[\s}]*[{.;,)<\]]', trailing_text):
error(filename, linenum, 'whitespace/braces', 5,
'Missing space before {')
# Make sure '} else {' has spaces.
if Search(r'}else', line):
error(filename, linenum, 'whitespace/braces', 5,
'Missing space before else')
# You shouldn't have spaces before your brackets, except maybe after
# 'delete []' or 'new char * []'.
if Search(r'\w\s+\[', line) and not Search(r'delete\s+\[', line):
error(filename, linenum, 'whitespace/braces', 5,
'Extra space before [')
# You shouldn't have a space before a semicolon at the end of the line.
# There's a special case for "for" since the style guide allows space before
# the semicolon there.
if Search(r':\s*;\s*$', line):
error(filename, linenum, 'whitespace/semicolon', 5,
'Semicolon defining empty statement. Use {} instead.')
elif Search(r'^\s*;\s*$', line):
error(filename, linenum, 'whitespace/semicolon', 5,
'Line contains only semicolon. If this should be an empty statement, '
'use {} instead.')
elif (Search(r'\s+;\s*$', line) and
not Search(r'\bfor\b', line)):
error(filename, linenum, 'whitespace/semicolon', 5,
'Extra space before last semicolon. If this should be an empty '
'statement, use {} instead.')
# In range-based for, we wanted spaces before and after the colon, but
# not around "::" tokens that might appear.
if (Search('for *\(.*[^:]:[^: ]', line) or
Search('for *\(.*[^: ]:[^:]', line)):
error(filename, linenum, 'whitespace/forcolon', 2,
'Missing space around colon in range-based for loop') | [
"def",
"CheckSpacing",
"(",
"filename",
",",
"clean_lines",
",",
"linenum",
",",
"nesting_state",
",",
"error",
")",
":",
"# Don't use \"elided\" lines here, otherwise we can't check commented lines.",
"# Don't want to use \"raw\" either, because we don't want to check inside C++11",
... | https://github.com/kevinlin311tw/Caffe-DeepBinaryCode/blob/9eaa7662be47d49f475ecbeea2bd51be105270d2/scripts/cpp_lint.py#L2643-L2988 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python3/src/Lib/logging/handlers.py | python | QueueListener.prepare | (self, record) | return record | Prepare a record for handling.
This method just returns the passed-in record. You may want to
override this method if you need to do any custom marshalling or
manipulation of the record before passing it to the handlers. | Prepare a record for handling. | [
"Prepare",
"a",
"record",
"for",
"handling",
"."
] | def prepare(self, record):
"""
Prepare a record for handling.
This method just returns the passed-in record. You may want to
override this method if you need to do any custom marshalling or
manipulation of the record before passing it to the handlers.
"""
return record | [
"def",
"prepare",
"(",
"self",
",",
"record",
")",
":",
"return",
"record"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/logging/handlers.py#L1499-L1507 | |
SoarGroup/Soar | a1c5e249499137a27da60533c72969eef3b8ab6b | scons/scons-local-4.1.0/SCons/Node/FS.py | python | FS.PyPackageDir | (self, modulename) | return self._lookup(dirpath, None, Dir, True) | r"""Locate the directory of a given python module name
For example scons might resolve to
Windows: C:\Python27\Lib\site-packages\scons-2.5.1
Linux: /usr/lib/scons
This can be useful when we want to determine a toolpath based on a python module name | r"""Locate the directory of a given python module name | [
"r",
"Locate",
"the",
"directory",
"of",
"a",
"given",
"python",
"module",
"name"
] | def PyPackageDir(self, modulename):
r"""Locate the directory of a given python module name
For example scons might resolve to
Windows: C:\Python27\Lib\site-packages\scons-2.5.1
Linux: /usr/lib/scons
This can be useful when we want to determine a toolpath based on a python module name"""
dirpath = ''
# Python3 Code
modspec = importlib.util.find_spec(modulename)
dirpath = os.path.dirname(modspec.origin)
return self._lookup(dirpath, None, Dir, True) | [
"def",
"PyPackageDir",
"(",
"self",
",",
"modulename",
")",
":",
"dirpath",
"=",
"''",
"# Python3 Code",
"modspec",
"=",
"importlib",
".",
"util",
".",
"find_spec",
"(",
"modulename",
")",
"dirpath",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"modspec",
... | https://github.com/SoarGroup/Soar/blob/a1c5e249499137a27da60533c72969eef3b8ab6b/scons/scons-local-4.1.0/SCons/Node/FS.py#L1436-L1450 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/core/indexes/multi.py | python | MultiIndex._get_loc_single_level_index | (self, level_index: Index, key: Hashable) | If key is NA value, location of index unify as -1.
Parameters
----------
level_index: Index
key : label
Returns
-------
loc : int
If key is NA value, loc is -1
Else, location of key in index.
See Also
--------
Index.get_loc : The get_loc method for (single-level) index. | If key is NA value, location of index unify as -1. | [
"If",
"key",
"is",
"NA",
"value",
"location",
"of",
"index",
"unify",
"as",
"-",
"1",
"."
] | def _get_loc_single_level_index(self, level_index: Index, key: Hashable) -> int:
"""
If key is NA value, location of index unify as -1.
Parameters
----------
level_index: Index
key : label
Returns
-------
loc : int
If key is NA value, loc is -1
Else, location of key in index.
See Also
--------
Index.get_loc : The get_loc method for (single-level) index.
"""
if is_scalar(key) and isna(key):
return -1
else:
return level_index.get_loc(key) | [
"def",
"_get_loc_single_level_index",
"(",
"self",
",",
"level_index",
":",
"Index",
",",
"key",
":",
"Hashable",
")",
"->",
"int",
":",
"if",
"is_scalar",
"(",
"key",
")",
"and",
"isna",
"(",
"key",
")",
":",
"return",
"-",
"1",
"else",
":",
"return",... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/core/indexes/multi.py#L2575-L2598 | ||
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/keras/backend.py | python | _get_current_tf_device | () | Return explicit device of current context, otherwise returns `None`.
Returns:
If the current device scope is explicitly set, it returns a string with
the device (`CPU` or `GPU`). If the scope is not explicitly set, it will
return `None`. | Return explicit device of current context, otherwise returns `None`. | [
"Return",
"explicit",
"device",
"of",
"current",
"context",
"otherwise",
"returns",
"None",
"."
] | def _get_current_tf_device():
"""Return explicit device of current context, otherwise returns `None`.
Returns:
If the current device scope is explicitly set, it returns a string with
the device (`CPU` or `GPU`). If the scope is not explicitly set, it will
return `None`.
"""
graph = get_graph()
op = _TfDeviceCaptureOp()
graph._apply_device_functions(op)
if tf2.enabled():
return device_spec.DeviceSpecV2.from_string(op.device)
else:
return device_spec.DeviceSpecV1.from_string(op.device) | [
"def",
"_get_current_tf_device",
"(",
")",
":",
"graph",
"=",
"get_graph",
"(",
")",
"op",
"=",
"_TfDeviceCaptureOp",
"(",
")",
"graph",
".",
"_apply_device_functions",
"(",
"op",
")",
"if",
"tf2",
".",
"enabled",
"(",
")",
":",
"return",
"device_spec",
".... | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/keras/backend.py#L856-L870 | ||
baidu-research/tensorflow-allreduce | 66d5b855e90b0949e9fa5cca5599fd729a70e874 | tensorflow/contrib/ndlstm/python/lstm2d.py | python | reduce_to_final | (images, num_filters_out, nhidden=None, scope=None) | Reduce an image to a final state by running two LSTMs.
Args:
images: (num_images, height, width, depth) tensor
num_filters_out: output layer depth
nhidden: hidden layer depth (defaults to num_filters_out)
scope: optional scope name
Returns:
A (num_images, num_filters_out) batch. | Reduce an image to a final state by running two LSTMs. | [
"Reduce",
"an",
"image",
"to",
"a",
"final",
"state",
"by",
"running",
"two",
"LSTMs",
"."
] | def reduce_to_final(images, num_filters_out, nhidden=None, scope=None):
"""Reduce an image to a final state by running two LSTMs.
Args:
images: (num_images, height, width, depth) tensor
num_filters_out: output layer depth
nhidden: hidden layer depth (defaults to num_filters_out)
scope: optional scope name
Returns:
A (num_images, num_filters_out) batch.
"""
with variable_scope.variable_scope(scope, "ReduceToFinal", [images]):
nhidden = nhidden or num_filters_out
batch_size, height, width, depth = _shape(images)
transposed = array_ops.transpose(images, [1, 0, 2, 3])
reshaped = array_ops.reshape(transposed,
[height, batch_size * width, depth])
with variable_scope.variable_scope("reduce1"):
reduced = lstm1d.sequence_to_final(reshaped, nhidden)
transposed_hidden = array_ops.reshape(reduced,
[batch_size, width, nhidden])
hidden = array_ops.transpose(transposed_hidden, [1, 0, 2])
with variable_scope.variable_scope("reduce2"):
output = lstm1d.sequence_to_final(hidden, num_filters_out)
return output | [
"def",
"reduce_to_final",
"(",
"images",
",",
"num_filters_out",
",",
"nhidden",
"=",
"None",
",",
"scope",
"=",
"None",
")",
":",
"with",
"variable_scope",
".",
"variable_scope",
"(",
"scope",
",",
"\"ReduceToFinal\"",
",",
"[",
"images",
"]",
")",
":",
"... | https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/contrib/ndlstm/python/lstm2d.py#L188-L213 | ||
lighttransport/nanort | 74063967336311f54ede5dffdfa242123825033b | deps/cpplint.py | python | NestingState.InnermostClass | (self) | return None | Get class info on the top of the stack.
Returns:
A _ClassInfo object if we are inside a class, or None otherwise. | Get class info on the top of the stack. | [
"Get",
"class",
"info",
"on",
"the",
"top",
"of",
"the",
"stack",
"."
] | def InnermostClass(self):
"""Get class info on the top of the stack.
Returns:
A _ClassInfo object if we are inside a class, or None otherwise.
"""
for i in range(len(self.stack), 0, -1):
classinfo = self.stack[i - 1]
if isinstance(classinfo, _ClassInfo):
return classinfo
return None | [
"def",
"InnermostClass",
"(",
"self",
")",
":",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"self",
".",
"stack",
")",
",",
"0",
",",
"-",
"1",
")",
":",
"classinfo",
"=",
"self",
".",
"stack",
"[",
"i",
"-",
"1",
"]",
"if",
"isinstance",
"(",
... | https://github.com/lighttransport/nanort/blob/74063967336311f54ede5dffdfa242123825033b/deps/cpplint.py#L2539-L2549 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/lib/agw/thumbnailctrl.py | python | ScrolledThumbnail.GetItemIndex | (self, x, y) | return index | Returns the thumbnail index at position (x, y).
:param `x`: the mouse `x` position;
:param `y`: the mouse `y` position. | Returns the thumbnail index at position (x, y). | [
"Returns",
"the",
"thumbnail",
"index",
"at",
"position",
"(",
"x",
"y",
")",
"."
] | def GetItemIndex(self, x, y):
"""
Returns the thumbnail index at position (x, y).
:param `x`: the mouse `x` position;
:param `y`: the mouse `y` position.
"""
col = (x - self._tBorder)/(self._tWidth + self._tBorder)
if col >= self._cols:
col = self._cols - 1
row = -1
y = y - self._tBorder
while y > 0:
row = row + 1
y = y - (self._tHeight + self._tBorder + self.GetCaptionHeight(row))
if row < 0:
row = 0
index = row*self._cols + col
if index >= len(self._items):
index = -1
return index | [
"def",
"GetItemIndex",
"(",
"self",
",",
"x",
",",
"y",
")",
":",
"col",
"=",
"(",
"x",
"-",
"self",
".",
"_tBorder",
")",
"/",
"(",
"self",
".",
"_tWidth",
"+",
"self",
".",
"_tBorder",
")",
"if",
"col",
">=",
"self",
".",
"_cols",
":",
"col",... | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/thumbnailctrl.py#L1793-L1822 | |
AutoRally/autorally | 48bae14fe4b2d56e5ca11fd2fec3d7dfac7a0e75 | autorally_gazebo/nodes/autorally_controller.py | python | AutoRallyCtrlr.__init__ | (self, namespace='controller_manager') | Initialize this _AutoRallyCtrlr. | Initialize this _AutoRallyCtrlr. | [
"Initialize",
"this",
"_AutoRallyCtrlr",
"."
] | def __init__(self, namespace='controller_manager'):
"""Initialize this _AutoRallyCtrlr."""
rospy.init_node("autorally_controller")
# Parameters
# Wheels
(left_steer_link_name, left_steer_ctrlr_name,
left_front_axle_ctrlr_name, self._left_front_inv_circ) = \
self._get_front_wheel_params("left")
(right_steer_link_name, right_steer_ctrlr_name,
right_front_axle_ctrlr_name, self._right_front_inv_circ) = \
self._get_front_wheel_params("right")
(left_rear_link_name, left_rear_axle_ctrlr_name,
self._left_rear_inv_circ) = \
self._get_rear_wheel_params("left")
(self._right_rear_link_name, right_rear_axle_ctrlr_name,
self._right_rear_inv_circ) = \
self._get_rear_wheel_params("right")
list_ctrlrs = rospy.ServiceProxy(namespace + '/list_controllers',
ListControllers)
list_ctrlrs.wait_for_service()
# Shock absorbers
shock_param_list = rospy.get_param("~shock_absorbers", [])
self._shock_pubs = []
try:
for shock_params in shock_param_list:
try:
ctrlr_name = shock_params["controller_name"]
try:
eq_pos = shock_params["equilibrium_position"]
except:
eq_pos = self._DEF_EQ_POS
eq_pos = float(eq_pos)
except:
rospy.logwarn("An invalid parameter was specified for a "
"shock absorber. The shock absorber will "
"not be used.")
continue
pub = rospy.Publisher(ctrlr_name + "/command", Float64,
latch=True, queue_size=1)
_wait_for_ctrlr(list_ctrlrs, ctrlr_name)
pub.publish(eq_pos)
self._shock_pubs.append(pub)
except:
rospy.logwarn("The specified list of shock absorbers is invalid. "
"No shock absorbers will be used.")
# Command timeout
try:
self._cmd_timeout = float(rospy.get_param("~cmd_timeout",
self._DEF_CMD_TIMEOUT))
except:
rospy.logwarn("The specified command timeout value is invalid. "
"The default timeout value will be used instead.")
self._cmd_timeout = self._DEF_CMD_TIMEOUT
try:
self._vehicle_prefix = rospy.get_param("~vehicle_prefix")
if self._vehicle_prefix != "":
self._vehicle_prefix = "/" + self._vehicle_prefix
except:
rospy.logwarn("The specified namespace value is invalid. "
"The default timeout value will be used instead.")
self._vehicle_prefix = ""
# Publishing frequency
try:
pub_freq = float(rospy.get_param("~publishing_frequency",
self._DEF_PUB_FREQ))
if pub_freq <= 0.0:
raise ValueError()
except:
rospy.logwarn("The specified publishing frequency is invalid. "
"The default frequency will be used instead.")
pub_freq = self._DEF_PUB_FREQ
self._sleep_timer = rospy.Rate(pub_freq)
# _last_cmd_time is the time at which the most recent Ackermann
# driving command was received.
self._last_cmd_time = rospy.get_time()
self._last_steer_ang = 0.0 # Last steering angle
self._theta_left = 0.0 # Left steering joint angle
self._theta_right = 0.0 # Right steering joint angle
self._last_speed = 0.0
self._last_accel_limit = 0.0 # Last acceleration limit
# Axle angular velocities
self._left_front_ang_vel = 0.0
self._right_front_ang_vel = 0.0
self._left_rear_ang_vel = 0.0
self._right_rear_ang_vel = 0.0
# _joint_dist_div_2 is the distance between the steering joints,
# divided by two.
tfl = tf.TransformListener()
ls_pos = self._get_link_pos(tfl, left_steer_link_name)
rs_pos = self._get_link_pos(tfl, right_steer_link_name)
self._joint_dist_div_2 = numpy.linalg.norm(ls_pos - rs_pos) / 2
lrw_pos = self._get_link_pos(tfl, left_rear_link_name)
rrw_pos = numpy.array([0.0] * 3)
front_cent_pos = (ls_pos + rs_pos) / 2 # Front center position
rear_cent_pos = (lrw_pos + rrw_pos) / 2 # Rear center position
self._wheelbase = numpy.linalg.norm(front_cent_pos - rear_cent_pos)
self._inv_wheelbase = 1 / self._wheelbase # Inverse of _wheelbase
self._wheelbase_sqr = self._wheelbase ** 2
#self.lastCmdTime = rospy.get_time()
self.chassisCmds = dict()
self.chassisCmdLock = threading.Lock()
#load chassis commander priorities
self.commandPriorities = rospy.get_param("~chassisCommandProirities", [])
self.commandPriorities = sorted(self.commandPriorities.items(), key=operator.itemgetter(1))
rospy.loginfo("AutoRallyGazeboController: Loaded %d chassis commanders", len(self.commandPriorities))
#runstop information
self.runstops = dict()
self.runstopLock = threading.Lock()
self.front_axle_max_effort = 2.5
self.front_axle_brake_effort = 2.5
self.rear_axle_max_effort = 8
self.rear_axle_brake_effort = 4
#self.rear_axle_reverse_percent = 0.25 # percent of max_effort applied when reversing
#self.rear_axle_reverse_effort = self.rear_axle_max_effort*self.rear_axle_reverse_percent
# Publishers and subscribers
self._left_steer_cmd_pub = \
_create_cmd_pub(list_ctrlrs, left_steer_ctrlr_name)
self._right_steer_cmd_pub = \
_create_cmd_pub(list_ctrlrs, right_steer_ctrlr_name)
self._left_front_axle_cmd_pub = \
_create_axle_cmd_pub(list_ctrlrs, left_front_axle_ctrlr_name)
self._right_front_axle_cmd_pub = \
_create_axle_cmd_pub(list_ctrlrs, right_front_axle_ctrlr_name)
self._left_rear_axle_cmd_pub = \
_create_axle_cmd_pub(list_ctrlrs, left_rear_axle_ctrlr_name)
self._right_rear_axle_cmd_pub = \
_create_axle_cmd_pub(list_ctrlrs, right_rear_axle_ctrlr_name)
self.left_front_name, self.left_front_dia = self.getJointStateWheelParams('left', 'front')
self.right_front_name, self.right_front_dia = self.getJointStateWheelParams('right', 'front')
self.left_rear_name, self.left_rear_dia = self.getJointStateWheelParams('left', 'rear')
self.right_rear_name, self.right_rear_dia = self.getJointStateWheelParams('right', 'rear')
self.wheelSpeedFront = 0.0;
#don't set up callback until params are initialized
self.wheelSpeedsPub = rospy.Publisher(self._vehicle_prefix + '/wheelSpeeds', wheelSpeeds, queue_size=1)
#self.sub = rospy.Subscriber('/autorally_platform/gazebo/link_states', ModelStates, self.callback)
self.chassisStatePub = rospy.Publisher(self._vehicle_prefix + "/chassisState", chassisState, queue_size=1)
self.chassisCmdSub = dict()
for cmd, priority in self.commandPriorities:
self.chassisCmdSub[cmd] = \
rospy.Subscriber(self._vehicle_prefix+"/"+cmd+"/chassisCommand", chassisCommand,
self.chassisCmdCb, queue_size=1)
self.runstopSub = rospy.Subscriber(self._vehicle_prefix + "/runstop", runstop, self.runstopCb, queue_size=5)
self.wheelSpeedSub = rospy.Subscriber(self._vehicle_prefix + '/joint_states', JointState, self.wheelSpeedsCb) | [
"def",
"__init__",
"(",
"self",
",",
"namespace",
"=",
"'controller_manager'",
")",
":",
"rospy",
".",
"init_node",
"(",
"\"autorally_controller\"",
")",
"# Parameters",
"# Wheels",
"(",
"left_steer_link_name",
",",
"left_steer_ctrlr_name",
",",
"left_front_axle_ctrlr_n... | https://github.com/AutoRally/autorally/blob/48bae14fe4b2d56e5ca11fd2fec3d7dfac7a0e75/autorally_gazebo/nodes/autorally_controller.py#L141-L312 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/_core.py | python | EventLoopBase.YieldFor | (*args, **kwargs) | return _core_.EventLoopBase_YieldFor(*args, **kwargs) | YieldFor(self, long eventsToProcess) -> bool | YieldFor(self, long eventsToProcess) -> bool | [
"YieldFor",
"(",
"self",
"long",
"eventsToProcess",
")",
"-",
">",
"bool"
] | def YieldFor(*args, **kwargs):
"""YieldFor(self, long eventsToProcess) -> bool"""
return _core_.EventLoopBase_YieldFor(*args, **kwargs) | [
"def",
"YieldFor",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_core_",
".",
"EventLoopBase_YieldFor",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_core.py#L8820-L8822 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.