nwo
stringlengths
5
86
sha
stringlengths
40
40
path
stringlengths
4
189
language
stringclasses
1 value
identifier
stringlengths
1
94
parameters
stringlengths
2
4.03k
argument_list
stringclasses
1 value
return_statement
stringlengths
0
11.5k
docstring
stringlengths
1
33.2k
docstring_summary
stringlengths
0
5.15k
docstring_tokens
list
function
stringlengths
34
151k
function_tokens
list
url
stringlengths
90
278
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/_core.py
python
Window.GetBestVirtualSize
(*args, **kwargs)
return _core_.Window_GetBestVirtualSize(*args, **kwargs)
GetBestVirtualSize(self) -> Size Return the largest of ClientSize and BestSize (as determined by a sizer, interior children, or other means)
GetBestVirtualSize(self) -> Size
[ "GetBestVirtualSize", "(", "self", ")", "-", ">", "Size" ]
def GetBestVirtualSize(*args, **kwargs): """ GetBestVirtualSize(self) -> Size Return the largest of ClientSize and BestSize (as determined by a sizer, interior children, or other means) """ return _core_.Window_GetBestVirtualSize(*args, **kwargs)
[ "def", "GetBestVirtualSize", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_core_", ".", "Window_GetBestVirtualSize", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_core.py#L9852-L9859
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_internal/configuration.py
python
Configuration.save
(self)
Save the current in-memory state.
Save the current in-memory state.
[ "Save", "the", "current", "in", "-", "memory", "state", "." ]
def save(self): # type: () -> None """Save the current in-memory state. """ self._ensure_have_load_only() for fname, parser in self._modified_parsers: logger.info("Writing to %s", fname) # Ensure directory exists. ensure_dir(os.path.dirname(fname)) with open(fname, "w") as f: parser.write(f)
[ "def", "save", "(", "self", ")", ":", "# type: () -> None", "self", ".", "_ensure_have_load_only", "(", ")", "for", "fname", ",", "parser", "in", "self", ".", "_modified_parsers", ":", "logger", ".", "info", "(", "\"Writing to %s\"", ",", "fname", ")", "# Ensure directory exists.", "ensure_dir", "(", "os", ".", "path", ".", "dirname", "(", "fname", ")", ")", "with", "open", "(", "fname", ",", "\"w\"", ")", "as", "f", ":", "parser", ".", "write", "(", "f", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_internal/configuration.py#L431-L457
microsoft/ivy
9f3c7ecc0b2383129fdd0953e10890d98d09a82d
ivy/ivy_dafny_grammar.py
python
p_expr_symbol_lparen_exprs_rparen
(p)
expr : symbol LPAREN exprs RPAREN
expr : symbol LPAREN exprs RPAREN
[ "expr", ":", "symbol", "LPAREN", "exprs", "RPAREN" ]
def p_expr_symbol_lparen_exprs_rparen(p): 'expr : symbol LPAREN exprs RPAREN' p[0] = da.Call(*([p[1]] + p[3]))
[ "def", "p_expr_symbol_lparen_exprs_rparen", "(", "p", ")", ":", "p", "[", "0", "]", "=", "da", ".", "Call", "(", "*", "(", "[", "p", "[", "1", "]", "]", "+", "p", "[", "3", "]", ")", ")" ]
https://github.com/microsoft/ivy/blob/9f3c7ecc0b2383129fdd0953e10890d98d09a82d/ivy/ivy_dafny_grammar.py#L160-L162
mapnik/mapnik
f3da900c355e1d15059c4a91b00203dcc9d9f0ef
scons/scons-local-4.1.0/SCons/Script/SConscript.py
python
BuildDefaultGlobals
()
return GlobalDict.copy()
Create a dictionary containing all the default globals for SConstruct and SConscript files.
Create a dictionary containing all the default globals for SConstruct and SConscript files.
[ "Create", "a", "dictionary", "containing", "all", "the", "default", "globals", "for", "SConstruct", "and", "SConscript", "files", "." ]
def BuildDefaultGlobals(): """ Create a dictionary containing all the default globals for SConstruct and SConscript files. """ global GlobalDict if GlobalDict is None: GlobalDict = {} import SCons.Script d = SCons.Script.__dict__ def not_a_module(m, d=d, mtype=type(SCons.Script)): return not isinstance(d[m], mtype) for m in filter(not_a_module, dir(SCons.Script)): GlobalDict[m] = d[m] return GlobalDict.copy()
[ "def", "BuildDefaultGlobals", "(", ")", ":", "global", "GlobalDict", "if", "GlobalDict", "is", "None", ":", "GlobalDict", "=", "{", "}", "import", "SCons", ".", "Script", "d", "=", "SCons", ".", "Script", ".", "__dict__", "def", "not_a_module", "(", "m", ",", "d", "=", "d", ",", "mtype", "=", "type", "(", "SCons", ".", "Script", ")", ")", ":", "return", "not", "isinstance", "(", "d", "[", "m", "]", ",", "mtype", ")", "for", "m", "in", "filter", "(", "not_a_module", ",", "dir", "(", "SCons", ".", "Script", ")", ")", ":", "GlobalDict", "[", "m", "]", "=", "d", "[", "m", "]", "return", "GlobalDict", ".", "copy", "(", ")" ]
https://github.com/mapnik/mapnik/blob/f3da900c355e1d15059c4a91b00203dcc9d9f0ef/scons/scons-local-4.1.0/SCons/Script/SConscript.py#L657-L674
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/_core.py
python
IndividualLayoutConstraint.GetMargin
(*args, **kwargs)
return _core_.IndividualLayoutConstraint_GetMargin(*args, **kwargs)
GetMargin(self) -> int
GetMargin(self) -> int
[ "GetMargin", "(", "self", ")", "-", ">", "int" ]
def GetMargin(*args, **kwargs): """GetMargin(self) -> int""" return _core_.IndividualLayoutConstraint_GetMargin(*args, **kwargs)
[ "def", "GetMargin", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_core_", ".", "IndividualLayoutConstraint_GetMargin", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_core.py#L16236-L16238
apple/turicreate
cce55aa5311300e3ce6af93cb45ba791fd1bdf49
src/external/boost/boost_1_68_0/tools/build/src/util/sequence.py
python
select_highest_ranked
(elements, ranks)
return result
Returns all of 'elements' for which corresponding element in parallel list 'rank' is equal to the maximum value in 'rank'.
Returns all of 'elements' for which corresponding element in parallel list 'rank' is equal to the maximum value in 'rank'.
[ "Returns", "all", "of", "elements", "for", "which", "corresponding", "element", "in", "parallel", "list", "rank", "is", "equal", "to", "the", "maximum", "value", "in", "rank", "." ]
def select_highest_ranked (elements, ranks): """ Returns all of 'elements' for which corresponding element in parallel list 'rank' is equal to the maximum value in 'rank'. """ assert is_iterable(elements) assert is_iterable(ranks) if not elements: return [] max_rank = max_element (ranks) result = [] while elements: if ranks [0] == max_rank: result.append (elements [0]) elements = elements [1:] ranks = ranks [1:] return result
[ "def", "select_highest_ranked", "(", "elements", ",", "ranks", ")", ":", "assert", "is_iterable", "(", "elements", ")", "assert", "is_iterable", "(", "ranks", ")", "if", "not", "elements", ":", "return", "[", "]", "max_rank", "=", "max_element", "(", "ranks", ")", "result", "=", "[", "]", "while", "elements", ":", "if", "ranks", "[", "0", "]", "==", "max_rank", ":", "result", ".", "append", "(", "elements", "[", "0", "]", ")", "elements", "=", "elements", "[", "1", ":", "]", "ranks", "=", "ranks", "[", "1", ":", "]", "return", "result" ]
https://github.com/apple/turicreate/blob/cce55aa5311300e3ce6af93cb45ba791fd1bdf49/src/external/boost/boost_1_68_0/tools/build/src/util/sequence.py#L39-L58
intel-iot-devkit/how-to-code-samples
b4ea616f36bbfa2e042beb1698f968cfd651d79f
equipment-activity-monitor/python/iot_equipment_activity_monitor/__main__.py
python
main
()
Start main function.
Start main function.
[ "Start", "main", "function", "." ]
def main(): """ Start main function. """ runner = Runner() print("Running {0} example.".format(runner.project_name)) runner.start() def signal_handle(sig, frame): reactor.stop() _exit(0) signal(SIGINT, signal_handle) reactor.run(installSignalHandlers=0)
[ "def", "main", "(", ")", ":", "runner", "=", "Runner", "(", ")", "print", "(", "\"Running {0} example.\"", ".", "format", "(", "runner", ".", "project_name", ")", ")", "runner", ".", "start", "(", ")", "def", "signal_handle", "(", "sig", ",", "frame", ")", ":", "reactor", ".", "stop", "(", ")", "_exit", "(", "0", ")", "signal", "(", "SIGINT", ",", "signal_handle", ")", "reactor", ".", "run", "(", "installSignalHandlers", "=", "0", ")" ]
https://github.com/intel-iot-devkit/how-to-code-samples/blob/b4ea616f36bbfa2e042beb1698f968cfd651d79f/equipment-activity-monitor/python/iot_equipment_activity_monitor/__main__.py#L32-L48
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/mailbox.py
python
BabylMessage.remove_label
(self, label)
Remove label from the list of labels on the message.
Remove label from the list of labels on the message.
[ "Remove", "label", "from", "the", "list", "of", "labels", "on", "the", "message", "." ]
def remove_label(self, label): """Remove label from the list of labels on the message.""" try: self._labels.remove(label) except ValueError: pass
[ "def", "remove_label", "(", "self", ",", "label", ")", ":", "try", ":", "self", ".", "_labels", ".", "remove", "(", "label", ")", "except", "ValueError", ":", "pass" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/mailbox.py#L1848-L1853
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/pandas/py2/pandas/io/stata.py
python
StataWriter._prepare_categoricals
(self, data)
return DataFrame.from_dict(OrderedDict(data_formatted))
Check for categorical columns, retain categorical information for Stata file and convert categorical data to int
Check for categorical columns, retain categorical information for Stata file and convert categorical data to int
[ "Check", "for", "categorical", "columns", "retain", "categorical", "information", "for", "Stata", "file", "and", "convert", "categorical", "data", "to", "int" ]
def _prepare_categoricals(self, data): """Check for categorical columns, retain categorical information for Stata file and convert categorical data to int""" is_cat = [is_categorical_dtype(data[col]) for col in data] self._is_col_cat = is_cat self._value_labels = [] if not any(is_cat): return data get_base_missing_value = StataMissingValue.get_base_missing_value data_formatted = [] for col, col_is_cat in zip(data, is_cat): if col_is_cat: self._value_labels.append(StataValueLabel(data[col])) dtype = data[col].cat.codes.dtype if dtype == np.int64: raise ValueError('It is not possible to export ' 'int64-based categorical data to Stata.') values = data[col].cat.codes.values.copy() # Upcast if needed so that correct missing values can be set if values.max() >= get_base_missing_value(dtype): if dtype == np.int8: dtype = np.int16 elif dtype == np.int16: dtype = np.int32 else: dtype = np.float64 values = np.array(values, dtype=dtype) # Replace missing values with Stata missing value for type values[values == -1] = get_base_missing_value(dtype) data_formatted.append((col, values)) else: data_formatted.append((col, data[col])) return DataFrame.from_dict(OrderedDict(data_formatted))
[ "def", "_prepare_categoricals", "(", "self", ",", "data", ")", ":", "is_cat", "=", "[", "is_categorical_dtype", "(", "data", "[", "col", "]", ")", "for", "col", "in", "data", "]", "self", ".", "_is_col_cat", "=", "is_cat", "self", ".", "_value_labels", "=", "[", "]", "if", "not", "any", "(", "is_cat", ")", ":", "return", "data", "get_base_missing_value", "=", "StataMissingValue", ".", "get_base_missing_value", "data_formatted", "=", "[", "]", "for", "col", ",", "col_is_cat", "in", "zip", "(", "data", ",", "is_cat", ")", ":", "if", "col_is_cat", ":", "self", ".", "_value_labels", ".", "append", "(", "StataValueLabel", "(", "data", "[", "col", "]", ")", ")", "dtype", "=", "data", "[", "col", "]", ".", "cat", ".", "codes", ".", "dtype", "if", "dtype", "==", "np", ".", "int64", ":", "raise", "ValueError", "(", "'It is not possible to export '", "'int64-based categorical data to Stata.'", ")", "values", "=", "data", "[", "col", "]", ".", "cat", ".", "codes", ".", "values", ".", "copy", "(", ")", "# Upcast if needed so that correct missing values can be set", "if", "values", ".", "max", "(", ")", ">=", "get_base_missing_value", "(", "dtype", ")", ":", "if", "dtype", "==", "np", ".", "int8", ":", "dtype", "=", "np", ".", "int16", "elif", "dtype", "==", "np", ".", "int16", ":", "dtype", "=", "np", ".", "int32", "else", ":", "dtype", "=", "np", ".", "float64", "values", "=", "np", ".", "array", "(", "values", ",", "dtype", "=", "dtype", ")", "# Replace missing values with Stata missing value for type", "values", "[", "values", "==", "-", "1", "]", "=", "get_base_missing_value", "(", "dtype", ")", "data_formatted", ".", "append", "(", "(", "col", ",", "values", ")", ")", "else", ":", "data_formatted", ".", "append", "(", "(", "col", ",", "data", "[", "col", "]", ")", ")", "return", "DataFrame", ".", "from_dict", "(", "OrderedDict", "(", "data_formatted", ")", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py2/pandas/io/stata.py#L2009-L2045
eventql/eventql
7ca0dbb2e683b525620ea30dc40540a22d5eb227
deps/3rdparty/spidermonkey/mozjs/python/bitstring/bitstring.py
python
BitArray.replace
(self, old, new, start=None, end=None, count=None, bytealigned=None)
return len(lengths) - 1
Replace all occurrences of old with new in place. Returns number of replacements made. old -- The bitstring to replace. new -- The replacement bitstring. start -- Any occurrences that start before this will not be replaced. Defaults to 0. end -- Any occurrences that finish after this will not be replaced. Defaults to self.len. count -- The maximum number of replacements to make. Defaults to replace all occurrences. bytealigned -- If True replacements will only be made on byte boundaries. Raises ValueError if old is empty or if start or end are out of range.
Replace all occurrences of old with new in place.
[ "Replace", "all", "occurrences", "of", "old", "with", "new", "in", "place", "." ]
def replace(self, old, new, start=None, end=None, count=None, bytealigned=None): """Replace all occurrences of old with new in place. Returns number of replacements made. old -- The bitstring to replace. new -- The replacement bitstring. start -- Any occurrences that start before this will not be replaced. Defaults to 0. end -- Any occurrences that finish after this will not be replaced. Defaults to self.len. count -- The maximum number of replacements to make. Defaults to replace all occurrences. bytealigned -- If True replacements will only be made on byte boundaries. Raises ValueError if old is empty or if start or end are out of range. """ old = Bits(old) new = Bits(new) if not old.len: raise ValueError("Empty bitstring cannot be replaced.") start, end = self._validate_slice(start, end) if bytealigned is None: bytealigned = globals()['bytealigned'] # Adjust count for use in split() if count is not None: count += 1 sections = self.split(old, start, end, count, bytealigned) lengths = [s.len for s in sections] if len(lengths) == 1: # Didn't find anything to replace. return 0 # no replacements done if new is self: # Prevent self assignment woes new = copy.copy(self) positions = [lengths[0] + start] for l in lengths[1:-1]: # Next position is the previous one plus the length of the next section. positions.append(positions[-1] + l) # We have all the positions that need replacements. We do them # in reverse order so that they won't move around as we replace. positions.reverse() try: # Need to calculate new pos, if this is a bitstream newpos = self._pos for p in positions: self[p:p + old.len] = new if old.len != new.len: diff = new.len - old.len for p in positions: if p >= newpos: continue if p + old.len <= newpos: newpos += diff else: newpos = p self._pos = newpos except AttributeError: for p in positions: self[p:p + old.len] = new assert self._assertsanity() return len(lengths) - 1
[ "def", "replace", "(", "self", ",", "old", ",", "new", ",", "start", "=", "None", ",", "end", "=", "None", ",", "count", "=", "None", ",", "bytealigned", "=", "None", ")", ":", "old", "=", "Bits", "(", "old", ")", "new", "=", "Bits", "(", "new", ")", "if", "not", "old", ".", "len", ":", "raise", "ValueError", "(", "\"Empty bitstring cannot be replaced.\"", ")", "start", ",", "end", "=", "self", ".", "_validate_slice", "(", "start", ",", "end", ")", "if", "bytealigned", "is", "None", ":", "bytealigned", "=", "globals", "(", ")", "[", "'bytealigned'", "]", "# Adjust count for use in split()", "if", "count", "is", "not", "None", ":", "count", "+=", "1", "sections", "=", "self", ".", "split", "(", "old", ",", "start", ",", "end", ",", "count", ",", "bytealigned", ")", "lengths", "=", "[", "s", ".", "len", "for", "s", "in", "sections", "]", "if", "len", "(", "lengths", ")", "==", "1", ":", "# Didn't find anything to replace.", "return", "0", "# no replacements done", "if", "new", "is", "self", ":", "# Prevent self assignment woes", "new", "=", "copy", ".", "copy", "(", "self", ")", "positions", "=", "[", "lengths", "[", "0", "]", "+", "start", "]", "for", "l", "in", "lengths", "[", "1", ":", "-", "1", "]", ":", "# Next position is the previous one plus the length of the next section.", "positions", ".", "append", "(", "positions", "[", "-", "1", "]", "+", "l", ")", "# We have all the positions that need replacements. We do them", "# in reverse order so that they won't move around as we replace.", "positions", ".", "reverse", "(", ")", "try", ":", "# Need to calculate new pos, if this is a bitstream", "newpos", "=", "self", ".", "_pos", "for", "p", "in", "positions", ":", "self", "[", "p", ":", "p", "+", "old", ".", "len", "]", "=", "new", "if", "old", ".", "len", "!=", "new", ".", "len", ":", "diff", "=", "new", ".", "len", "-", "old", ".", "len", "for", "p", "in", "positions", ":", "if", "p", ">=", "newpos", ":", "continue", "if", "p", "+", "old", ".", "len", "<=", "newpos", ":", "newpos", "+=", "diff", "else", ":", "newpos", "=", "p", "self", ".", "_pos", "=", "newpos", "except", "AttributeError", ":", "for", "p", "in", "positions", ":", "self", "[", "p", ":", "p", "+", "old", ".", "len", "]", "=", "new", "assert", "self", ".", "_assertsanity", "(", ")", "return", "len", "(", "lengths", ")", "-", "1" ]
https://github.com/eventql/eventql/blob/7ca0dbb2e683b525620ea30dc40540a22d5eb227/deps/3rdparty/spidermonkey/mozjs/python/bitstring/bitstring.py#L3290-L3355
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/ntpath.py
python
normcase
(s)
Normalize case of pathname. Makes all characters lowercase and all slashes into backslashes.
Normalize case of pathname.
[ "Normalize", "case", "of", "pathname", "." ]
def normcase(s): """Normalize case of pathname. Makes all characters lowercase and all slashes into backslashes.""" s = os.fspath(s) try: if isinstance(s, bytes): return s.replace(b'/', b'\\').lower() else: return s.replace('/', '\\').lower() except (TypeError, AttributeError): if not isinstance(s, (bytes, str)): raise TypeError("normcase() argument must be str or bytes, " "not %r" % s.__class__.__name__) from None raise
[ "def", "normcase", "(", "s", ")", ":", "s", "=", "os", ".", "fspath", "(", "s", ")", "try", ":", "if", "isinstance", "(", "s", ",", "bytes", ")", ":", "return", "s", ".", "replace", "(", "b'/'", ",", "b'\\\\'", ")", ".", "lower", "(", ")", "else", ":", "return", "s", ".", "replace", "(", "'/'", ",", "'\\\\'", ")", ".", "lower", "(", ")", "except", "(", "TypeError", ",", "AttributeError", ")", ":", "if", "not", "isinstance", "(", "s", ",", "(", "bytes", ",", "str", ")", ")", ":", "raise", "TypeError", "(", "\"normcase() argument must be str or bytes, \"", "\"not %r\"", "%", "s", ".", "__class__", ".", "__name__", ")", "from", "None", "raise" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/ntpath.py#L44-L58
pskun/finance_news_analysis
6ac13e32deede37a4cf57bba8b2897941ae3d80d
preprocess/guba_preprocess_handler.py
python
GubaPreprocessHandler.init_handler
(self)
初始化handler
初始化handler
[ "初始化handler" ]
def init_handler(self): ''' 初始化handler ''' pass
[ "def", "init_handler", "(", "self", ")", ":", "pass" ]
https://github.com/pskun/finance_news_analysis/blob/6ac13e32deede37a4cf57bba8b2897941ae3d80d/preprocess/guba_preprocess_handler.py#L47-L49
esa/pykep
b410363653623730b577de257c04b0e0289f2014
pykep/trajopt/_mga.py
python
mga.alpha2direct
(self, x)
return retval
alpha2direct(x) Args: - x (``array-like``): a chromosome encoding an MGA trajectory in the alpha encoding Returns: ``numpy.array``: a chromosome encoding the MGA trajectory using the direct encoding
alpha2direct(x)
[ "alpha2direct", "(", "x", ")" ]
def alpha2direct(self, x): """alpha2direct(x) Args: - x (``array-like``): a chromosome encoding an MGA trajectory in the alpha encoding Returns: ``numpy.array``: a chromosome encoding the MGA trajectory using the direct encoding """ T = np.log(x[2:]) retval = T / sum(T) * x[1] retval = np.insert(retval, 0, x[0]) return retval
[ "def", "alpha2direct", "(", "self", ",", "x", ")", ":", "T", "=", "np", ".", "log", "(", "x", "[", "2", ":", "]", ")", "retval", "=", "T", "/", "sum", "(", "T", ")", "*", "x", "[", "1", "]", "retval", "=", "np", ".", "insert", "(", "retval", ",", "0", ",", "x", "[", "0", "]", ")", "return", "retval" ]
https://github.com/esa/pykep/blob/b410363653623730b577de257c04b0e0289f2014/pykep/trajopt/_mga.py#L171-L183
baidu-research/tensorflow-allreduce
66d5b855e90b0949e9fa5cca5599fd729a70e874
tensorflow/python/framework/registry.py
python
Registry.lookup
(self, name)
Looks up "name". Args: name: a string specifying the registry key for the candidate. Returns: Registered object if found Raises: LookupError: if "name" has not been registered.
Looks up "name".
[ "Looks", "up", "name", "." ]
def lookup(self, name): """Looks up "name". Args: name: a string specifying the registry key for the candidate. Returns: Registered object if found Raises: LookupError: if "name" has not been registered. """ name = compat.as_str(name) if name in self._registry: return self._registry[name][_TYPE_TAG] else: raise LookupError( "%s registry has no entry for: %s" % (self._name, name))
[ "def", "lookup", "(", "self", ",", "name", ")", ":", "name", "=", "compat", ".", "as_str", "(", "name", ")", "if", "name", "in", "self", ".", "_registry", ":", "return", "self", ".", "_registry", "[", "name", "]", "[", "_TYPE_TAG", "]", "else", ":", "raise", "LookupError", "(", "\"%s registry has no entry for: %s\"", "%", "(", "self", ".", "_name", ",", "name", ")", ")" ]
https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/python/framework/registry.py#L78-L93
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/tools/Editra/src/ed_book.py
python
EdBaseBook.UseIcons
(self)
return bUseIcons
Is the book using tab icons?
Is the book using tab icons?
[ "Is", "the", "book", "using", "tab", "icons?" ]
def UseIcons(self): """Is the book using tab icons?""" bUseIcons = Profile_Get('TABICONS', default=True) return bUseIcons
[ "def", "UseIcons", "(", "self", ")", ":", "bUseIcons", "=", "Profile_Get", "(", "'TABICONS'", ",", "default", "=", "True", ")", "return", "bUseIcons" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/ed_book.py#L95-L98
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/cython/Cython/Plex/DFA.py
python
nfa_to_dfa
(old_machine, debug=None)
return new_machine
Given a nondeterministic Machine, return a new equivalent Machine which is deterministic.
Given a nondeterministic Machine, return a new equivalent Machine which is deterministic.
[ "Given", "a", "nondeterministic", "Machine", "return", "a", "new", "equivalent", "Machine", "which", "is", "deterministic", "." ]
def nfa_to_dfa(old_machine, debug=None): """ Given a nondeterministic Machine, return a new equivalent Machine which is deterministic. """ # We build a new machine whose states correspond to sets of states # in the old machine. Initially we add a new state corresponding to # the epsilon-closure of each initial old state. Then we give transitions # to each new state which are the union of all transitions out of any # of the corresponding old states. The new state reached on a given # character is the one corresponding to the set of states reachable # on that character from any of the old states. As new combinations of # old states are created, new states are added as needed until closure # is reached. new_machine = Machines.FastMachine() state_map = StateMap(new_machine) # Seed the process using the initial states of the old machine. # Make the corresponding new states into initial states of the new # machine with the same names. for (key, old_state) in old_machine.initial_states.items(): new_state = state_map.old_to_new(epsilon_closure(old_state)) new_machine.make_initial_state(key, new_state) # Tricky bit here: we add things to the end of this list while we're # iterating over it. The iteration stops when closure is achieved. for new_state in new_machine.states: transitions = TransitionMap() for old_state in state_map.new_to_old(new_state): for event, old_target_states in old_state.transitions.items(): if event and old_target_states: transitions.add_set(event, set_epsilon_closure(old_target_states)) for event, old_states in transitions.items(): new_machine.add_transitions(new_state, event, state_map.old_to_new(old_states)) if debug: debug.write("\n===== State Mapping =====\n") state_map.dump(debug) return new_machine
[ "def", "nfa_to_dfa", "(", "old_machine", ",", "debug", "=", "None", ")", ":", "# We build a new machine whose states correspond to sets of states", "# in the old machine. Initially we add a new state corresponding to", "# the epsilon-closure of each initial old state. Then we give transitions", "# to each new state which are the union of all transitions out of any", "# of the corresponding old states. The new state reached on a given", "# character is the one corresponding to the set of states reachable", "# on that character from any of the old states. As new combinations of", "# old states are created, new states are added as needed until closure", "# is reached.", "new_machine", "=", "Machines", ".", "FastMachine", "(", ")", "state_map", "=", "StateMap", "(", "new_machine", ")", "# Seed the process using the initial states of the old machine.", "# Make the corresponding new states into initial states of the new", "# machine with the same names.", "for", "(", "key", ",", "old_state", ")", "in", "old_machine", ".", "initial_states", ".", "items", "(", ")", ":", "new_state", "=", "state_map", ".", "old_to_new", "(", "epsilon_closure", "(", "old_state", ")", ")", "new_machine", ".", "make_initial_state", "(", "key", ",", "new_state", ")", "# Tricky bit here: we add things to the end of this list while we're", "# iterating over it. The iteration stops when closure is achieved.", "for", "new_state", "in", "new_machine", ".", "states", ":", "transitions", "=", "TransitionMap", "(", ")", "for", "old_state", "in", "state_map", ".", "new_to_old", "(", "new_state", ")", ":", "for", "event", ",", "old_target_states", "in", "old_state", ".", "transitions", ".", "items", "(", ")", ":", "if", "event", "and", "old_target_states", ":", "transitions", ".", "add_set", "(", "event", ",", "set_epsilon_closure", "(", "old_target_states", ")", ")", "for", "event", ",", "old_states", "in", "transitions", ".", "items", "(", ")", ":", "new_machine", ".", "add_transitions", "(", "new_state", ",", "event", ",", "state_map", ".", "old_to_new", "(", "old_states", ")", ")", "if", "debug", ":", "debug", ".", "write", "(", "\"\\n===== State Mapping =====\\n\"", ")", "state_map", ".", "dump", "(", "debug", ")", "return", "new_machine" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/cython/Cython/Plex/DFA.py#L16-L51
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/WebOb/webob/response.py
python
Response._json_body__get
(self)
return json.loads(self.body.decode(self.charset or 'UTF-8'))
Access the body of the response as JSON
Access the body of the response as JSON
[ "Access", "the", "body", "of", "the", "response", "as", "JSON" ]
def _json_body__get(self): """Access the body of the response as JSON""" # Note: UTF-8 is a content-type specific default for JSON: return json.loads(self.body.decode(self.charset or 'UTF-8'))
[ "def", "_json_body__get", "(", "self", ")", ":", "# Note: UTF-8 is a content-type specific default for JSON:", "return", "json", ".", "loads", "(", "self", ".", "body", ".", "decode", "(", "self", ".", "charset", "or", "'UTF-8'", ")", ")" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/WebOb/webob/response.py#L387-L390
SpenceKonde/megaTinyCore
1c4a70b18a149fe6bcb551dfa6db11ca50b8997b
megaavr/tools/libs/serial/rfc2217.py
python
Serial._update_dtr_state
(self)
Set terminal status line: Data Terminal Ready.
Set terminal status line: Data Terminal Ready.
[ "Set", "terminal", "status", "line", ":", "Data", "Terminal", "Ready", "." ]
def _update_dtr_state(self): """Set terminal status line: Data Terminal Ready.""" if not self.is_open: raise portNotOpenError if self.logger: self.logger.info('set DTR to {}'.format('active' if self._dtr_state else 'inactive')) if self._dtr_state: self.rfc2217_set_control(SET_CONTROL_DTR_ON) else: self.rfc2217_set_control(SET_CONTROL_DTR_OFF)
[ "def", "_update_dtr_state", "(", "self", ")", ":", "if", "not", "self", ".", "is_open", ":", "raise", "portNotOpenError", "if", "self", ".", "logger", ":", "self", ".", "logger", ".", "info", "(", "'set DTR to {}'", ".", "format", "(", "'active'", "if", "self", ".", "_dtr_state", "else", "'inactive'", ")", ")", "if", "self", ".", "_dtr_state", ":", "self", ".", "rfc2217_set_control", "(", "SET_CONTROL_DTR_ON", ")", "else", ":", "self", ".", "rfc2217_set_control", "(", "SET_CONTROL_DTR_OFF", ")" ]
https://github.com/SpenceKonde/megaTinyCore/blob/1c4a70b18a149fe6bcb551dfa6db11ca50b8997b/megaavr/tools/libs/serial/rfc2217.py#L682-L691
trilinos/Trilinos
6168be6dd51e35e1cd681e9c4b24433e709df140
packages/muelu/utils/genClass/genClass.py
python
deleteDir
(path)
deletes the path entirely
deletes the path entirely
[ "deletes", "the", "path", "entirely" ]
def deleteDir(path): """deletes the path entirely""" cmd = "rm -rf "+path result = getstatusoutput(cmd) if(result[0]!=0): raise RuntimeError(result[1])
[ "def", "deleteDir", "(", "path", ")", ":", "cmd", "=", "\"rm -rf \"", "+", "path", "result", "=", "getstatusoutput", "(", "cmd", ")", "if", "(", "result", "[", "0", "]", "!=", "0", ")", ":", "raise", "RuntimeError", "(", "result", "[", "1", "]", ")" ]
https://github.com/trilinos/Trilinos/blob/6168be6dd51e35e1cd681e9c4b24433e709df140/packages/muelu/utils/genClass/genClass.py#L18-L23
mongodb/mongo
d8ff665343ad29cf286ee2cf4a1960d29371937b
buildscripts/linter/git_base.py
python
Repository.fetch_remote_branch
(self, repository, branch)
return self.git_fetch([repository, branch])
Fetch the changes from a remote branch.
Fetch the changes from a remote branch.
[ "Fetch", "the", "changes", "from", "a", "remote", "branch", "." ]
def fetch_remote_branch(self, repository, branch): """Fetch the changes from a remote branch.""" return self.git_fetch([repository, branch])
[ "def", "fetch_remote_branch", "(", "self", ",", "repository", ",", "branch", ")", ":", "return", "self", ".", "git_fetch", "(", "[", "repository", ",", "branch", "]", ")" ]
https://github.com/mongodb/mongo/blob/d8ff665343ad29cf286ee2cf4a1960d29371937b/buildscripts/linter/git_base.py#L144-L146
mongodb/mongo
d8ff665343ad29cf286ee2cf4a1960d29371937b
buildscripts/todo_check.py
python
TodoChecker.validate_commit_queue
(self, commit_message: str)
return found_any
Check that the given commit message does not reference TODO comments. :param commit_message: Commit message to check. :return: True if any TODOs were found.
Check that the given commit message does not reference TODO comments.
[ "Check", "that", "the", "given", "commit", "message", "does", "not", "reference", "TODO", "comments", "." ]
def validate_commit_queue(self, commit_message: str) -> bool: """ Check that the given commit message does not reference TODO comments. :param commit_message: Commit message to check. :return: True if any TODOs were found. """ print("*" * 80) print("Checking for TODOs associated with Jira key in commit message.") if "revert" in commit_message.lower(): print("Skipping checks since it looks like this is a revert.") # Reverts are a special case and we shouldn't fail them. return False found_any = False ticket = Todo.get_issue_key_from_line(commit_message) while ticket: found_any = self.report_on_ticket(ticket) or found_any rest_index = commit_message.find(ticket) commit_message = commit_message[rest_index + len(ticket):] ticket = Todo.get_issue_key_from_line(commit_message) print(f"Checking complete - todos found: {found_any}") print("*" * 80) return found_any
[ "def", "validate_commit_queue", "(", "self", ",", "commit_message", ":", "str", ")", "->", "bool", ":", "print", "(", "\"*\"", "*", "80", ")", "print", "(", "\"Checking for TODOs associated with Jira key in commit message.\"", ")", "if", "\"revert\"", "in", "commit_message", ".", "lower", "(", ")", ":", "print", "(", "\"Skipping checks since it looks like this is a revert.\"", ")", "# Reverts are a special case and we shouldn't fail them.", "return", "False", "found_any", "=", "False", "ticket", "=", "Todo", ".", "get_issue_key_from_line", "(", "commit_message", ")", "while", "ticket", ":", "found_any", "=", "self", ".", "report_on_ticket", "(", "ticket", ")", "or", "found_any", "rest_index", "=", "commit_message", ".", "find", "(", "ticket", ")", "commit_message", "=", "commit_message", "[", "rest_index", "+", "len", "(", "ticket", ")", ":", "]", "ticket", "=", "Todo", ".", "get_issue_key_from_line", "(", "commit_message", ")", "print", "(", "f\"Checking complete - todos found: {found_any}\"", ")", "print", "(", "\"*\"", "*", "80", ")", "return", "found_any" ]
https://github.com/mongodb/mongo/blob/d8ff665343ad29cf286ee2cf4a1960d29371937b/buildscripts/todo_check.py#L151-L175
CRYTEK/CRYENGINE
232227c59a220cbbd311576f0fbeba7bb53b2a8c
Tools/CryVersionSelector/cryselect.py
python
error_engine_tool_not_found
(args, path)
Error to specify that a specific engine tool couldn't be found. For example cryrun.exe.
Error to specify that a specific engine tool couldn't be found. For example cryrun.exe.
[ "Error", "to", "specify", "that", "a", "specific", "engine", "tool", "couldn", "t", "be", "found", ".", "For", "example", "cryrun", ".", "exe", "." ]
def error_engine_tool_not_found(args, path): """ Error to specify that a specific engine tool couldn't be found. For example cryrun.exe. """ message = "'{}' not found. Please re-register CRYENGINE version that " \ "includes the required tool.\n".format(path) if not args.silent and HAS_WIN_MODULES: MESSAGEBOX(None, message, command_title(args), win32con.MB_OK | win32con.MB_ICONERROR) else: sys.stderr.write(message) sys.exit(620)
[ "def", "error_engine_tool_not_found", "(", "args", ",", "path", ")", ":", "message", "=", "\"'{}' not found. Please re-register CRYENGINE version that \"", "\"includes the required tool.\\n\"", ".", "format", "(", "path", ")", "if", "not", "args", ".", "silent", "and", "HAS_WIN_MODULES", ":", "MESSAGEBOX", "(", "None", ",", "message", ",", "command_title", "(", "args", ")", ",", "win32con", ".", "MB_OK", "|", "win32con", ".", "MB_ICONERROR", ")", "else", ":", "sys", ".", "stderr", ".", "write", "(", "message", ")", "sys", ".", "exit", "(", "620", ")" ]
https://github.com/CRYTEK/CRYENGINE/blob/232227c59a220cbbd311576f0fbeba7bb53b2a8c/Tools/CryVersionSelector/cryselect.py#L156-L168
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/pandas/py3/pandas/io/parsers/python_parser.py
python
FixedWidthFieldParser._remove_empty_lines
(self, lines)
return [ line for line in lines if any(not isinstance(e, str) or e.strip() for e in line) ]
Returns the list of lines without the empty ones. With fixed-width fields, empty lines become arrays of empty strings. See PythonParser._remove_empty_lines.
Returns the list of lines without the empty ones. With fixed-width fields, empty lines become arrays of empty strings.
[ "Returns", "the", "list", "of", "lines", "without", "the", "empty", "ones", ".", "With", "fixed", "-", "width", "fields", "empty", "lines", "become", "arrays", "of", "empty", "strings", "." ]
def _remove_empty_lines(self, lines) -> list: """ Returns the list of lines without the empty ones. With fixed-width fields, empty lines become arrays of empty strings. See PythonParser._remove_empty_lines. """ return [ line for line in lines if any(not isinstance(e, str) or e.strip() for e in line) ]
[ "def", "_remove_empty_lines", "(", "self", ",", "lines", ")", "->", "list", ":", "return", "[", "line", "for", "line", "in", "lines", "if", "any", "(", "not", "isinstance", "(", "e", ",", "str", ")", "or", "e", ".", "strip", "(", ")", "for", "e", "in", "line", ")", "]" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py3/pandas/io/parsers/python_parser.py#L1215-L1226
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python/src/Tools/compiler/astgen.py
python
strip_default
(arg)
return t
Return the argname from an 'arg = default' string
Return the argname from an 'arg = default' string
[ "Return", "the", "argname", "from", "an", "arg", "=", "default", "string" ]
def strip_default(arg): """Return the argname from an 'arg = default' string""" i = arg.find('=') if i == -1: return arg t = arg[:i].strip() return t
[ "def", "strip_default", "(", "arg", ")", ":", "i", "=", "arg", ".", "find", "(", "'='", ")", "if", "i", "==", "-", "1", ":", "return", "arg", "t", "=", "arg", "[", ":", "i", "]", ".", "strip", "(", ")", "return", "t" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Tools/compiler/astgen.py#L28-L34
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/AWSPythonSDK/1.5.8/docutils/parsers/rst/states.py
python
build_regexp
(definition, compile=True)
Build, compile and return a regular expression based on `definition`. :Parameter: `definition`: a 4-tuple (group name, prefix, suffix, parts), where "parts" is a list of regular expressions and/or regular expression definitions to be joined into an or-group.
Build, compile and return a regular expression based on `definition`.
[ "Build", "compile", "and", "return", "a", "regular", "expression", "based", "on", "definition", "." ]
def build_regexp(definition, compile=True): """ Build, compile and return a regular expression based on `definition`. :Parameter: `definition`: a 4-tuple (group name, prefix, suffix, parts), where "parts" is a list of regular expressions and/or regular expression definitions to be joined into an or-group. """ name, prefix, suffix, parts = definition part_strings = [] for part in parts: if type(part) is tuple: part_strings.append(build_regexp(part, None)) else: part_strings.append(part) or_group = '|'.join(part_strings) regexp = '%(prefix)s(?P<%(name)s>%(or_group)s)%(suffix)s' % locals() if compile: return re.compile(regexp, re.UNICODE) else: return regexp
[ "def", "build_regexp", "(", "definition", ",", "compile", "=", "True", ")", ":", "name", ",", "prefix", ",", "suffix", ",", "parts", "=", "definition", "part_strings", "=", "[", "]", "for", "part", "in", "parts", ":", "if", "type", "(", "part", ")", "is", "tuple", ":", "part_strings", ".", "append", "(", "build_regexp", "(", "part", ",", "None", ")", ")", "else", ":", "part_strings", ".", "append", "(", "part", ")", "or_group", "=", "'|'", ".", "join", "(", "part_strings", ")", "regexp", "=", "'%(prefix)s(?P<%(name)s>%(or_group)s)%(suffix)s'", "%", "locals", "(", ")", "if", "compile", ":", "return", "re", ".", "compile", "(", "regexp", ",", "re", ".", "UNICODE", ")", "else", ":", "return", "regexp" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/AWSPythonSDK/1.5.8/docutils/parsers/rst/states.py#L437-L457
snap-stanford/snap-python
d53c51b0a26aa7e3e7400b014cdf728948fde80a
setup/snap.py
python
CntDegNodes
(*args)
return _snap.CntDegNodes(*args)
CntDegNodes(PNEANet Graph, int const & NodeDeg) -> int Parameters: Graph: TPt< TNEANet > const & NodeDeg: int const &
CntDegNodes(PNEANet Graph, int const & NodeDeg) -> int
[ "CntDegNodes", "(", "PNEANet", "Graph", "int", "const", "&", "NodeDeg", ")", "-", ">", "int" ]
def CntDegNodes(*args): """ CntDegNodes(PNEANet Graph, int const & NodeDeg) -> int Parameters: Graph: TPt< TNEANet > const & NodeDeg: int const & """ return _snap.CntDegNodes(*args)
[ "def", "CntDegNodes", "(", "*", "args", ")", ":", "return", "_snap", ".", "CntDegNodes", "(", "*", "args", ")" ]
https://github.com/snap-stanford/snap-python/blob/d53c51b0a26aa7e3e7400b014cdf728948fde80a/setup/snap.py#L24755-L24764
stitchEm/stitchEm
0f399501d41ab77933677f2907f41f80ceb704d7
lib/bindings/samples/server/debug/systemmonitor.py
python
SystemMonitor.status
(self)
return r
General status of the system components.
General status of the system components.
[ "General", "status", "of", "the", "system", "components", "." ]
def status(self): """General status of the system components. """ r = { 'cpu': utils.performance.getCpuInfo(), 'cuda': utils.performance.getCudaInfo(), 'memory': utils.performance.getMemoryInfo(), 'storage': self.storage(), 'rtmp_server': self.rtmp_server(), } return r
[ "def", "status", "(", "self", ")", ":", "r", "=", "{", "'cpu'", ":", "utils", ".", "performance", ".", "getCpuInfo", "(", ")", ",", "'cuda'", ":", "utils", ".", "performance", ".", "getCudaInfo", "(", ")", ",", "'memory'", ":", "utils", ".", "performance", ".", "getMemoryInfo", "(", ")", ",", "'storage'", ":", "self", ".", "storage", "(", ")", ",", "'rtmp_server'", ":", "self", ".", "rtmp_server", "(", ")", ",", "}", "return", "r" ]
https://github.com/stitchEm/stitchEm/blob/0f399501d41ab77933677f2907f41f80ceb704d7/lib/bindings/samples/server/debug/systemmonitor.py#L45-L55
glotzerlab/hoomd-blue
f7f97abfa3fcc2522fa8d458d65d0aeca7ba781a
hoomd/hpmc/pair/user.py
python
CPPPotentialBase.energy
(self)
return integrator._cpp_obj.computePatchEnergy(timestep)
float: Total interaction energy of the system in the current state. Returns `None` when the patch object and integrator are not attached.
float: Total interaction energy of the system in the current state.
[ "float", ":", "Total", "interaction", "energy", "of", "the", "system", "in", "the", "current", "state", "." ]
def energy(self): """float: Total interaction energy of the system in the current state. Returns `None` when the patch object and integrator are not attached. """ integrator = self._simulation.operations.integrator timestep = self._simulation.timestep return integrator._cpp_obj.computePatchEnergy(timestep)
[ "def", "energy", "(", "self", ")", ":", "integrator", "=", "self", ".", "_simulation", ".", "operations", ".", "integrator", "timestep", "=", "self", ".", "_simulation", ".", "timestep", "return", "integrator", ".", "_cpp_obj", ".", "computePatchEnergy", "(", "timestep", ")" ]
https://github.com/glotzerlab/hoomd-blue/blob/f7f97abfa3fcc2522fa8d458d65d0aeca7ba781a/hoomd/hpmc/pair/user.py#L83-L91
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/richtext.py
python
TextBoxAttr.GetBottom
(*args)
return _richtext.TextBoxAttr_GetBottom(*args)
GetBottom(self) -> TextAttrDimension GetBottom(self) -> TextAttrDimension
GetBottom(self) -> TextAttrDimension GetBottom(self) -> TextAttrDimension
[ "GetBottom", "(", "self", ")", "-", ">", "TextAttrDimension", "GetBottom", "(", "self", ")", "-", ">", "TextAttrDimension" ]
def GetBottom(*args): """ GetBottom(self) -> TextAttrDimension GetBottom(self) -> TextAttrDimension """ return _richtext.TextBoxAttr_GetBottom(*args)
[ "def", "GetBottom", "(", "*", "args", ")", ":", "return", "_richtext", ".", "TextBoxAttr_GetBottom", "(", "*", "args", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/richtext.py#L691-L696
benoitsteiner/tensorflow-opencl
cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5
tensorflow/contrib/tpu/python/tpu/tpu_feed.py
python
InfeedQueue.shard_dimensions
(self)
return [policy.shard_dimension for policy in self._sharding_policies]
Gets the shard dimension of each tuple element. Returns: A list of length number_of_tuple_elements, where each list entry is the shard dimension of that tuple element or None if the shard dimension has not been set.
Gets the shard dimension of each tuple element.
[ "Gets", "the", "shard", "dimension", "of", "each", "tuple", "element", "." ]
def shard_dimensions(self): """Gets the shard dimension of each tuple element. Returns: A list of length number_of_tuple_elements, where each list entry is the shard dimension of that tuple element or None if the shard dimension has not been set. """ # The number of shards is always the same for all the policies. return [policy.shard_dimension for policy in self._sharding_policies]
[ "def", "shard_dimensions", "(", "self", ")", ":", "# The number of shards is always the same for all the policies.", "return", "[", "policy", ".", "shard_dimension", "for", "policy", "in", "self", ".", "_sharding_policies", "]" ]
https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/contrib/tpu/python/tpu/tpu_feed.py#L213-L222
benoitsteiner/tensorflow-opencl
cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5
tensorflow/python/ops/variables.py
python
PartitionedVariable.as_tensor
(self)
Returns the overall concatenated value as a `Tensor`. The returned tensor will not inherit the control dependencies from the scope where the value is used, which is similar to getting the value of `Variable`. Returns: `Tensor` containing the concatenated value.
Returns the overall concatenated value as a `Tensor`.
[ "Returns", "the", "overall", "concatenated", "value", "as", "a", "Tensor", "." ]
def as_tensor(self): """Returns the overall concatenated value as a `Tensor`. The returned tensor will not inherit the control dependencies from the scope where the value is used, which is similar to getting the value of `Variable`. Returns: `Tensor` containing the concatenated value. """ with ops.control_dependencies(None): return self._concat()
[ "def", "as_tensor", "(", "self", ")", ":", "with", "ops", ".", "control_dependencies", "(", "None", ")", ":", "return", "self", ".", "_concat", "(", ")" ]
https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/ops/variables.py#L1180-L1191
papyrussolution/OpenPapyrus
bbfb5ec2ea2109b8e2f125edd838e12eaf7b8b91
Src/OSF/protobuf-3.19.1/python/google/protobuf/internal/well_known_types.py
python
_IsValidPath
(message_descriptor, path)
return last in message_descriptor.fields_by_name
Checks whether the path is valid for Message Descriptor.
Checks whether the path is valid for Message Descriptor.
[ "Checks", "whether", "the", "path", "is", "valid", "for", "Message", "Descriptor", "." ]
def _IsValidPath(message_descriptor, path): """Checks whether the path is valid for Message Descriptor.""" parts = path.split('.') last = parts.pop() for name in parts: field = message_descriptor.fields_by_name.get(name) if (field is None or field.label == FieldDescriptor.LABEL_REPEATED or field.type != FieldDescriptor.TYPE_MESSAGE): return False message_descriptor = field.message_type return last in message_descriptor.fields_by_name
[ "def", "_IsValidPath", "(", "message_descriptor", ",", "path", ")", ":", "parts", "=", "path", ".", "split", "(", "'.'", ")", "last", "=", "parts", ".", "pop", "(", ")", "for", "name", "in", "parts", ":", "field", "=", "message_descriptor", ".", "fields_by_name", ".", "get", "(", "name", ")", "if", "(", "field", "is", "None", "or", "field", ".", "label", "==", "FieldDescriptor", ".", "LABEL_REPEATED", "or", "field", ".", "type", "!=", "FieldDescriptor", ".", "TYPE_MESSAGE", ")", ":", "return", "False", "message_descriptor", "=", "field", ".", "message_type", "return", "last", "in", "message_descriptor", ".", "fields_by_name" ]
https://github.com/papyrussolution/OpenPapyrus/blob/bbfb5ec2ea2109b8e2f125edd838e12eaf7b8b91/Src/OSF/protobuf-3.19.1/python/google/protobuf/internal/well_known_types.py#L497-L508
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
ParserElement.suppress
(self)
return Suppress(self)
Suppresses the output of this :class:`ParserElement`; useful to keep punctuation from cluttering up returned output.
Suppresses the output of this :class:`ParserElement`; useful to keep punctuation from cluttering up returned output.
[ "Suppresses", "the", "output", "of", "this", ":", "class", ":", "ParserElement", ";", "useful", "to", "keep", "punctuation", "from", "cluttering", "up", "returned", "output", "." ]
def suppress(self): """ Suppresses the output of this :class:`ParserElement`; useful to keep punctuation from cluttering up returned output. """ return Suppress(self)
[ "def", "suppress", "(", "self", ")", ":", "return", "Suppress", "(", "self", ")" ]
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#L2434-L2439
mapnik/mapnik
f3da900c355e1d15059c4a91b00203dcc9d9f0ef
scons/scons-local-4.1.0/SCons/Tool/install.py
python
installShlibLinks
(dest, source, env)
return
If we are installing a versioned shared library create the required links.
If we are installing a versioned shared library create the required links.
[ "If", "we", "are", "installing", "a", "versioned", "shared", "library", "create", "the", "required", "links", "." ]
def installShlibLinks(dest, source, env): """If we are installing a versioned shared library create the required links.""" Verbose = False symlinks = listShlibLinksToInstall(dest, source, env) if Verbose: print('installShlibLinks: symlinks={!r}'.format(StringizeLibSymlinks(symlinks))) if symlinks: CreateLibSymlinks(env, symlinks) return
[ "def", "installShlibLinks", "(", "dest", ",", "source", ",", "env", ")", ":", "Verbose", "=", "False", "symlinks", "=", "listShlibLinksToInstall", "(", "dest", ",", "source", ",", "env", ")", "if", "Verbose", ":", "print", "(", "'installShlibLinks: symlinks={!r}'", ".", "format", "(", "StringizeLibSymlinks", "(", "symlinks", ")", ")", ")", "if", "symlinks", ":", "CreateLibSymlinks", "(", "env", ",", "symlinks", ")", "return" ]
https://github.com/mapnik/mapnik/blob/f3da900c355e1d15059c4a91b00203dcc9d9f0ef/scons/scons-local-4.1.0/SCons/Tool/install.py#L211-L219
arangodb/arangodb
0d658689c7d1b721b314fa3ca27d38303e1570c8
3rdParty/V8/v7.9.317/tools/run_perf.py
python
MakeGraphConfig
(suite, arch, parent)
Factory method for making graph configuration objects.
Factory method for making graph configuration objects.
[ "Factory", "method", "for", "making", "graph", "configuration", "objects", "." ]
def MakeGraphConfig(suite, arch, parent): """Factory method for making graph configuration objects.""" if isinstance(parent, RunnableConfig): # Below a runnable can only be traces. return TraceConfig(suite, parent, arch) elif suite.get('main') is not None: # A main file makes this graph runnable. Empty strings are accepted. if suite.get('tests'): # This graph has subgraphs (traces). return RunnableConfig(suite, parent, arch) else: # This graph has no subgraphs, it's a leaf. return RunnableTraceConfig(suite, parent, arch) elif suite.get('tests'): # This is neither a leaf nor a runnable. return GraphConfig(suite, parent, arch) else: # pragma: no cover raise Exception('Invalid suite configuration.')
[ "def", "MakeGraphConfig", "(", "suite", ",", "arch", ",", "parent", ")", ":", "if", "isinstance", "(", "parent", ",", "RunnableConfig", ")", ":", "# Below a runnable can only be traces.", "return", "TraceConfig", "(", "suite", ",", "parent", ",", "arch", ")", "elif", "suite", ".", "get", "(", "'main'", ")", "is", "not", "None", ":", "# A main file makes this graph runnable. Empty strings are accepted.", "if", "suite", ".", "get", "(", "'tests'", ")", ":", "# This graph has subgraphs (traces).", "return", "RunnableConfig", "(", "suite", ",", "parent", ",", "arch", ")", "else", ":", "# This graph has no subgraphs, it's a leaf.", "return", "RunnableTraceConfig", "(", "suite", ",", "parent", ",", "arch", ")", "elif", "suite", ".", "get", "(", "'tests'", ")", ":", "# This is neither a leaf nor a runnable.", "return", "GraphConfig", "(", "suite", ",", "parent", ",", "arch", ")", "else", ":", "# pragma: no cover", "raise", "Exception", "(", "'Invalid suite configuration.'", ")" ]
https://github.com/arangodb/arangodb/blob/0d658689c7d1b721b314fa3ca27d38303e1570c8/3rdParty/V8/v7.9.317/tools/run_perf.py#L526-L543
echronos/echronos
c996f1d2c8af6c6536205eb319c1bf1d4d84569c
external_tools/ply_info/example/BASIC/basparse.py
python
p_statement
(p)
statement : INTEGER command NEWLINE
statement : INTEGER command NEWLINE
[ "statement", ":", "INTEGER", "command", "NEWLINE" ]
def p_statement(p): '''statement : INTEGER command NEWLINE''' if isinstance(p[2],str): print("%s %s %s" % (p[2],"AT LINE", p[1])) p[0] = None p.parser.error = 1 else: lineno = int(p[1]) p[0] = (lineno,p[2])
[ "def", "p_statement", "(", "p", ")", ":", "if", "isinstance", "(", "p", "[", "2", "]", ",", "str", ")", ":", "print", "(", "\"%s %s %s\"", "%", "(", "p", "[", "2", "]", ",", "\"AT LINE\"", ",", "p", "[", "1", "]", ")", ")", "p", "[", "0", "]", "=", "None", "p", ".", "parser", ".", "error", "=", "1", "else", ":", "lineno", "=", "int", "(", "p", "[", "1", "]", ")", "p", "[", "0", "]", "=", "(", "lineno", ",", "p", "[", "2", "]", ")" ]
https://github.com/echronos/echronos/blob/c996f1d2c8af6c6536205eb319c1bf1d4d84569c/external_tools/ply_info/example/BASIC/basparse.py#L44-L52
eclipse/sumo
7132a9b8b6eea734bdec38479026b4d8c4336d03
tools/contributed/sumopy/agilepy/lib_base/xmlman.py
python
write_obj_to_xml
(obj, filepath, encoding='UTF-8', # 'iso-8859-1' )
Universal xml writer for objects
Universal xml writer for objects
[ "Universal", "xml", "writer", "for", "objects" ]
def write_obj_to_xml(obj, filepath, encoding='UTF-8', # 'iso-8859-1' ): """ Universal xml writer for objects """ try: fd = open(filepath, 'w') except: print 'WARNING in write_obj_to_xml: could not open', filepath return False fd.write('<?xml version="1.0" encoding="%s"?>\n' % encoding) indent = 0 obj.write_xml(fd, indent) fd.close()
[ "def", "write_obj_to_xml", "(", "obj", ",", "filepath", ",", "encoding", "=", "'UTF-8'", ",", "# 'iso-8859-1'", ")", ":", "try", ":", "fd", "=", "open", "(", "filepath", ",", "'w'", ")", "except", ":", "print", "'WARNING in write_obj_to_xml: could not open'", ",", "filepath", "return", "False", "fd", ".", "write", "(", "'<?xml version=\"1.0\" encoding=\"%s\"?>\\n'", "%", "encoding", ")", "indent", "=", "0", "obj", ".", "write_xml", "(", "fd", ",", "indent", ")", "fd", ".", "close", "(", ")" ]
https://github.com/eclipse/sumo/blob/7132a9b8b6eea734bdec38479026b4d8c4336d03/tools/contributed/sumopy/agilepy/lib_base/xmlman.py#L25-L39
microsoft/ELL
a1d6bacc37a14879cc025d9be2ba40b1a0632315
tools/utilities/pythonlibs/audio/training/make_featurizer.py
python
make_featurizer
(output_filename, sample_rate, window_size, input_buffer_size, filterbank_type, filterbank_size, pre_emphasis=0.97, nfft=None, iir_node=False, log_node=False, dct_node=False, power_spec=False, log_delta=1.0, filterbank_nfft=None, hamming_window=False, auto_scale=False)
return output_filename
Create a new featurizer ELL model: output_filename - the output ELL model file name sample_rate - the sample rate of the audio window_size - the featurizer input window size input_buffer_size - the size of the buffer node to use filterbank_type - the type of filter bank to use (e.g. 'mel', 'linear' or 'none') nfft - the size of the FFT (defaults to input size) filterbank_size - the number of filters to use iir_node - whether to insert an IIR filter node log_node - whether to append a logarithm node dct_node - whether to include a DCT node in the model filterbank_nfft - allows you to override the nfft parameter on the MelFilterBank (for testing only)
Create a new featurizer ELL model: output_filename - the output ELL model file name sample_rate - the sample rate of the audio window_size - the featurizer input window size input_buffer_size - the size of the buffer node to use filterbank_type - the type of filter bank to use (e.g. 'mel', 'linear' or 'none') nfft - the size of the FFT (defaults to input size) filterbank_size - the number of filters to use iir_node - whether to insert an IIR filter node log_node - whether to append a logarithm node dct_node - whether to include a DCT node in the model filterbank_nfft - allows you to override the nfft parameter on the MelFilterBank (for testing only)
[ "Create", "a", "new", "featurizer", "ELL", "model", ":", "output_filename", "-", "the", "output", "ELL", "model", "file", "name", "sample_rate", "-", "the", "sample", "rate", "of", "the", "audio", "window_size", "-", "the", "featurizer", "input", "window", "size", "input_buffer_size", "-", "the", "size", "of", "the", "buffer", "node", "to", "use", "filterbank_type", "-", "the", "type", "of", "filter", "bank", "to", "use", "(", "e", ".", "g", ".", "mel", "linear", "or", "none", ")", "nfft", "-", "the", "size", "of", "the", "FFT", "(", "defaults", "to", "input", "size", ")", "filterbank_size", "-", "the", "number", "of", "filters", "to", "use", "iir_node", "-", "whether", "to", "insert", "an", "IIR", "filter", "node", "log_node", "-", "whether", "to", "append", "a", "logarithm", "node", "dct_node", "-", "whether", "to", "include", "a", "DCT", "node", "in", "the", "model", "filterbank_nfft", "-", "allows", "you", "to", "override", "the", "nfft", "parameter", "on", "the", "MelFilterBank", "(", "for", "testing", "only", ")" ]
def make_featurizer(output_filename, sample_rate, window_size, input_buffer_size, filterbank_type, filterbank_size, pre_emphasis=0.97, nfft=None, iir_node=False, log_node=False, dct_node=False, power_spec=False, log_delta=1.0, filterbank_nfft=None, hamming_window=False, auto_scale=False): """ Create a new featurizer ELL model: output_filename - the output ELL model file name sample_rate - the sample rate of the audio window_size - the featurizer input window size input_buffer_size - the size of the buffer node to use filterbank_type - the type of filter bank to use (e.g. 'mel', 'linear' or 'none') nfft - the size of the FFT (defaults to input size) filterbank_size - the number of filters to use iir_node - whether to insert an IIR filter node log_node - whether to append a logarithm node dct_node - whether to include a DCT node in the model filterbank_nfft - allows you to override the nfft parameter on the MelFilterBank (for testing only) """ # Create output directory if necessary output_directory = os.path.dirname(output_filename) if output_directory and not os.path.isdir(output_directory): os.makedirs(output_directory) map = _create_model(sample_rate, window_size, input_buffer_size, filterbank_type, filterbank_size, pre_emphasis, nfft, iir_node, log_node, dct_node, power_spec, log_delta, filterbank_nfft, hamming_window, auto_scale) # print("Saving model {}".format(output_filename)) map.Save(output_filename) print("Saved {}".format(output_filename)) return output_filename
[ "def", "make_featurizer", "(", "output_filename", ",", "sample_rate", ",", "window_size", ",", "input_buffer_size", ",", "filterbank_type", ",", "filterbank_size", ",", "pre_emphasis", "=", "0.97", ",", "nfft", "=", "None", ",", "iir_node", "=", "False", ",", "log_node", "=", "False", ",", "dct_node", "=", "False", ",", "power_spec", "=", "False", ",", "log_delta", "=", "1.0", ",", "filterbank_nfft", "=", "None", ",", "hamming_window", "=", "False", ",", "auto_scale", "=", "False", ")", ":", "# Create output directory if necessary", "output_directory", "=", "os", ".", "path", ".", "dirname", "(", "output_filename", ")", "if", "output_directory", "and", "not", "os", ".", "path", ".", "isdir", "(", "output_directory", ")", ":", "os", ".", "makedirs", "(", "output_directory", ")", "map", "=", "_create_model", "(", "sample_rate", ",", "window_size", ",", "input_buffer_size", ",", "filterbank_type", ",", "filterbank_size", ",", "pre_emphasis", ",", "nfft", ",", "iir_node", ",", "log_node", ",", "dct_node", ",", "power_spec", ",", "log_delta", ",", "filterbank_nfft", ",", "hamming_window", ",", "auto_scale", ")", "# print(\"Saving model {}\".format(output_filename))", "map", ".", "Save", "(", "output_filename", ")", "print", "(", "\"Saved {}\"", ".", "format", "(", "output_filename", ")", ")", "return", "output_filename" ]
https://github.com/microsoft/ELL/blob/a1d6bacc37a14879cc025d9be2ba40b1a0632315/tools/utilities/pythonlibs/audio/training/make_featurizer.py#L134-L164
PaddlePaddle/Paddle
1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c
python/paddle/distributed/fleet/utils/http_server.py
python
KVServer.__init__
(self, port, size={})
Init.
Init.
[ "Init", "." ]
def __init__(self, port, size={}): """Init.""" self.http_server = KVHTTPServer(port, KVHandler) self.listen_thread = None self.size = size
[ "def", "__init__", "(", "self", ",", "port", ",", "size", "=", "{", "}", ")", ":", "self", ".", "http_server", "=", "KVHTTPServer", "(", "port", ",", "KVHandler", ")", "self", ".", "listen_thread", "=", "None", "self", ".", "size", "=", "size" ]
https://github.com/PaddlePaddle/Paddle/blob/1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c/python/paddle/distributed/fleet/utils/http_server.py#L161-L165
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/idlelib/configdialog.py
python
GenPage.update_help_changes
(self)
Clear and rebuild the HelpFiles section in changes
Clear and rebuild the HelpFiles section in changes
[ "Clear", "and", "rebuild", "the", "HelpFiles", "section", "in", "changes" ]
def update_help_changes(self): "Clear and rebuild the HelpFiles section in changes" changes['main']['HelpFiles'] = {} for num in range(1, len(self.user_helplist) + 1): changes.add_option( 'main', 'HelpFiles', str(num), ';'.join(self.user_helplist[num-1][:2]))
[ "def", "update_help_changes", "(", "self", ")", ":", "changes", "[", "'main'", "]", "[", "'HelpFiles'", "]", "=", "{", "}", "for", "num", "in", "range", "(", "1", ",", "len", "(", "self", ".", "user_helplist", ")", "+", "1", ")", ":", "changes", ".", "add_option", "(", "'main'", ",", "'HelpFiles'", ",", "str", "(", "num", ")", ",", "';'", ".", "join", "(", "self", ".", "user_helplist", "[", "num", "-", "1", "]", "[", ":", "2", "]", ")", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/idlelib/configdialog.py#L2188-L2194
google/mysql-protobuf
467cda676afaa49e762c5c9164a43f6ad31a1fbf
protobuf/python/mox.py
python
StrContains.__init__
(self, search_string)
Initialize. Args: # search_string: the string you are searching for search_string: str
Initialize.
[ "Initialize", "." ]
def __init__(self, search_string): """Initialize. Args: # search_string: the string you are searching for search_string: str """ self._search_string = search_string
[ "def", "__init__", "(", "self", ",", "search_string", ")", ":", "self", ".", "_search_string", "=", "search_string" ]
https://github.com/google/mysql-protobuf/blob/467cda676afaa49e762c5c9164a43f6ad31a1fbf/protobuf/python/mox.py#L874-L882
modm-io/modm
845840ec08566a3aa9c04167b1a18a56255afa4f
tools/xpcc_generator/xmlparser/component.py
python
ComponentDictionary.__iter__
(self)
return self.iter(None)
Generates an iterator that will iterate over all non abstract components
Generates an iterator that will iterate over all non abstract components
[ "Generates", "an", "iterator", "that", "will", "iterate", "over", "all", "non", "abstract", "components" ]
def __iter__(self): """ Generates an iterator that will iterate over all non abstract components """ return self.iter(None)
[ "def", "__iter__", "(", "self", ")", ":", "return", "self", ".", "iter", "(", "None", ")" ]
https://github.com/modm-io/modm/blob/845840ec08566a3aa9c04167b1a18a56255afa4f/tools/xpcc_generator/xmlparser/component.py#L111-L113
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python/src/Lib/idlelib/tabbedpages.py
python
TabSet.remove_tab
(self, tab_name)
Remove the tab named <tab_name>
Remove the tab named <tab_name>
[ "Remove", "the", "tab", "named", "<tab_name", ">" ]
def remove_tab(self, tab_name): """Remove the tab named <tab_name>""" if not tab_name in self._tab_names: raise KeyError("No such Tab: '%s" % page_name) self._tab_names.remove(tab_name) self._arrange_tabs()
[ "def", "remove_tab", "(", "self", ",", "tab_name", ")", ":", "if", "not", "tab_name", "in", "self", ".", "_tab_names", ":", "raise", "KeyError", "(", "\"No such Tab: '%s\"", "%", "page_name", ")", "self", ".", "_tab_names", ".", "remove", "(", "tab_name", ")", "self", ".", "_arrange_tabs", "(", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/idlelib/tabbedpages.py#L78-L84
stellar-deprecated/stellard
67eabb2217bdfa9a6ea317f62338fb6bca458c90
src/beast/python/beast/util/String.py
python
single_line
(line, report_errors=True, joiner='+')
return joiner.join(lines)
Force a string to be a single line with no carriage returns, and report a warning if there was more than one line.
Force a string to be a single line with no carriage returns, and report a warning if there was more than one line.
[ "Force", "a", "string", "to", "be", "a", "single", "line", "with", "no", "carriage", "returns", "and", "report", "a", "warning", "if", "there", "was", "more", "than", "one", "line", "." ]
def single_line(line, report_errors=True, joiner='+'): """Force a string to be a single line with no carriage returns, and report a warning if there was more than one line.""" lines = line.strip().splitlines() if report_errors and len(lines) > 1: print('multiline result:', lines) return joiner.join(lines)
[ "def", "single_line", "(", "line", ",", "report_errors", "=", "True", ",", "joiner", "=", "'+'", ")", ":", "lines", "=", "line", ".", "strip", "(", ")", ".", "splitlines", "(", ")", "if", "report_errors", "and", "len", "(", "lines", ")", ">", "1", ":", "print", "(", "'multiline result:'", ",", "lines", ")", "return", "joiner", ".", "join", "(", "lines", ")" ]
https://github.com/stellar-deprecated/stellard/blob/67eabb2217bdfa9a6ea317f62338fb6bca458c90/src/beast/python/beast/util/String.py#L23-L29
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/x86/toolchain/lib/python2.7/lib-tk/Tkinter.py
python
Grid.grid_info
(self)
return dict
Return information about the options for positioning this widget in a grid.
Return information about the options for positioning this widget in a grid.
[ "Return", "information", "about", "the", "options", "for", "positioning", "this", "widget", "in", "a", "grid", "." ]
def grid_info(self): """Return information about the options for positioning this widget in a grid.""" words = self.tk.splitlist( self.tk.call('grid', 'info', self._w)) dict = {} for i in range(0, len(words), 2): key = words[i][1:] value = words[i+1] if value[:1] == '.': value = self._nametowidget(value) dict[key] = value return dict
[ "def", "grid_info", "(", "self", ")", ":", "words", "=", "self", ".", "tk", ".", "splitlist", "(", "self", ".", "tk", ".", "call", "(", "'grid'", ",", "'info'", ",", "self", ".", "_w", ")", ")", "dict", "=", "{", "}", "for", "i", "in", "range", "(", "0", ",", "len", "(", "words", ")", ",", "2", ")", ":", "key", "=", "words", "[", "i", "]", "[", "1", ":", "]", "value", "=", "words", "[", "i", "+", "1", "]", "if", "value", "[", ":", "1", "]", "==", "'.'", ":", "value", "=", "self", ".", "_nametowidget", "(", "value", ")", "dict", "[", "key", "]", "=", "value", "return", "dict" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/lib-tk/Tkinter.py#L1974-L1986
oracle/graaljs
36a56e8e993d45fc40939a3a4d9c0c24990720f1
graal-nodejs/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/eclipse.py
python
GenerateClasspathFile
( target_list, target_dicts, toplevel_dir, toplevel_build, out_name )
Generates a classpath file suitable for symbol navigation and code completion of Java code (such as in Android projects) by finding all .java and .jar files used as action inputs.
Generates a classpath file suitable for symbol navigation and code completion of Java code (such as in Android projects) by finding all .java and .jar files used as action inputs.
[ "Generates", "a", "classpath", "file", "suitable", "for", "symbol", "navigation", "and", "code", "completion", "of", "Java", "code", "(", "such", "as", "in", "Android", "projects", ")", "by", "finding", "all", ".", "java", "and", ".", "jar", "files", "used", "as", "action", "inputs", "." ]
def GenerateClasspathFile( target_list, target_dicts, toplevel_dir, toplevel_build, out_name ): """Generates a classpath file suitable for symbol navigation and code completion of Java code (such as in Android projects) by finding all .java and .jar files used as action inputs.""" gyp.common.EnsureDirExists(out_name) result = ET.Element("classpath") def AddElements(kind, paths): # First, we need to normalize the paths so they are all relative to the # toplevel dir. rel_paths = set() for path in paths: if os.path.isabs(path): rel_paths.add(os.path.relpath(path, toplevel_dir)) else: rel_paths.add(path) for path in sorted(rel_paths): entry_element = ET.SubElement(result, "classpathentry") entry_element.set("kind", kind) entry_element.set("path", path) AddElements("lib", GetJavaJars(target_list, target_dicts, toplevel_dir)) AddElements("src", GetJavaSourceDirs(target_list, target_dicts, toplevel_dir)) # Include the standard JRE container and a dummy out folder AddElements("con", ["org.eclipse.jdt.launching.JRE_CONTAINER"]) # Include a dummy out folder so that Eclipse doesn't use the default /bin # folder in the root of the project. AddElements("output", [os.path.join(toplevel_build, ".eclipse-java-build")]) ET.ElementTree(result).write(out_name)
[ "def", "GenerateClasspathFile", "(", "target_list", ",", "target_dicts", ",", "toplevel_dir", ",", "toplevel_build", ",", "out_name", ")", ":", "gyp", ".", "common", ".", "EnsureDirExists", "(", "out_name", ")", "result", "=", "ET", ".", "Element", "(", "\"classpath\"", ")", "def", "AddElements", "(", "kind", ",", "paths", ")", ":", "# First, we need to normalize the paths so they are all relative to the", "# toplevel dir.", "rel_paths", "=", "set", "(", ")", "for", "path", "in", "paths", ":", "if", "os", ".", "path", ".", "isabs", "(", "path", ")", ":", "rel_paths", ".", "add", "(", "os", ".", "path", ".", "relpath", "(", "path", ",", "toplevel_dir", ")", ")", "else", ":", "rel_paths", ".", "add", "(", "path", ")", "for", "path", "in", "sorted", "(", "rel_paths", ")", ":", "entry_element", "=", "ET", ".", "SubElement", "(", "result", ",", "\"classpathentry\"", ")", "entry_element", ".", "set", "(", "\"kind\"", ",", "kind", ")", "entry_element", ".", "set", "(", "\"path\"", ",", "path", ")", "AddElements", "(", "\"lib\"", ",", "GetJavaJars", "(", "target_list", ",", "target_dicts", ",", "toplevel_dir", ")", ")", "AddElements", "(", "\"src\"", ",", "GetJavaSourceDirs", "(", "target_list", ",", "target_dicts", ",", "toplevel_dir", ")", ")", "# Include the standard JRE container and a dummy out folder", "AddElements", "(", "\"con\"", ",", "[", "\"org.eclipse.jdt.launching.JRE_CONTAINER\"", "]", ")", "# Include a dummy out folder so that Eclipse doesn't use the default /bin", "# folder in the root of the project.", "AddElements", "(", "\"output\"", ",", "[", "os", ".", "path", ".", "join", "(", "toplevel_build", ",", "\".eclipse-java-build\"", ")", "]", ")", "ET", ".", "ElementTree", "(", "result", ")", ".", "write", "(", "out_name", ")" ]
https://github.com/oracle/graaljs/blob/36a56e8e993d45fc40939a3a4d9c0c24990720f1/graal-nodejs/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/eclipse.py#L374-L406
scribusproject/scribus
41ec7c775a060912cf251682a8b1437f753f80f4
scribus/plugins/scriptplugin/scripts/CalendarWizard.py
python
ScVerticalCalendar.setupMasterPage
(self)
Draw invariant calendar header: Days of the week
Draw invariant calendar header: Days of the week
[ "Draw", "invariant", "calendar", "header", ":", "Days", "of", "the", "week" ]
def setupMasterPage(self): """ Draw invariant calendar header: Days of the week """ createMasterPage(self.masterPage) editMasterPage(self.masterPage) setActiveLayer(self.layerCal) rowCnt = 0 for j in self.dayOrder: # days cel = createText(self.marginl + rowCnt*self.colSize, self.calHeight + self.rowSize, self.colSize, self.rowSize) setText(j, cel) setStyle(self.pStyleWeekday, cel) rowCnt+=1 closeMasterPage()
[ "def", "setupMasterPage", "(", "self", ")", ":", "createMasterPage", "(", "self", ".", "masterPage", ")", "editMasterPage", "(", "self", ".", "masterPage", ")", "setActiveLayer", "(", "self", ".", "layerCal", ")", "rowCnt", "=", "0", "for", "j", "in", "self", ".", "dayOrder", ":", "# days", "cel", "=", "createText", "(", "self", ".", "marginl", "+", "rowCnt", "*", "self", ".", "colSize", ",", "self", ".", "calHeight", "+", "self", ".", "rowSize", ",", "self", ".", "colSize", ",", "self", ".", "rowSize", ")", "setText", "(", "j", ",", "cel", ")", "setStyle", "(", "self", ".", "pStyleWeekday", ",", "cel", ")", "rowCnt", "+=", "1", "closeMasterPage", "(", ")" ]
https://github.com/scribusproject/scribus/blob/41ec7c775a060912cf251682a8b1437f753f80f4/scribus/plugins/scriptplugin/scripts/CalendarWizard.py#L403-L416
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/lib-tk/turtle.py
python
TurtleScreen._incrementudc
(self)
Increment upadate counter.
Increment upadate counter.
[ "Increment", "upadate", "counter", "." ]
def _incrementudc(self): """Increment upadate counter.""" if not TurtleScreen._RUNNING: TurtleScreen._RUNNNING = True raise Terminator if self._tracing > 0: self._updatecounter += 1 self._updatecounter %= self._tracing
[ "def", "_incrementudc", "(", "self", ")", ":", "if", "not", "TurtleScreen", ".", "_RUNNING", ":", "TurtleScreen", ".", "_RUNNNING", "=", "True", "raise", "Terminator", "if", "self", ".", "_tracing", ">", "0", ":", "self", ".", "_updatecounter", "+=", "1", "self", ".", "_updatecounter", "%=", "self", ".", "_tracing" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/lib-tk/turtle.py#L1235-L1242
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/autograph/operators/logical.py
python
and_
(a, b)
return _py_lazy_and(a_val, b)
Functional form of "and". Uses lazy evaluation semantics.
Functional form of "and". Uses lazy evaluation semantics.
[ "Functional", "form", "of", "and", ".", "Uses", "lazy", "evaluation", "semantics", "." ]
def and_(a, b): """Functional form of "and". Uses lazy evaluation semantics.""" a_val = a() if tensor_util.is_tf_type(a_val): return _tf_lazy_and(a_val, b) return _py_lazy_and(a_val, b)
[ "def", "and_", "(", "a", ",", "b", ")", ":", "a_val", "=", "a", "(", ")", "if", "tensor_util", ".", "is_tf_type", "(", "a_val", ")", ":", "return", "_tf_lazy_and", "(", "a_val", ",", "b", ")", "return", "_py_lazy_and", "(", "a_val", ",", "b", ")" ]
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/autograph/operators/logical.py#L39-L44
miyosuda/TensorFlowAndroidMNIST
7b5a4603d2780a8a2834575706e9001977524007
jni-build/jni/include/tensorflow/contrib/framework/python/ops/variables.py
python
assign_from_checkpoint
(model_path, var_list)
return assign_op, feed_dict
Creates an operation to assign specific variables from a checkpoint. Args: model_path: The full path to the model checkpoint. To get latest checkpoint use `model_path = tf.train.latest_checkpoint(checkpoint_dir)` var_list: A list of `Variable` objects or a dictionary mapping names in the checkpoint to the correspoing variables to initialize. If empty or None, it would return no_op(), None. Returns: the restore_op and the feed_dict that need to be run to restore var_list. Raises: ValueError: If the checkpoint specified at `model_path` is missing one of the variables in `var_list`.
Creates an operation to assign specific variables from a checkpoint.
[ "Creates", "an", "operation", "to", "assign", "specific", "variables", "from", "a", "checkpoint", "." ]
def assign_from_checkpoint(model_path, var_list): """Creates an operation to assign specific variables from a checkpoint. Args: model_path: The full path to the model checkpoint. To get latest checkpoint use `model_path = tf.train.latest_checkpoint(checkpoint_dir)` var_list: A list of `Variable` objects or a dictionary mapping names in the checkpoint to the correspoing variables to initialize. If empty or None, it would return no_op(), None. Returns: the restore_op and the feed_dict that need to be run to restore var_list. Raises: ValueError: If the checkpoint specified at `model_path` is missing one of the variables in `var_list`. """ reader = pywrap_tensorflow.NewCheckpointReader(model_path) if isinstance(var_list, (tuple, list)): var_list = {var.op.name: var for var in var_list} feed_dict = {} assign_ops = [] for checkpoint_var_name in var_list: var = var_list[checkpoint_var_name] if not reader.has_tensor(checkpoint_var_name): raise ValueError( 'Checkpoint is missing variable [%s]' % checkpoint_var_name) var_value = reader.get_tensor(checkpoint_var_name) placeholder_name = 'placeholder/' + var.op.name placeholder_value = array_ops.placeholder( dtype=var.dtype.base_dtype, shape=var.get_shape(), name=placeholder_name) assign_ops.append(var.assign(placeholder_value)) feed_dict[placeholder_value] = var_value.reshape(var.get_shape()) assign_op = control_flow_ops.group(*assign_ops) return assign_op, feed_dict
[ "def", "assign_from_checkpoint", "(", "model_path", ",", "var_list", ")", ":", "reader", "=", "pywrap_tensorflow", ".", "NewCheckpointReader", "(", "model_path", ")", "if", "isinstance", "(", "var_list", ",", "(", "tuple", ",", "list", ")", ")", ":", "var_list", "=", "{", "var", ".", "op", ".", "name", ":", "var", "for", "var", "in", "var_list", "}", "feed_dict", "=", "{", "}", "assign_ops", "=", "[", "]", "for", "checkpoint_var_name", "in", "var_list", ":", "var", "=", "var_list", "[", "checkpoint_var_name", "]", "if", "not", "reader", ".", "has_tensor", "(", "checkpoint_var_name", ")", ":", "raise", "ValueError", "(", "'Checkpoint is missing variable [%s]'", "%", "checkpoint_var_name", ")", "var_value", "=", "reader", ".", "get_tensor", "(", "checkpoint_var_name", ")", "placeholder_name", "=", "'placeholder/'", "+", "var", ".", "op", ".", "name", "placeholder_value", "=", "array_ops", ".", "placeholder", "(", "dtype", "=", "var", ".", "dtype", ".", "base_dtype", ",", "shape", "=", "var", ".", "get_shape", "(", ")", ",", "name", "=", "placeholder_name", ")", "assign_ops", ".", "append", "(", "var", ".", "assign", "(", "placeholder_value", ")", ")", "feed_dict", "[", "placeholder_value", "]", "=", "var_value", ".", "reshape", "(", "var", ".", "get_shape", "(", ")", ")", "assign_op", "=", "control_flow_ops", ".", "group", "(", "*", "assign_ops", ")", "return", "assign_op", ",", "feed_dict" ]
https://github.com/miyosuda/TensorFlowAndroidMNIST/blob/7b5a4603d2780a8a2834575706e9001977524007/jni-build/jni/include/tensorflow/contrib/framework/python/ops/variables.py#L465-L507
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scipy/scipy/linalg/_interpolative_backend.py
python
idzp_asvd
(eps, A)
return U, V, S
Compute SVD of a complex matrix to a specified relative precision using random sampling. :param eps: Relative precision. :type eps: float :param A: Matrix. :type A: :class:`numpy.ndarray` :return: Left singular vectors. :rtype: :class:`numpy.ndarray` :return: Right singular vectors. :rtype: :class:`numpy.ndarray` :return: Singular values. :rtype: :class:`numpy.ndarray`
Compute SVD of a complex matrix to a specified relative precision using random sampling.
[ "Compute", "SVD", "of", "a", "complex", "matrix", "to", "a", "specified", "relative", "precision", "using", "random", "sampling", "." ]
def idzp_asvd(eps, A): """ Compute SVD of a complex matrix to a specified relative precision using random sampling. :param eps: Relative precision. :type eps: float :param A: Matrix. :type A: :class:`numpy.ndarray` :return: Left singular vectors. :rtype: :class:`numpy.ndarray` :return: Right singular vectors. :rtype: :class:`numpy.ndarray` :return: Singular values. :rtype: :class:`numpy.ndarray` """ A = np.asfortranarray(A) m, n = A.shape n2, winit = _id.idz_frmi(m) w = np.empty( max((min(m, n) + 1)*(3*m + 5*n + 11) + 8*min(m, n)**2, (2*n + 1)*(n2 + 1)), dtype=np.complex128, order='F') k, iU, iV, iS, w, ier = _id.idzp_asvd(eps, A, winit, w) if ier: raise _RETCODE_ERROR U = w[iU-1:iU+m*k-1].reshape((m, k), order='F') V = w[iV-1:iV+n*k-1].reshape((n, k), order='F') S = w[iS-1:iS+k-1] return U, V, S
[ "def", "idzp_asvd", "(", "eps", ",", "A", ")", ":", "A", "=", "np", ".", "asfortranarray", "(", "A", ")", "m", ",", "n", "=", "A", ".", "shape", "n2", ",", "winit", "=", "_id", ".", "idz_frmi", "(", "m", ")", "w", "=", "np", ".", "empty", "(", "max", "(", "(", "min", "(", "m", ",", "n", ")", "+", "1", ")", "*", "(", "3", "*", "m", "+", "5", "*", "n", "+", "11", ")", "+", "8", "*", "min", "(", "m", ",", "n", ")", "**", "2", ",", "(", "2", "*", "n", "+", "1", ")", "*", "(", "n2", "+", "1", ")", ")", ",", "dtype", "=", "np", ".", "complex128", ",", "order", "=", "'F'", ")", "k", ",", "iU", ",", "iV", ",", "iS", ",", "w", ",", "ier", "=", "_id", ".", "idzp_asvd", "(", "eps", ",", "A", ",", "winit", ",", "w", ")", "if", "ier", ":", "raise", "_RETCODE_ERROR", "U", "=", "w", "[", "iU", "-", "1", ":", "iU", "+", "m", "*", "k", "-", "1", "]", ".", "reshape", "(", "(", "m", ",", "k", ")", ",", "order", "=", "'F'", ")", "V", "=", "w", "[", "iV", "-", "1", ":", "iV", "+", "n", "*", "k", "-", "1", "]", ".", "reshape", "(", "(", "n", ",", "k", ")", ",", "order", "=", "'F'", ")", "S", "=", "w", "[", "iS", "-", "1", ":", "iS", "+", "k", "-", "1", "]", "return", "U", ",", "V", ",", "S" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/scipy/linalg/_interpolative_backend.py#L1339-L1374
weolar/miniblink49
1c4678db0594a4abde23d3ebbcc7cd13c3170777
third_party/skia/make.py
python
CheckWindowsEnvironment
()
For Windows: check environment variables needed for command-line build. If those environment variables are missing, try to set them. If environment variables can be set up, this function returns; otherwise, it displays an error message and exits.
For Windows: check environment variables needed for command-line build.
[ "For", "Windows", ":", "check", "environment", "variables", "needed", "for", "command", "-", "line", "build", "." ]
def CheckWindowsEnvironment(): """For Windows: check environment variables needed for command-line build. If those environment variables are missing, try to set them. If environment variables can be set up, this function returns; otherwise, it displays an error message and exits. """ # If we already have the proper environment variables, nothing to do here. if os.environ.get('DevEnvDir'): return print ('\nCould not find Visual Studio environment variables.' '\nPerhaps you have not yet run vcvars32.bat as described at' '\nhttp://msdn.microsoft.com/en-us/library/f2ccy3wt.aspx ?') found_path = None try: possible_path = os.path.abspath(os.path.join( os.environ['VS100COMNTOOLS'], os.path.pardir, os.path.pardir, 'VC', 'bin', 'vcvars32.bat')) if os.path.exists(possible_path): found_path = possible_path except KeyError: pass if found_path: print '\nIt looks like you can run that script at:\n%s' % found_path else: print '\nUnable to find vcvars32.bat on your system.' sys.exit(1)
[ "def", "CheckWindowsEnvironment", "(", ")", ":", "# If we already have the proper environment variables, nothing to do here.", "if", "os", ".", "environ", ".", "get", "(", "'DevEnvDir'", ")", ":", "return", "print", "(", "'\\nCould not find Visual Studio environment variables.'", "'\\nPerhaps you have not yet run vcvars32.bat as described at'", "'\\nhttp://msdn.microsoft.com/en-us/library/f2ccy3wt.aspx ?'", ")", "found_path", "=", "None", "try", ":", "possible_path", "=", "os", ".", "path", ".", "abspath", "(", "os", ".", "path", ".", "join", "(", "os", ".", "environ", "[", "'VS100COMNTOOLS'", "]", ",", "os", ".", "path", ".", "pardir", ",", "os", ".", "path", ".", "pardir", ",", "'VC'", ",", "'bin'", ",", "'vcvars32.bat'", ")", ")", "if", "os", ".", "path", ".", "exists", "(", "possible_path", ")", ":", "found_path", "=", "possible_path", "except", "KeyError", ":", "pass", "if", "found_path", ":", "print", "'\\nIt looks like you can run that script at:\\n%s'", "%", "found_path", "else", ":", "print", "'\\nUnable to find vcvars32.bat on your system.'", "sys", ".", "exit", "(", "1", ")" ]
https://github.com/weolar/miniblink49/blob/1c4678db0594a4abde23d3ebbcc7cd13c3170777/third_party/skia/make.py#L56-L83
zachriggle/ida-splode
a4aee3be415b318a0e051a523ebd0a8d6d5e0026
py/idasplode/addr.py
python
ModuleImports
()
return Imports
Returns: List of all imported routines from the import section
Returns: List of all imported routines from the import section
[ "Returns", ":", "List", "of", "all", "imported", "routines", "from", "the", "import", "section" ]
def ModuleImports(): """Returns: List of all imported routines from the import section """ Imports = {} def Callback(ea, n, ordinal): n = name.DemangleShort(n) Imports.update({n:ea}) return 1 for n in xrange(ida.get_import_module_qty()): ida.enum_import_names(n, Callback) return Imports
[ "def", "ModuleImports", "(", ")", ":", "Imports", "=", "{", "}", "def", "Callback", "(", "ea", ",", "n", ",", "ordinal", ")", ":", "n", "=", "name", ".", "DemangleShort", "(", "n", ")", "Imports", ".", "update", "(", "{", "n", ":", "ea", "}", ")", "return", "1", "for", "n", "in", "xrange", "(", "ida", ".", "get_import_module_qty", "(", ")", ")", ":", "ida", ".", "enum_import_names", "(", "n", ",", "Callback", ")", "return", "Imports" ]
https://github.com/zachriggle/ida-splode/blob/a4aee3be415b318a0e051a523ebd0a8d6d5e0026/py/idasplode/addr.py#L13-L27
kushview/Element
1cc16380caa2ab79461246ba758b9de1f46db2a5
waflib/extras/cython.py
python
cython.runnable_status
(self)
return super(cython, self).runnable_status()
Perform a double-check to add the headers created by cython to the output nodes. The scanner is executed only when the cython task must be executed (optimization).
Perform a double-check to add the headers created by cython to the output nodes. The scanner is executed only when the cython task must be executed (optimization).
[ "Perform", "a", "double", "-", "check", "to", "add", "the", "headers", "created", "by", "cython", "to", "the", "output", "nodes", ".", "The", "scanner", "is", "executed", "only", "when", "the", "cython", "task", "must", "be", "executed", "(", "optimization", ")", "." ]
def runnable_status(self): """ Perform a double-check to add the headers created by cython to the output nodes. The scanner is executed only when the cython task must be executed (optimization). """ ret = super(cython, self).runnable_status() if ret == Task.ASK_LATER: return ret for x in self.generator.bld.raw_deps[self.uid()]: if x.startswith('header:'): self.outputs.append(self.inputs[0].parent.find_or_declare(x.replace('header:', ''))) return super(cython, self).runnable_status()
[ "def", "runnable_status", "(", "self", ")", ":", "ret", "=", "super", "(", "cython", ",", "self", ")", ".", "runnable_status", "(", ")", "if", "ret", "==", "Task", ".", "ASK_LATER", ":", "return", "ret", "for", "x", "in", "self", ".", "generator", ".", "bld", ".", "raw_deps", "[", "self", ".", "uid", "(", ")", "]", ":", "if", "x", ".", "startswith", "(", "'header:'", ")", ":", "self", ".", "outputs", ".", "append", "(", "self", ".", "inputs", "[", "0", "]", ".", "parent", ".", "find_or_declare", "(", "x", ".", "replace", "(", "'header:'", ",", "''", ")", ")", ")", "return", "super", "(", "cython", ",", "self", ")", ".", "runnable_status", "(", ")" ]
https://github.com/kushview/Element/blob/1cc16380caa2ab79461246ba758b9de1f46db2a5/waflib/extras/cython.py#L55-L67
google/shaka-packager
e1b0c7c45431327fd3ce193514a5407d07b39b22
packager/third_party/protobuf/python/google/protobuf/message.py
python
Message.Clear
(self)
Clears all data that was set in the message.
Clears all data that was set in the message.
[ "Clears", "all", "data", "that", "was", "set", "in", "the", "message", "." ]
def Clear(self): """Clears all data that was set in the message.""" raise NotImplementedError
[ "def", "Clear", "(", "self", ")", ":", "raise", "NotImplementedError" ]
https://github.com/google/shaka-packager/blob/e1b0c7c45431327fd3ce193514a5407d07b39b22/packager/third_party/protobuf/python/google/protobuf/message.py#L120-L122
quantOS-org/DataCore
e2ef9bd2c22ee9e2845675b6435a14fa607f3551
mdlink/deps/windows/protobuf-2.5.0/python/google/protobuf/text_format.py
python
_Tokenizer.Consume
(self, token)
Consumes a piece of text. Args: token: Text to consume. Raises: ParseError: If the text couldn't be consumed.
Consumes a piece of text.
[ "Consumes", "a", "piece", "of", "text", "." ]
def Consume(self, token): """Consumes a piece of text. Args: token: Text to consume. Raises: ParseError: If the text couldn't be consumed. """ if not self.TryConsume(token): raise self._ParseError('Expected "%s".' % token)
[ "def", "Consume", "(", "self", ",", "token", ")", ":", "if", "not", "self", ".", "TryConsume", "(", "token", ")", ":", "raise", "self", ".", "_ParseError", "(", "'Expected \"%s\".'", "%", "token", ")" ]
https://github.com/quantOS-org/DataCore/blob/e2ef9bd2c22ee9e2845675b6435a14fa607f3551/mdlink/deps/windows/protobuf-2.5.0/python/google/protobuf/text_format.py#L368-L378
mindspore-ai/mindspore
fb8fd3338605bb34fa5cea054e535a8b1d753fab
mindspore/python/mindspore/nn/probability/distribution/cauchy.py
python
Cauchy._log_cdf
(self, value, loc=None, scale=None)
return self.log1p(2. * self.atan(z) / np.pi) - self.log(self.const(2.))
r""" Evaluate the log cumulative distribution function on the given value. Args: value (Tensor): The value to be evaluated. loc (Tensor): The location of the distribution. Default: self.loc. scale (Tensor): The scale the distribution. Default: self.scale. .. math:: log_cdf(x) = \log(\frac{\arctan(\frac{x-loc}{scale})}{\pi} + 0.5) = \log {\arctan(\frac{x-loc}{scale}) + 0.5pi}{pi} = \log1p \frac{2 * arctan(\frac{x-loc}{scale})}{pi} - \log2
r""" Evaluate the log cumulative distribution function on the given value.
[ "r", "Evaluate", "the", "log", "cumulative", "distribution", "function", "on", "the", "given", "value", "." ]
def _log_cdf(self, value, loc=None, scale=None): r""" Evaluate the log cumulative distribution function on the given value. Args: value (Tensor): The value to be evaluated. loc (Tensor): The location of the distribution. Default: self.loc. scale (Tensor): The scale the distribution. Default: self.scale. .. math:: log_cdf(x) = \log(\frac{\arctan(\frac{x-loc}{scale})}{\pi} + 0.5) = \log {\arctan(\frac{x-loc}{scale}) + 0.5pi}{pi} = \log1p \frac{2 * arctan(\frac{x-loc}{scale})}{pi} - \log2 """ value = self._check_value(value, 'value') value = self.cast(value, self.dtype) loc, scale = self._check_param_type(loc, scale) z = (value - loc) / scale return self.log1p(2. * self.atan(z) / np.pi) - self.log(self.const(2.))
[ "def", "_log_cdf", "(", "self", ",", "value", ",", "loc", "=", "None", ",", "scale", "=", "None", ")", ":", "value", "=", "self", ".", "_check_value", "(", "value", ",", "'value'", ")", "value", "=", "self", ".", "cast", "(", "value", ",", "self", ".", "dtype", ")", "loc", ",", "scale", "=", "self", ".", "_check_param_type", "(", "loc", ",", "scale", ")", "z", "=", "(", "value", "-", "loc", ")", "/", "scale", "return", "self", ".", "log1p", "(", "2.", "*", "self", ".", "atan", "(", "z", ")", "/", "np", ".", "pi", ")", "-", "self", ".", "log", "(", "self", ".", "const", "(", "2.", ")", ")" ]
https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/nn/probability/distribution/cauchy.py#L305-L323
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/cookielib.py
python
FileCookieJar.__init__
(self, filename=None, delayload=False, policy=None)
Cookies are NOT loaded from the named file until either the .load() or .revert() method is called.
Cookies are NOT loaded from the named file until either the .load() or .revert() method is called.
[ "Cookies", "are", "NOT", "loaded", "from", "the", "named", "file", "until", "either", "the", ".", "load", "()", "or", ".", "revert", "()", "method", "is", "called", "." ]
def __init__(self, filename=None, delayload=False, policy=None): """ Cookies are NOT loaded from the named file until either the .load() or .revert() method is called. """ CookieJar.__init__(self, policy) if filename is not None: try: filename+"" except: raise ValueError("filename must be string-like") self.filename = filename self.delayload = bool(delayload)
[ "def", "__init__", "(", "self", ",", "filename", "=", "None", ",", "delayload", "=", "False", ",", "policy", "=", "None", ")", ":", "CookieJar", ".", "__init__", "(", "self", ",", "policy", ")", "if", "filename", "is", "not", "None", ":", "try", ":", "filename", "+", "\"\"", "except", ":", "raise", "ValueError", "(", "\"filename must be string-like\"", ")", "self", ".", "filename", "=", "filename", "self", ".", "delayload", "=", "bool", "(", "delayload", ")" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/cookielib.py#L1736-L1749
p4lang/behavioral-model
81ce0163f0770c6b9d6056a28ce2e0cc035bb6e9
tools/cpplint.py
python
FileInfo.Extension
(self)
return self.Split()[2]
File extension - text following the final period, includes that period.
File extension - text following the final period, includes that period.
[ "File", "extension", "-", "text", "following", "the", "final", "period", "includes", "that", "period", "." ]
def Extension(self): """File extension - text following the final period, includes that period.""" return self.Split()[2]
[ "def", "Extension", "(", "self", ")", ":", "return", "self", ".", "Split", "(", ")", "[", "2", "]" ]
https://github.com/p4lang/behavioral-model/blob/81ce0163f0770c6b9d6056a28ce2e0cc035bb6e9/tools/cpplint.py#L1642-L1644
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/_misc.py
python
Display.GetFromWindow
(*args, **kwargs)
return _misc_.Display_GetFromWindow(*args, **kwargs)
GetFromWindow(Window window) -> int Find the display where the given window lies, return wx.NOT_FOUND if it is not shown at all.
GetFromWindow(Window window) -> int
[ "GetFromWindow", "(", "Window", "window", ")", "-", ">", "int" ]
def GetFromWindow(*args, **kwargs): """ GetFromWindow(Window window) -> int Find the display where the given window lies, return wx.NOT_FOUND if it is not shown at all. """ return _misc_.Display_GetFromWindow(*args, **kwargs)
[ "def", "GetFromWindow", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_misc_", ".", "Display_GetFromWindow", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_misc.py#L6111-L6118
ApolloAuto/apollo
463fb82f9e979d02dcb25044e60931293ab2dba0
modules/tools/dump_gpsbin/dump_gpsbin.py
python
process_record_file
(args)
Read record file and extract the message with specified channels
Read record file and extract the message with specified channels
[ "Read", "record", "file", "and", "extract", "the", "message", "with", "specified", "channels" ]
def process_record_file(args): """Read record file and extract the message with specified channels""" freader = record.RecordReader(args.input_file) glog.info('#processing record file {}'.format(args.input_file)) time.sleep(1) output_file = os.path.join(args.output_dir, 'gpsimu.bin') with open(output_file, 'wb') as outfile: for channel, message, _type, _timestamp in freader.read_messages(): if channel == args.gps_raw_data_channel: raw_data = RawData() raw_data.ParseFromString(message) outfile.write(raw_data.data)
[ "def", "process_record_file", "(", "args", ")", ":", "freader", "=", "record", ".", "RecordReader", "(", "args", ".", "input_file", ")", "glog", ".", "info", "(", "'#processing record file {}'", ".", "format", "(", "args", ".", "input_file", ")", ")", "time", ".", "sleep", "(", "1", ")", "output_file", "=", "os", ".", "path", ".", "join", "(", "args", ".", "output_dir", ",", "'gpsimu.bin'", ")", "with", "open", "(", "output_file", ",", "'wb'", ")", "as", "outfile", ":", "for", "channel", ",", "message", ",", "_type", ",", "_timestamp", "in", "freader", ".", "read_messages", "(", ")", ":", "if", "channel", "==", "args", ".", "gps_raw_data_channel", ":", "raw_data", "=", "RawData", "(", ")", "raw_data", ".", "ParseFromString", "(", "message", ")", "outfile", ".", "write", "(", "raw_data", ".", "data", ")" ]
https://github.com/ApolloAuto/apollo/blob/463fb82f9e979d02dcb25044e60931293ab2dba0/modules/tools/dump_gpsbin/dump_gpsbin.py#L52-L63
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/_pydecimal.py
python
Context.copy_negate
(self, a)
return a.copy_negate()
Returns a copy of the operand with the sign inverted. >>> ExtendedContext.copy_negate(Decimal('101.5')) Decimal('-101.5') >>> ExtendedContext.copy_negate(Decimal('-101.5')) Decimal('101.5') >>> ExtendedContext.copy_negate(1) Decimal('-1')
Returns a copy of the operand with the sign inverted.
[ "Returns", "a", "copy", "of", "the", "operand", "with", "the", "sign", "inverted", "." ]
def copy_negate(self, a): """Returns a copy of the operand with the sign inverted. >>> ExtendedContext.copy_negate(Decimal('101.5')) Decimal('-101.5') >>> ExtendedContext.copy_negate(Decimal('-101.5')) Decimal('101.5') >>> ExtendedContext.copy_negate(1) Decimal('-1') """ a = _convert_other(a, raiseit=True) return a.copy_negate()
[ "def", "copy_negate", "(", "self", ",", "a", ")", ":", "a", "=", "_convert_other", "(", "a", ",", "raiseit", "=", "True", ")", "return", "a", ".", "copy_negate", "(", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/_pydecimal.py#L4321-L4332
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/dataview.py
python
DataViewModel.ItemChanged
(*args, **kwargs)
return _dataview.DataViewModel_ItemChanged(*args, **kwargs)
ItemChanged(self, DataViewItem item) -> bool Call this to inform the registered notifiers that an item has changed. This will eventually result in a EVT_DATAVIEW_ITEM_VALUE_CHANGED event, in which the column field will not be set.
ItemChanged(self, DataViewItem item) -> bool
[ "ItemChanged", "(", "self", "DataViewItem", "item", ")", "-", ">", "bool" ]
def ItemChanged(*args, **kwargs): """ ItemChanged(self, DataViewItem item) -> bool Call this to inform the registered notifiers that an item has changed. This will eventually result in a EVT_DATAVIEW_ITEM_VALUE_CHANGED event, in which the column field will not be set. """ return _dataview.DataViewModel_ItemChanged(*args, **kwargs)
[ "def", "ItemChanged", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_dataview", ".", "DataViewModel_ItemChanged", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/dataview.py#L589-L597
benoitsteiner/tensorflow-opencl
cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5
tensorflow/python/ops/embedding_ops.py
python
_gather
(params, ids, name=None)
Helper function for _embedding_lookup_and_transform. This function gathers embeddings from a single tensor. The gather deals with resource variables specially. Args: params: A `Tensor` of embeddings. ids: A `Tensor` indexing the embeddings to be retrieved from `params`. name: A name for the operation (optional). Returns: A `Tensor` with the same type as `params`.
Helper function for _embedding_lookup_and_transform.
[ "Helper", "function", "for", "_embedding_lookup_and_transform", "." ]
def _gather(params, ids, name=None): """Helper function for _embedding_lookup_and_transform. This function gathers embeddings from a single tensor. The gather deals with resource variables specially. Args: params: A `Tensor` of embeddings. ids: A `Tensor` indexing the embeddings to be retrieved from `params`. name: A name for the operation (optional). Returns: A `Tensor` with the same type as `params`. """ if isinstance(params, resource_variable_ops.ResourceVariable): return params.sparse_read(ids, name=name) else: return array_ops.gather(params, ids, name=name)
[ "def", "_gather", "(", "params", ",", "ids", ",", "name", "=", "None", ")", ":", "if", "isinstance", "(", "params", ",", "resource_variable_ops", ".", "ResourceVariable", ")", ":", "return", "params", ".", "sparse_read", "(", "ids", ",", "name", "=", "name", ")", "else", ":", "return", "array_ops", ".", "gather", "(", "params", ",", "ids", ",", "name", "=", "name", ")" ]
https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/ops/embedding_ops.py#L37-L54
microsoft/TSS.MSR
0f2516fca2cd9929c31d5450e39301c9bde43688
TSS.Py/src/Tpm.py
python
Tpm.PolicyOR
(self, policySession, pHashList)
return self.processResponse(respBuf)
This command allows options in authorizations without requiring that the TPM evaluate all of the options. If a policy may be satisfied by different sets of conditions, the TPM need only evaluate one set that satisfies the policy. This command will indicate that one of the required sets of conditions has been satisfied. Args: policySession (TPM_HANDLE): Handle for the policy session being extended Auth Index: None pHashList (TPM2B_DIGEST[]): The list of hashes to check for a match
This command allows options in authorizations without requiring that the TPM evaluate all of the options. If a policy may be satisfied by different sets of conditions, the TPM need only evaluate one set that satisfies the policy. This command will indicate that one of the required sets of conditions has been satisfied.
[ "This", "command", "allows", "options", "in", "authorizations", "without", "requiring", "that", "the", "TPM", "evaluate", "all", "of", "the", "options", ".", "If", "a", "policy", "may", "be", "satisfied", "by", "different", "sets", "of", "conditions", "the", "TPM", "need", "only", "evaluate", "one", "set", "that", "satisfies", "the", "policy", ".", "This", "command", "will", "indicate", "that", "one", "of", "the", "required", "sets", "of", "conditions", "has", "been", "satisfied", "." ]
def PolicyOR(self, policySession, pHashList): """ This command allows options in authorizations without requiring that the TPM evaluate all of the options. If a policy may be satisfied by different sets of conditions, the TPM need only evaluate one set that satisfies the policy. This command will indicate that one of the required sets of conditions has been satisfied. Args: policySession (TPM_HANDLE): Handle for the policy session being extended Auth Index: None pHashList (TPM2B_DIGEST[]): The list of hashes to check for a match """ req = TPM2_PolicyOR_REQUEST(policySession, pHashList) respBuf = self.dispatchCommand(TPM_CC.PolicyOR, req) return self.processResponse(respBuf)
[ "def", "PolicyOR", "(", "self", ",", "policySession", ",", "pHashList", ")", ":", "req", "=", "TPM2_PolicyOR_REQUEST", "(", "policySession", ",", "pHashList", ")", "respBuf", "=", "self", ".", "dispatchCommand", "(", "TPM_CC", ".", "PolicyOR", ",", "req", ")", "return", "self", ".", "processResponse", "(", "respBuf", ")" ]
https://github.com/microsoft/TSS.MSR/blob/0f2516fca2cd9929c31d5450e39301c9bde43688/TSS.Py/src/Tpm.py#L1506-L1520
francinexue/xuefu
b6ff79747a42e020588c0c0a921048e08fe4680c
ctpx/ctp3/ctpmd.py
python
CtpMd.onRspUnSubMarketData
(self, SpecificInstrumentField, RspInfoField, requestId, final)
取消订阅行情应答
取消订阅行情应答
[ "取消订阅行情应答" ]
def onRspUnSubMarketData(self, SpecificInstrumentField, RspInfoField, requestId, final): """取消订阅行情应答""" pass
[ "def", "onRspUnSubMarketData", "(", "self", ",", "SpecificInstrumentField", ",", "RspInfoField", ",", "requestId", ",", "final", ")", ":", "pass" ]
https://github.com/francinexue/xuefu/blob/b6ff79747a42e020588c0c0a921048e08fe4680c/ctpx/ctp3/ctpmd.py#L79-L81
swift/swift
12d031cf8177fdec0137f9aa7e2912fa23c4416b
3rdParty/SCons/scons-3.0.1/engine/SCons/Node/FS.py
python
Dir.alter_targets
(self)
return self.fs.variant_dir_target_climb(self, self, [])
Return any corresponding targets in a variant directory.
Return any corresponding targets in a variant directory.
[ "Return", "any", "corresponding", "targets", "in", "a", "variant", "directory", "." ]
def alter_targets(self): """Return any corresponding targets in a variant directory. """ return self.fs.variant_dir_target_climb(self, self, [])
[ "def", "alter_targets", "(", "self", ")", ":", "return", "self", ".", "fs", ".", "variant_dir_target_climb", "(", "self", ",", "self", ",", "[", "]", ")" ]
https://github.com/swift/swift/blob/12d031cf8177fdec0137f9aa7e2912fa23c4416b/3rdParty/SCons/scons-3.0.1/engine/SCons/Node/FS.py#L1813-L1816
apple/turicreate
cce55aa5311300e3ce6af93cb45ba791fd1bdf49
src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/text_format.py
python
MessageToString
(message, as_utf8=False, as_one_line=False, pointy_brackets=False, use_index_order=False, float_format=None, use_field_number=False, descriptor_pool=None, indent=0)
return result
Convert protobuf message to text format. Floating point values can be formatted compactly with 15 digits of precision (which is the most that IEEE 754 "double" can guarantee) using float_format='.15g'. To ensure that converting to text and back to a proto will result in an identical value, float_format='.17g' should be used. Args: message: The protocol buffers message. as_utf8: Produce text output in UTF8 format. as_one_line: Don't introduce newlines between fields. pointy_brackets: If True, use angle brackets instead of curly braces for nesting. use_index_order: If True, print fields of a proto message using the order defined in source code instead of the field number. By default, use the field number order. float_format: If set, use this to specify floating point number formatting (per the "Format Specification Mini-Language"); otherwise, str() is used. use_field_number: If True, print field numbers instead of names. descriptor_pool: A DescriptorPool used to resolve Any types. indent: The indent level, in terms of spaces, for pretty print. Returns: A string of the text formatted protocol buffer message.
Convert protobuf message to text format.
[ "Convert", "protobuf", "message", "to", "text", "format", "." ]
def MessageToString(message, as_utf8=False, as_one_line=False, pointy_brackets=False, use_index_order=False, float_format=None, use_field_number=False, descriptor_pool=None, indent=0): """Convert protobuf message to text format. Floating point values can be formatted compactly with 15 digits of precision (which is the most that IEEE 754 "double" can guarantee) using float_format='.15g'. To ensure that converting to text and back to a proto will result in an identical value, float_format='.17g' should be used. Args: message: The protocol buffers message. as_utf8: Produce text output in UTF8 format. as_one_line: Don't introduce newlines between fields. pointy_brackets: If True, use angle brackets instead of curly braces for nesting. use_index_order: If True, print fields of a proto message using the order defined in source code instead of the field number. By default, use the field number order. float_format: If set, use this to specify floating point number formatting (per the "Format Specification Mini-Language"); otherwise, str() is used. use_field_number: If True, print field numbers instead of names. descriptor_pool: A DescriptorPool used to resolve Any types. indent: The indent level, in terms of spaces, for pretty print. Returns: A string of the text formatted protocol buffer message. """ out = TextWriter(as_utf8) printer = _Printer(out, indent, as_utf8, as_one_line, pointy_brackets, use_index_order, float_format, use_field_number, descriptor_pool) printer.PrintMessage(message) result = out.getvalue() out.close() if as_one_line: return result.rstrip() return result
[ "def", "MessageToString", "(", "message", ",", "as_utf8", "=", "False", ",", "as_one_line", "=", "False", ",", "pointy_brackets", "=", "False", ",", "use_index_order", "=", "False", ",", "float_format", "=", "None", ",", "use_field_number", "=", "False", ",", "descriptor_pool", "=", "None", ",", "indent", "=", "0", ")", ":", "out", "=", "TextWriter", "(", "as_utf8", ")", "printer", "=", "_Printer", "(", "out", ",", "indent", ",", "as_utf8", ",", "as_one_line", ",", "pointy_brackets", ",", "use_index_order", ",", "float_format", ",", "use_field_number", ",", "descriptor_pool", ")", "printer", ".", "PrintMessage", "(", "message", ")", "result", "=", "out", ".", "getvalue", "(", ")", "out", ".", "close", "(", ")", "if", "as_one_line", ":", "return", "result", ".", "rstrip", "(", ")", "return", "result" ]
https://github.com/apple/turicreate/blob/cce55aa5311300e3ce6af93cb45ba791fd1bdf49/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/text_format.py#L121-L164
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/linalg/linear_operator_util.py
python
use_operator_or_provided_hint_unless_contradicting
( operator, hint_attr_name, provided_hint_value, message)
return None
Get combined hint in the case where operator.hint should equal hint. Args: operator: LinearOperator that a meta-operator was initialized with. hint_attr_name: String name for the attribute. provided_hint_value: Bool or None. Value passed by user in initialization. message: Error message to print if hints contradict. Returns: True, False, or None. Raises: ValueError: If hints contradict.
Get combined hint in the case where operator.hint should equal hint.
[ "Get", "combined", "hint", "in", "the", "case", "where", "operator", ".", "hint", "should", "equal", "hint", "." ]
def use_operator_or_provided_hint_unless_contradicting( operator, hint_attr_name, provided_hint_value, message): """Get combined hint in the case where operator.hint should equal hint. Args: operator: LinearOperator that a meta-operator was initialized with. hint_attr_name: String name for the attribute. provided_hint_value: Bool or None. Value passed by user in initialization. message: Error message to print if hints contradict. Returns: True, False, or None. Raises: ValueError: If hints contradict. """ op_hint = getattr(operator, hint_attr_name) # pylint: disable=g-bool-id-comparison if op_hint is False and provided_hint_value: raise ValueError(message) if op_hint and provided_hint_value is False: raise ValueError(message) if op_hint or provided_hint_value: return True if op_hint is False or provided_hint_value is False: return False # pylint: enable=g-bool-id-comparison return None
[ "def", "use_operator_or_provided_hint_unless_contradicting", "(", "operator", ",", "hint_attr_name", ",", "provided_hint_value", ",", "message", ")", ":", "op_hint", "=", "getattr", "(", "operator", ",", "hint_attr_name", ")", "# pylint: disable=g-bool-id-comparison", "if", "op_hint", "is", "False", "and", "provided_hint_value", ":", "raise", "ValueError", "(", "message", ")", "if", "op_hint", "and", "provided_hint_value", "is", "False", ":", "raise", "ValueError", "(", "message", ")", "if", "op_hint", "or", "provided_hint_value", ":", "return", "True", "if", "op_hint", "is", "False", "or", "provided_hint_value", "is", "False", ":", "return", "False", "# pylint: enable=g-bool-id-comparison", "return", "None" ]
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/linalg/linear_operator_util.py#L534-L561
apple/turicreate
cce55aa5311300e3ce6af93cb45ba791fd1bdf49
deps/src/libxml2-2.9.1/python/libxml2class.py
python
xmlNode.getBase
(self, doc)
return ret
Searches for the BASE URL. The code should work on both XML and HTML document even if base mechanisms are completely different. It returns the base as defined in RFC 2396 sections 5.1.1. Base URI within Document Content and 5.1.2. Base URI from the Encapsulating Entity However it does not return the document base (5.1.3), use doc->URL in this case
Searches for the BASE URL. The code should work on both XML and HTML document even if base mechanisms are completely different. It returns the base as defined in RFC 2396 sections 5.1.1. Base URI within Document Content and 5.1.2. Base URI from the Encapsulating Entity However it does not return the document base (5.1.3), use doc->URL in this case
[ "Searches", "for", "the", "BASE", "URL", ".", "The", "code", "should", "work", "on", "both", "XML", "and", "HTML", "document", "even", "if", "base", "mechanisms", "are", "completely", "different", ".", "It", "returns", "the", "base", "as", "defined", "in", "RFC", "2396", "sections", "5", ".", "1", ".", "1", ".", "Base", "URI", "within", "Document", "Content", "and", "5", ".", "1", ".", "2", ".", "Base", "URI", "from", "the", "Encapsulating", "Entity", "However", "it", "does", "not", "return", "the", "document", "base", "(", "5", ".", "1", ".", "3", ")", "use", "doc", "-", ">", "URL", "in", "this", "case" ]
def getBase(self, doc): """Searches for the BASE URL. The code should work on both XML and HTML document even if base mechanisms are completely different. It returns the base as defined in RFC 2396 sections 5.1.1. Base URI within Document Content and 5.1.2. Base URI from the Encapsulating Entity However it does not return the document base (5.1.3), use doc->URL in this case """ if doc is None: doc__o = None else: doc__o = doc._o ret = libxml2mod.xmlNodeGetBase(doc__o, self._o) return ret
[ "def", "getBase", "(", "self", ",", "doc", ")", ":", "if", "doc", "is", "None", ":", "doc__o", "=", "None", "else", ":", "doc__o", "=", "doc", ".", "_o", "ret", "=", "libxml2mod", ".", "xmlNodeGetBase", "(", "doc__o", ",", "self", ".", "_o", ")", "return", "ret" ]
https://github.com/apple/turicreate/blob/cce55aa5311300e3ce6af93cb45ba791fd1bdf49/deps/src/libxml2-2.9.1/python/libxml2class.py#L2450-L2460
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/numpy/py3/numpy/distutils/command/autodist.py
python
check_compiler_gcc
(cmd)
return cmd.try_compile(body, None, None)
Check if the compiler is GCC.
Check if the compiler is GCC.
[ "Check", "if", "the", "compiler", "is", "GCC", "." ]
def check_compiler_gcc(cmd): """Check if the compiler is GCC.""" cmd._check_compiler() body = textwrap.dedent(""" int main() { #if (! defined __GNUC__) #error gcc required #endif return 0; } """) return cmd.try_compile(body, None, None)
[ "def", "check_compiler_gcc", "(", "cmd", ")", ":", "cmd", ".", "_check_compiler", "(", ")", "body", "=", "textwrap", ".", "dedent", "(", "\"\"\"\n int\n main()\n {\n #if (! defined __GNUC__)\n #error gcc required\n #endif\n return 0;\n }\n \"\"\"", ")", "return", "cmd", ".", "try_compile", "(", "body", ",", "None", ",", "None", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/numpy/py3/numpy/distutils/command/autodist.py#L49-L63
nasa/astrobee
9241e67e6692810d6e275abb3165b6d02f4ca5ef
scripts/git/cpplint.py
python
CheckAccess
(filename, clean_lines, linenum, nesting_state, error)
Checks for improper use of DISALLOW* macros. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. 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 improper use of DISALLOW* macros.
[ "Checks", "for", "improper", "use", "of", "DISALLOW", "*", "macros", "." ]
def CheckAccess(filename, clean_lines, linenum, nesting_state, error): """Checks for improper use of DISALLOW* macros. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. 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. """ line = clean_lines.elided[linenum] # get rid of comments and strings matched = Match( (r"\s*(DISALLOW_COPY_AND_ASSIGN|" r"DISALLOW_IMPLICIT_CONSTRUCTORS)"), line ) if not matched: return if nesting_state.stack and isinstance(nesting_state.stack[-1], _ClassInfo): if nesting_state.stack[-1].access != "private": error( filename, linenum, "readability/constructors", 3, "%s must be in the private: section" % matched.group(1), ) else: # Found DISALLOW* macro outside a class declaration, or perhaps it # was used inside a function when it should have been part of the # class declaration. We could issue a warning here, but it # probably resulted in a compiler error already. pass
[ "def", "CheckAccess", "(", "filename", ",", "clean_lines", ",", "linenum", ",", "nesting_state", ",", "error", ")", ":", "line", "=", "clean_lines", ".", "elided", "[", "linenum", "]", "# get rid of comments and strings", "matched", "=", "Match", "(", "(", "r\"\\s*(DISALLOW_COPY_AND_ASSIGN|\"", "r\"DISALLOW_IMPLICIT_CONSTRUCTORS)\"", ")", ",", "line", ")", "if", "not", "matched", ":", "return", "if", "nesting_state", ".", "stack", "and", "isinstance", "(", "nesting_state", ".", "stack", "[", "-", "1", "]", ",", "_ClassInfo", ")", ":", "if", "nesting_state", ".", "stack", "[", "-", "1", "]", ".", "access", "!=", "\"private\"", ":", "error", "(", "filename", ",", "linenum", ",", "\"readability/constructors\"", ",", "3", ",", "\"%s must be in the private: section\"", "%", "matched", ".", "group", "(", "1", ")", ",", ")", "else", ":", "# Found DISALLOW* macro outside a class declaration, or perhaps it", "# was used inside a function when it should have been part of the", "# class declaration. We could issue a warning here, but it", "# probably resulted in a compiler error already.", "pass" ]
https://github.com/nasa/astrobee/blob/9241e67e6692810d6e275abb3165b6d02f4ca5ef/scripts/git/cpplint.py#L3226-L3259
gem5/gem5
141cc37c2d4b93959d4c249b8f7e6a8b2ef75338
src/python/m5/ext/pyfdt/pyfdt.py
python
FdtPropertyWords.__str__
(self)
return "Property(%s,Words:%s)" % (self.name, self.words)
String representation
String representation
[ "String", "representation" ]
def __str__(self): """String representation""" return "Property(%s,Words:%s)" % (self.name, self.words)
[ "def", "__str__", "(", "self", ")", ":", "return", "\"Property(%s,Words:%s)\"", "%", "(", "self", ".", "name", ",", "self", ".", "words", ")" ]
https://github.com/gem5/gem5/blob/141cc37c2d4b93959d4c249b8f7e6a8b2ef75338/src/python/m5/ext/pyfdt/pyfdt.py#L299-L301
intel/llvm
e6d0547e9d99b5a56430c4749f6c7e328bf221ab
llvm/utils/lint/common_lint.py
python
VerifyLineLength
(filename, lines, max_length)
return lint
Checks to make sure the file has no lines with lines exceeding the length limit. Args: filename: the file under consideration as string lines: contents of the file as string array max_length: maximum acceptable line length as number Returns: A list of tuples with format [(filename, line number, msg), ...] with any violations found.
Checks to make sure the file has no lines with lines exceeding the length limit.
[ "Checks", "to", "make", "sure", "the", "file", "has", "no", "lines", "with", "lines", "exceeding", "the", "length", "limit", "." ]
def VerifyLineLength(filename, lines, max_length): """Checks to make sure the file has no lines with lines exceeding the length limit. Args: filename: the file under consideration as string lines: contents of the file as string array max_length: maximum acceptable line length as number Returns: A list of tuples with format [(filename, line number, msg), ...] with any violations found. """ lint = [] line_num = 1 for line in lines: length = len(line.rstrip('\n')) if length > max_length: lint.append((filename, line_num, 'Line exceeds %d chars (%d)' % (max_length, length))) line_num += 1 return lint
[ "def", "VerifyLineLength", "(", "filename", ",", "lines", ",", "max_length", ")", ":", "lint", "=", "[", "]", "line_num", "=", "1", "for", "line", "in", "lines", ":", "length", "=", "len", "(", "line", ".", "rstrip", "(", "'\\n'", ")", ")", "if", "length", ">", "max_length", ":", "lint", ".", "append", "(", "(", "filename", ",", "line_num", ",", "'Line exceeds %d chars (%d)'", "%", "(", "max_length", ",", "length", ")", ")", ")", "line_num", "+=", "1", "return", "lint" ]
https://github.com/intel/llvm/blob/e6d0547e9d99b5a56430c4749f6c7e328bf221ab/llvm/utils/lint/common_lint.py#L8-L29
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python3/src/Lib/_collections_abc.py
python
AsyncGenerator.aclose
(self)
Raise GeneratorExit inside coroutine.
Raise GeneratorExit inside coroutine.
[ "Raise", "GeneratorExit", "inside", "coroutine", "." ]
async def aclose(self): """Raise GeneratorExit inside coroutine. """ try: await self.athrow(GeneratorExit) except (GeneratorExit, StopAsyncIteration): pass else: raise RuntimeError("asynchronous generator ignored GeneratorExit")
[ "async", "def", "aclose", "(", "self", ")", ":", "try", ":", "await", "self", ".", "athrow", "(", "GeneratorExit", ")", "except", "(", "GeneratorExit", ",", "StopAsyncIteration", ")", ":", "pass", "else", ":", "raise", "RuntimeError", "(", "\"asynchronous generator ignored GeneratorExit\"", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/_collections_abc.py#L232-L240
mindspore-ai/mindspore
fb8fd3338605bb34fa5cea054e535a8b1d753fab
mindspore/python/mindspore/parallel/mpi/_mpi_config.py
python
_get_mpi_config
(attr_key)
return getattr(_mpi_config(), attr_key)
Gets mpi config attribute value according to the input key. Args: attr_key (str): The key of the attribute. Returns: Object, The value of given attribute key. Raises: ValueError: If input key is not an attribute in config.
Gets mpi config attribute value according to the input key.
[ "Gets", "mpi", "config", "attribute", "value", "according", "to", "the", "input", "key", "." ]
def _get_mpi_config(attr_key): """ Gets mpi config attribute value according to the input key. Args: attr_key (str): The key of the attribute. Returns: Object, The value of given attribute key. Raises: ValueError: If input key is not an attribute in config. """ if not hasattr(_mpi_config(), attr_key): raise ValueError("Get context keyword %s is not recognized!" % attr_key) return getattr(_mpi_config(), attr_key)
[ "def", "_get_mpi_config", "(", "attr_key", ")", ":", "if", "not", "hasattr", "(", "_mpi_config", "(", ")", ",", "attr_key", ")", ":", "raise", "ValueError", "(", "\"Get context keyword %s is not recognized!\"", "%", "attr_key", ")", "return", "getattr", "(", "_mpi_config", "(", ")", ",", "attr_key", ")" ]
https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/parallel/mpi/_mpi_config.py#L100-L115
domino-team/openwrt-cc
8b181297c34d14d3ca521cc9f31430d561dbc688
package/gli-pub/openwrt-node-packages-master/node/node-v6.9.1/tools/gyp/pylib/gyp/msvs_emulation.py
python
MsvsSettings.GetDefFile
(self, gyp_to_build_path)
return None
Returns the .def file from sources, if any. Otherwise returns None.
Returns the .def file from sources, if any. Otherwise returns None.
[ "Returns", "the", ".", "def", "file", "from", "sources", "if", "any", ".", "Otherwise", "returns", "None", "." ]
def GetDefFile(self, gyp_to_build_path): """Returns the .def file from sources, if any. Otherwise returns None.""" spec = self.spec if spec['type'] in ('shared_library', 'loadable_module', 'executable'): def_files = [s for s in spec.get('sources', []) if s.endswith('.def')] if len(def_files) == 1: return gyp_to_build_path(def_files[0]) elif len(def_files) > 1: raise Exception("Multiple .def files") return None
[ "def", "GetDefFile", "(", "self", ",", "gyp_to_build_path", ")", ":", "spec", "=", "self", ".", "spec", "if", "spec", "[", "'type'", "]", "in", "(", "'shared_library'", ",", "'loadable_module'", ",", "'executable'", ")", ":", "def_files", "=", "[", "s", "for", "s", "in", "spec", ".", "get", "(", "'sources'", ",", "[", "]", ")", "if", "s", ".", "endswith", "(", "'.def'", ")", "]", "if", "len", "(", "def_files", ")", "==", "1", ":", "return", "gyp_to_build_path", "(", "def_files", "[", "0", "]", ")", "elif", "len", "(", "def_files", ")", ">", "1", ":", "raise", "Exception", "(", "\"Multiple .def files\"", ")", "return", "None" ]
https://github.com/domino-team/openwrt-cc/blob/8b181297c34d14d3ca521cc9f31430d561dbc688/package/gli-pub/openwrt-node-packages-master/node/node-v6.9.1/tools/gyp/pylib/gyp/msvs_emulation.py#L527-L536
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/_gdi.py
python
TestFontEncoding
(*args, **kwargs)
return _gdi_.TestFontEncoding(*args, **kwargs)
TestFontEncoding(NativeEncodingInfo info) -> bool
TestFontEncoding(NativeEncodingInfo info) -> bool
[ "TestFontEncoding", "(", "NativeEncodingInfo", "info", ")", "-", ">", "bool" ]
def TestFontEncoding(*args, **kwargs): """TestFontEncoding(NativeEncodingInfo info) -> bool""" return _gdi_.TestFontEncoding(*args, **kwargs)
[ "def", "TestFontEncoding", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_gdi_", ".", "TestFontEncoding", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_gdi.py#L2004-L2006
raspberrypi/tools
13474ee775d0c5ec8a7da4fb0a9fa84187abfc87
arm-bcm2708/arm-rpi-4.9.3-linux-gnueabihf/share/gdb/python/gdb/unwinder.py
python
register_unwinder
(locus, unwinder, replace=False)
Register unwinder in given locus. The unwinder is prepended to the locus's unwinders list. Unwinder name should be unique. Arguments: locus: Either an objfile, progspace, or None (in which case the unwinder is registered globally). unwinder: An object of a gdb.Unwinder subclass replace: If True, replaces existing unwinder with the same name. Otherwise, raises exception if unwinder with the same name already exists. Returns: Nothing. Raises: RuntimeError: Unwinder name is not unique TypeError: Bad locus type
Register unwinder in given locus.
[ "Register", "unwinder", "in", "given", "locus", "." ]
def register_unwinder(locus, unwinder, replace=False): """Register unwinder in given locus. The unwinder is prepended to the locus's unwinders list. Unwinder name should be unique. Arguments: locus: Either an objfile, progspace, or None (in which case the unwinder is registered globally). unwinder: An object of a gdb.Unwinder subclass replace: If True, replaces existing unwinder with the same name. Otherwise, raises exception if unwinder with the same name already exists. Returns: Nothing. Raises: RuntimeError: Unwinder name is not unique TypeError: Bad locus type """ if locus is None: if gdb.parameter("verbose"): gdb.write("Registering global %s unwinder ...\n" % unwinder.name) locus = gdb elif isinstance(locus, gdb.Objfile) or isinstance(locus, gdb.Progspace): if gdb.parameter("verbose"): gdb.write("Registering %s unwinder for %s ...\n" % (unwinder.name, locus.filename)) else: raise TypeError("locus should be gdb.Objfile or gdb.Progspace or None") i = 0 for needle in locus.frame_unwinders: if needle.name == unwinder.name: if replace: del locus.frame_unwinders[i] else: raise RuntimeError("Unwinder %s already exists." % unwinder.name) i += 1 locus.frame_unwinders.insert(0, unwinder)
[ "def", "register_unwinder", "(", "locus", ",", "unwinder", ",", "replace", "=", "False", ")", ":", "if", "locus", "is", "None", ":", "if", "gdb", ".", "parameter", "(", "\"verbose\"", ")", ":", "gdb", ".", "write", "(", "\"Registering global %s unwinder ...\\n\"", "%", "unwinder", ".", "name", ")", "locus", "=", "gdb", "elif", "isinstance", "(", "locus", ",", "gdb", ".", "Objfile", ")", "or", "isinstance", "(", "locus", ",", "gdb", ".", "Progspace", ")", ":", "if", "gdb", ".", "parameter", "(", "\"verbose\"", ")", ":", "gdb", ".", "write", "(", "\"Registering %s unwinder for %s ...\\n\"", "%", "(", "unwinder", ".", "name", ",", "locus", ".", "filename", ")", ")", "else", ":", "raise", "TypeError", "(", "\"locus should be gdb.Objfile or gdb.Progspace or None\"", ")", "i", "=", "0", "for", "needle", "in", "locus", ".", "frame_unwinders", ":", "if", "needle", ".", "name", "==", "unwinder", ".", "name", ":", "if", "replace", ":", "del", "locus", ".", "frame_unwinders", "[", "i", "]", "else", ":", "raise", "RuntimeError", "(", "\"Unwinder %s already exists.\"", "%", "unwinder", ".", "name", ")", "i", "+=", "1", "locus", ".", "frame_unwinders", ".", "insert", "(", "0", ",", "unwinder", ")" ]
https://github.com/raspberrypi/tools/blob/13474ee775d0c5ec8a7da4fb0a9fa84187abfc87/arm-bcm2708/arm-rpi-4.9.3-linux-gnueabihf/share/gdb/python/gdb/unwinder.py#L53-L94
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/_pydecimal.py
python
_format_align
(sign, body, spec)
return result
Given an unpadded, non-aligned numeric string 'body' and sign string 'sign', add padding and alignment conforming to the given format specifier dictionary 'spec' (as produced by parse_format_specifier).
Given an unpadded, non-aligned numeric string 'body' and sign string 'sign', add padding and alignment conforming to the given format specifier dictionary 'spec' (as produced by parse_format_specifier).
[ "Given", "an", "unpadded", "non", "-", "aligned", "numeric", "string", "body", "and", "sign", "string", "sign", "add", "padding", "and", "alignment", "conforming", "to", "the", "given", "format", "specifier", "dictionary", "spec", "(", "as", "produced", "by", "parse_format_specifier", ")", "." ]
def _format_align(sign, body, spec): """Given an unpadded, non-aligned numeric string 'body' and sign string 'sign', add padding and alignment conforming to the given format specifier dictionary 'spec' (as produced by parse_format_specifier). """ # how much extra space do we have to play with? minimumwidth = spec['minimumwidth'] fill = spec['fill'] padding = fill*(minimumwidth - len(sign) - len(body)) align = spec['align'] if align == '<': result = sign + body + padding elif align == '>': result = padding + sign + body elif align == '=': result = sign + padding + body elif align == '^': half = len(padding)//2 result = padding[:half] + sign + body + padding[half:] else: raise ValueError('Unrecognised alignment field') return result
[ "def", "_format_align", "(", "sign", ",", "body", ",", "spec", ")", ":", "# how much extra space do we have to play with?", "minimumwidth", "=", "spec", "[", "'minimumwidth'", "]", "fill", "=", "spec", "[", "'fill'", "]", "padding", "=", "fill", "*", "(", "minimumwidth", "-", "len", "(", "sign", ")", "-", "len", "(", "body", ")", ")", "align", "=", "spec", "[", "'align'", "]", "if", "align", "==", "'<'", ":", "result", "=", "sign", "+", "body", "+", "padding", "elif", "align", "==", "'>'", ":", "result", "=", "padding", "+", "sign", "+", "body", "elif", "align", "==", "'='", ":", "result", "=", "sign", "+", "padding", "+", "body", "elif", "align", "==", "'^'", ":", "half", "=", "len", "(", "padding", ")", "//", "2", "result", "=", "padding", "[", ":", "half", "]", "+", "sign", "+", "body", "+", "padding", "[", "half", ":", "]", "else", ":", "raise", "ValueError", "(", "'Unrecognised alignment field'", ")", "return", "result" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/_pydecimal.py#L6255-L6280
Yelp/MOE
5b5a6a2c6c3cf47320126f7f5894e2a83e347f5c
moe/bandit/data_containers.py
python
SampleArm.__init__
(self, win=0.0, loss=0.0, total=0, variance=None)
Allocate and construct a new instance with the specified data fields; see class docstring for input descriptions.
Allocate and construct a new instance with the specified data fields; see class docstring for input descriptions.
[ "Allocate", "and", "construct", "a", "new", "instance", "with", "the", "specified", "data", "fields", ";", "see", "class", "docstring", "for", "input", "descriptions", "." ]
def __init__(self, win=0.0, loss=0.0, total=0, variance=None): """Allocate and construct a new instance with the specified data fields; see class docstring for input descriptions.""" self._win = win self._loss = loss self._total = total self._variance = variance self.validate()
[ "def", "__init__", "(", "self", ",", "win", "=", "0.0", ",", "loss", "=", "0.0", ",", "total", "=", "0", ",", "variance", "=", "None", ")", ":", "self", ".", "_win", "=", "win", "self", ".", "_loss", "=", "loss", "self", ".", "_total", "=", "total", "self", ".", "_variance", "=", "variance", "self", ".", "validate", "(", ")" ]
https://github.com/Yelp/MOE/blob/5b5a6a2c6c3cf47320126f7f5894e2a83e347f5c/moe/bandit/data_containers.py#L27-L33
hakuna-m/wubiuefi
caec1af0a09c78fd5a345180ada1fe45e0c63493
src/openpgp/sap/msg/KeyMsg.py
python
PublicKeyMsg.seq
(self)
return pkts
Retrieve the key message's packet sequence. :Returns: list of packet instances
Retrieve the key message's packet sequence.
[ "Retrieve", "the", "key", "message", "s", "packet", "sequence", "." ]
def seq(self): """Retrieve the key message's packet sequence. :Returns: list of packet instances """ pkts = self._b_primary.seq() # primary block for block in self._b_userids.list(): # user IDs pkts.extend(block.seq()) pkts.extend(self._b_userattrs) # user attributes for block in self._b_subkeys.list(): # subkeys pkts.extend(block.seq()) return pkts
[ "def", "seq", "(", "self", ")", ":", "pkts", "=", "self", ".", "_b_primary", ".", "seq", "(", ")", "# primary block", "for", "block", "in", "self", ".", "_b_userids", ".", "list", "(", ")", ":", "# user IDs", "pkts", ".", "extend", "(", "block", ".", "seq", "(", ")", ")", "pkts", ".", "extend", "(", "self", ".", "_b_userattrs", ")", "# user attributes", "for", "block", "in", "self", ".", "_b_subkeys", ".", "list", "(", ")", ":", "# subkeys", "pkts", ".", "extend", "(", "block", ".", "seq", "(", ")", ")", "return", "pkts" ]
https://github.com/hakuna-m/wubiuefi/blob/caec1af0a09c78fd5a345180ada1fe45e0c63493/src/openpgp/sap/msg/KeyMsg.py#L269-L280
PaddlePaddle/Paddle
1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c
python/paddle/fluid/framework.py
python
Program._inference_optimize
(self, prune_read_op=True)
return res
This method will create a new program and do following adjustments on it: 1. Remove all reader variables and their creator ops if exist. 2. Remove the :code:`read_op` if exists. 3. change the :code:`is_test` attribute of operators to :code:`True`. All the :code:`Parameter` information will be lost. Args: prune_read_op(bool): remove the read ops that are added by py_reader for cpp inference library Notes: This API is a very low level API. Use :code:`Program.clone(for_test=True)` instead. Returns: Program: The new program.
This method will create a new program and do following adjustments on it: 1. Remove all reader variables and their creator ops if exist.
[ "This", "method", "will", "create", "a", "new", "program", "and", "do", "following", "adjustments", "on", "it", ":", "1", ".", "Remove", "all", "reader", "variables", "and", "their", "creator", "ops", "if", "exist", "." ]
def _inference_optimize(self, prune_read_op=True): """ This method will create a new program and do following adjustments on it: 1. Remove all reader variables and their creator ops if exist. 2. Remove the :code:`read_op` if exists. 3. change the :code:`is_test` attribute of operators to :code:`True`. All the :code:`Parameter` information will be lost. Args: prune_read_op(bool): remove the read ops that are added by py_reader for cpp inference library Notes: This API is a very low level API. Use :code:`Program.clone(for_test=True)` instead. Returns: Program: The new program. """ res = Program() res.desc = core.ProgramDesc(self.desc) # remove all readers and the read_op if exist read_op_idx = 0 root_block = res.desc.block(0) if prune_read_op: while True: if read_op_idx >= root_block.op_size() or root_block.op( read_op_idx).type() == 'read': break read_op_idx += 1 if read_op_idx < root_block.op_size(): root_block._remove_op(0, read_op_idx + 1) for var in root_block.all_vars(): if var.type() == core.VarDesc.VarType.READER: root_block._remove_var(cpt.to_bytes(var.name())) # change all `is_test` attributes to True for i in six.moves.range(res.desc.num_blocks()): block = res.desc.block(i) for j in six.moves.range(block.op_size()): op = block.op(j) if op.has_attr('is_test'): op._set_attr('is_test', True) if op.type() == "batch_norm": # Remove the output ReserveSpace of batch_norm if exists. op.remove_output("ReserveSpace") res.blocks = [ Block(res, i) for i in six.moves.range(res.desc.num_blocks()) ] res._sync_with_cpp() return res
[ "def", "_inference_optimize", "(", "self", ",", "prune_read_op", "=", "True", ")", ":", "res", "=", "Program", "(", ")", "res", ".", "desc", "=", "core", ".", "ProgramDesc", "(", "self", ".", "desc", ")", "# remove all readers and the read_op if exist", "read_op_idx", "=", "0", "root_block", "=", "res", ".", "desc", ".", "block", "(", "0", ")", "if", "prune_read_op", ":", "while", "True", ":", "if", "read_op_idx", ">=", "root_block", ".", "op_size", "(", ")", "or", "root_block", ".", "op", "(", "read_op_idx", ")", ".", "type", "(", ")", "==", "'read'", ":", "break", "read_op_idx", "+=", "1", "if", "read_op_idx", "<", "root_block", ".", "op_size", "(", ")", ":", "root_block", ".", "_remove_op", "(", "0", ",", "read_op_idx", "+", "1", ")", "for", "var", "in", "root_block", ".", "all_vars", "(", ")", ":", "if", "var", ".", "type", "(", ")", "==", "core", ".", "VarDesc", ".", "VarType", ".", "READER", ":", "root_block", ".", "_remove_var", "(", "cpt", ".", "to_bytes", "(", "var", ".", "name", "(", ")", ")", ")", "# change all `is_test` attributes to True", "for", "i", "in", "six", ".", "moves", ".", "range", "(", "res", ".", "desc", ".", "num_blocks", "(", ")", ")", ":", "block", "=", "res", ".", "desc", ".", "block", "(", "i", ")", "for", "j", "in", "six", ".", "moves", ".", "range", "(", "block", ".", "op_size", "(", ")", ")", ":", "op", "=", "block", ".", "op", "(", "j", ")", "if", "op", ".", "has_attr", "(", "'is_test'", ")", ":", "op", ".", "_set_attr", "(", "'is_test'", ",", "True", ")", "if", "op", ".", "type", "(", ")", "==", "\"batch_norm\"", ":", "# Remove the output ReserveSpace of batch_norm if exists.", "op", ".", "remove_output", "(", "\"ReserveSpace\"", ")", "res", ".", "blocks", "=", "[", "Block", "(", "res", ",", "i", ")", "for", "i", "in", "six", ".", "moves", ".", "range", "(", "res", ".", "desc", ".", "num_blocks", "(", ")", ")", "]", "res", ".", "_sync_with_cpp", "(", ")", "return", "res" ]
https://github.com/PaddlePaddle/Paddle/blob/1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c/python/paddle/fluid/framework.py#L5437-L5490
BitMEX/api-connectors
37a3a5b806ad5d0e0fc975ab86d9ed43c3bcd812
auto-generated/python/swagger_client/models/position.py
python
Position.taxable_margin
(self, taxable_margin)
Sets the taxable_margin of this Position. :param taxable_margin: The taxable_margin of this Position. # noqa: E501 :type: float
Sets the taxable_margin of this Position.
[ "Sets", "the", "taxable_margin", "of", "this", "Position", "." ]
def taxable_margin(self, taxable_margin): """Sets the taxable_margin of this Position. :param taxable_margin: The taxable_margin of this Position. # noqa: E501 :type: float """ self._taxable_margin = taxable_margin
[ "def", "taxable_margin", "(", "self", ",", "taxable_margin", ")", ":", "self", ".", "_taxable_margin", "=", "taxable_margin" ]
https://github.com/BitMEX/api-connectors/blob/37a3a5b806ad5d0e0fc975ab86d9ed43c3bcd812/auto-generated/python/swagger_client/models/position.py#L1732-L1740
HKUST-Aerial-Robotics/Fast-Planner
2ddd7793eecd573dbb5b47e2c985aa06606df3cf
uav_simulator/Utils/quadrotor_msgs/src/quadrotor_msgs/msg/_TRPYCommand.py
python
TRPYCommand.__init__
(self, *args, **kwds)
Constructor. Any message fields that are implicitly/explicitly set to None will be assigned a default value. The recommend use is keyword arguments as this is more robust to future message changes. You cannot mix in-order arguments and keyword arguments. The available fields are: header,thrust,roll,pitch,yaw,aux :param args: complete set of field values, in .msg order :param kwds: use keyword arguments corresponding to message field names to set specific fields.
Constructor. Any message fields that are implicitly/explicitly set to None will be assigned a default value. The recommend use is keyword arguments as this is more robust to future message changes. You cannot mix in-order arguments and keyword arguments.
[ "Constructor", ".", "Any", "message", "fields", "that", "are", "implicitly", "/", "explicitly", "set", "to", "None", "will", "be", "assigned", "a", "default", "value", ".", "The", "recommend", "use", "is", "keyword", "arguments", "as", "this", "is", "more", "robust", "to", "future", "message", "changes", ".", "You", "cannot", "mix", "in", "-", "order", "arguments", "and", "keyword", "arguments", "." ]
def __init__(self, *args, **kwds): """ Constructor. Any message fields that are implicitly/explicitly set to None will be assigned a default value. The recommend use is keyword arguments as this is more robust to future message changes. You cannot mix in-order arguments and keyword arguments. The available fields are: header,thrust,roll,pitch,yaw,aux :param args: complete set of field values, in .msg order :param kwds: use keyword arguments corresponding to message field names to set specific fields. """ if args or kwds: super(TRPYCommand, self).__init__(*args, **kwds) #message fields cannot be None, assign default values for those that are if self.header is None: self.header = std_msgs.msg.Header() if self.thrust is None: self.thrust = 0. if self.roll is None: self.roll = 0. if self.pitch is None: self.pitch = 0. if self.yaw is None: self.yaw = 0. if self.aux is None: self.aux = quadrotor_msgs.msg.AuxCommand() else: self.header = std_msgs.msg.Header() self.thrust = 0. self.roll = 0. self.pitch = 0. self.yaw = 0. self.aux = quadrotor_msgs.msg.AuxCommand()
[ "def", "__init__", "(", "self", ",", "*", "args", ",", "*", "*", "kwds", ")", ":", "if", "args", "or", "kwds", ":", "super", "(", "TRPYCommand", ",", "self", ")", ".", "__init__", "(", "*", "args", ",", "*", "*", "kwds", ")", "#message fields cannot be None, assign default values for those that are", "if", "self", ".", "header", "is", "None", ":", "self", ".", "header", "=", "std_msgs", ".", "msg", ".", "Header", "(", ")", "if", "self", ".", "thrust", "is", "None", ":", "self", ".", "thrust", "=", "0.", "if", "self", ".", "roll", "is", "None", ":", "self", ".", "roll", "=", "0.", "if", "self", ".", "pitch", "is", "None", ":", "self", ".", "pitch", "=", "0.", "if", "self", ".", "yaw", "is", "None", ":", "self", ".", "yaw", "=", "0.", "if", "self", ".", "aux", "is", "None", ":", "self", ".", "aux", "=", "quadrotor_msgs", ".", "msg", ".", "AuxCommand", "(", ")", "else", ":", "self", ".", "header", "=", "std_msgs", ".", "msg", ".", "Header", "(", ")", "self", ".", "thrust", "=", "0.", "self", ".", "roll", "=", "0.", "self", ".", "pitch", "=", "0.", "self", ".", "yaw", "=", "0.", "self", ".", "aux", "=", "quadrotor_msgs", ".", "msg", ".", "AuxCommand", "(", ")" ]
https://github.com/HKUST-Aerial-Robotics/Fast-Planner/blob/2ddd7793eecd573dbb5b47e2c985aa06606df3cf/uav_simulator/Utils/quadrotor_msgs/src/quadrotor_msgs/msg/_TRPYCommand.py#L51-L86
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/_controls.py
python
ListItemAttr.GetTextColour
(*args, **kwargs)
return _controls_.ListItemAttr_GetTextColour(*args, **kwargs)
GetTextColour(self) -> Colour
GetTextColour(self) -> Colour
[ "GetTextColour", "(", "self", ")", "-", ">", "Colour" ]
def GetTextColour(*args, **kwargs): """GetTextColour(self) -> Colour""" return _controls_.ListItemAttr_GetTextColour(*args, **kwargs)
[ "def", "GetTextColour", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_controls_", ".", "ListItemAttr_GetTextColour", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_controls.py#L4114-L4116
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/autograph/operators/symbols.py
python
SubscriptSymbol.maybe_compute_value
(self)
Compute the value corresponding to the subscript access or `Undefined`. This will be `Undefined` if no such value exists either because there is no element corresponding to the given subscript or if the base itself is not defined. Returns: value corresponding to the subscript access or `Undefined`
Compute the value corresponding to the subscript access or `Undefined`.
[ "Compute", "the", "value", "corresponding", "to", "the", "subscript", "access", "or", "Undefined", "." ]
def maybe_compute_value(self): """Compute the value corresponding to the subscript access or `Undefined`. This will be `Undefined` if no such value exists either because there is no element corresponding to the given subscript or if the base itself is not defined. Returns: value corresponding to the subscript access or `Undefined` """ parent_value = self.parent_symbol.maybe_compute_value() index_value = self.index_symbol.maybe_compute_value() if is_undefined(parent_value) or is_undefined(index_value): return Undefined(self.name) else: try: return parent_value[index_value] except (IndexError, KeyError, TypeError): # Reify the lack of an object for the given index/key # This allows us to define them later without regret return Undefined(self.name)
[ "def", "maybe_compute_value", "(", "self", ")", ":", "parent_value", "=", "self", ".", "parent_symbol", ".", "maybe_compute_value", "(", ")", "index_value", "=", "self", ".", "index_symbol", ".", "maybe_compute_value", "(", ")", "if", "is_undefined", "(", "parent_value", ")", "or", "is_undefined", "(", "index_value", ")", ":", "return", "Undefined", "(", "self", ".", "name", ")", "else", ":", "try", ":", "return", "parent_value", "[", "index_value", "]", "except", "(", "IndexError", ",", "KeyError", ",", "TypeError", ")", ":", "# Reify the lack of an object for the given index/key", "# This allows us to define them later without regret", "return", "Undefined", "(", "self", ".", "name", ")" ]
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/autograph/operators/symbols.py#L95-L115
giuspen/cherrytree
84712f206478fcf9acf30174009ad28c648c6344
pygtk2/modules/exports.py
python
Export2Html.table_export_to_html
(self, table_dict)
return html_text
Returns the HTML given the table dict
Returns the HTML given the table dict
[ "Returns", "the", "HTML", "given", "the", "table", "dict" ]
def table_export_to_html(self, table_dict): """Returns the HTML given the table dict""" html_text = cons.HTML_HEADER % "" html_text += self.get_table_html([0, table_dict, cons.TAG_PROP_LEFT]) html_text += cons.HTML_FOOTER return html_text
[ "def", "table_export_to_html", "(", "self", ",", "table_dict", ")", ":", "html_text", "=", "cons", ".", "HTML_HEADER", "%", "\"\"", "html_text", "+=", "self", ".", "get_table_html", "(", "[", "0", ",", "table_dict", ",", "cons", ".", "TAG_PROP_LEFT", "]", ")", "html_text", "+=", "cons", ".", "HTML_FOOTER", "return", "html_text" ]
https://github.com/giuspen/cherrytree/blob/84712f206478fcf9acf30174009ad28c648c6344/pygtk2/modules/exports.py#L757-L762
apache/singa
93fd9da72694e68bfe3fb29d0183a65263d238a1
python/singa/autograd.py
python
Equal.forward
(self, x, y)
return singa.__eq__(x, y)
Return `a=b`, where a and b are CTensor.
Return `a=b`, where a and b are CTensor.
[ "Return", "a", "=", "b", "where", "a", "and", "b", "are", "CTensor", "." ]
def forward(self, x, y): """ Return `a=b`, where a and b are CTensor. """ return singa.__eq__(x, y)
[ "def", "forward", "(", "self", ",", "x", ",", "y", ")", ":", "return", "singa", ".", "__eq__", "(", "x", ",", "y", ")" ]
https://github.com/apache/singa/blob/93fd9da72694e68bfe3fb29d0183a65263d238a1/python/singa/autograd.py#L972-L976
Ewenwan/MVision
97b394dfa48cb21c82cd003b1a952745e413a17f
deepLearning/06_rbm.py
python
RBM.gibbs_hvh
(self, h0_sample)
return (v1_mean, v1_sample, h1_mean, h1_sample)
Implement one step of Gibbs sampling from the hidden state
Implement one step of Gibbs sampling from the hidden state
[ "Implement", "one", "step", "of", "Gibbs", "sampling", "from", "the", "hidden", "state" ]
def gibbs_hvh(self, h0_sample): """Implement one step of Gibbs sampling from the hidden state""" v1_mean, v1_sample = self.sample_v_given_h(h0_sample) h1_mean, h1_sample = self.sample_h_given_v(v1_sample) return (v1_mean, v1_sample, h1_mean, h1_sample)
[ "def", "gibbs_hvh", "(", "self", ",", "h0_sample", ")", ":", "v1_mean", ",", "v1_sample", "=", "self", ".", "sample_v_given_h", "(", "h0_sample", ")", "h1_mean", ",", "h1_sample", "=", "self", ".", "sample_h_given_v", "(", "v1_sample", ")", "return", "(", "v1_mean", ",", "v1_sample", ",", "h1_mean", ",", "h1_sample", ")" ]
https://github.com/Ewenwan/MVision/blob/97b394dfa48cb21c82cd003b1a952745e413a17f/deepLearning/06_rbm.py#L76-L80
FreeCAD/FreeCAD
ba42231b9c6889b89e064d6d563448ed81e376ec
src/Mod/Fem/feminout/importInpMesh.py
python
import_inp
(filename)
read a FEM mesh from a Z88 mesh file and insert a FreeCAD FEM Mesh object in the ActiveDocument
read a FEM mesh from a Z88 mesh file and insert a FreeCAD FEM Mesh object in the ActiveDocument
[ "read", "a", "FEM", "mesh", "from", "a", "Z88", "mesh", "file", "and", "insert", "a", "FreeCAD", "FEM", "Mesh", "object", "in", "the", "ActiveDocument" ]
def import_inp(filename): """read a FEM mesh from a Z88 mesh file and insert a FreeCAD FEM Mesh object in the ActiveDocument """ femmesh = read(filename) mesh_name = os.path.splitext(os.path.basename(filename))[0] if femmesh: mesh_object = FreeCAD.ActiveDocument.addObject("Fem::FemMeshObject", mesh_name) mesh_object.FemMesh = femmesh
[ "def", "import_inp", "(", "filename", ")", ":", "femmesh", "=", "read", "(", "filename", ")", "mesh_name", "=", "os", ".", "path", ".", "splitext", "(", "os", ".", "path", ".", "basename", "(", "filename", ")", ")", "[", "0", "]", "if", "femmesh", ":", "mesh_object", "=", "FreeCAD", ".", "ActiveDocument", ".", "addObject", "(", "\"Fem::FemMeshObject\"", ",", "mesh_name", ")", "mesh_object", ".", "FemMesh", "=", "femmesh" ]
https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/Fem/feminout/importInpMesh.py#L75-L82
sc0ty/subsync
be5390d00ff475b6543eb0140c7e65b34317d95b
subsync/synchro/input.py
python
InputFile.isSelect
(self)
return self.path != None and self.no != None
Check whether stream is selected.
Check whether stream is selected.
[ "Check", "whether", "stream", "is", "selected", "." ]
def isSelect(self): """Check whether stream is selected.""" return self.path != None and self.no != None
[ "def", "isSelect", "(", "self", ")", ":", "return", "self", ".", "path", "!=", "None", "and", "self", ".", "no", "!=", "None" ]
https://github.com/sc0ty/subsync/blob/be5390d00ff475b6543eb0140c7e65b34317d95b/subsync/synchro/input.py#L162-L164
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/_core.py
python
FileSystemHandler_GetProtocol
(*args, **kwargs)
return _core_.FileSystemHandler_GetProtocol(*args, **kwargs)
FileSystemHandler_GetProtocol(String location) -> String
FileSystemHandler_GetProtocol(String location) -> String
[ "FileSystemHandler_GetProtocol", "(", "String", "location", ")", "-", ">", "String" ]
def FileSystemHandler_GetProtocol(*args, **kwargs): """FileSystemHandler_GetProtocol(String location) -> String""" return _core_.FileSystemHandler_GetProtocol(*args, **kwargs)
[ "def", "FileSystemHandler_GetProtocol", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_core_", ".", "FileSystemHandler_GetProtocol", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_core.py#L2387-L2389
giuspen/cherrytree
84712f206478fcf9acf30174009ad28c648c6344
pygtk2/modules/exports.py
python
Export2Html.html_get_from_treestore_node
(self, node_iter, sel_range=None)
return [self.curr_html_slots, pixbuf_table_codebox_vector]
Given a treestore iter returns the HTML rich text
Given a treestore iter returns the HTML rich text
[ "Given", "a", "treestore", "iter", "returns", "the", "HTML", "rich", "text" ]
def html_get_from_treestore_node(self, node_iter, sel_range=None): """Given a treestore iter returns the HTML rich text""" #print "to html node", self.dad.treestore[node_iter][1] curr_buffer = self.dad.treestore[node_iter][2] pixbuf_table_codebox_vector = self.dad.state_machine.get_embedded_pixbufs_tables_codeboxes(curr_buffer, for_print=2, sel_range=sel_range) # pixbuf_table_codebox_vector is [ [ "pixbuf"/"table"/"codebox", [offset, pixbuf, alignment] ],... ] self.curr_html_slots = [] start_offset = 0 if not sel_range else sel_range[0] for end_offset_element in pixbuf_table_codebox_vector: end_offset = end_offset_element[1][0] self.html_process_slot(start_offset, end_offset, curr_buffer) start_offset = end_offset if not sel_range: self.html_process_slot(start_offset, -1, curr_buffer) else: self.html_process_slot(start_offset, sel_range[1], curr_buffer) #print "curr_html_slots", self.curr_html_slots #print "pixbuf_table_codebox_vector", pixbuf_table_codebox_vector return [self.curr_html_slots, pixbuf_table_codebox_vector]
[ "def", "html_get_from_treestore_node", "(", "self", ",", "node_iter", ",", "sel_range", "=", "None", ")", ":", "#print \"to html node\", self.dad.treestore[node_iter][1]", "curr_buffer", "=", "self", ".", "dad", ".", "treestore", "[", "node_iter", "]", "[", "2", "]", "pixbuf_table_codebox_vector", "=", "self", ".", "dad", ".", "state_machine", ".", "get_embedded_pixbufs_tables_codeboxes", "(", "curr_buffer", ",", "for_print", "=", "2", ",", "sel_range", "=", "sel_range", ")", "# pixbuf_table_codebox_vector is [ [ \"pixbuf\"/\"table\"/\"codebox\", [offset, pixbuf, alignment] ],... ]", "self", ".", "curr_html_slots", "=", "[", "]", "start_offset", "=", "0", "if", "not", "sel_range", "else", "sel_range", "[", "0", "]", "for", "end_offset_element", "in", "pixbuf_table_codebox_vector", ":", "end_offset", "=", "end_offset_element", "[", "1", "]", "[", "0", "]", "self", ".", "html_process_slot", "(", "start_offset", ",", "end_offset", ",", "curr_buffer", ")", "start_offset", "=", "end_offset", "if", "not", "sel_range", ":", "self", ".", "html_process_slot", "(", "start_offset", ",", "-", "1", ",", "curr_buffer", ")", "else", ":", "self", ".", "html_process_slot", "(", "start_offset", ",", "sel_range", "[", "1", "]", ",", "curr_buffer", ")", "#print \"curr_html_slots\", self.curr_html_slots", "#print \"pixbuf_table_codebox_vector\", pixbuf_table_codebox_vector", "return", "[", "self", ".", "curr_html_slots", ",", "pixbuf_table_codebox_vector", "]" ]
https://github.com/giuspen/cherrytree/blob/84712f206478fcf9acf30174009ad28c648c6344/pygtk2/modules/exports.py#L882-L900
kushview/Element
1cc16380caa2ab79461246ba758b9de1f46db2a5
waflib/ConfigSet.py
python
ConfigSet.__str__
(self)
return "\n".join(["%r %r" % (x, self.__getitem__(x)) for x in self.keys()])
Text representation of the ConfigSet (for debugging purposes)
Text representation of the ConfigSet (for debugging purposes)
[ "Text", "representation", "of", "the", "ConfigSet", "(", "for", "debugging", "purposes", ")" ]
def __str__(self): """Text representation of the ConfigSet (for debugging purposes)""" return "\n".join(["%r %r" % (x, self.__getitem__(x)) for x in self.keys()])
[ "def", "__str__", "(", "self", ")", ":", "return", "\"\\n\"", ".", "join", "(", "[", "\"%r %r\"", "%", "(", "x", ",", "self", ".", "__getitem__", "(", "x", ")", ")", "for", "x", "in", "self", ".", "keys", "(", ")", "]", ")" ]
https://github.com/kushview/Element/blob/1cc16380caa2ab79461246ba758b9de1f46db2a5/waflib/ConfigSet.py#L68-L70
trilinos/Trilinos
6168be6dd51e35e1cd681e9c4b24433e709df140
packages/seacas/libraries/ioss/src/visualization/catalyst/phactori/PhactoriDriver.py
python
RequestDataDescriptionSub
(datadescription)
return 1
Callback to populate the request for current timestep
Callback to populate the request for current timestep
[ "Callback", "to", "populate", "the", "request", "for", "current", "timestep" ]
def RequestDataDescriptionSub(datadescription): myDebugPrint("PhactoriDriver.RequestDataDescriptionSub entered\n"); "Callback to populate the request for current timestep" TestUserDataForBypassScript(datadescription) if GetBypassUserDataFlag() == False: fd = datadescription.GetUserData() if fd == None: myDebugPrint2("no user data, returning {}\n") returnViewMapC = {} return returnViewMapC global coprocessor global gFirstTimeInDoCoProcessing global gSkipCountdown if gFirstTimeInDoCoProcessing == True: myDebugPrint2("RequestDataDescription doing gFirstTimeInDoCoProcessing\n") myDebugPrint2(" skip countdown is " + str(gSkipCountdown) + "\n") if gSkipCountdown > 0: gSkipCountdown = gSkipCountdown - 1 return 0 coprocessor = CreateCoProcessor() coprocessor.EnableLiveVisualization(False) gFirstTimeInDoCoProcessing = False #import pdb #pdb.set_trace() InitializePerPipeRoot(datadescription, coprocessor) if datadescription.GetForceOutput() == True: # We are just going to request all fields and meshes from the simulation # code/adaptor. for i in range(datadescription.GetNumberOfInputDescriptions()): datadescription.GetInputDescription(i).AllFieldsOn() datadescription.GetInputDescription(i).GenerateMeshOn() return 1 # setup requests for all inputs based on the requirements of the # pipeline. coprocessor.LoadRequestedData(datadescription) return 1
[ "def", "RequestDataDescriptionSub", "(", "datadescription", ")", ":", "myDebugPrint", "(", "\"PhactoriDriver.RequestDataDescriptionSub entered\\n\"", ")", "TestUserDataForBypassScript", "(", "datadescription", ")", "if", "GetBypassUserDataFlag", "(", ")", "==", "False", ":", "fd", "=", "datadescription", ".", "GetUserData", "(", ")", "if", "fd", "==", "None", ":", "myDebugPrint2", "(", "\"no user data, returning {}\\n\"", ")", "returnViewMapC", "=", "{", "}", "return", "returnViewMapC", "global", "coprocessor", "global", "gFirstTimeInDoCoProcessing", "global", "gSkipCountdown", "if", "gFirstTimeInDoCoProcessing", "==", "True", ":", "myDebugPrint2", "(", "\"RequestDataDescription doing gFirstTimeInDoCoProcessing\\n\"", ")", "myDebugPrint2", "(", "\" skip countdown is \"", "+", "str", "(", "gSkipCountdown", ")", "+", "\"\\n\"", ")", "if", "gSkipCountdown", ">", "0", ":", "gSkipCountdown", "=", "gSkipCountdown", "-", "1", "return", "0", "coprocessor", "=", "CreateCoProcessor", "(", ")", "coprocessor", ".", "EnableLiveVisualization", "(", "False", ")", "gFirstTimeInDoCoProcessing", "=", "False", "#import pdb", "#pdb.set_trace()", "InitializePerPipeRoot", "(", "datadescription", ",", "coprocessor", ")", "if", "datadescription", ".", "GetForceOutput", "(", ")", "==", "True", ":", "# We are just going to request all fields and meshes from the simulation", "# code/adaptor.", "for", "i", "in", "range", "(", "datadescription", ".", "GetNumberOfInputDescriptions", "(", ")", ")", ":", "datadescription", ".", "GetInputDescription", "(", "i", ")", ".", "AllFieldsOn", "(", ")", "datadescription", ".", "GetInputDescription", "(", "i", ")", ".", "GenerateMeshOn", "(", ")", "return", "1", "# setup requests for all inputs based on the requirements of the", "# pipeline.", "coprocessor", ".", "LoadRequestedData", "(", "datadescription", ")", "return", "1" ]
https://github.com/trilinos/Trilinos/blob/6168be6dd51e35e1cd681e9c4b24433e709df140/packages/seacas/libraries/ioss/src/visualization/catalyst/phactori/PhactoriDriver.py#L26111-L26156
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/dashboard/dashboard/models/alert_group.py
python
_AddAlertToGroup
(alert_entity, group)
Adds an anomaly to group and updates the group's properties.
Adds an anomaly to group and updates the group's properties.
[ "Adds", "an", "anomaly", "to", "group", "and", "updates", "the", "group", "s", "properties", "." ]
def _AddAlertToGroup(alert_entity, group): """Adds an anomaly to group and updates the group's properties.""" update_group = False if alert_entity.start_revision > group.start_revision: # TODO(qyearsley): Add test coverage. See catapult:#1346. group.start_revision = alert_entity.start_revision update_group = True if alert_entity.end_revision < group.end_revision: group.end_revision = alert_entity.end_revision update_group = True if update_group: group.put() if group.bug_id: alert_entity.bug_id = group.bug_id _AddLogForBugAssociate(alert_entity, group.bug_id) alert_entity.group = group.key logging.debug('Auto triage: Associated anomaly on %s with %s.', utils.TestPath(alert_entity.GetTestMetadataKey()), group.key.urlsafe())
[ "def", "_AddAlertToGroup", "(", "alert_entity", ",", "group", ")", ":", "update_group", "=", "False", "if", "alert_entity", ".", "start_revision", ">", "group", ".", "start_revision", ":", "# TODO(qyearsley): Add test coverage. See catapult:#1346.", "group", ".", "start_revision", "=", "alert_entity", ".", "start_revision", "update_group", "=", "True", "if", "alert_entity", ".", "end_revision", "<", "group", ".", "end_revision", ":", "group", ".", "end_revision", "=", "alert_entity", ".", "end_revision", "update_group", "=", "True", "if", "update_group", ":", "group", ".", "put", "(", ")", "if", "group", ".", "bug_id", ":", "alert_entity", ".", "bug_id", "=", "group", ".", "bug_id", "_AddLogForBugAssociate", "(", "alert_entity", ",", "group", ".", "bug_id", ")", "alert_entity", ".", "group", "=", "group", ".", "key", "logging", ".", "debug", "(", "'Auto triage: Associated anomaly on %s with %s.'", ",", "utils", ".", "TestPath", "(", "alert_entity", ".", "GetTestMetadataKey", "(", ")", ")", ",", "group", ".", "key", ".", "urlsafe", "(", ")", ")" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/dashboard/dashboard/models/alert_group.py#L121-L140
ucisysarch/opencvjs
7fe821305dffdc3ca6c7edfaa779d045f0406961
binding-gen/hdr_parser.py
python
CppHeaderParser.find_next_token
(self, s, tlist, p=0)
return token, tpos
Finds the next token from the 'tlist' in the input 's', starting from position 'p'. Returns the first occured token and its position, or ("", len(s)) when no token is found
Finds the next token from the 'tlist' in the input 's', starting from position 'p'. Returns the first occured token and its position, or ("", len(s)) when no token is found
[ "Finds", "the", "next", "token", "from", "the", "tlist", "in", "the", "input", "s", "starting", "from", "position", "p", ".", "Returns", "the", "first", "occured", "token", "and", "its", "position", "or", "(", "len", "(", "s", "))", "when", "no", "token", "is", "found" ]
def find_next_token(self, s, tlist, p=0): """ Finds the next token from the 'tlist' in the input 's', starting from position 'p'. Returns the first occured token and its position, or ("", len(s)) when no token is found """ token = "" tpos = len(s) for t in tlist: pos = s.find(t, p) if pos < 0: continue if pos < tpos: tpos = pos token = t return token, tpos
[ "def", "find_next_token", "(", "self", ",", "s", ",", "tlist", ",", "p", "=", "0", ")", ":", "token", "=", "\"\"", "tpos", "=", "len", "(", "s", ")", "for", "t", "in", "tlist", ":", "pos", "=", "s", ".", "find", "(", "t", ",", "p", ")", "if", "pos", "<", "0", ":", "continue", "if", "pos", "<", "tpos", ":", "tpos", "=", "pos", "token", "=", "t", "return", "token", ",", "tpos" ]
https://github.com/ucisysarch/opencvjs/blob/7fe821305dffdc3ca6c7edfaa779d045f0406961/binding-gen/hdr_parser.py#L784-L798
oracle/graaljs
36a56e8e993d45fc40939a3a4d9c0c24990720f1
graal-nodejs/tools/inspector_protocol/jinja2/filters.py
python
do_batch
(value, linecount, fill_with=None)
A filter that batches items. It works pretty much like `slice` just the other way round. It returns a list of lists with the given number of items. If you provide a second parameter this is used to fill up missing items. See this example: .. sourcecode:: html+jinja <table> {%- for row in items|batch(3, '&nbsp;') %} <tr> {%- for column in row %} <td>{{ column }}</td> {%- endfor %} </tr> {%- endfor %} </table>
A filter that batches items. It works pretty much like `slice` just the other way round. It returns a list of lists with the given number of items. If you provide a second parameter this is used to fill up missing items. See this example:
[ "A", "filter", "that", "batches", "items", ".", "It", "works", "pretty", "much", "like", "slice", "just", "the", "other", "way", "round", ".", "It", "returns", "a", "list", "of", "lists", "with", "the", "given", "number", "of", "items", ".", "If", "you", "provide", "a", "second", "parameter", "this", "is", "used", "to", "fill", "up", "missing", "items", ".", "See", "this", "example", ":" ]
def do_batch(value, linecount, fill_with=None): """ A filter that batches items. It works pretty much like `slice` just the other way round. It returns a list of lists with the given number of items. If you provide a second parameter this is used to fill up missing items. See this example: .. sourcecode:: html+jinja <table> {%- for row in items|batch(3, '&nbsp;') %} <tr> {%- for column in row %} <td>{{ column }}</td> {%- endfor %} </tr> {%- endfor %} </table> """ tmp = [] for item in value: if len(tmp) == linecount: yield tmp tmp = [] tmp.append(item) if tmp: if fill_with is not None and len(tmp) < linecount: tmp += [fill_with] * (linecount - len(tmp)) yield tmp
[ "def", "do_batch", "(", "value", ",", "linecount", ",", "fill_with", "=", "None", ")", ":", "tmp", "=", "[", "]", "for", "item", "in", "value", ":", "if", "len", "(", "tmp", ")", "==", "linecount", ":", "yield", "tmp", "tmp", "=", "[", "]", "tmp", ".", "append", "(", "item", ")", "if", "tmp", ":", "if", "fill_with", "is", "not", "None", "and", "len", "(", "tmp", ")", "<", "linecount", ":", "tmp", "+=", "[", "fill_with", "]", "*", "(", "linecount", "-", "len", "(", "tmp", ")", ")", "yield", "tmp" ]
https://github.com/oracle/graaljs/blob/36a56e8e993d45fc40939a3a4d9c0c24990720f1/graal-nodejs/tools/inspector_protocol/jinja2/filters.py#L737-L765
eventql/eventql
7ca0dbb2e683b525620ea30dc40540a22d5eb227
deps/3rdparty/spidermonkey/mozjs/python/bitstring/bitstring.py
python
Bits._setse
(self, i)
Initialise bitstring with signed exponential-Golomb code for integer i.
Initialise bitstring with signed exponential-Golomb code for integer i.
[ "Initialise", "bitstring", "with", "signed", "exponential", "-", "Golomb", "code", "for", "integer", "i", "." ]
def _setse(self, i): """Initialise bitstring with signed exponential-Golomb code for integer i.""" if i > 0: u = (i * 2) - 1 else: u = -2 * i self._setue(u)
[ "def", "_setse", "(", "self", ",", "i", ")", ":", "if", "i", ">", "0", ":", "u", "=", "(", "i", "*", "2", ")", "-", "1", "else", ":", "u", "=", "-", "2", "*", "i", "self", ".", "_setue", "(", "u", ")" ]
https://github.com/eventql/eventql/blob/7ca0dbb2e683b525620ea30dc40540a22d5eb227/deps/3rdparty/spidermonkey/mozjs/python/bitstring/bitstring.py#L1675-L1681